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