1//===--- RecursiveASTVisitor.h - Recursive AST Visitor ----------*- C++ -*-===//
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// This file defines the RecursiveASTVisitor interface, which recursively
10// traverses the entire AST.
11//
12//===----------------------------------------------------------------------===//
13#ifndef LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
14#define LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
15
16#include "clang/AST/Attr.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclOpenMP.h"
24#include "clang/AST/DeclTemplate.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/LambdaCapture.h"
30#include "clang/AST/NestedNameSpecifier.h"
31#include "clang/AST/OpenMPClause.h"
32#include "clang/AST/Stmt.h"
33#include "clang/AST/StmtCXX.h"
34#include "clang/AST/StmtObjC.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TemplateBase.h"
37#include "clang/AST/TemplateName.h"
38#include "clang/AST/Type.h"
39#include "clang/AST/TypeLoc.h"
40#include "clang/Basic/LLVM.h"
41#include "clang/Basic/OpenMPKinds.h"
42#include "clang/Basic/Specifiers.h"
43#include "llvm/ADT/PointerIntPair.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/Support/Casting.h"
46#include <algorithm>
47#include <cstddef>
48#include <type_traits>
49
50// The following three macros are used for meta programming. The code
51// using them is responsible for defining macro OPERATOR().
52
53// All unary operators.
54#define UNARYOP_LIST() \
55 OPERATOR(PostInc) OPERATOR(PostDec) OPERATOR(PreInc) OPERATOR(PreDec) \
56 OPERATOR(AddrOf) OPERATOR(Deref) OPERATOR(Plus) OPERATOR(Minus) \
57 OPERATOR(Not) OPERATOR(LNot) OPERATOR(Real) OPERATOR(Imag) \
58 OPERATOR(Extension) OPERATOR(Coawait)
59
60// All binary operators (excluding compound assign operators).
61#define BINOP_LIST() \
62 OPERATOR(PtrMemD) OPERATOR(PtrMemI) OPERATOR(Mul) OPERATOR(Div) \
63 OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) OPERATOR(Shl) OPERATOR(Shr) \
64 OPERATOR(LT) OPERATOR(GT) OPERATOR(LE) OPERATOR(GE) OPERATOR(EQ) \
65 OPERATOR(NE) OPERATOR(Cmp) OPERATOR(And) OPERATOR(Xor) OPERATOR(Or) \
66 OPERATOR(LAnd) OPERATOR(LOr) OPERATOR(Assign) OPERATOR(Comma)
67
68// All compound assign operators.
69#define CAO_LIST() \
70 OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) \
71 OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or) OPERATOR(Xor)
72
73namespace clang {
74
75// A helper macro to implement short-circuiting when recursing. It
76// invokes CALL_EXPR, which must be a method call, on the derived
77// object (s.t. a user of RecursiveASTVisitor can override the method
78// in CALL_EXPR).
79#define TRY_TO(CALL_EXPR) \
80 do { \
81 if (!getDerived().CALL_EXPR) \
82 return false; \
83 } while (false)
84
85/// A class that does preorder or postorder
86/// depth-first traversal on the entire Clang AST and visits each node.
87///
88/// This class performs three distinct tasks:
89/// 1. traverse the AST (i.e. go to each node);
90/// 2. at a given node, walk up the class hierarchy, starting from
91/// the node's dynamic type, until the top-most class (e.g. Stmt,
92/// Decl, or Type) is reached.
93/// 3. given a (node, class) combination, where 'class' is some base
94/// class of the dynamic type of 'node', call a user-overridable
95/// function to actually visit the node.
96///
97/// These tasks are done by three groups of methods, respectively:
98/// 1. TraverseDecl(Decl *x) does task #1. It is the entry point
99/// for traversing an AST rooted at x. This method simply
100/// dispatches (i.e. forwards) to TraverseFoo(Foo *x) where Foo
101/// is the dynamic type of *x, which calls WalkUpFromFoo(x) and
102/// then recursively visits the child nodes of x.
103/// TraverseStmt(Stmt *x) and TraverseType(QualType x) work
104/// similarly.
105/// 2. WalkUpFromFoo(Foo *x) does task #2. It does not try to visit
106/// any child node of x. Instead, it first calls WalkUpFromBar(x)
107/// where Bar is the direct parent class of Foo (unless Foo has
108/// no parent), and then calls VisitFoo(x) (see the next list item).
109/// 3. VisitFoo(Foo *x) does task #3.
110///
111/// These three method groups are tiered (Traverse* > WalkUpFrom* >
112/// Visit*). A method (e.g. Traverse*) may call methods from the same
113/// tier (e.g. other Traverse*) or one tier lower (e.g. WalkUpFrom*).
114/// It may not call methods from a higher tier.
115///
116/// Note that since WalkUpFromFoo() calls WalkUpFromBar() (where Bar
117/// is Foo's super class) before calling VisitFoo(), the result is
118/// that the Visit*() methods for a given node are called in the
119/// top-down order (e.g. for a node of type NamespaceDecl, the order will
120/// be VisitDecl(), VisitNamedDecl(), and then VisitNamespaceDecl()).
121///
122/// This scheme guarantees that all Visit*() calls for the same AST
123/// node are grouped together. In other words, Visit*() methods for
124/// different nodes are never interleaved.
125///
126/// Clients of this visitor should subclass the visitor (providing
127/// themselves as the template argument, using the curiously recurring
128/// template pattern) and override any of the Traverse*, WalkUpFrom*,
129/// and Visit* methods for declarations, types, statements,
130/// expressions, or other AST nodes where the visitor should customize
131/// behavior. Most users only need to override Visit*. Advanced
132/// users may override Traverse* and WalkUpFrom* to implement custom
133/// traversal strategies. Returning false from one of these overridden
134/// functions will abort the entire traversal.
135///
136/// By default, this visitor tries to visit every part of the explicit
137/// source code exactly once. The default policy towards templates
138/// is to descend into the 'pattern' class or function body, not any
139/// explicit or implicit instantiations. Explicit specializations
140/// are still visited, and the patterns of partial specializations
141/// are visited separately. This behavior can be changed by
142/// overriding shouldVisitTemplateInstantiations() in the derived class
143/// to return true, in which case all known implicit and explicit
144/// instantiations will be visited at the same time as the pattern
145/// from which they were produced.
146///
147/// By default, this visitor preorder traverses the AST. If postorder traversal
148/// is needed, the \c shouldTraversePostOrder method needs to be overridden
149/// to return \c true.
150template <typename Derived> class RecursiveASTVisitor {
151public:
152 /// A queue used for performing data recursion over statements.
153 /// Parameters involving this type are used to implement data
154 /// recursion over Stmts and Exprs within this class, and should
155 /// typically not be explicitly specified by derived classes.
156 /// The bool bit indicates whether the statement has been traversed or not.
157 typedef SmallVectorImpl<llvm::PointerIntPair<Stmt *, 1, bool>>
158 DataRecursionQueue;
159
160 /// Return a reference to the derived class.
161 Derived &getDerived() { return *static_cast<Derived *>(this); }
162
163 /// Return whether this visitor should recurse into
164 /// template instantiations.
165 bool shouldVisitTemplateInstantiations() const { return false; }
166
167 /// Return whether this visitor should recurse into the types of
168 /// TypeLocs.
169 bool shouldWalkTypesOfTypeLocs() const { return true; }
170
171 /// Return whether this visitor should recurse into implicit
172 /// code, e.g., implicit constructors and destructors.
173 bool shouldVisitImplicitCode() const { return false; }
174
175 /// Return whether this visitor should traverse post-order.
176 bool shouldTraversePostOrder() const { return false; }
177
178 /// Recursively visits an entire AST, starting from the top-level Decls
179 /// in the AST traversal scope (by default, the TranslationUnitDecl).
180 /// \returns false if visitation was terminated early.
181 bool TraverseAST(ASTContext &AST) {
182 for (Decl *D : AST.getTraversalScope())
183 if (!getDerived().TraverseDecl(D))
184 return false;
185 return true;
186 }
187
188 /// Recursively visit a statement or expression, by
189 /// dispatching to Traverse*() based on the argument's dynamic type.
190 ///
191 /// \returns false if the visitation was terminated early, true
192 /// otherwise (including when the argument is nullptr).
193 bool TraverseStmt(Stmt *S, DataRecursionQueue *Queue = nullptr);
194
195 /// Invoked before visiting a statement or expression via data recursion.
196 ///
197 /// \returns false to skip visiting the node, true otherwise.
198 bool dataTraverseStmtPre(Stmt *S) { return true; }
199
200 /// Invoked after visiting a statement or expression via data recursion.
201 /// This is not invoked if the previously invoked \c dataTraverseStmtPre
202 /// returned false.
203 ///
204 /// \returns false if the visitation was terminated early, true otherwise.
205 bool dataTraverseStmtPost(Stmt *S) { return true; }
206
207 /// Recursively visit a type, by dispatching to
208 /// Traverse*Type() based on the argument's getTypeClass() property.
209 ///
210 /// \returns false if the visitation was terminated early, true
211 /// otherwise (including when the argument is a Null type).
212 bool TraverseType(QualType T);
213
214 /// Recursively visit a type with location, by dispatching to
215 /// Traverse*TypeLoc() based on the argument type's getTypeClass() property.
216 ///
217 /// \returns false if the visitation was terminated early, true
218 /// otherwise (including when the argument is a Null type location).
219 bool TraverseTypeLoc(TypeLoc TL);
220
221 /// Recursively visit an attribute, by dispatching to
222 /// Traverse*Attr() based on the argument's dynamic type.
223 ///
224 /// \returns false if the visitation was terminated early, true
225 /// otherwise (including when the argument is a Null type location).
226 bool TraverseAttr(Attr *At);
227
228 /// Recursively visit a declaration, by dispatching to
229 /// Traverse*Decl() based on the argument's dynamic type.
230 ///
231 /// \returns false if the visitation was terminated early, true
232 /// otherwise (including when the argument is NULL).
233 bool TraverseDecl(Decl *D);
234
235 /// Recursively visit a C++ nested-name-specifier.
236 ///
237 /// \returns false if the visitation was terminated early, true otherwise.
238 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
239
240 /// Recursively visit a C++ nested-name-specifier with location
241 /// information.
242 ///
243 /// \returns false if the visitation was terminated early, true otherwise.
244 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
245
246 /// Recursively visit a name with its location information.
247 ///
248 /// \returns false if the visitation was terminated early, true otherwise.
249 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo);
250
251 /// Recursively visit a template name and dispatch to the
252 /// appropriate method.
253 ///
254 /// \returns false if the visitation was terminated early, true otherwise.
255 bool TraverseTemplateName(TemplateName Template);
256
257 /// Recursively visit a template argument and dispatch to the
258 /// appropriate method for the argument type.
259 ///
260 /// \returns false if the visitation was terminated early, true otherwise.
261 // FIXME: migrate callers to TemplateArgumentLoc instead.
262 bool TraverseTemplateArgument(const TemplateArgument &Arg);
263
264 /// Recursively visit a template argument location and dispatch to the
265 /// appropriate method for the argument type.
266 ///
267 /// \returns false if the visitation was terminated early, true otherwise.
268 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc);
269
270 /// Recursively visit a set of template arguments.
271 /// This can be overridden by a subclass, but it's not expected that
272 /// will be needed -- this visitor always dispatches to another.
273 ///
274 /// \returns false if the visitation was terminated early, true otherwise.
275 // FIXME: take a TemplateArgumentLoc* (or TemplateArgumentListInfo) instead.
276 bool TraverseTemplateArguments(const TemplateArgument *Args,
277 unsigned NumArgs);
278
279 /// Recursively visit a base specifier. This can be overridden by a
280 /// subclass.
281 ///
282 /// \returns false if the visitation was terminated early, true otherwise.
283 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base);
284
285 /// Recursively visit a constructor initializer. This
286 /// automatically dispatches to another visitor for the initializer
287 /// expression, but not for the name of the initializer, so may
288 /// be overridden for clients that need access to the name.
289 ///
290 /// \returns false if the visitation was terminated early, true otherwise.
291 bool TraverseConstructorInitializer(CXXCtorInitializer *Init);
292
293 /// Recursively visit a lambda capture. \c Init is the expression that
294 /// will be used to initialize the capture.
295 ///
296 /// \returns false if the visitation was terminated early, true otherwise.
297 bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C,
298 Expr *Init);
299
300 /// Recursively visit the syntactic or semantic form of an
301 /// initialization list.
302 ///
303 /// \returns false if the visitation was terminated early, true otherwise.
304 bool TraverseSynOrSemInitListExpr(InitListExpr *S,
305 DataRecursionQueue *Queue = nullptr);
306
307 // ---- Methods on Attrs ----
308
309 // Visit an attribute.
310 bool VisitAttr(Attr *A) { return true; }
311
312// Declare Traverse* and empty Visit* for all Attr classes.
313#define ATTR_VISITOR_DECLS_ONLY
314#include "clang/AST/AttrVisitor.inc"
315#undef ATTR_VISITOR_DECLS_ONLY
316
317// ---- Methods on Stmts ----
318
319 Stmt::child_range getStmtChildren(Stmt *S) { return S->children(); }
320
321private:
322 template<typename T, typename U>
323 struct has_same_member_pointer_type : std::false_type {};
324 template<typename T, typename U, typename R, typename... P>
325 struct has_same_member_pointer_type<R (T::*)(P...), R (U::*)(P...)>
326 : std::true_type {};
327
328 // Traverse the given statement. If the most-derived traverse function takes a
329 // data recursion queue, pass it on; otherwise, discard it. Note that the
330 // first branch of this conditional must compile whether or not the derived
331 // class can take a queue, so if we're taking the second arm, make the first
332 // arm call our function rather than the derived class version.
333#define TRAVERSE_STMT_BASE(NAME, CLASS, VAR, QUEUE) \
334 (has_same_member_pointer_type<decltype( \
335 &RecursiveASTVisitor::Traverse##NAME), \
336 decltype(&Derived::Traverse##NAME)>::value \
337 ? static_cast<typename std::conditional< \
338 has_same_member_pointer_type< \
339 decltype(&RecursiveASTVisitor::Traverse##NAME), \
340 decltype(&Derived::Traverse##NAME)>::value, \
341 Derived &, RecursiveASTVisitor &>::type>(*this) \
342 .Traverse##NAME(static_cast<CLASS *>(VAR), QUEUE) \
343 : getDerived().Traverse##NAME(static_cast<CLASS *>(VAR)))
344
345// Try to traverse the given statement, or enqueue it if we're performing data
346// recursion in the middle of traversing another statement. Can only be called
347// from within a DEF_TRAVERSE_STMT body or similar context.
348#define TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S) \
349 do { \
350 if (!TRAVERSE_STMT_BASE(Stmt, Stmt, S, Queue)) \
351 return false; \
352 } while (false)
353
354public:
355// Declare Traverse*() for all concrete Stmt classes.
356#define ABSTRACT_STMT(STMT)
357#define STMT(CLASS, PARENT) \
358 bool Traverse##CLASS(CLASS *S, DataRecursionQueue *Queue = nullptr);
359#include "clang/AST/StmtNodes.inc"
360 // The above header #undefs ABSTRACT_STMT and STMT upon exit.
361
362 // Define WalkUpFrom*() and empty Visit*() for all Stmt classes.
363 bool WalkUpFromStmt(Stmt *S) { return getDerived().VisitStmt(S); }
364 bool VisitStmt(Stmt *S) { return true; }
365#define STMT(CLASS, PARENT) \
366 bool WalkUpFrom##CLASS(CLASS *S) { \
367 TRY_TO(WalkUpFrom##PARENT(S)); \
368 TRY_TO(Visit##CLASS(S)); \
369 return true; \
370 } \
371 bool Visit##CLASS(CLASS *S) { return true; }
372#include "clang/AST/StmtNodes.inc"
373
374// Define Traverse*(), WalkUpFrom*(), and Visit*() for unary
375// operator methods. Unary operators are not classes in themselves
376// (they're all opcodes in UnaryOperator) but do have visitors.
377#define OPERATOR(NAME) \
378 bool TraverseUnary##NAME(UnaryOperator *S, \
379 DataRecursionQueue *Queue = nullptr) { \
380 if (!getDerived().shouldTraversePostOrder()) \
381 TRY_TO(WalkUpFromUnary##NAME(S)); \
382 TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getSubExpr()); \
383 return true; \
384 } \
385 bool WalkUpFromUnary##NAME(UnaryOperator *S) { \
386 TRY_TO(WalkUpFromUnaryOperator(S)); \
387 TRY_TO(VisitUnary##NAME(S)); \
388 return true; \
389 } \
390 bool VisitUnary##NAME(UnaryOperator *S) { return true; }
391
392 UNARYOP_LIST()
393#undef OPERATOR
394
395// Define Traverse*(), WalkUpFrom*(), and Visit*() for binary
396// operator methods. Binary operators are not classes in themselves
397// (they're all opcodes in BinaryOperator) but do have visitors.
398#define GENERAL_BINOP_FALLBACK(NAME, BINOP_TYPE) \
399 bool TraverseBin##NAME(BINOP_TYPE *S, DataRecursionQueue *Queue = nullptr) { \
400 if (!getDerived().shouldTraversePostOrder()) \
401 TRY_TO(WalkUpFromBin##NAME(S)); \
402 TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getLHS()); \
403 TRY_TO_TRAVERSE_OR_ENQUEUE_STMT(S->getRHS()); \
404 return true; \
405 } \
406 bool WalkUpFromBin##NAME(BINOP_TYPE *S) { \
407 TRY_TO(WalkUpFrom##BINOP_TYPE(S)); \
408 TRY_TO(VisitBin##NAME(S)); \
409 return true; \
410 } \
411 bool VisitBin##NAME(BINOP_TYPE *S) { return true; }
412
413#define OPERATOR(NAME) GENERAL_BINOP_FALLBACK(NAME, BinaryOperator)
414 BINOP_LIST()
415#undef OPERATOR
416
417// Define Traverse*(), WalkUpFrom*(), and Visit*() for compound
418// assignment methods. Compound assignment operators are not
419// classes in themselves (they're all opcodes in
420// CompoundAssignOperator) but do have visitors.
421#define OPERATOR(NAME) \
422 GENERAL_BINOP_FALLBACK(NAME##Assign, CompoundAssignOperator)
423
424 CAO_LIST()
425#undef OPERATOR
426#undef GENERAL_BINOP_FALLBACK
427
428// ---- Methods on Types ----
429// FIXME: revamp to take TypeLoc's rather than Types.
430
431// Declare Traverse*() for all concrete Type classes.
432#define ABSTRACT_TYPE(CLASS, BASE)
433#define TYPE(CLASS, BASE) bool Traverse##CLASS##Type(CLASS##Type *T);
434#include "clang/AST/TypeNodes.def"
435 // The above header #undefs ABSTRACT_TYPE and TYPE upon exit.
436
437 // Define WalkUpFrom*() and empty Visit*() for all Type classes.
438 bool WalkUpFromType(Type *T) { return getDerived().VisitType(T); }
439 bool VisitType(Type *T) { return true; }
440#define TYPE(CLASS, BASE) \
441 bool WalkUpFrom##CLASS##Type(CLASS##Type *T) { \
442 TRY_TO(WalkUpFrom##BASE(T)); \
443 TRY_TO(Visit##CLASS##Type(T)); \
444 return true; \
445 } \
446 bool Visit##CLASS##Type(CLASS##Type *T) { return true; }
447#include "clang/AST/TypeNodes.def"
448
449// ---- Methods on TypeLocs ----
450// FIXME: this currently just calls the matching Type methods
451
452// Declare Traverse*() for all concrete TypeLoc classes.
453#define ABSTRACT_TYPELOC(CLASS, BASE)
454#define TYPELOC(CLASS, BASE) bool Traverse##CLASS##TypeLoc(CLASS##TypeLoc TL);
455#include "clang/AST/TypeLocNodes.def"
456 // The above header #undefs ABSTRACT_TYPELOC and TYPELOC upon exit.
457
458 // Define WalkUpFrom*() and empty Visit*() for all TypeLoc classes.
459 bool WalkUpFromTypeLoc(TypeLoc TL) { return getDerived().VisitTypeLoc(TL); }
460 bool VisitTypeLoc(TypeLoc TL) { return true; }
461
462 // QualifiedTypeLoc and UnqualTypeLoc are not declared in
463 // TypeNodes.def and thus need to be handled specially.
464 bool WalkUpFromQualifiedTypeLoc(QualifiedTypeLoc TL) {
465 return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
466 }
467 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return true; }
468 bool WalkUpFromUnqualTypeLoc(UnqualTypeLoc TL) {
469 return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
470 }
471 bool VisitUnqualTypeLoc(UnqualTypeLoc TL) { return true; }
472
473// Note that BASE includes trailing 'Type' which CLASS doesn't.
474#define TYPE(CLASS, BASE) \
475 bool WalkUpFrom##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
476 TRY_TO(WalkUpFrom##BASE##Loc(TL)); \
477 TRY_TO(Visit##CLASS##TypeLoc(TL)); \
478 return true; \
479 } \
480 bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { return true; }
481#include "clang/AST/TypeNodes.def"
482
483// ---- Methods on Decls ----
484
485// Declare Traverse*() for all concrete Decl classes.
486#define ABSTRACT_DECL(DECL)
487#define DECL(CLASS, BASE) bool Traverse##CLASS##Decl(CLASS##Decl *D);
488#include "clang/AST/DeclNodes.inc"
489 // The above header #undefs ABSTRACT_DECL and DECL upon exit.
490
491 // Define WalkUpFrom*() and empty Visit*() for all Decl classes.
492 bool WalkUpFromDecl(Decl *D) { return getDerived().VisitDecl(D); }
493 bool VisitDecl(Decl *D) { return true; }
494#define DECL(CLASS, BASE) \
495 bool WalkUpFrom##CLASS##Decl(CLASS##Decl *D) { \
496 TRY_TO(WalkUpFrom##BASE(D)); \
497 TRY_TO(Visit##CLASS##Decl(D)); \
498 return true; \
499 } \
500 bool Visit##CLASS##Decl(CLASS##Decl *D) { return true; }
501#include "clang/AST/DeclNodes.inc"
502
503 bool canIgnoreChildDeclWhileTraversingDeclContext(const Decl *Child);
504
505private:
506 // These are helper methods used by more than one Traverse* method.
507 bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
508
509 // Traverses template parameter lists of either a DeclaratorDecl or TagDecl.
510 template <typename T>
511 bool TraverseDeclTemplateParameterLists(T *D);
512
513#define DEF_TRAVERSE_TMPL_INST(TMPLDECLKIND) \
514 bool TraverseTemplateInstantiations(TMPLDECLKIND##TemplateDecl *D);
515 DEF_TRAVERSE_TMPL_INST(Class)
516 DEF_TRAVERSE_TMPL_INST(Var)
517 DEF_TRAVERSE_TMPL_INST(Function)
518#undef DEF_TRAVERSE_TMPL_INST
519 bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL,
520 unsigned Count);
521 bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL);
522 bool TraverseRecordHelper(RecordDecl *D);
523 bool TraverseCXXRecordHelper(CXXRecordDecl *D);
524 bool TraverseDeclaratorHelper(DeclaratorDecl *D);
525 bool TraverseDeclContextHelper(DeclContext *DC);
526 bool TraverseFunctionHelper(FunctionDecl *D);
527 bool TraverseVarHelper(VarDecl *D);
528 bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
529 bool TraverseOMPLoopDirective(OMPLoopDirective *S);
530 bool TraverseOMPClause(OMPClause *C);
531#define OPENMP_CLAUSE(Name, Class) bool Visit##Class(Class *C);
532 OPENMP_CLAUSE(flush, OMPFlushClause)
533#include "clang/Basic/OpenMPKinds.def"
534 /// Process clauses with list of variables.
535 template <typename T> bool VisitOMPClauseList(T *Node);
536 /// Process clauses with pre-initis.
537 bool VisitOMPClauseWithPreInit(OMPClauseWithPreInit *Node);
538 bool VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *Node);
539
540 bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue);
541 bool PostVisitStmt(Stmt *S);
542};
543
544template <typename Derived>
545bool RecursiveASTVisitor<Derived>::dataTraverseNode(Stmt *S,
546 DataRecursionQueue *Queue) {
547#define DISPATCH_STMT(NAME, CLASS, VAR) \
548 return TRAVERSE_STMT_BASE(NAME, CLASS, VAR, Queue);
549
550 // If we have a binary expr, dispatch to the subcode of the binop. A smart
551 // optimizer (e.g. LLVM) will fold this comparison into the switch stmt
552 // below.
553 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
554 switch (BinOp->getOpcode()) {
555#define OPERATOR(NAME) \
556 case BO_##NAME: \
557 DISPATCH_STMT(Bin##NAME, BinaryOperator, S);
558
559 BINOP_LIST()
560#undef OPERATOR
561#undef BINOP_LIST
562
563#define OPERATOR(NAME) \
564 case BO_##NAME##Assign: \
565 DISPATCH_STMT(Bin##NAME##Assign, CompoundAssignOperator, S);
566
567 CAO_LIST()
568#undef OPERATOR
569#undef CAO_LIST
570 }
571 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
572 switch (UnOp->getOpcode()) {
573#define OPERATOR(NAME) \
574 case UO_##NAME: \
575 DISPATCH_STMT(Unary##NAME, UnaryOperator, S);
576
577 UNARYOP_LIST()
578#undef OPERATOR
579#undef UNARYOP_LIST
580 }
581 }
582
583 // Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
584 switch (S->getStmtClass()) {
585 case Stmt::NoStmtClass:
586 break;
587#define ABSTRACT_STMT(STMT)
588#define STMT(CLASS, PARENT) \
589 case Stmt::CLASS##Class: \
590 DISPATCH_STMT(CLASS, CLASS, S);
591#include "clang/AST/StmtNodes.inc"
592 }
593
594 return true;
595}
596
597#undef DISPATCH_STMT
598
599template <typename Derived>
600bool RecursiveASTVisitor<Derived>::PostVisitStmt(Stmt *S) {
601 switch (S->getStmtClass()) {
602 case Stmt::NoStmtClass:
603 break;
604#define ABSTRACT_STMT(STMT)
605#define STMT(CLASS, PARENT) \
606 case Stmt::CLASS##Class: \
607 TRY_TO(WalkUpFrom##CLASS(static_cast<CLASS *>(S))); break;
608#define INITLISTEXPR(CLASS, PARENT) \
609 case Stmt::CLASS##Class: \
610 { \
611 auto ILE = static_cast<CLASS *>(S); \
612 if (auto Syn = ILE->isSemanticForm() ? ILE->getSyntacticForm() : ILE) \
613 TRY_TO(WalkUpFrom##CLASS(Syn)); \
614 if (auto Sem = ILE->isSemanticForm() ? ILE : ILE->getSemanticForm()) \
615 TRY_TO(WalkUpFrom##CLASS(Sem)); \
616 break; \
617 }
618#include "clang/AST/StmtNodes.inc"
619 }
620
621 return true;
622}
623
624#undef DISPATCH_STMT
625
626template <typename Derived>
627bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S,
628 DataRecursionQueue *Queue) {
629 if (!S)
630 return true;
631
632 if (Queue) {
633 Queue->push_back({S, false});
634 return true;
635 }
636
637 SmallVector<llvm::PointerIntPair<Stmt *, 1, bool>, 8> LocalQueue;
638 LocalQueue.push_back({S, false});
639
640 while (!LocalQueue.empty()) {
641 auto &CurrSAndVisited = LocalQueue.back();
642 Stmt *CurrS = CurrSAndVisited.getPointer();
643 bool Visited = CurrSAndVisited.getInt();
644 if (Visited) {
645 LocalQueue.pop_back();
646 TRY_TO(dataTraverseStmtPost(CurrS));
647 if (getDerived().shouldTraversePostOrder()) {
648 TRY_TO(PostVisitStmt(CurrS));
649 }
650 continue;
651 }
652
653 if (getDerived().dataTraverseStmtPre(CurrS)) {
654 CurrSAndVisited.setInt(true);
655 size_t N = LocalQueue.size();
656 TRY_TO(dataTraverseNode(CurrS, &LocalQueue));
657 // Process new children in the order they were added.
658 std::reverse(LocalQueue.begin() + N, LocalQueue.end());
659 } else {
660 LocalQueue.pop_back();
661 }
662 }
663
664 return true;
665}
666
667#define DISPATCH(NAME, CLASS, VAR) \
668 return getDerived().Traverse##NAME(static_cast<CLASS *>(VAR))
669
670template <typename Derived>
671bool RecursiveASTVisitor<Derived>::TraverseType(QualType T) {
672 if (T.isNull())
673 return true;
674
675 switch (T->getTypeClass()) {
676#define ABSTRACT_TYPE(CLASS, BASE)
677#define TYPE(CLASS, BASE) \
678 case Type::CLASS: \
679 DISPATCH(CLASS##Type, CLASS##Type, const_cast<Type *>(T.getTypePtr()));
680#include "clang/AST/TypeNodes.def"
681 }
682
683 return true;
684}
685
686template <typename Derived>
687bool RecursiveASTVisitor<Derived>::TraverseTypeLoc(TypeLoc TL) {
688 if (TL.isNull())
689 return true;
690
691 switch (TL.getTypeLocClass()) {
692#define ABSTRACT_TYPELOC(CLASS, BASE)
693#define TYPELOC(CLASS, BASE) \
694 case TypeLoc::CLASS: \
695 return getDerived().Traverse##CLASS##TypeLoc(TL.castAs<CLASS##TypeLoc>());
696#include "clang/AST/TypeLocNodes.def"
697 }
698
699 return true;
700}
701
702// Define the Traverse*Attr(Attr* A) methods
703#define VISITORCLASS RecursiveASTVisitor
704#include "clang/AST/AttrVisitor.inc"
705#undef VISITORCLASS
706
707template <typename Derived>
708bool RecursiveASTVisitor<Derived>::TraverseDecl(Decl *D) {
709 if (!D)
710 return true;
711
712 // As a syntax visitor, by default we want to ignore declarations for
713 // implicit declarations (ones not typed explicitly by the user).
714 if (!getDerived().shouldVisitImplicitCode() && D->isImplicit())
715 return true;
716
717 switch (D->getKind()) {
718#define ABSTRACT_DECL(DECL)
719#define DECL(CLASS, BASE) \
720 case Decl::CLASS: \
721 if (!getDerived().Traverse##CLASS##Decl(static_cast<CLASS##Decl *>(D))) \
722 return false; \
723 break;
724#include "clang/AST/DeclNodes.inc"
725 }
726
727 // Visit any attributes attached to this declaration.
728 for (auto *I : D->attrs()) {
729 if (!getDerived().TraverseAttr(I))
730 return false;
731 }
732 return true;
733}
734
735#undef DISPATCH
736
737template <typename Derived>
738bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifier(
739 NestedNameSpecifier *NNS) {
740 if (!NNS)
741 return true;
742
743 if (NNS->getPrefix())
744 TRY_TO(TraverseNestedNameSpecifier(NNS->getPrefix()));
745
746 switch (NNS->getKind()) {
747 case NestedNameSpecifier::Identifier:
748 case NestedNameSpecifier::Namespace:
749 case NestedNameSpecifier::NamespaceAlias:
750 case NestedNameSpecifier::Global:
751 case NestedNameSpecifier::Super:
752 return true;
753
754 case NestedNameSpecifier::TypeSpec:
755 case NestedNameSpecifier::TypeSpecWithTemplate:
756 TRY_TO(TraverseType(QualType(NNS->getAsType(), 0)));
757 }
758
759 return true;
760}
761
762template <typename Derived>
763bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifierLoc(
764 NestedNameSpecifierLoc NNS) {
765 if (!NNS)
766 return true;
767
768 if (NestedNameSpecifierLoc Prefix = NNS.getPrefix())
769 TRY_TO(TraverseNestedNameSpecifierLoc(Prefix));
770
771 switch (NNS.getNestedNameSpecifier()->getKind()) {
772 case NestedNameSpecifier::Identifier:
773 case NestedNameSpecifier::Namespace:
774 case NestedNameSpecifier::NamespaceAlias:
775 case NestedNameSpecifier::Global:
776 case NestedNameSpecifier::Super:
777 return true;
778
779 case NestedNameSpecifier::TypeSpec:
780 case NestedNameSpecifier::TypeSpecWithTemplate:
781 TRY_TO(TraverseTypeLoc(NNS.getTypeLoc()));
782 break;
783 }
784
785 return true;
786}
787
788template <typename Derived>
789bool RecursiveASTVisitor<Derived>::TraverseDeclarationNameInfo(
790 DeclarationNameInfo NameInfo) {
791 switch (NameInfo.getName().getNameKind()) {
792 case DeclarationName::CXXConstructorName:
793 case DeclarationName::CXXDestructorName:
794 case DeclarationName::CXXConversionFunctionName:
795 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
796 TRY_TO(TraverseTypeLoc(TSInfo->getTypeLoc()));
797 break;
798
799 case DeclarationName::CXXDeductionGuideName:
800 TRY_TO(TraverseTemplateName(
801 TemplateName(NameInfo.getName().getCXXDeductionGuideTemplate())));
802 break;
803
804 case DeclarationName::Identifier:
805 case DeclarationName::ObjCZeroArgSelector:
806 case DeclarationName::ObjCOneArgSelector:
807 case DeclarationName::ObjCMultiArgSelector:
808 case DeclarationName::CXXOperatorName:
809 case DeclarationName::CXXLiteralOperatorName:
810 case DeclarationName::CXXUsingDirective:
811 break;
812 }
813
814 return true;
815}
816
817template <typename Derived>
818bool RecursiveASTVisitor<Derived>::TraverseTemplateName(TemplateName Template) {
819 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
820 TRY_TO(TraverseNestedNameSpecifier(DTN->getQualifier()));
821 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
822 TRY_TO(TraverseNestedNameSpecifier(QTN->getQualifier()));
823
824 return true;
825}
826
827template <typename Derived>
828bool RecursiveASTVisitor<Derived>::TraverseTemplateArgument(
829 const TemplateArgument &Arg) {
830 switch (Arg.getKind()) {
831 case TemplateArgument::Null:
832 case TemplateArgument::Declaration:
833 case TemplateArgument::Integral:
834 case TemplateArgument::NullPtr:
835 return true;
836
837 case TemplateArgument::Type:
838 return getDerived().TraverseType(Arg.getAsType());
839
840 case TemplateArgument::Template:
841 case TemplateArgument::TemplateExpansion:
842 return getDerived().TraverseTemplateName(
843 Arg.getAsTemplateOrTemplatePattern());
844
845 case TemplateArgument::Expression:
846 return getDerived().TraverseStmt(Arg.getAsExpr());
847
848 case TemplateArgument::Pack:
849 return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
850 Arg.pack_size());
851 }
852
853 return true;
854}
855
856// FIXME: no template name location?
857// FIXME: no source locations for a template argument pack?
858template <typename Derived>
859bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLoc(
860 const TemplateArgumentLoc &ArgLoc) {
861 const TemplateArgument &Arg = ArgLoc.getArgument();
862
863 switch (Arg.getKind()) {
864 case TemplateArgument::Null:
865 case TemplateArgument::Declaration:
866 case TemplateArgument::Integral:
867 case TemplateArgument::NullPtr:
868 return true;
869
870 case TemplateArgument::Type: {
871 // FIXME: how can TSI ever be NULL?
872 if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo())
873 return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
874 else
875 return getDerived().TraverseType(Arg.getAsType());
876 }
877
878 case TemplateArgument::Template:
879 case TemplateArgument::TemplateExpansion:
880 if (ArgLoc.getTemplateQualifierLoc())
881 TRY_TO(getDerived().TraverseNestedNameSpecifierLoc(
882 ArgLoc.getTemplateQualifierLoc()));
883 return getDerived().TraverseTemplateName(
884 Arg.getAsTemplateOrTemplatePattern());
885
886 case TemplateArgument::Expression:
887 return getDerived().TraverseStmt(ArgLoc.getSourceExpression());
888
889 case TemplateArgument::Pack:
890 return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
891 Arg.pack_size());
892 }
893
894 return true;
895}
896
897template <typename Derived>
898bool RecursiveASTVisitor<Derived>::TraverseTemplateArguments(
899 const TemplateArgument *Args, unsigned NumArgs) {
900 for (unsigned I = 0; I != NumArgs; ++I) {
901 TRY_TO(TraverseTemplateArgument(Args[I]));
902 }
903
904 return true;
905}
906
907template <typename Derived>
908bool RecursiveASTVisitor<Derived>::TraverseConstructorInitializer(
909 CXXCtorInitializer *Init) {
910 if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo())
911 TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
912
913 if (Init->isWritten() || getDerived().shouldVisitImplicitCode())
914 TRY_TO(TraverseStmt(Init->getInit()));
915
916 return true;
917}
918
919template <typename Derived>
920bool
921RecursiveASTVisitor<Derived>::TraverseLambdaCapture(LambdaExpr *LE,
922 const LambdaCapture *C,
923 Expr *Init) {
924 if (LE->isInitCapture(C))
925 TRY_TO(TraverseDecl(C->getCapturedVar()));
926 else
927 TRY_TO(TraverseStmt(Init));
928 return true;
929}
930
931// ----------------- Type traversal -----------------
932
933// This macro makes available a variable T, the passed-in type.
934#define DEF_TRAVERSE_TYPE(TYPE, CODE) \
935 template <typename Derived> \
936 bool RecursiveASTVisitor<Derived>::Traverse##TYPE(TYPE *T) { \
937 if (!getDerived().shouldTraversePostOrder()) \
938 TRY_TO(WalkUpFrom##TYPE(T)); \
939 { CODE; } \
940 if (getDerived().shouldTraversePostOrder()) \
941 TRY_TO(WalkUpFrom##TYPE(T)); \
942 return true; \
943 }
944
945DEF_TRAVERSE_TYPE(BuiltinType, {})
946
947DEF_TRAVERSE_TYPE(ComplexType, { TRY_TO(TraverseType(T->getElementType())); })
948
949DEF_TRAVERSE_TYPE(PointerType, { TRY_TO(TraverseType(T->getPointeeType())); })
950
951DEF_TRAVERSE_TYPE(BlockPointerType,
952 { TRY_TO(TraverseType(T->getPointeeType())); })
953
954DEF_TRAVERSE_TYPE(LValueReferenceType,
955 { TRY_TO(TraverseType(T->getPointeeType())); })
956
957DEF_TRAVERSE_TYPE(RValueReferenceType,
958 { TRY_TO(TraverseType(T->getPointeeType())); })
959
960DEF_TRAVERSE_TYPE(MemberPointerType, {
961 TRY_TO(TraverseType(QualType(T->getClass(), 0)));
962 TRY_TO(TraverseType(T->getPointeeType()));
963})
964
965DEF_TRAVERSE_TYPE(AdjustedType, { TRY_TO(TraverseType(T->getOriginalType())); })
966
967DEF_TRAVERSE_TYPE(DecayedType, { TRY_TO(TraverseType(T->getOriginalType())); })
968
969DEF_TRAVERSE_TYPE(ConstantArrayType,
970 { TRY_TO(TraverseType(T->getElementType())); })
971
972DEF_TRAVERSE_TYPE(IncompleteArrayType,
973 { TRY_TO(TraverseType(T->getElementType())); })
974
975DEF_TRAVERSE_TYPE(VariableArrayType, {
976 TRY_TO(TraverseType(T->getElementType()));
977 TRY_TO(TraverseStmt(T->getSizeExpr()));
978})
979
980DEF_TRAVERSE_TYPE(DependentSizedArrayType, {
981 TRY_TO(TraverseType(T->getElementType()));
982 if (T->getSizeExpr())
983 TRY_TO(TraverseStmt(T->getSizeExpr()));
984})
985
986DEF_TRAVERSE_TYPE(DependentAddressSpaceType, {
987 TRY_TO(TraverseStmt(T->getAddrSpaceExpr()));
988 TRY_TO(TraverseType(T->getPointeeType()));
989})
990
991DEF_TRAVERSE_TYPE(DependentVectorType, {
992 if (T->getSizeExpr())
993 TRY_TO(TraverseStmt(T->getSizeExpr()));
994 TRY_TO(TraverseType(T->getElementType()));
995})
996
997DEF_TRAVERSE_TYPE(DependentSizedExtVectorType, {
998 if (T->getSizeExpr())
999 TRY_TO(TraverseStmt(T->getSizeExpr()));
1000 TRY_TO(TraverseType(T->getElementType()));
1001})
1002
1003DEF_TRAVERSE_TYPE(VectorType, { TRY_TO(TraverseType(T->getElementType())); })
1004
1005DEF_TRAVERSE_TYPE(ExtVectorType, { TRY_TO(TraverseType(T->getElementType())); })
1006
1007DEF_TRAVERSE_TYPE(FunctionNoProtoType,
1008 { TRY_TO(TraverseType(T->getReturnType())); })
1009
1010DEF_TRAVERSE_TYPE(FunctionProtoType, {
1011 TRY_TO(TraverseType(T->getReturnType()));
1012
1013 for (const auto &A : T->param_types()) {
1014 TRY_TO(TraverseType(A));
1015 }
1016
1017 for (const auto &E : T->exceptions()) {
1018 TRY_TO(TraverseType(E));
1019 }
1020
1021 if (Expr *NE = T->getNoexceptExpr())
1022 TRY_TO(TraverseStmt(NE));
1023})
1024
1025DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})
1026DEF_TRAVERSE_TYPE(TypedefType, {})
1027
1028DEF_TRAVERSE_TYPE(TypeOfExprType,
1029 { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
1030
1031DEF_TRAVERSE_TYPE(TypeOfType, { TRY_TO(TraverseType(T->getUnderlyingType())); })
1032
1033DEF_TRAVERSE_TYPE(DecltypeType,
1034 { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
1035
1036DEF_TRAVERSE_TYPE(UnaryTransformType, {
1037 TRY_TO(TraverseType(T->getBaseType()));
1038 TRY_TO(TraverseType(T->getUnderlyingType()));
1039})
1040
1041DEF_TRAVERSE_TYPE(AutoType, { TRY_TO(TraverseType(T->getDeducedType())); })
1042DEF_TRAVERSE_TYPE(DeducedTemplateSpecializationType, {
1043 TRY_TO(TraverseTemplateName(T->getTemplateName()));
1044 TRY_TO(TraverseType(T->getDeducedType()));
1045})
1046
1047DEF_TRAVERSE_TYPE(RecordType, {})
1048DEF_TRAVERSE_TYPE(EnumType, {})
1049DEF_TRAVERSE_TYPE(TemplateTypeParmType, {})
1050DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, {
1051 TRY_TO(TraverseType(T->getReplacementType()));
1052})
1053DEF_TRAVERSE_TYPE(SubstTemplateTypeParmPackType, {
1054 TRY_TO(TraverseTemplateArgument(T->getArgumentPack()));
1055})
1056
1057DEF_TRAVERSE_TYPE(TemplateSpecializationType, {
1058 TRY_TO(TraverseTemplateName(T->getTemplateName()));
1059 TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
1060})
1061
1062DEF_TRAVERSE_TYPE(InjectedClassNameType, {})
1063
1064DEF_TRAVERSE_TYPE(AttributedType,
1065 { TRY_TO(TraverseType(T->getModifiedType())); })
1066
1067DEF_TRAVERSE_TYPE(ParenType, { TRY_TO(TraverseType(T->getInnerType())); })
1068
1069DEF_TRAVERSE_TYPE(ElaboratedType, {
1070 if (T->getQualifier()) {
1071 TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
1072 }
1073 TRY_TO(TraverseType(T->getNamedType()));
1074})
1075
1076DEF_TRAVERSE_TYPE(DependentNameType,
1077 { TRY_TO(TraverseNestedNameSpecifier(T->getQualifier())); })
1078
1079DEF_TRAVERSE_TYPE(DependentTemplateSpecializationType, {
1080 TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
1081 TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
1082})
1083
1084DEF_TRAVERSE_TYPE(PackExpansionType, { TRY_TO(TraverseType(T->getPattern())); })
1085
1086DEF_TRAVERSE_TYPE(ObjCTypeParamType, {})
1087
1088DEF_TRAVERSE_TYPE(ObjCInterfaceType, {})
1089
1090DEF_TRAVERSE_TYPE(ObjCObjectType, {
1091 // We have to watch out here because an ObjCInterfaceType's base
1092 // type is itself.
1093 if (T->getBaseType().getTypePtr() != T)
1094 TRY_TO(TraverseType(T->getBaseType()));
1095 for (auto typeArg : T->getTypeArgsAsWritten()) {
1096 TRY_TO(TraverseType(typeArg));
1097 }
1098})
1099
1100DEF_TRAVERSE_TYPE(ObjCObjectPointerType,
1101 { TRY_TO(TraverseType(T->getPointeeType())); })
1102
1103DEF_TRAVERSE_TYPE(AtomicType, { TRY_TO(TraverseType(T->getValueType())); })
1104
1105DEF_TRAVERSE_TYPE(PipeType, { TRY_TO(TraverseType(T->getElementType())); })
1106
1107#undef DEF_TRAVERSE_TYPE
1108
1109// ----------------- TypeLoc traversal -----------------
1110
1111// This macro makes available a variable TL, the passed-in TypeLoc.
1112// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,
1113// in addition to WalkUpFrom* for the TypeLoc itself, such that existing
1114// clients that override the WalkUpFrom*Type() and/or Visit*Type() methods
1115// continue to work.
1116#define DEF_TRAVERSE_TYPELOC(TYPE, CODE) \
1117 template <typename Derived> \
1118 bool RecursiveASTVisitor<Derived>::Traverse##TYPE##Loc(TYPE##Loc TL) { \
1119 if (getDerived().shouldWalkTypesOfTypeLocs()) \
1120 TRY_TO(WalkUpFrom##TYPE(const_cast<TYPE *>(TL.getTypePtr()))); \
1121 TRY_TO(WalkUpFrom##TYPE##Loc(TL)); \
1122 { CODE; } \
1123 return true; \
1124 }
1125
1126template <typename Derived>
1127bool
1128RecursiveASTVisitor<Derived>::TraverseQualifiedTypeLoc(QualifiedTypeLoc TL) {
1129 // Move this over to the 'main' typeloc tree. Note that this is a
1130 // move -- we pretend that we were really looking at the unqualified
1131 // typeloc all along -- rather than a recursion, so we don't follow
1132 // the normal CRTP plan of going through
1133 // getDerived().TraverseTypeLoc. If we did, we'd be traversing
1134 // twice for the same type (once as a QualifiedTypeLoc version of
1135 // the type, once as an UnqualifiedTypeLoc version of the type),
1136 // which in effect means we'd call VisitTypeLoc twice with the
1137 // 'same' type. This solves that problem, at the cost of never
1138 // seeing the qualified version of the type (unless the client
1139 // subclasses TraverseQualifiedTypeLoc themselves). It's not a
1140 // perfect solution. A perfect solution probably requires making
1141 // QualifiedTypeLoc a wrapper around TypeLoc -- like QualType is a
1142 // wrapper around Type* -- rather than being its own class in the
1143 // type hierarchy.
1144 return TraverseTypeLoc(TL.getUnqualifiedLoc());
1145}
1146
1147DEF_TRAVERSE_TYPELOC(BuiltinType, {})
1148
1149// FIXME: ComplexTypeLoc is unfinished
1150DEF_TRAVERSE_TYPELOC(ComplexType, {
1151 TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1152})
1153
1154DEF_TRAVERSE_TYPELOC(PointerType,
1155 { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1156
1157DEF_TRAVERSE_TYPELOC(BlockPointerType,
1158 { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1159
1160DEF_TRAVERSE_TYPELOC(LValueReferenceType,
1161 { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1162
1163DEF_TRAVERSE_TYPELOC(RValueReferenceType,
1164 { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1165
1166// FIXME: location of base class?
1167// We traverse this in the type case as well, but how is it not reached through
1168// the pointee type?
1169DEF_TRAVERSE_TYPELOC(MemberPointerType, {
1170 TRY_TO(TraverseType(QualType(TL.getTypePtr()->getClass(), 0)));
1171 TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
1172})
1173
1174DEF_TRAVERSE_TYPELOC(AdjustedType,
1175 { TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
1176
1177DEF_TRAVERSE_TYPELOC(DecayedType,
1178 { TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
1179
1180template <typename Derived>
1181bool RecursiveASTVisitor<Derived>::TraverseArrayTypeLocHelper(ArrayTypeLoc TL) {
1182 // This isn't available for ArrayType, but is for the ArrayTypeLoc.
1183 TRY_TO(TraverseStmt(TL.getSizeExpr()));
1184 return true;
1185}
1186
1187DEF_TRAVERSE_TYPELOC(ConstantArrayType, {
1188 TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1189 return TraverseArrayTypeLocHelper(TL);
1190})
1191
1192DEF_TRAVERSE_TYPELOC(IncompleteArrayType, {
1193 TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1194 return TraverseArrayTypeLocHelper(TL);
1195})
1196
1197DEF_TRAVERSE_TYPELOC(VariableArrayType, {
1198 TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1199 return TraverseArrayTypeLocHelper(TL);
1200})
1201
1202DEF_TRAVERSE_TYPELOC(DependentSizedArrayType, {
1203 TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1204 return TraverseArrayTypeLocHelper(TL);
1205})
1206
1207DEF_TRAVERSE_TYPELOC(DependentAddressSpaceType, {
1208 TRY_TO(TraverseStmt(TL.getTypePtr()->getAddrSpaceExpr()));
1209 TRY_TO(TraverseType(TL.getTypePtr()->getPointeeType()));
1210})
1211
1212// FIXME: order? why not size expr first?
1213// FIXME: base VectorTypeLoc is unfinished
1214DEF_TRAVERSE_TYPELOC(DependentSizedExtVectorType, {
1215 if (TL.getTypePtr()->getSizeExpr())
1216 TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
1217 TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1218})
1219
1220// FIXME: VectorTypeLoc is unfinished
1221DEF_TRAVERSE_TYPELOC(VectorType, {
1222 TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1223})
1224
1225DEF_TRAVERSE_TYPELOC(DependentVectorType, {
1226 if (TL.getTypePtr()->getSizeExpr())
1227 TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
1228 TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1229})
1230
1231// FIXME: size and attributes
1232// FIXME: base VectorTypeLoc is unfinished
1233DEF_TRAVERSE_TYPELOC(ExtVectorType, {
1234 TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1235})
1236
1237DEF_TRAVERSE_TYPELOC(FunctionNoProtoType,
1238 { TRY_TO(TraverseTypeLoc(TL.getReturnLoc())); })
1239
1240// FIXME: location of exception specifications (attributes?)
1241DEF_TRAVERSE_TYPELOC(FunctionProtoType, {
1242 TRY_TO(TraverseTypeLoc(TL.getReturnLoc()));
1243
1244 const FunctionProtoType *T = TL.getTypePtr();
1245
1246 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
1247 if (TL.getParam(I)) {
1248 TRY_TO(TraverseDecl(TL.getParam(I)));
1249 } else if (I < T->getNumParams()) {
1250 TRY_TO(TraverseType(T->getParamType(I)));
1251 }
1252 }
1253
1254 for (const auto &E : T->exceptions()) {
1255 TRY_TO(TraverseType(E));
1256 }
1257
1258 if (Expr *NE = T->getNoexceptExpr())
1259 TRY_TO(TraverseStmt(NE));
1260})
1261
1262DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, {})
1263DEF_TRAVERSE_TYPELOC(TypedefType, {})
1264
1265DEF_TRAVERSE_TYPELOC(TypeOfExprType,
1266 { TRY_TO(TraverseStmt(TL.getUnderlyingExpr())); })
1267
1268DEF_TRAVERSE_TYPELOC(TypeOfType, {
1269 TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
1270})
1271
1272// FIXME: location of underlying expr
1273DEF_TRAVERSE_TYPELOC(DecltypeType, {
1274 TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr()));
1275})
1276
1277DEF_TRAVERSE_TYPELOC(UnaryTransformType, {
1278 TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
1279})
1280
1281DEF_TRAVERSE_TYPELOC(AutoType, {
1282 TRY_TO(TraverseType(TL.getTypePtr()->getDeducedType()));
1283})
1284
1285DEF_TRAVERSE_TYPELOC(DeducedTemplateSpecializationType, {
1286 TRY_TO(TraverseTemplateName(TL.getTypePtr()->getTemplateName()));
1287 TRY_TO(TraverseType(TL.getTypePtr()->getDeducedType()));
1288})
1289
1290DEF_TRAVERSE_TYPELOC(RecordType, {})
1291DEF_TRAVERSE_TYPELOC(EnumType, {})
1292DEF_TRAVERSE_TYPELOC(TemplateTypeParmType, {})
1293DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmType, {
1294 TRY_TO(TraverseType(TL.getTypePtr()->getReplacementType()));
1295})
1296DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmPackType, {
1297 TRY_TO(TraverseTemplateArgument(TL.getTypePtr()->getArgumentPack()));
1298})
1299
1300// FIXME: use the loc for the template name?
1301DEF_TRAVERSE_TYPELOC(TemplateSpecializationType, {
1302 TRY_TO(TraverseTemplateName(TL.getTypePtr()->getTemplateName()));
1303 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
1304 TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
1305 }
1306})
1307
1308DEF_TRAVERSE_TYPELOC(InjectedClassNameType, {})
1309
1310DEF_TRAVERSE_TYPELOC(ParenType, { TRY_TO(TraverseTypeLoc(TL.getInnerLoc())); })
1311
1312DEF_TRAVERSE_TYPELOC(AttributedType,
1313 { TRY_TO(TraverseTypeLoc(TL.getModifiedLoc())); })
1314
1315DEF_TRAVERSE_TYPELOC(ElaboratedType, {
1316 if (TL.getQualifierLoc()) {
1317 TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1318 }
1319 TRY_TO(TraverseTypeLoc(TL.getNamedTypeLoc()));
1320})
1321
1322DEF_TRAVERSE_TYPELOC(DependentNameType, {
1323 TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1324})
1325
1326DEF_TRAVERSE_TYPELOC(DependentTemplateSpecializationType, {
1327 if (TL.getQualifierLoc()) {
1328 TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1329 }
1330
1331 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
1332 TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
1333 }
1334})
1335
1336DEF_TRAVERSE_TYPELOC(PackExpansionType,
1337 { TRY_TO(TraverseTypeLoc(TL.getPatternLoc())); })
1338
1339DEF_TRAVERSE_TYPELOC(ObjCTypeParamType, {})
1340
1341DEF_TRAVERSE_TYPELOC(ObjCInterfaceType, {})
1342
1343DEF_TRAVERSE_TYPELOC(ObjCObjectType, {
1344 // We have to watch out here because an ObjCInterfaceType's base
1345 // type is itself.
1346 if (TL.getTypePtr()->getBaseType().getTypePtr() != TL.getTypePtr())
1347 TRY_TO(TraverseTypeLoc(TL.getBaseLoc()));
1348 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
1349 TRY_TO(TraverseTypeLoc(TL.getTypeArgTInfo(i)->getTypeLoc()));
1350})
1351
1352DEF_TRAVERSE_TYPELOC(ObjCObjectPointerType,
1353 { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1354
1355DEF_TRAVERSE_TYPELOC(AtomicType, { TRY_TO(TraverseTypeLoc(TL.getValueLoc())); })
1356
1357DEF_TRAVERSE_TYPELOC(PipeType, { TRY_TO(TraverseTypeLoc(TL.getValueLoc())); })
1358
1359#undef DEF_TRAVERSE_TYPELOC
1360
1361// ----------------- Decl traversal -----------------
1362//
1363// For a Decl, we automate (in the DEF_TRAVERSE_DECL macro) traversing
1364// the children that come from the DeclContext associated with it.
1365// Therefore each Traverse* only needs to worry about children other
1366// than those.
1367
1368template <typename Derived>
1369bool RecursiveASTVisitor<Derived>::canIgnoreChildDeclWhileTraversingDeclContext(
1370 const Decl *Child) {
1371 // BlockDecls are traversed through BlockExprs,
1372 // CapturedDecls are traversed through CapturedStmts.
1373 if (isa<BlockDecl>(Child) || isa<CapturedDecl>(Child))
1374 return true;
1375 // Lambda classes are traversed through LambdaExprs.
1376 if (const CXXRecordDecl* Cls = dyn_cast<CXXRecordDecl>(Child))
1377 return Cls->isLambda();
1378 return false;
1379}
1380
1381template <typename Derived>
1382bool RecursiveASTVisitor<Derived>::TraverseDeclContextHelper(DeclContext *DC) {
1383 if (!DC)
1384 return true;
1385
1386 for (auto *Child : DC->decls()) {
1387 if (!canIgnoreChildDeclWhileTraversingDeclContext(Child))
1388 TRY_TO(TraverseDecl(Child));
1389 }
1390
1391 return true;
1392}
1393
1394// This macro makes available a variable D, the passed-in decl.
1395#define DEF_TRAVERSE_DECL(DECL, CODE) \
1396 template <typename Derived> \
1397 bool RecursiveASTVisitor<Derived>::Traverse##DECL(DECL *D) { \
1398 bool ShouldVisitChildren = true; \
1399 bool ReturnValue = true; \
1400 if (!getDerived().shouldTraversePostOrder()) \
1401 TRY_TO(WalkUpFrom##DECL(D)); \
1402 { CODE; } \
1403 if (ReturnValue && ShouldVisitChildren) \
1404 TRY_TO(TraverseDeclContextHelper(dyn_cast<DeclContext>(D))); \
1405 if (ReturnValue && getDerived().shouldTraversePostOrder()) \
1406 TRY_TO(WalkUpFrom##DECL(D)); \
1407 return ReturnValue; \
1408 }
1409
1410DEF_TRAVERSE_DECL(AccessSpecDecl, {})
1411
1412DEF_TRAVERSE_DECL(BlockDecl, {
1413 if (TypeSourceInfo *TInfo = D->getSignatureAsWritten())
1414 TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
1415 TRY_TO(TraverseStmt(D->getBody()));
1416 for (const auto &I : D->captures()) {
1417 if (I.hasCopyExpr()) {
1418 TRY_TO(TraverseStmt(I.getCopyExpr()));
1419 }
1420 }
1421 ShouldVisitChildren = false;
1422})
1423
1424DEF_TRAVERSE_DECL(CapturedDecl, {
1425 TRY_TO(TraverseStmt(D->getBody()));
1426 ShouldVisitChildren = false;
1427})
1428
1429DEF_TRAVERSE_DECL(EmptyDecl, {})
1430
1431DEF_TRAVERSE_DECL(FileScopeAsmDecl,
1432 { TRY_TO(TraverseStmt(D->getAsmString())); })
1433
1434DEF_TRAVERSE_DECL(ImportDecl, {})
1435
1436DEF_TRAVERSE_DECL(FriendDecl, {
1437 // Friend is either decl or a type.
1438 if (D->getFriendType())
1439 TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
1440 else
1441 TRY_TO(TraverseDecl(D->getFriendDecl()));
1442})
1443
1444DEF_TRAVERSE_DECL(FriendTemplateDecl, {
1445 if (D->getFriendType())
1446 TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
1447 else
1448 TRY_TO(TraverseDecl(D->getFriendDecl()));
1449 for (unsigned I = 0, E = D->getNumTemplateParameters(); I < E; ++I) {
1450 TemplateParameterList *TPL = D->getTemplateParameterList(I);
1451 for (TemplateParameterList::iterator ITPL = TPL->begin(), ETPL = TPL->end();
1452 ITPL != ETPL; ++ITPL) {
1453 TRY_TO(TraverseDecl(*ITPL));
1454 }
1455 }
1456})
1457
1458DEF_TRAVERSE_DECL(ClassScopeFunctionSpecializationDecl, {
1459 TRY_TO(TraverseDecl(D->getSpecialization()));
1460
1461 if (D->hasExplicitTemplateArgs()) {
1462 const TemplateArgumentListInfo &args = D->templateArgs();
1463 TRY_TO(TraverseTemplateArgumentLocsHelper(args.getArgumentArray(),
1464 args.size()));
1465 }
1466})
1467
1468DEF_TRAVERSE_DECL(LinkageSpecDecl, {})
1469
1470DEF_TRAVERSE_DECL(ExportDecl, {})
1471
1472DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {// FIXME: implement this
1473 })
1474
1475DEF_TRAVERSE_DECL(StaticAssertDecl, {
1476 TRY_TO(TraverseStmt(D->getAssertExpr()));
1477 TRY_TO(TraverseStmt(D->getMessage()));
1478})
1479
1480DEF_TRAVERSE_DECL(
1481 TranslationUnitDecl,
1482 {// Code in an unnamed namespace shows up automatically in
1483 // decls_begin()/decls_end(). Thus we don't need to recurse on
1484 // D->getAnonymousNamespace().
1485 })
1486
1487DEF_TRAVERSE_DECL(PragmaCommentDecl, {})
1488
1489DEF_TRAVERSE_DECL(PragmaDetectMismatchDecl, {})
1490
1491DEF_TRAVERSE_DECL(ExternCContextDecl, {})
1492
1493DEF_TRAVERSE_DECL(NamespaceAliasDecl, {
1494 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1495
1496 // We shouldn't traverse an aliased namespace, since it will be
1497 // defined (and, therefore, traversed) somewhere else.
1498 ShouldVisitChildren = false;
1499})
1500
1501DEF_TRAVERSE_DECL(LabelDecl, {// There is no code in a LabelDecl.
1502 })
1503
1504DEF_TRAVERSE_DECL(
1505 NamespaceDecl,
1506 {// Code in an unnamed namespace shows up automatically in
1507 // decls_begin()/decls_end(). Thus we don't need to recurse on
1508 // D->getAnonymousNamespace().
1509 })
1510
1511DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, {// FIXME: implement
1512 })
1513
1514DEF_TRAVERSE_DECL(ObjCCategoryDecl, {// FIXME: implement
1515 if (ObjCTypeParamList *typeParamList = D->getTypeParamList()) {
1516 for (auto typeParam : *typeParamList) {
1517 TRY_TO(TraverseObjCTypeParamDecl(typeParam));
1518 }
1519 }
1520})
1521
1522DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, {// FIXME: implement
1523 })
1524
1525DEF_TRAVERSE_DECL(ObjCImplementationDecl, {// FIXME: implement
1526 })
1527
1528DEF_TRAVERSE_DECL(ObjCInterfaceDecl, {// FIXME: implement
1529 if (ObjCTypeParamList *typeParamList = D->getTypeParamListAsWritten()) {
1530 for (auto typeParam : *typeParamList) {
1531 TRY_TO(TraverseObjCTypeParamDecl(typeParam));
1532 }
1533 }
1534
1535 if (TypeSourceInfo *superTInfo = D->getSuperClassTInfo()) {
1536 TRY_TO(TraverseTypeLoc(superTInfo->getTypeLoc()));
1537 }
1538})
1539
1540DEF_TRAVERSE_DECL(ObjCProtocolDecl, {// FIXME: implement
1541 })
1542
1543DEF_TRAVERSE_DECL(ObjCMethodDecl, {
1544 if (D->getReturnTypeSourceInfo()) {
1545 TRY_TO(TraverseTypeLoc(D->getReturnTypeSourceInfo()->getTypeLoc()));
1546 }
1547 for (ParmVarDecl *Parameter : D->parameters()) {
1548 TRY_TO(TraverseDecl(Parameter));
1549 }
1550 if (D->isThisDeclarationADefinition()) {
1551 TRY_TO(TraverseStmt(D->getBody()));
1552 }
1553 ShouldVisitChildren = false;
1554})
1555
1556DEF_TRAVERSE_DECL(ObjCTypeParamDecl, {
1557 if (D->hasExplicitBound()) {
1558 TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1559 // We shouldn't traverse D->getTypeForDecl(); it's a result of
1560 // declaring the type alias, not something that was written in the
1561 // source.
1562 }
1563})
1564
1565DEF_TRAVERSE_DECL(ObjCPropertyDecl, {
1566 if (D->getTypeSourceInfo())
1567 TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1568 else
1569 TRY_TO(TraverseType(D->getType()));
1570 ShouldVisitChildren = false;
1571})
1572
1573DEF_TRAVERSE_DECL(UsingDecl, {
1574 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1575 TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1576})
1577
1578DEF_TRAVERSE_DECL(UsingPackDecl, {})
1579
1580DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
1581 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1582})
1583
1584DEF_TRAVERSE_DECL(UsingShadowDecl, {})
1585
1586DEF_TRAVERSE_DECL(ConstructorUsingShadowDecl, {})
1587
1588DEF_TRAVERSE_DECL(OMPThreadPrivateDecl, {
1589 for (auto *I : D->varlists()) {
1590 TRY_TO(TraverseStmt(I));
1591 }
1592 })
1593
1594DEF_TRAVERSE_DECL(OMPRequiresDecl, {
1595 for (auto *C : D->clauselists()) {
1596 TRY_TO(TraverseOMPClause(C));
1597 }
1598})
1599
1600DEF_TRAVERSE_DECL(OMPDeclareReductionDecl, {
1601 TRY_TO(TraverseStmt(D->getCombiner()));
1602 if (auto *Initializer = D->getInitializer())
1603 TRY_TO(TraverseStmt(Initializer));
1604 TRY_TO(TraverseType(D->getType()));
1605 return true;
1606})
1607
1608DEF_TRAVERSE_DECL(OMPDeclareMapperDecl, {
1609 for (auto *C : D->clauselists())
1610 TRY_TO(TraverseOMPClause(C));
1611 TRY_TO(TraverseType(D->getType()));
1612 return true;
1613})
1614
1615DEF_TRAVERSE_DECL(OMPCapturedExprDecl, { TRY_TO(TraverseVarHelper(D)); })
1616
1617// A helper method for TemplateDecl's children.
1618template <typename Derived>
1619bool RecursiveASTVisitor<Derived>::TraverseTemplateParameterListHelper(
1620 TemplateParameterList *TPL) {
1621 if (TPL) {
1622 for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();
1623 I != E; ++I) {
1624 TRY_TO(TraverseDecl(*I));
1625 }
1626 }
1627 return true;
1628}
1629
1630template <typename Derived>
1631template <typename T>
1632bool RecursiveASTVisitor<Derived>::TraverseDeclTemplateParameterLists(T *D) {
1633 for (unsigned i = 0; i < D->getNumTemplateParameterLists(); i++) {
1634 TemplateParameterList *TPL = D->getTemplateParameterList(i);
1635 TraverseTemplateParameterListHelper(TPL);
1636 }
1637 return true;
1638}
1639
1640template <typename Derived>
1641bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1642 ClassTemplateDecl *D) {
1643 for (auto *SD : D->specializations()) {
1644 for (auto *RD : SD->redecls()) {
1645 // We don't want to visit injected-class-names in this traversal.
1646 if (cast<CXXRecordDecl>(RD)->isInjectedClassName())
1647 continue;
1648
1649 switch (
1650 cast<ClassTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
1651 // Visit the implicit instantiations with the requested pattern.
1652 case TSK_Undeclared:
1653 case TSK_ImplicitInstantiation:
1654 TRY_TO(TraverseDecl(RD));
1655 break;
1656
1657 // We don't need to do anything on an explicit instantiation
1658 // or explicit specialization because there will be an explicit
1659 // node for it elsewhere.
1660 case TSK_ExplicitInstantiationDeclaration:
1661 case TSK_ExplicitInstantiationDefinition:
1662 case TSK_ExplicitSpecialization:
1663 break;
1664 }
1665 }
1666 }
1667
1668 return true;
1669}
1670
1671template <typename Derived>
1672bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1673 VarTemplateDecl *D) {
1674 for (auto *SD : D->specializations()) {
1675 for (auto *RD : SD->redecls()) {
1676 switch (
1677 cast<VarTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
1678 case TSK_Undeclared:
1679 case TSK_ImplicitInstantiation:
1680 TRY_TO(TraverseDecl(RD));
1681 break;
1682
1683 case TSK_ExplicitInstantiationDeclaration:
1684 case TSK_ExplicitInstantiationDefinition:
1685 case TSK_ExplicitSpecialization:
1686 break;
1687 }
1688 }
1689 }
1690
1691 return true;
1692}
1693
1694// A helper method for traversing the instantiations of a
1695// function while skipping its specializations.
1696template <typename Derived>
1697bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1698 FunctionTemplateDecl *D) {
1699 for (auto *FD : D->specializations()) {
1700 for (auto *RD : FD->redecls()) {
1701 switch (RD->getTemplateSpecializationKind()) {
1702 case TSK_Undeclared:
1703 case TSK_ImplicitInstantiation:
1704 // We don't know what kind of FunctionDecl this is.
1705 TRY_TO(TraverseDecl(RD));
1706 break;
1707
1708 // FIXME: For now traverse explicit instantiations here. Change that
1709 // once they are represented as dedicated nodes in the AST.
1710 case TSK_ExplicitInstantiationDeclaration:
1711 case TSK_ExplicitInstantiationDefinition:
1712 TRY_TO(TraverseDecl(RD));
1713 break;
1714
1715 case TSK_ExplicitSpecialization:
1716 break;
1717 }
1718 }
1719 }
1720
1721 return true;
1722}
1723
1724// This macro unifies the traversal of class, variable and function
1725// template declarations.
1726#define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND) \
1727 DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, { \
1728 TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \
1729 TRY_TO(TraverseDecl(D->getTemplatedDecl())); \
1730 \
1731 /* By default, we do not traverse the instantiations of \
1732 class templates since they do not appear in the user code. The \
1733 following code optionally traverses them. \
1734 \
1735 We only traverse the class instantiations when we see the canonical \
1736 declaration of the template, to ensure we only visit them once. */ \
1737 if (getDerived().shouldVisitTemplateInstantiations() && \
1738 D == D->getCanonicalDecl()) \
1739 TRY_TO(TraverseTemplateInstantiations(D)); \
1740 \
1741 /* Note that getInstantiatedFromMemberTemplate() is just a link \
1742 from a template instantiation back to the template from which \
1743 it was instantiated, and thus should not be traversed. */ \
1744 })
1745
1746DEF_TRAVERSE_TMPL_DECL(Class)
1747DEF_TRAVERSE_TMPL_DECL(Var)
1748DEF_TRAVERSE_TMPL_DECL(Function)
1749
1750DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, {
1751 // D is the "T" in something like
1752 // template <template <typename> class T> class container { };
1753 TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1754 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
1755 TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
1756 }
1757 TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1758})
1759
1760DEF_TRAVERSE_DECL(BuiltinTemplateDecl, {
1761 TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1762})
1763
1764DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
1765 // D is the "T" in something like "template<typename T> class vector;"
1766 if (D->getTypeForDecl())
1767 TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1768 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
1769 TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
1770})
1771
1772DEF_TRAVERSE_DECL(TypedefDecl, {
1773 TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1774 // We shouldn't traverse D->getTypeForDecl(); it's a result of
1775 // declaring the typedef, not something that was written in the
1776 // source.
1777})
1778
1779DEF_TRAVERSE_DECL(TypeAliasDecl, {
1780 TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1781 // We shouldn't traverse D->getTypeForDecl(); it's a result of
1782 // declaring the type alias, not something that was written in the
1783 // source.
1784})
1785
1786DEF_TRAVERSE_DECL(TypeAliasTemplateDecl, {
1787 TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1788 TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1789})
1790
1791DEF_TRAVERSE_DECL(UnresolvedUsingTypenameDecl, {
1792 // A dependent using declaration which was marked with 'typename'.
1793 // template<class T> class A : public B<T> { using typename B<T>::foo; };
1794 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1795 // We shouldn't traverse D->getTypeForDecl(); it's a result of
1796 // declaring the type, not something that was written in the
1797 // source.
1798})
1799
1800DEF_TRAVERSE_DECL(EnumDecl, {
1801 TRY_TO(TraverseDeclTemplateParameterLists(D));
1802
1803 if (D->getTypeForDecl())
1804 TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1805
1806 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1807 // The enumerators are already traversed by
1808 // decls_begin()/decls_end().
1809})
1810
1811// Helper methods for RecordDecl and its children.
1812template <typename Derived>
1813bool RecursiveASTVisitor<Derived>::TraverseRecordHelper(RecordDecl *D) {
1814 // We shouldn't traverse D->getTypeForDecl(); it's a result of
1815 // declaring the type, not something that was written in the source.
1816
1817 TRY_TO(TraverseDeclTemplateParameterLists(D));
1818 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1819 return true;
1820}
1821
1822template <typename Derived>
1823bool RecursiveASTVisitor<Derived>::TraverseCXXBaseSpecifier(
1824 const CXXBaseSpecifier &Base) {
1825 TRY_TO(TraverseTypeLoc(Base.getTypeSourceInfo()->getTypeLoc()));
1826 return true;
1827}
1828
1829template <typename Derived>
1830bool RecursiveASTVisitor<Derived>::TraverseCXXRecordHelper(CXXRecordDecl *D) {
1831 if (!TraverseRecordHelper(D))
1832 return false;
1833 if (D->isCompleteDefinition()) {
1834 for (const auto &I : D->bases()) {
1835 TRY_TO(TraverseCXXBaseSpecifier(I));
1836 }
1837 // We don't traverse the friends or the conversions, as they are
1838 // already in decls_begin()/decls_end().
1839 }
1840 return true;
1841}
1842
1843DEF_TRAVERSE_DECL(RecordDecl, { TRY_TO(TraverseRecordHelper(D)); })
1844
1845DEF_TRAVERSE_DECL(CXXRecordDecl, { TRY_TO(TraverseCXXRecordHelper(D)); })
1846
1847#define DEF_TRAVERSE_TMPL_SPEC_DECL(TMPLDECLKIND) \
1848 DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateSpecializationDecl, { \
1849 /* For implicit instantiations ("set<int> x;"), we don't want to \
1850 recurse at all, since the instatiated template isn't written in \
1851 the source code anywhere. (Note the instatiated *type* -- \
1852 set<int> -- is written, and will still get a callback of \
1853 TemplateSpecializationType). For explicit instantiations \
1854 ("template set<int>;"), we do need a callback, since this \
1855 is the only callback that's made for this instantiation. \
1856 We use getTypeAsWritten() to distinguish. */ \
1857 if (TypeSourceInfo *TSI = D->getTypeAsWritten()) \
1858 TRY_TO(TraverseTypeLoc(TSI->getTypeLoc())); \
1859 \
1860 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc())); \
1861 if (!getDerived().shouldVisitTemplateInstantiations() && \
1862 D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) \
1863 /* Returning from here skips traversing the \
1864 declaration context of the *TemplateSpecializationDecl \
1865 (embedded in the DEF_TRAVERSE_DECL() macro) \
1866 which contains the instantiated members of the template. */ \
1867 return true; \
1868 })
1869
1870DEF_TRAVERSE_TMPL_SPEC_DECL(Class)
1871DEF_TRAVERSE_TMPL_SPEC_DECL(Var)
1872
1873template <typename Derived>
1874bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLocsHelper(
1875 const TemplateArgumentLoc *TAL, unsigned Count) {
1876 for (unsigned I = 0; I < Count; ++I) {
1877 TRY_TO(TraverseTemplateArgumentLoc(TAL[I]));
1878 }
1879 return true;
1880}
1881
1882#define DEF_TRAVERSE_TMPL_PART_SPEC_DECL(TMPLDECLKIND, DECLKIND) \
1883 DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplatePartialSpecializationDecl, { \
1884 /* The partial specialization. */ \
1885 if (TemplateParameterList *TPL = D->getTemplateParameters()) { \
1886 for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end(); \
1887 I != E; ++I) { \
1888 TRY_TO(TraverseDecl(*I)); \
1889 } \
1890 } \
1891 /* The args that remains unspecialized. */ \
1892 TRY_TO(TraverseTemplateArgumentLocsHelper( \
1893 D->getTemplateArgsAsWritten()->getTemplateArgs(), \
1894 D->getTemplateArgsAsWritten()->NumTemplateArgs)); \
1895 \
1896 /* Don't need the *TemplatePartialSpecializationHelper, even \
1897 though that's our parent class -- we already visit all the \
1898 template args here. */ \
1899 TRY_TO(Traverse##DECLKIND##Helper(D)); \
1900 \
1901 /* Instantiations will have been visited with the primary template. */ \
1902 })
1903
1904DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Class, CXXRecord)
1905DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Var, Var)
1906
1907DEF_TRAVERSE_DECL(EnumConstantDecl, { TRY_TO(TraverseStmt(D->getInitExpr())); })
1908
1909DEF_TRAVERSE_DECL(UnresolvedUsingValueDecl, {
1910 // Like UnresolvedUsingTypenameDecl, but without the 'typename':
1911 // template <class T> Class A : public Base<T> { using Base<T>::foo; };
1912 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1913 TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1914})
1915
1916DEF_TRAVERSE_DECL(IndirectFieldDecl, {})
1917
1918template <typename Derived>
1919bool RecursiveASTVisitor<Derived>::TraverseDeclaratorHelper(DeclaratorDecl *D) {
1920 TRY_TO(TraverseDeclTemplateParameterLists(D));
1921 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1922 if (D->getTypeSourceInfo())
1923 TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1924 else
1925 TRY_TO(TraverseType(D->getType()));
1926 return true;
1927}
1928
1929DEF_TRAVERSE_DECL(DecompositionDecl, {
1930 TRY_TO(TraverseVarHelper(D));
1931 for (auto *Binding : D->bindings()) {
1932 TRY_TO(TraverseDecl(Binding));
1933 }
1934})
1935
1936DEF_TRAVERSE_DECL(BindingDecl, {
1937 if (getDerived().shouldVisitImplicitCode())
1938 TRY_TO(TraverseStmt(D->getBinding()));
1939})
1940
1941DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })
1942
1943DEF_TRAVERSE_DECL(FieldDecl, {
1944 TRY_TO(TraverseDeclaratorHelper(D));
1945 if (D->isBitField())
1946 TRY_TO(TraverseStmt(D->getBitWidth()));
1947 else if (D->hasInClassInitializer())
1948 TRY_TO(TraverseStmt(D->getInClassInitializer()));
1949})
1950
1951DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
1952 TRY_TO(TraverseDeclaratorHelper(D));
1953 if (D->isBitField())
1954 TRY_TO(TraverseStmt(D->getBitWidth()));
1955 // FIXME: implement the rest.
1956})
1957
1958DEF_TRAVERSE_DECL(ObjCIvarDecl, {
1959 TRY_TO(TraverseDeclaratorHelper(D));
1960 if (D->isBitField())
1961 TRY_TO(TraverseStmt(D->getBitWidth()));
1962 // FIXME: implement the rest.
1963})
1964
1965template <typename Derived>
1966bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D) {
1967 TRY_TO(TraverseDeclTemplateParameterLists(D));
1968 TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1969 TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1970
1971 // If we're an explicit template specialization, iterate over the
1972 // template args that were explicitly specified. If we were doing
1973 // this in typing order, we'd do it between the return type and
1974 // the function args, but both are handled by the FunctionTypeLoc
1975 // above, so we have to choose one side. I've decided to do before.
1976 if (const FunctionTemplateSpecializationInfo *FTSI =
1977 D->getTemplateSpecializationInfo()) {
1978 if (FTSI->getTemplateSpecializationKind() != TSK_Undeclared &&
1979 FTSI->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
1980 // A specialization might not have explicit template arguments if it has
1981 // a templated return type and concrete arguments.
1982 if (const ASTTemplateArgumentListInfo *TALI =
1983 FTSI->TemplateArgumentsAsWritten) {
1984 TRY_TO(TraverseTemplateArgumentLocsHelper(TALI->getTemplateArgs(),
1985 TALI->NumTemplateArgs));
1986 }
1987 }
1988 }
1989
1990 // Visit the function type itself, which can be either
1991 // FunctionNoProtoType or FunctionProtoType, or a typedef. This
1992 // also covers the return type and the function parameters,
1993 // including exception specifications.
1994 if (TypeSourceInfo *TSI = D->getTypeSourceInfo()) {
1995 TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
1996 } else if (getDerived().shouldVisitImplicitCode()) {
1997 // Visit parameter variable declarations of the implicit function
1998 // if the traverser is visiting implicit code. Parameter variable
1999 // declarations do not have valid TypeSourceInfo, so to visit them
2000 // we need to traverse the declarations explicitly.
2001 for (ParmVarDecl *Parameter : D->parameters()) {
2002 TRY_TO(TraverseDecl(Parameter));
2003 }
2004 }
2005
2006 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
2007 // Constructor initializers.
2008 for (auto *I : Ctor->inits()) {
2009 TRY_TO(TraverseConstructorInitializer(I));
2010 }
2011 }
2012
2013 if (D->isThisDeclarationADefinition()) {
2014 TRY_TO(TraverseStmt(D->getBody())); // Function body.
2015 }
2016 return true;
2017}
2018
2019DEF_TRAVERSE_DECL(FunctionDecl, {
2020 // We skip decls_begin/decls_end, which are already covered by
2021 // TraverseFunctionHelper().
2022 ShouldVisitChildren = false;
2023 ReturnValue = TraverseFunctionHelper(D);
2024})
2025
2026DEF_TRAVERSE_DECL(CXXDeductionGuideDecl, {
2027 // We skip decls_begin/decls_end, which are already covered by
2028 // TraverseFunctionHelper().
2029 ShouldVisitChildren = false;
2030 ReturnValue = TraverseFunctionHelper(D);
2031})
2032
2033DEF_TRAVERSE_DECL(CXXMethodDecl, {
2034 // We skip decls_begin/decls_end, which are already covered by
2035 // TraverseFunctionHelper().
2036 ShouldVisitChildren = false;
2037 ReturnValue = TraverseFunctionHelper(D);
2038})
2039
2040DEF_TRAVERSE_DECL(CXXConstructorDecl, {
2041 // We skip decls_begin/decls_end, which are already covered by
2042 // TraverseFunctionHelper().
2043 ShouldVisitChildren = false;
2044 ReturnValue = TraverseFunctionHelper(D);
2045})
2046
2047// CXXConversionDecl is the declaration of a type conversion operator.
2048// It's not a cast expression.
2049DEF_TRAVERSE_DECL(CXXConversionDecl, {
2050 // We skip decls_begin/decls_end, which are already covered by
2051 // TraverseFunctionHelper().
2052 ShouldVisitChildren = false;
2053 ReturnValue = TraverseFunctionHelper(D);
2054})
2055
2056DEF_TRAVERSE_DECL(CXXDestructorDecl, {
2057 // We skip decls_begin/decls_end, which are already covered by
2058 // TraverseFunctionHelper().
2059 ShouldVisitChildren = false;
2060 ReturnValue = TraverseFunctionHelper(D);
2061})
2062
2063template <typename Derived>
2064bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
2065 TRY_TO(TraverseDeclaratorHelper(D));
2066 // Default params are taken care of when we traverse the ParmVarDecl.
2067 if (!isa<ParmVarDecl>(D) &&
2068 (!D->isCXXForRangeDecl() || getDerived().shouldVisitImplicitCode()))
2069 TRY_TO(TraverseStmt(D->getInit()));
2070 return true;
2071}
2072
2073DEF_TRAVERSE_DECL(VarDecl, { TRY_TO(TraverseVarHelper(D)); })
2074
2075DEF_TRAVERSE_DECL(ImplicitParamDecl, { TRY_TO(TraverseVarHelper(D)); })
2076
2077DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, {
2078 // A non-type template parameter, e.g. "S" in template<int S> class Foo ...
2079 TRY_TO(TraverseDeclaratorHelper(D));
2080 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
2081 TRY_TO(TraverseStmt(D->getDefaultArgument()));
2082})
2083
2084DEF_TRAVERSE_DECL(ParmVarDecl, {
2085 TRY_TO(TraverseVarHelper(D));
2086
2087 if (D->hasDefaultArg() && D->hasUninstantiatedDefaultArg() &&
2088 !D->hasUnparsedDefaultArg())
2089 TRY_TO(TraverseStmt(D->getUninstantiatedDefaultArg()));
2090
2091 if (D->hasDefaultArg() && !D->hasUninstantiatedDefaultArg() &&
2092 !D->hasUnparsedDefaultArg())
2093 TRY_TO(TraverseStmt(D->getDefaultArg()));
2094})
2095
2096#undef DEF_TRAVERSE_DECL
2097
2098// ----------------- Stmt traversal -----------------
2099//
2100// For stmts, we automate (in the DEF_TRAVERSE_STMT macro) iterating
2101// over the children defined in children() (every stmt defines these,
2102// though sometimes the range is empty). Each individual Traverse*
2103// method only needs to worry about children other than those. To see
2104// what children() does for a given class, see, e.g.,
2105// http://clang.llvm.org/doxygen/Stmt_8cpp_source.html
2106
2107// This macro makes available a variable S, the passed-in stmt.
2108#define DEF_TRAVERSE_STMT(STMT, CODE) \
2109 template <typename Derived> \
2110 bool RecursiveASTVisitor<Derived>::Traverse##STMT( \
2111 STMT *S, DataRecursionQueue *Queue</