RecursiveASTVisitor.h revision 6bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89
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/DeclCXX.h"
20#include "clang/AST/DeclFriend.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclOpenMP.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
31#include "clang/AST/StmtOpenMP.h"
32#include "clang/AST/TemplateBase.h"
33#include "clang/AST/TemplateName.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
36
37// The following three macros are used for meta programming.  The code
38// using them is responsible for defining macro OPERATOR().
39
40// All unary operators.
41#define UNARYOP_LIST()                                                         \
42  OPERATOR(PostInc) OPERATOR(PostDec) OPERATOR(PreInc) OPERATOR(PreDec)        \
43      OPERATOR(AddrOf) OPERATOR(Deref) OPERATOR(Plus) OPERATOR(Minus)          \
44      OPERATOR(Not) OPERATOR(LNot) OPERATOR(Real) OPERATOR(Imag)               \
45      OPERATOR(Extension)
46
47// All binary operators (excluding compound assign operators).
48#define BINOP_LIST()                                                           \
49  OPERATOR(PtrMemD) OPERATOR(PtrMemI) OPERATOR(Mul) OPERATOR(Div)              \
50      OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) OPERATOR(Shl) OPERATOR(Shr)    \
51      OPERATOR(LT) OPERATOR(GT) OPERATOR(LE) OPERATOR(GE) OPERATOR(EQ)         \
52      OPERATOR(NE) OPERATOR(And) OPERATOR(Xor) OPERATOR(Or) OPERATOR(LAnd)     \
53      OPERATOR(LOr) OPERATOR(Assign) OPERATOR(Comma)
54
55// All compound assign operators.
56#define CAO_LIST()                                                             \
57  OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub)        \
58      OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or) OPERATOR(Xor)
59
60namespace clang {
61
62// A helper macro to implement short-circuiting when recursing.  It
63// invokes CALL_EXPR, which must be a method call, on the derived
64// object (s.t. a user of RecursiveASTVisitor can override the method
65// in CALL_EXPR).
66#define TRY_TO(CALL_EXPR)                                                      \
67  do {                                                                         \
68    if (!getDerived().CALL_EXPR)                                               \
69      return false;                                                            \
70  } while (0)
71
72/// \brief A class that does preorder depth-first traversal on the
73/// entire Clang AST and visits each node.
74///
75/// This class performs three distinct tasks:
76///   1. traverse the AST (i.e. go to each node);
77///   2. at a given node, walk up the class hierarchy, starting from
78///      the node's dynamic type, until the top-most class (e.g. Stmt,
79///      Decl, or Type) is reached.
80///   3. given a (node, class) combination, where 'class' is some base
81///      class of the dynamic type of 'node', call a user-overridable
82///      function to actually visit the node.
83///
84/// These tasks are done by three groups of methods, respectively:
85///   1. TraverseDecl(Decl *x) does task #1.  It is the entry point
86///      for traversing an AST rooted at x.  This method simply
87///      dispatches (i.e. forwards) to TraverseFoo(Foo *x) where Foo
88///      is the dynamic type of *x, which calls WalkUpFromFoo(x) and
89///      then recursively visits the child nodes of x.
90///      TraverseStmt(Stmt *x) and TraverseType(QualType x) work
91///      similarly.
92///   2. WalkUpFromFoo(Foo *x) does task #2.  It does not try to visit
93///      any child node of x.  Instead, it first calls WalkUpFromBar(x)
94///      where Bar is the direct parent class of Foo (unless Foo has
95///      no parent), and then calls VisitFoo(x) (see the next list item).
96///   3. VisitFoo(Foo *x) does task #3.
97///
98/// These three method groups are tiered (Traverse* > WalkUpFrom* >
99/// Visit*).  A method (e.g. Traverse*) may call methods from the same
100/// tier (e.g. other Traverse*) or one tier lower (e.g. WalkUpFrom*).
101/// It may not call methods from a higher tier.
102///
103/// Note that since WalkUpFromFoo() calls WalkUpFromBar() (where Bar
104/// is Foo's super class) before calling VisitFoo(), the result is
105/// that the Visit*() methods for a given node are called in the
106/// top-down order (e.g. for a node of type NamespaceDecl, the order will
107/// be VisitDecl(), VisitNamedDecl(), and then VisitNamespaceDecl()).
108///
109/// This scheme guarantees that all Visit*() calls for the same AST
110/// node are grouped together.  In other words, Visit*() methods for
111/// different nodes are never interleaved.
112///
113/// Clients of this visitor should subclass the visitor (providing
114/// themselves as the template argument, using the curiously recurring
115/// template pattern) and override any of the Traverse*, WalkUpFrom*,
116/// and Visit* methods for declarations, types, statements,
117/// expressions, or other AST nodes where the visitor should customize
118/// behavior.  Most users only need to override Visit*.  Advanced
119/// users may override Traverse* and WalkUpFrom* to implement custom
120/// traversal strategies.  Returning false from one of these overridden
121/// functions will abort the entire traversal.
122///
123/// By default, this visitor tries to visit every part of the explicit
124/// source code exactly once.  The default policy towards templates
125/// is to descend into the 'pattern' class or function body, not any
126/// explicit or implicit instantiations.  Explicit specializations
127/// are still visited, and the patterns of partial specializations
128/// are visited separately.  This behavior can be changed by
129/// overriding shouldVisitTemplateInstantiations() in the derived class
130/// to return true, in which case all known implicit and explicit
131/// instantiations will be visited at the same time as the pattern
132/// from which they were produced.
133template <typename Derived> class RecursiveASTVisitor {
134public:
135  /// \brief Return a reference to the derived class.
136  Derived &getDerived() { return *static_cast<Derived *>(this); }
137
138  /// \brief Return whether this visitor should recurse into
139  /// template instantiations.
140  bool shouldVisitTemplateInstantiations() const { return false; }
141
142  /// \brief Return whether this visitor should recurse into the types of
143  /// TypeLocs.
144  bool shouldWalkTypesOfTypeLocs() const { return true; }
145
146  /// \brief Return whether this visitor should recurse into implicit
147  /// code, e.g., implicit constructors and destructors.
148  bool shouldVisitImplicitCode() const { return false; }
149
150  /// \brief Return whether \param S should be traversed using data recursion
151  /// to avoid a stack overflow with extreme cases.
152  bool shouldUseDataRecursionFor(Stmt *S) const {
153    return isa<BinaryOperator>(S) || isa<UnaryOperator>(S) ||
154           isa<CaseStmt>(S) || isa<CXXOperatorCallExpr>(S);
155  }
156
157  /// \brief Recursively visit a statement or expression, by
158  /// dispatching to Traverse*() based on the argument's dynamic type.
159  ///
160  /// \returns false if the visitation was terminated early, true
161  /// otherwise (including when the argument is NULL).
162  bool TraverseStmt(Stmt *S);
163
164  /// \brief Recursively visit a type, by dispatching to
165  /// Traverse*Type() based on the argument's getTypeClass() property.
166  ///
167  /// \returns false if the visitation was terminated early, true
168  /// otherwise (including when the argument is a Null type).
169  bool TraverseType(QualType T);
170
171  /// \brief Recursively visit a type with location, by dispatching to
172  /// Traverse*TypeLoc() based on the argument type's getTypeClass() property.
173  ///
174  /// \returns false if the visitation was terminated early, true
175  /// otherwise (including when the argument is a Null type location).
176  bool TraverseTypeLoc(TypeLoc TL);
177
178  /// \brief Recursively visit an attribute, by dispatching to
179  /// Traverse*Attr() based on the argument's dynamic type.
180  ///
181  /// \returns false if the visitation was terminated early, true
182  /// otherwise (including when the argument is a Null type location).
183  bool TraverseAttr(Attr *At);
184
185  /// \brief Recursively visit a declaration, by dispatching to
186  /// Traverse*Decl() based on the argument's dynamic type.
187  ///
188  /// \returns false if the visitation was terminated early, true
189  /// otherwise (including when the argument is NULL).
190  bool TraverseDecl(Decl *D);
191
192  /// \brief Recursively visit a C++ nested-name-specifier.
193  ///
194  /// \returns false if the visitation was terminated early, true otherwise.
195  bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
196
197  /// \brief Recursively visit a C++ nested-name-specifier with location
198  /// information.
199  ///
200  /// \returns false if the visitation was terminated early, true otherwise.
201  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
202
203  /// \brief Recursively visit a name with its location information.
204  ///
205  /// \returns false if the visitation was terminated early, true otherwise.
206  bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo);
207
208  /// \brief Recursively visit a template name and dispatch to the
209  /// appropriate method.
210  ///
211  /// \returns false if the visitation was terminated early, true otherwise.
212  bool TraverseTemplateName(TemplateName Template);
213
214  /// \brief Recursively visit a template argument and dispatch to the
215  /// appropriate method for the argument type.
216  ///
217  /// \returns false if the visitation was terminated early, true otherwise.
218  // FIXME: migrate callers to TemplateArgumentLoc instead.
219  bool TraverseTemplateArgument(const TemplateArgument &Arg);
220
221  /// \brief Recursively visit a template argument location and dispatch to the
222  /// appropriate method for the argument type.
223  ///
224  /// \returns false if the visitation was terminated early, true otherwise.
225  bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc);
226
227  /// \brief Recursively visit a set of template arguments.
228  /// This can be overridden by a subclass, but it's not expected that
229  /// will be needed -- this visitor always dispatches to another.
230  ///
231  /// \returns false if the visitation was terminated early, true otherwise.
232  // FIXME: take a TemplateArgumentLoc* (or TemplateArgumentListInfo) instead.
233  bool TraverseTemplateArguments(const TemplateArgument *Args,
234                                 unsigned NumArgs);
235
236  /// \brief Recursively visit a constructor initializer.  This
237  /// automatically dispatches to another visitor for the initializer
238  /// expression, but not for the name of the initializer, so may
239  /// be overridden for clients that need access to the name.
240  ///
241  /// \returns false if the visitation was terminated early, true otherwise.
242  bool TraverseConstructorInitializer(CXXCtorInitializer *Init);
243
244  /// \brief Recursively visit a lambda capture.
245  ///
246  /// \returns false if the visitation was terminated early, true otherwise.
247  bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C);
248
249  /// \brief Recursively visit the body of a lambda expression.
250  ///
251  /// This provides a hook for visitors that need more context when visiting
252  /// \c LE->getBody().
253  ///
254  /// \returns false if the visitation was terminated early, true otherwise.
255  bool TraverseLambdaBody(LambdaExpr *LE);
256
257  // ---- Methods on Attrs ----
258
259  // \brief Visit an attribute.
260  bool VisitAttr(Attr *A) { return true; }
261
262// Declare Traverse* and empty Visit* for all Attr classes.
263#define ATTR_VISITOR_DECLS_ONLY
264#include "clang/AST/AttrVisitor.inc"
265#undef ATTR_VISITOR_DECLS_ONLY
266
267// ---- Methods on Stmts ----
268
269// Declare Traverse*() for all concrete Stmt classes.
270#define ABSTRACT_STMT(STMT)
271#define STMT(CLASS, PARENT) bool Traverse##CLASS(CLASS *S);
272#include "clang/AST/StmtNodes.inc"
273  // The above header #undefs ABSTRACT_STMT and STMT upon exit.
274
275  // Define WalkUpFrom*() and empty Visit*() for all Stmt classes.
276  bool WalkUpFromStmt(Stmt *S) { return getDerived().VisitStmt(S); }
277  bool VisitStmt(Stmt *S) { return true; }
278#define STMT(CLASS, PARENT)                                                    \
279  bool WalkUpFrom##CLASS(CLASS *S) {                                           \
280    TRY_TO(WalkUpFrom##PARENT(S));                                             \
281    TRY_TO(Visit##CLASS(S));                                                   \
282    return true;                                                               \
283  }                                                                            \
284  bool Visit##CLASS(CLASS *S) { return true; }
285#include "clang/AST/StmtNodes.inc"
286
287// Define Traverse*(), WalkUpFrom*(), and Visit*() for unary
288// operator methods.  Unary operators are not classes in themselves
289// (they're all opcodes in UnaryOperator) but do have visitors.
290#define OPERATOR(NAME)                                                         \
291  bool TraverseUnary##NAME(UnaryOperator *S) {                                 \
292    TRY_TO(WalkUpFromUnary##NAME(S));                                          \
293    TRY_TO(TraverseStmt(S->getSubExpr()));                                     \
294    return true;                                                               \
295  }                                                                            \
296  bool WalkUpFromUnary##NAME(UnaryOperator *S) {                               \
297    TRY_TO(WalkUpFromUnaryOperator(S));                                        \
298    TRY_TO(VisitUnary##NAME(S));                                               \
299    return true;                                                               \
300  }                                                                            \
301  bool VisitUnary##NAME(UnaryOperator *S) { return true; }
302
303  UNARYOP_LIST()
304#undef OPERATOR
305
306// Define Traverse*(), WalkUpFrom*(), and Visit*() for binary
307// operator methods.  Binary operators are not classes in themselves
308// (they're all opcodes in BinaryOperator) but do have visitors.
309#define GENERAL_BINOP_FALLBACK(NAME, BINOP_TYPE)                               \
310  bool TraverseBin##NAME(BINOP_TYPE *S) {                                      \
311    TRY_TO(WalkUpFromBin##NAME(S));                                            \
312    TRY_TO(TraverseStmt(S->getLHS()));                                         \
313    TRY_TO(TraverseStmt(S->getRHS()));                                         \
314    return true;                                                               \
315  }                                                                            \
316  bool WalkUpFromBin##NAME(BINOP_TYPE *S) {                                    \
317    TRY_TO(WalkUpFrom##BINOP_TYPE(S));                                         \
318    TRY_TO(VisitBin##NAME(S));                                                 \
319    return true;                                                               \
320  }                                                                            \
321  bool VisitBin##NAME(BINOP_TYPE *S) { return true; }
322
323#define OPERATOR(NAME) GENERAL_BINOP_FALLBACK(NAME, BinaryOperator)
324  BINOP_LIST()
325#undef OPERATOR
326
327// Define Traverse*(), WalkUpFrom*(), and Visit*() for compound
328// assignment methods.  Compound assignment operators are not
329// classes in themselves (they're all opcodes in
330// CompoundAssignOperator) but do have visitors.
331#define OPERATOR(NAME)                                                         \
332  GENERAL_BINOP_FALLBACK(NAME##Assign, CompoundAssignOperator)
333
334  CAO_LIST()
335#undef OPERATOR
336#undef GENERAL_BINOP_FALLBACK
337
338// ---- Methods on Types ----
339// FIXME: revamp to take TypeLoc's rather than Types.
340
341// Declare Traverse*() for all concrete Type classes.
342#define ABSTRACT_TYPE(CLASS, BASE)
343#define TYPE(CLASS, BASE) bool Traverse##CLASS##Type(CLASS##Type *T);
344#include "clang/AST/TypeNodes.def"
345  // The above header #undefs ABSTRACT_TYPE and TYPE upon exit.
346
347  // Define WalkUpFrom*() and empty Visit*() for all Type classes.
348  bool WalkUpFromType(Type *T) { return getDerived().VisitType(T); }
349  bool VisitType(Type *T) { return true; }
350#define TYPE(CLASS, BASE)                                                      \
351  bool WalkUpFrom##CLASS##Type(CLASS##Type *T) {                               \
352    TRY_TO(WalkUpFrom##BASE(T));                                               \
353    TRY_TO(Visit##CLASS##Type(T));                                             \
354    return true;                                                               \
355  }                                                                            \
356  bool Visit##CLASS##Type(CLASS##Type *T) { return true; }
357#include "clang/AST/TypeNodes.def"
358
359// ---- Methods on TypeLocs ----
360// FIXME: this currently just calls the matching Type methods
361
362// Declare Traverse*() for all concrete TypeLoc classes.
363#define ABSTRACT_TYPELOC(CLASS, BASE)
364#define TYPELOC(CLASS, BASE) bool Traverse##CLASS##TypeLoc(CLASS##TypeLoc TL);
365#include "clang/AST/TypeLocNodes.def"
366  // The above header #undefs ABSTRACT_TYPELOC and TYPELOC upon exit.
367
368  // Define WalkUpFrom*() and empty Visit*() for all TypeLoc classes.
369  bool WalkUpFromTypeLoc(TypeLoc TL) { return getDerived().VisitTypeLoc(TL); }
370  bool VisitTypeLoc(TypeLoc TL) { return true; }
371
372  // QualifiedTypeLoc and UnqualTypeLoc are not declared in
373  // TypeNodes.def and thus need to be handled specially.
374  bool WalkUpFromQualifiedTypeLoc(QualifiedTypeLoc TL) {
375    return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
376  }
377  bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return true; }
378  bool WalkUpFromUnqualTypeLoc(UnqualTypeLoc TL) {
379    return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
380  }
381  bool VisitUnqualTypeLoc(UnqualTypeLoc TL) { return true; }
382
383// Note that BASE includes trailing 'Type' which CLASS doesn't.
384#define TYPE(CLASS, BASE)                                                      \
385  bool WalkUpFrom##CLASS##TypeLoc(CLASS##TypeLoc TL) {                         \
386    TRY_TO(WalkUpFrom##BASE##Loc(TL));                                         \
387    TRY_TO(Visit##CLASS##TypeLoc(TL));                                         \
388    return true;                                                               \
389  }                                                                            \
390  bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { return true; }
391#include "clang/AST/TypeNodes.def"
392
393// ---- Methods on Decls ----
394
395// Declare Traverse*() for all concrete Decl classes.
396#define ABSTRACT_DECL(DECL)
397#define DECL(CLASS, BASE) bool Traverse##CLASS##Decl(CLASS##Decl *D);
398#include "clang/AST/DeclNodes.inc"
399  // The above header #undefs ABSTRACT_DECL and DECL upon exit.
400
401  // Define WalkUpFrom*() and empty Visit*() for all Decl classes.
402  bool WalkUpFromDecl(Decl *D) { return getDerived().VisitDecl(D); }
403  bool VisitDecl(Decl *D) { return true; }
404#define DECL(CLASS, BASE)                                                      \
405  bool WalkUpFrom##CLASS##Decl(CLASS##Decl *D) {                               \
406    TRY_TO(WalkUpFrom##BASE(D));                                               \
407    TRY_TO(Visit##CLASS##Decl(D));                                             \
408    return true;                                                               \
409  }                                                                            \
410  bool Visit##CLASS##Decl(CLASS##Decl *D) { return true; }
411#include "clang/AST/DeclNodes.inc"
412
413private:
414  // These are helper methods used by more than one Traverse* method.
415  bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
416#define DEF_TRAVERSE_TMPL_INST(TMPLDECLKIND)                                   \
417  bool TraverseTemplateInstantiations(TMPLDECLKIND##TemplateDecl *D);
418  DEF_TRAVERSE_TMPL_INST(Class)
419  DEF_TRAVERSE_TMPL_INST(Var)
420  DEF_TRAVERSE_TMPL_INST(Function)
421#undef DEF_TRAVERSE_TMPL_INST
422  bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL,
423                                          unsigned Count);
424  bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL);
425  bool TraverseRecordHelper(RecordDecl *D);
426  bool TraverseCXXRecordHelper(CXXRecordDecl *D);
427  bool TraverseDeclaratorHelper(DeclaratorDecl *D);
428  bool TraverseDeclContextHelper(DeclContext *DC);
429  bool TraverseFunctionHelper(FunctionDecl *D);
430  bool TraverseVarHelper(VarDecl *D);
431  bool TraverseOMPClause(OMPClause *C);
432  bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
433#define OPENMP_CLAUSE(Name, Class) bool Visit##Class(Class *C);
434#include "clang/Basic/OpenMPKinds.def"
435  /// \brief Process clauses with list of variables.
436  template <typename T> void VisitOMPClauseList(T *Node);
437
438  struct EnqueueJob {
439    Stmt *S;
440    Stmt::child_iterator StmtIt;
441
442    EnqueueJob(Stmt *S) : S(S), StmtIt() {}
443  };
444  bool dataTraverse(Stmt *S);
445  bool dataTraverseNode(Stmt *S, bool &EnqueueChildren);
446};
447
448template <typename Derived>
449bool RecursiveASTVisitor<Derived>::dataTraverse(Stmt *S) {
450
451  SmallVector<EnqueueJob, 16> Queue;
452  Queue.push_back(S);
453
454  while (!Queue.empty()) {
455    EnqueueJob &job = Queue.back();
456    Stmt *CurrS = job.S;
457    if (!CurrS) {
458      Queue.pop_back();
459      continue;
460    }
461
462    if (getDerived().shouldUseDataRecursionFor(CurrS)) {
463      if (job.StmtIt == Stmt::child_iterator()) {
464        bool EnqueueChildren = true;
465        if (!dataTraverseNode(CurrS, EnqueueChildren))
466          return false;
467        if (!EnqueueChildren) {
468          Queue.pop_back();
469          continue;
470        }
471        job.StmtIt = CurrS->child_begin();
472      } else {
473        ++job.StmtIt;
474      }
475
476      if (job.StmtIt != CurrS->child_end())
477        Queue.push_back(*job.StmtIt);
478      else
479        Queue.pop_back();
480      continue;
481    }
482
483    Queue.pop_back();
484    TRY_TO(TraverseStmt(CurrS));
485  }
486
487  return true;
488}
489
490template <typename Derived>
491bool RecursiveASTVisitor<Derived>::dataTraverseNode(Stmt *S,
492                                                    bool &EnqueueChildren) {
493
494// Dispatch to the corresponding WalkUpFrom* function only if the derived
495// class didn't override Traverse* (and thus the traversal is trivial).
496#define DISPATCH_WALK(NAME, CLASS, VAR)                                        \
497  {                                                                            \
498    bool (Derived::*DerivedFn)(CLASS *) = &Derived::Traverse##NAME;            \
499    bool (Derived::*BaseFn)(CLASS *) = &RecursiveASTVisitor::Traverse##NAME;   \
500    if (DerivedFn == BaseFn)                                                   \
501      return getDerived().WalkUpFrom##NAME(static_cast<CLASS *>(VAR));         \
502  }                                                                            \
503  EnqueueChildren = false;                                                     \
504  return getDerived().Traverse##NAME(static_cast<CLASS *>(VAR));
505
506  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
507    switch (BinOp->getOpcode()) {
508#define OPERATOR(NAME)                                                         \
509  case BO_##NAME:                                                              \
510    DISPATCH_WALK(Bin##NAME, BinaryOperator, S);
511
512      BINOP_LIST()
513#undef OPERATOR
514
515#define OPERATOR(NAME)                                                         \
516  case BO_##NAME##Assign:                                                      \
517    DISPATCH_WALK(Bin##NAME##Assign, CompoundAssignOperator, S);
518
519      CAO_LIST()
520#undef OPERATOR
521    }
522  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
523    switch (UnOp->getOpcode()) {
524#define OPERATOR(NAME)                                                         \
525  case UO_##NAME:                                                              \
526    DISPATCH_WALK(Unary##NAME, UnaryOperator, S);
527
528      UNARYOP_LIST()
529#undef OPERATOR
530    }
531  }
532
533  // Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
534  switch (S->getStmtClass()) {
535  case Stmt::NoStmtClass:
536    break;
537#define ABSTRACT_STMT(STMT)
538#define STMT(CLASS, PARENT)                                                    \
539  case Stmt::CLASS##Class:                                                     \
540    DISPATCH_WALK(CLASS, CLASS, S);
541#include "clang/AST/StmtNodes.inc"
542  }
543
544#undef DISPATCH_WALK
545
546  return true;
547}
548
549#define DISPATCH(NAME, CLASS, VAR)                                             \
550  return getDerived().Traverse##NAME(static_cast<CLASS *>(VAR))
551
552template <typename Derived>
553bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S) {
554  if (!S)
555    return true;
556
557#define DISPATCH_STMT(NAME, CLASS, VAR) DISPATCH(NAME, CLASS, VAR)
558
559  if (getDerived().shouldUseDataRecursionFor(S))
560    return dataTraverse(S);
561
562  // If we have a binary expr, dispatch to the subcode of the binop.  A smart
563  // optimizer (e.g. LLVM) will fold this comparison into the switch stmt
564  // below.
565  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
566    switch (BinOp->getOpcode()) {
567#define OPERATOR(NAME)                                                         \
568  case BO_##NAME:                                                              \
569    DISPATCH_STMT(Bin##NAME, BinaryOperator, S);
570
571      BINOP_LIST()
572#undef OPERATOR
573#undef BINOP_LIST
574
575#define OPERATOR(NAME)                                                         \
576  case BO_##NAME##Assign:                                                      \
577    DISPATCH_STMT(Bin##NAME##Assign, CompoundAssignOperator, S);
578
579      CAO_LIST()
580#undef OPERATOR
581#undef CAO_LIST
582    }
583  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
584    switch (UnOp->getOpcode()) {
585#define OPERATOR(NAME)                                                         \
586  case UO_##NAME:                                                              \
587    DISPATCH_STMT(Unary##NAME, UnaryOperator, S);
588
589      UNARYOP_LIST()
590#undef OPERATOR
591#undef UNARYOP_LIST
592    }
593  }
594
595  // Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
596  switch (S->getStmtClass()) {
597  case Stmt::NoStmtClass:
598    break;
599#define ABSTRACT_STMT(STMT)
600#define STMT(CLASS, PARENT)                                                    \
601  case Stmt::CLASS##Class:                                                     \
602    DISPATCH_STMT(CLASS, CLASS, S);
603#include "clang/AST/StmtNodes.inc"
604  }
605
606  return true;
607}
608
609#undef DISPATCH_STMT
610
611template <typename Derived>
612bool RecursiveASTVisitor<Derived>::TraverseType(QualType T) {
613  if (T.isNull())
614    return true;
615
616  switch (T->getTypeClass()) {
617#define ABSTRACT_TYPE(CLASS, BASE)
618#define TYPE(CLASS, BASE)                                                      \
619  case Type::CLASS:                                                            \
620    DISPATCH(CLASS##Type, CLASS##Type, const_cast<Type *>(T.getTypePtr()));
621#include "clang/AST/TypeNodes.def"
622  }
623
624  return true;
625}
626
627template <typename Derived>
628bool RecursiveASTVisitor<Derived>::TraverseTypeLoc(TypeLoc TL) {
629  if (TL.isNull())
630    return true;
631
632  switch (TL.getTypeLocClass()) {
633#define ABSTRACT_TYPELOC(CLASS, BASE)
634#define TYPELOC(CLASS, BASE)                                                   \
635  case TypeLoc::CLASS:                                                         \
636    return getDerived().Traverse##CLASS##TypeLoc(TL.castAs<CLASS##TypeLoc>());
637#include "clang/AST/TypeLocNodes.def"
638  }
639
640  return true;
641}
642
643// Define the Traverse*Attr(Attr* A) methods
644#define VISITORCLASS RecursiveASTVisitor
645#include "clang/AST/AttrVisitor.inc"
646#undef VISITORCLASS
647
648template <typename Derived>
649bool RecursiveASTVisitor<Derived>::TraverseDecl(Decl *D) {
650  if (!D)
651    return true;
652
653  // As a syntax visitor, by default we want to ignore declarations for
654  // implicit declarations (ones not typed explicitly by the user).
655  if (!getDerived().shouldVisitImplicitCode() && D->isImplicit())
656    return true;
657
658  switch (D->getKind()) {
659#define ABSTRACT_DECL(DECL)
660#define DECL(CLASS, BASE)                                                      \
661  case Decl::CLASS:                                                            \
662    if (!getDerived().Traverse##CLASS##Decl(static_cast<CLASS##Decl *>(D)))    \
663      return false;                                                            \
664    break;
665#include "clang/AST/DeclNodes.inc"
666  }
667
668  // Visit any attributes attached to this declaration.
669  for (auto *I : D->attrs()) {
670    if (!getDerived().TraverseAttr(I))
671      return false;
672  }
673  return true;
674}
675
676#undef DISPATCH
677
678template <typename Derived>
679bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifier(
680    NestedNameSpecifier *NNS) {
681  if (!NNS)
682    return true;
683
684  if (NNS->getPrefix())
685    TRY_TO(TraverseNestedNameSpecifier(NNS->getPrefix()));
686
687  switch (NNS->getKind()) {
688  case NestedNameSpecifier::Identifier:
689  case NestedNameSpecifier::Namespace:
690  case NestedNameSpecifier::NamespaceAlias:
691  case NestedNameSpecifier::Global:
692    return true;
693
694  case NestedNameSpecifier::TypeSpec:
695  case NestedNameSpecifier::TypeSpecWithTemplate:
696    TRY_TO(TraverseType(QualType(NNS->getAsType(), 0)));
697  }
698
699  return true;
700}
701
702template <typename Derived>
703bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifierLoc(
704    NestedNameSpecifierLoc NNS) {
705  if (!NNS)
706    return true;
707
708  if (NestedNameSpecifierLoc Prefix = NNS.getPrefix())
709    TRY_TO(TraverseNestedNameSpecifierLoc(Prefix));
710
711  switch (NNS.getNestedNameSpecifier()->getKind()) {
712  case NestedNameSpecifier::Identifier:
713  case NestedNameSpecifier::Namespace:
714  case NestedNameSpecifier::NamespaceAlias:
715  case NestedNameSpecifier::Global:
716    return true;
717
718  case NestedNameSpecifier::TypeSpec:
719  case NestedNameSpecifier::TypeSpecWithTemplate:
720    TRY_TO(TraverseTypeLoc(NNS.getTypeLoc()));
721    break;
722  }
723
724  return true;
725}
726
727template <typename Derived>
728bool RecursiveASTVisitor<Derived>::TraverseDeclarationNameInfo(
729    DeclarationNameInfo NameInfo) {
730  switch (NameInfo.getName().getNameKind()) {
731  case DeclarationName::CXXConstructorName:
732  case DeclarationName::CXXDestructorName:
733  case DeclarationName::CXXConversionFunctionName:
734    if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
735      TRY_TO(TraverseTypeLoc(TSInfo->getTypeLoc()));
736
737    break;
738
739  case DeclarationName::Identifier:
740  case DeclarationName::ObjCZeroArgSelector:
741  case DeclarationName::ObjCOneArgSelector:
742  case DeclarationName::ObjCMultiArgSelector:
743  case DeclarationName::CXXOperatorName:
744  case DeclarationName::CXXLiteralOperatorName:
745  case DeclarationName::CXXUsingDirective:
746    break;
747  }
748
749  return true;
750}
751
752template <typename Derived>
753bool RecursiveASTVisitor<Derived>::TraverseTemplateName(TemplateName Template) {
754  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
755    TRY_TO(TraverseNestedNameSpecifier(DTN->getQualifier()));
756  else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
757    TRY_TO(TraverseNestedNameSpecifier(QTN->getQualifier()));
758
759  return true;
760}
761
762template <typename Derived>
763bool RecursiveASTVisitor<Derived>::TraverseTemplateArgument(
764    const TemplateArgument &Arg) {
765  switch (Arg.getKind()) {
766  case TemplateArgument::Null:
767  case TemplateArgument::Declaration:
768  case TemplateArgument::Integral:
769  case TemplateArgument::NullPtr:
770    return true;
771
772  case TemplateArgument::Type:
773    return getDerived().TraverseType(Arg.getAsType());
774
775  case TemplateArgument::Template:
776  case TemplateArgument::TemplateExpansion:
777    return getDerived().TraverseTemplateName(
778        Arg.getAsTemplateOrTemplatePattern());
779
780  case TemplateArgument::Expression:
781    return getDerived().TraverseStmt(Arg.getAsExpr());
782
783  case TemplateArgument::Pack:
784    return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
785                                                  Arg.pack_size());
786  }
787
788  return true;
789}
790
791// FIXME: no template name location?
792// FIXME: no source locations for a template argument pack?
793template <typename Derived>
794bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLoc(
795    const TemplateArgumentLoc &ArgLoc) {
796  const TemplateArgument &Arg = ArgLoc.getArgument();
797
798  switch (Arg.getKind()) {
799  case TemplateArgument::Null:
800  case TemplateArgument::Declaration:
801  case TemplateArgument::Integral:
802  case TemplateArgument::NullPtr:
803    return true;
804
805  case TemplateArgument::Type: {
806    // FIXME: how can TSI ever be NULL?
807    if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo())
808      return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
809    else
810      return getDerived().TraverseType(Arg.getAsType());
811  }
812
813  case TemplateArgument::Template:
814  case TemplateArgument::TemplateExpansion:
815    if (ArgLoc.getTemplateQualifierLoc())
816      TRY_TO(getDerived().TraverseNestedNameSpecifierLoc(
817          ArgLoc.getTemplateQualifierLoc()));
818    return getDerived().TraverseTemplateName(
819        Arg.getAsTemplateOrTemplatePattern());
820
821  case TemplateArgument::Expression:
822    return getDerived().TraverseStmt(ArgLoc.getSourceExpression());
823
824  case TemplateArgument::Pack:
825    return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
826                                                  Arg.pack_size());
827  }
828
829  return true;
830}
831
832template <typename Derived>
833bool RecursiveASTVisitor<Derived>::TraverseTemplateArguments(
834    const TemplateArgument *Args, unsigned NumArgs) {
835  for (unsigned I = 0; I != NumArgs; ++I) {
836    TRY_TO(TraverseTemplateArgument(Args[I]));
837  }
838
839  return true;
840}
841
842template <typename Derived>
843bool RecursiveASTVisitor<Derived>::TraverseConstructorInitializer(
844    CXXCtorInitializer *Init) {
845  if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo())
846    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
847
848  if (Init->isWritten() || getDerived().shouldVisitImplicitCode())
849    TRY_TO(TraverseStmt(Init->getInit()));
850  return true;
851}
852
853template <typename Derived>
854bool
855RecursiveASTVisitor<Derived>::TraverseLambdaCapture(LambdaExpr *LE,
856                                                    const LambdaCapture *C) {
857  if (C->isInitCapture())
858    TRY_TO(TraverseDecl(C->getCapturedVar()));
859  return true;
860}
861
862template <typename Derived>
863bool RecursiveASTVisitor<Derived>::TraverseLambdaBody(LambdaExpr *LE) {
864  TRY_TO(TraverseStmt(LE->getBody()));
865  return true;
866}
867
868// ----------------- Type traversal -----------------
869
870// This macro makes available a variable T, the passed-in type.
871#define DEF_TRAVERSE_TYPE(TYPE, CODE)                                          \
872  template <typename Derived>                                                  \
873  bool RecursiveASTVisitor<Derived>::Traverse##TYPE(TYPE *T) {                 \
874    TRY_TO(WalkUpFrom##TYPE(T));                                               \
875    { CODE; }                                                                  \
876    return true;                                                               \
877  }
878
879DEF_TRAVERSE_TYPE(BuiltinType, {})
880
881DEF_TRAVERSE_TYPE(ComplexType, { TRY_TO(TraverseType(T->getElementType())); })
882
883DEF_TRAVERSE_TYPE(PointerType, { TRY_TO(TraverseType(T->getPointeeType())); })
884
885DEF_TRAVERSE_TYPE(BlockPointerType,
886                  { TRY_TO(TraverseType(T->getPointeeType())); })
887
888DEF_TRAVERSE_TYPE(LValueReferenceType,
889                  { TRY_TO(TraverseType(T->getPointeeType())); })
890
891DEF_TRAVERSE_TYPE(RValueReferenceType,
892                  { TRY_TO(TraverseType(T->getPointeeType())); })
893
894DEF_TRAVERSE_TYPE(MemberPointerType, {
895  TRY_TO(TraverseType(QualType(T->getClass(), 0)));
896  TRY_TO(TraverseType(T->getPointeeType()));
897})
898
899DEF_TRAVERSE_TYPE(AdjustedType, { TRY_TO(TraverseType(T->getOriginalType())); })
900
901DEF_TRAVERSE_TYPE(DecayedType, { TRY_TO(TraverseType(T->getOriginalType())); })
902
903DEF_TRAVERSE_TYPE(ConstantArrayType,
904                  { TRY_TO(TraverseType(T->getElementType())); })
905
906DEF_TRAVERSE_TYPE(IncompleteArrayType,
907                  { TRY_TO(TraverseType(T->getElementType())); })
908
909DEF_TRAVERSE_TYPE(VariableArrayType, {
910  TRY_TO(TraverseType(T->getElementType()));
911  TRY_TO(TraverseStmt(T->getSizeExpr()));
912})
913
914DEF_TRAVERSE_TYPE(DependentSizedArrayType, {
915  TRY_TO(TraverseType(T->getElementType()));
916  if (T->getSizeExpr())
917    TRY_TO(TraverseStmt(T->getSizeExpr()));
918})
919
920DEF_TRAVERSE_TYPE(DependentSizedExtVectorType, {
921  if (T->getSizeExpr())
922    TRY_TO(TraverseStmt(T->getSizeExpr()));
923  TRY_TO(TraverseType(T->getElementType()));
924})
925
926DEF_TRAVERSE_TYPE(VectorType, { TRY_TO(TraverseType(T->getElementType())); })
927
928DEF_TRAVERSE_TYPE(ExtVectorType, { TRY_TO(TraverseType(T->getElementType())); })
929
930DEF_TRAVERSE_TYPE(FunctionNoProtoType,
931                  { TRY_TO(TraverseType(T->getReturnType())); })
932
933DEF_TRAVERSE_TYPE(FunctionProtoType, {
934  TRY_TO(TraverseType(T->getReturnType()));
935
936  for (const auto &A : T->param_types()) {
937    TRY_TO(TraverseType(A));
938  }
939
940  for (const auto &E : T->exceptions()) {
941    TRY_TO(TraverseType(E));
942  }
943})
944
945DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})
946DEF_TRAVERSE_TYPE(TypedefType, {})
947
948DEF_TRAVERSE_TYPE(TypeOfExprType,
949                  { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
950
951DEF_TRAVERSE_TYPE(TypeOfType, { TRY_TO(TraverseType(T->getUnderlyingType())); })
952
953DEF_TRAVERSE_TYPE(DecltypeType,
954                  { TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
955
956DEF_TRAVERSE_TYPE(UnaryTransformType, {
957  TRY_TO(TraverseType(T->getBaseType()));
958  TRY_TO(TraverseType(T->getUnderlyingType()));
959})
960
961DEF_TRAVERSE_TYPE(AutoType, { TRY_TO(TraverseType(T->getDeducedType())); })
962
963DEF_TRAVERSE_TYPE(RecordType, {})
964DEF_TRAVERSE_TYPE(EnumType, {})
965DEF_TRAVERSE_TYPE(TemplateTypeParmType, {})
966DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, {})
967DEF_TRAVERSE_TYPE(SubstTemplateTypeParmPackType, {})
968
969DEF_TRAVERSE_TYPE(TemplateSpecializationType, {
970  TRY_TO(TraverseTemplateName(T->getTemplateName()));
971  TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
972})
973
974DEF_TRAVERSE_TYPE(InjectedClassNameType, {})
975
976DEF_TRAVERSE_TYPE(AttributedType,
977                  { TRY_TO(TraverseType(T->getModifiedType())); })
978
979DEF_TRAVERSE_TYPE(ParenType, { TRY_TO(TraverseType(T->getInnerType())); })
980
981DEF_TRAVERSE_TYPE(ElaboratedType, {
982  if (T->getQualifier()) {
983    TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
984  }
985  TRY_TO(TraverseType(T->getNamedType()));
986})
987
988DEF_TRAVERSE_TYPE(DependentNameType,
989                  { TRY_TO(TraverseNestedNameSpecifier(T->getQualifier())); })
990
991DEF_TRAVERSE_TYPE(DependentTemplateSpecializationType, {
992  TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
993  TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
994})
995
996DEF_TRAVERSE_TYPE(PackExpansionType, { TRY_TO(TraverseType(T->getPattern())); })
997
998DEF_TRAVERSE_TYPE(ObjCInterfaceType, {})
999
1000DEF_TRAVERSE_TYPE(ObjCObjectType, {
1001  // We have to watch out here because an ObjCInterfaceType's base
1002  // type is itself.
1003  if (T->getBaseType().getTypePtr() != T)
1004    TRY_TO(TraverseType(T->getBaseType()));
1005})
1006
1007DEF_TRAVERSE_TYPE(ObjCObjectPointerType,
1008                  { TRY_TO(TraverseType(T->getPointeeType())); })
1009
1010DEF_TRAVERSE_TYPE(AtomicType, { TRY_TO(TraverseType(T->getValueType())); })
1011
1012#undef DEF_TRAVERSE_TYPE
1013
1014// ----------------- TypeLoc traversal -----------------
1015
1016// This macro makes available a variable TL, the passed-in TypeLoc.
1017// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,
1018// in addition to WalkUpFrom* for the TypeLoc itself, such that existing
1019// clients that override the WalkUpFrom*Type() and/or Visit*Type() methods
1020// continue to work.
1021#define DEF_TRAVERSE_TYPELOC(TYPE, CODE)                                       \
1022  template <typename Derived>                                                  \
1023  bool RecursiveASTVisitor<Derived>::Traverse##TYPE##Loc(TYPE##Loc TL) {       \
1024    if (getDerived().shouldWalkTypesOfTypeLocs())                              \
1025      TRY_TO(WalkUpFrom##TYPE(const_cast<TYPE *>(TL.getTypePtr())));           \
1026    TRY_TO(WalkUpFrom##TYPE##Loc(TL));                                         \
1027    { CODE; }                                                                  \
1028    return true;                                                               \
1029  }
1030
1031template <typename Derived>
1032bool
1033RecursiveASTVisitor<Derived>::TraverseQualifiedTypeLoc(QualifiedTypeLoc TL) {
1034  // Move this over to the 'main' typeloc tree.  Note that this is a
1035  // move -- we pretend that we were really looking at the unqualified
1036  // typeloc all along -- rather than a recursion, so we don't follow
1037  // the normal CRTP plan of going through
1038  // getDerived().TraverseTypeLoc.  If we did, we'd be traversing
1039  // twice for the same type (once as a QualifiedTypeLoc version of
1040  // the type, once as an UnqualifiedTypeLoc version of the type),
1041  // which in effect means we'd call VisitTypeLoc twice with the
1042  // 'same' type.  This solves that problem, at the cost of never
1043  // seeing the qualified version of the type (unless the client
1044  // subclasses TraverseQualifiedTypeLoc themselves).  It's not a
1045  // perfect solution.  A perfect solution probably requires making
1046  // QualifiedTypeLoc a wrapper around TypeLoc -- like QualType is a
1047  // wrapper around Type* -- rather than being its own class in the
1048  // type hierarchy.
1049  return TraverseTypeLoc(TL.getUnqualifiedLoc());
1050}
1051
1052DEF_TRAVERSE_TYPELOC(BuiltinType, {})
1053
1054// FIXME: ComplexTypeLoc is unfinished
1055DEF_TRAVERSE_TYPELOC(ComplexType, {
1056  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1057})
1058
1059DEF_TRAVERSE_TYPELOC(PointerType,
1060                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1061
1062DEF_TRAVERSE_TYPELOC(BlockPointerType,
1063                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1064
1065DEF_TRAVERSE_TYPELOC(LValueReferenceType,
1066                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1067
1068DEF_TRAVERSE_TYPELOC(RValueReferenceType,
1069                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1070
1071// FIXME: location of base class?
1072// We traverse this in the type case as well, but how is it not reached through
1073// the pointee type?
1074DEF_TRAVERSE_TYPELOC(MemberPointerType, {
1075  TRY_TO(TraverseType(QualType(TL.getTypePtr()->getClass(), 0)));
1076  TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
1077})
1078
1079DEF_TRAVERSE_TYPELOC(AdjustedType,
1080                     { TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
1081
1082DEF_TRAVERSE_TYPELOC(DecayedType,
1083                     { TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
1084
1085template <typename Derived>
1086bool RecursiveASTVisitor<Derived>::TraverseArrayTypeLocHelper(ArrayTypeLoc TL) {
1087  // This isn't available for ArrayType, but is for the ArrayTypeLoc.
1088  TRY_TO(TraverseStmt(TL.getSizeExpr()));
1089  return true;
1090}
1091
1092DEF_TRAVERSE_TYPELOC(ConstantArrayType, {
1093  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1094  return TraverseArrayTypeLocHelper(TL);
1095})
1096
1097DEF_TRAVERSE_TYPELOC(IncompleteArrayType, {
1098  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1099  return TraverseArrayTypeLocHelper(TL);
1100})
1101
1102DEF_TRAVERSE_TYPELOC(VariableArrayType, {
1103  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1104  return TraverseArrayTypeLocHelper(TL);
1105})
1106
1107DEF_TRAVERSE_TYPELOC(DependentSizedArrayType, {
1108  TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
1109  return TraverseArrayTypeLocHelper(TL);
1110})
1111
1112// FIXME: order? why not size expr first?
1113// FIXME: base VectorTypeLoc is unfinished
1114DEF_TRAVERSE_TYPELOC(DependentSizedExtVectorType, {
1115  if (TL.getTypePtr()->getSizeExpr())
1116    TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
1117  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1118})
1119
1120// FIXME: VectorTypeLoc is unfinished
1121DEF_TRAVERSE_TYPELOC(VectorType, {
1122  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1123})
1124
1125// FIXME: size and attributes
1126// FIXME: base VectorTypeLoc is unfinished
1127DEF_TRAVERSE_TYPELOC(ExtVectorType, {
1128  TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
1129})
1130
1131DEF_TRAVERSE_TYPELOC(FunctionNoProtoType,
1132                     { TRY_TO(TraverseTypeLoc(TL.getReturnLoc())); })
1133
1134// FIXME: location of exception specifications (attributes?)
1135DEF_TRAVERSE_TYPELOC(FunctionProtoType, {
1136  TRY_TO(TraverseTypeLoc(TL.getReturnLoc()));
1137
1138  const FunctionProtoType *T = TL.getTypePtr();
1139
1140  for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
1141    if (TL.getParam(I)) {
1142      TRY_TO(TraverseDecl(TL.getParam(I)));
1143    } else if (I < T->getNumParams()) {
1144      TRY_TO(TraverseType(T->getParamType(I)));
1145    }
1146  }
1147
1148  for (const auto &E : T->exceptions()) {
1149    TRY_TO(TraverseType(E));
1150  }
1151})
1152
1153DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, {})
1154DEF_TRAVERSE_TYPELOC(TypedefType, {})
1155
1156DEF_TRAVERSE_TYPELOC(TypeOfExprType,
1157                     { TRY_TO(TraverseStmt(TL.getUnderlyingExpr())); })
1158
1159DEF_TRAVERSE_TYPELOC(TypeOfType, {
1160  TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
1161})
1162
1163// FIXME: location of underlying expr
1164DEF_TRAVERSE_TYPELOC(DecltypeType, {
1165  TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr()));
1166})
1167
1168DEF_TRAVERSE_TYPELOC(UnaryTransformType, {
1169  TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
1170})
1171
1172DEF_TRAVERSE_TYPELOC(AutoType, {
1173  TRY_TO(TraverseType(TL.getTypePtr()->getDeducedType()));
1174})
1175
1176DEF_TRAVERSE_TYPELOC(RecordType, {})
1177DEF_TRAVERSE_TYPELOC(EnumType, {})
1178DEF_TRAVERSE_TYPELOC(TemplateTypeParmType, {})
1179DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmType, {})
1180DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmPackType, {})
1181
1182// FIXME: use the loc for the template name?
1183DEF_TRAVERSE_TYPELOC(TemplateSpecializationType, {
1184  TRY_TO(TraverseTemplateName(TL.getTypePtr()->getTemplateName()));
1185  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
1186    TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
1187  }
1188})
1189
1190DEF_TRAVERSE_TYPELOC(InjectedClassNameType, {})
1191
1192DEF_TRAVERSE_TYPELOC(ParenType, { TRY_TO(TraverseTypeLoc(TL.getInnerLoc())); })
1193
1194DEF_TRAVERSE_TYPELOC(AttributedType,
1195                     { TRY_TO(TraverseTypeLoc(TL.getModifiedLoc())); })
1196
1197DEF_TRAVERSE_TYPELOC(ElaboratedType, {
1198  if (TL.getQualifierLoc()) {
1199    TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1200  }
1201  TRY_TO(TraverseTypeLoc(TL.getNamedTypeLoc()));
1202})
1203
1204DEF_TRAVERSE_TYPELOC(DependentNameType, {
1205  TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1206})
1207
1208DEF_TRAVERSE_TYPELOC(DependentTemplateSpecializationType, {
1209  if (TL.getQualifierLoc()) {
1210    TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
1211  }
1212
1213  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
1214    TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
1215  }
1216})
1217
1218DEF_TRAVERSE_TYPELOC(PackExpansionType,
1219                     { TRY_TO(TraverseTypeLoc(TL.getPatternLoc())); })
1220
1221DEF_TRAVERSE_TYPELOC(ObjCInterfaceType, {})
1222
1223DEF_TRAVERSE_TYPELOC(ObjCObjectType, {
1224  // We have to watch out here because an ObjCInterfaceType's base
1225  // type is itself.
1226  if (TL.getTypePtr()->getBaseType().getTypePtr() != TL.getTypePtr())
1227    TRY_TO(TraverseTypeLoc(TL.getBaseLoc()));
1228})
1229
1230DEF_TRAVERSE_TYPELOC(ObjCObjectPointerType,
1231                     { TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
1232
1233DEF_TRAVERSE_TYPELOC(AtomicType, { TRY_TO(TraverseTypeLoc(TL.getValueLoc())); })
1234
1235#undef DEF_TRAVERSE_TYPELOC
1236
1237// ----------------- Decl traversal -----------------
1238//
1239// For a Decl, we automate (in the DEF_TRAVERSE_DECL macro) traversing
1240// the children that come from the DeclContext associated with it.
1241// Therefore each Traverse* only needs to worry about children other
1242// than those.
1243
1244template <typename Derived>
1245bool RecursiveASTVisitor<Derived>::TraverseDeclContextHelper(DeclContext *DC) {
1246  if (!DC)
1247    return true;
1248
1249  for (auto *Child : DC->decls()) {
1250    // BlockDecls and CapturedDecls are traversed through BlockExprs and
1251    // CapturedStmts respectively.
1252    if (!isa<BlockDecl>(Child) && !isa<CapturedDecl>(Child))
1253      TRY_TO(TraverseDecl(Child));
1254  }
1255
1256  return true;
1257}
1258
1259// This macro makes available a variable D, the passed-in decl.
1260#define DEF_TRAVERSE_DECL(DECL, CODE)                                          \
1261  template <typename Derived>                                                  \
1262  bool RecursiveASTVisitor<Derived>::Traverse##DECL(DECL *D) {                 \
1263    TRY_TO(WalkUpFrom##DECL(D));                                               \
1264    { CODE; }                                                                  \
1265    TRY_TO(TraverseDeclContextHelper(dyn_cast<DeclContext>(D)));               \
1266    return true;                                                               \
1267  }
1268
1269DEF_TRAVERSE_DECL(AccessSpecDecl, {})
1270
1271DEF_TRAVERSE_DECL(BlockDecl, {
1272  if (TypeSourceInfo *TInfo = D->getSignatureAsWritten())
1273    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
1274  TRY_TO(TraverseStmt(D->getBody()));
1275  // This return statement makes sure the traversal of nodes in
1276  // decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
1277  // is skipped - don't remove it.
1278  return true;
1279})
1280
1281DEF_TRAVERSE_DECL(CapturedDecl, {
1282  TRY_TO(TraverseStmt(D->getBody()));
1283  // This return statement makes sure the traversal of nodes in
1284  // decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
1285  // is skipped - don't remove it.
1286  return true;
1287})
1288
1289DEF_TRAVERSE_DECL(EmptyDecl, {})
1290
1291DEF_TRAVERSE_DECL(FileScopeAsmDecl,
1292                  { TRY_TO(TraverseStmt(D->getAsmString())); })
1293
1294DEF_TRAVERSE_DECL(ImportDecl, {})
1295
1296DEF_TRAVERSE_DECL(FriendDecl, {
1297  // Friend is either decl or a type.
1298  if (D->getFriendType())
1299    TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
1300  else
1301    TRY_TO(TraverseDecl(D->getFriendDecl()));
1302})
1303
1304DEF_TRAVERSE_DECL(FriendTemplateDecl, {
1305  if (D->getFriendType())
1306    TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
1307  else
1308    TRY_TO(TraverseDecl(D->getFriendDecl()));
1309  for (unsigned I = 0, E = D->getNumTemplateParameters(); I < E; ++I) {
1310    TemplateParameterList *TPL = D->getTemplateParameterList(I);
1311    for (TemplateParameterList::iterator ITPL = TPL->begin(), ETPL = TPL->end();
1312         ITPL != ETPL; ++ITPL) {
1313      TRY_TO(TraverseDecl(*ITPL));
1314    }
1315  }
1316})
1317
1318DEF_TRAVERSE_DECL(ClassScopeFunctionSpecializationDecl, {
1319  TRY_TO(TraverseDecl(D->getSpecialization()));
1320
1321  if (D->hasExplicitTemplateArgs()) {
1322    const TemplateArgumentListInfo &args = D->templateArgs();
1323    TRY_TO(TraverseTemplateArgumentLocsHelper(args.getArgumentArray(),
1324                                              args.size()));
1325  }
1326})
1327
1328DEF_TRAVERSE_DECL(LinkageSpecDecl, {})
1329
1330DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {// FIXME: implement this
1331                                        })
1332
1333DEF_TRAVERSE_DECL(StaticAssertDecl, {
1334  TRY_TO(TraverseStmt(D->getAssertExpr()));
1335  TRY_TO(TraverseStmt(D->getMessage()));
1336})
1337
1338DEF_TRAVERSE_DECL(
1339    TranslationUnitDecl,
1340    {// Code in an unnamed namespace shows up automatically in
1341     // decls_begin()/decls_end().  Thus we don't need to recurse on
1342     // D->getAnonymousNamespace().
1343    })
1344
1345DEF_TRAVERSE_DECL(NamespaceAliasDecl, {
1346  // We shouldn't traverse an aliased namespace, since it will be
1347  // defined (and, therefore, traversed) somewhere else.
1348  //
1349  // This return statement makes sure the traversal of nodes in
1350  // decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
1351  // is skipped - don't remove it.
1352  return true;
1353})
1354
1355DEF_TRAVERSE_DECL(LabelDecl, {// There is no code in a LabelDecl.
1356                             })
1357
1358DEF_TRAVERSE_DECL(
1359    NamespaceDecl,
1360    {// Code in an unnamed namespace shows up automatically in
1361     // decls_begin()/decls_end().  Thus we don't need to recurse on
1362     // D->getAnonymousNamespace().
1363    })
1364
1365DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, {// FIXME: implement
1366                                           })
1367
1368DEF_TRAVERSE_DECL(ObjCCategoryDecl, {// FIXME: implement
1369                                    })
1370
1371DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, {// FIXME: implement
1372                                        })
1373
1374DEF_TRAVERSE_DECL(ObjCImplementationDecl, {// FIXME: implement
1375                                          })
1376
1377DEF_TRAVERSE_DECL(ObjCInterfaceDecl, {// FIXME: implement
1378                                     })
1379
1380DEF_TRAVERSE_DECL(ObjCProtocolDecl, {// FIXME: implement
1381                                    })
1382
1383DEF_TRAVERSE_DECL(ObjCMethodDecl, {
1384  if (D->getReturnTypeSourceInfo()) {
1385    TRY_TO(TraverseTypeLoc(D->getReturnTypeSourceInfo()->getTypeLoc()));
1386  }
1387  for (ObjCMethodDecl::param_iterator I = D->param_begin(), E = D->param_end();
1388       I != E; ++I) {
1389    TRY_TO(TraverseDecl(*I));
1390  }
1391  if (D->isThisDeclarationADefinition()) {
1392    TRY_TO(TraverseStmt(D->getBody()));
1393  }
1394  return true;
1395})
1396
1397DEF_TRAVERSE_DECL(ObjCPropertyDecl, {// FIXME: implement
1398                                    })
1399
1400DEF_TRAVERSE_DECL(UsingDecl, {
1401  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1402  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1403})
1404
1405DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
1406  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1407})
1408
1409DEF_TRAVERSE_DECL(UsingShadowDecl, {})
1410
1411DEF_TRAVERSE_DECL(OMPThreadPrivateDecl, {
1412  for (auto *I : D->varlists()) {
1413    TRY_TO(TraverseStmt(I));
1414  }
1415})
1416
1417// A helper method for TemplateDecl's children.
1418template <typename Derived>
1419bool RecursiveASTVisitor<Derived>::TraverseTemplateParameterListHelper(
1420    TemplateParameterList *TPL) {
1421  if (TPL) {
1422    for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();
1423         I != E; ++I) {
1424      TRY_TO(TraverseDecl(*I));
1425    }
1426  }
1427  return true;
1428}
1429
1430template <typename Derived>
1431bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1432    ClassTemplateDecl *D) {
1433  for (auto *SD : D->specializations()) {
1434    for (auto *RD : SD->redecls()) {
1435      // We don't want to visit injected-class-names in this traversal.
1436      if (cast<CXXRecordDecl>(RD)->isInjectedClassName())
1437        continue;
1438
1439      switch (
1440          cast<ClassTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
1441      // Visit the implicit instantiations with the requested pattern.
1442      case TSK_Undeclared:
1443      case TSK_ImplicitInstantiation:
1444        TRY_TO(TraverseDecl(RD));
1445        break;
1446
1447      // We don't need to do anything on an explicit instantiation
1448      // or explicit specialization because there will be an explicit
1449      // node for it elsewhere.
1450      case TSK_ExplicitInstantiationDeclaration:
1451      case TSK_ExplicitInstantiationDefinition:
1452      case TSK_ExplicitSpecialization:
1453        break;
1454      }
1455    }
1456  }
1457
1458  return true;
1459}
1460
1461template <typename Derived>
1462bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1463    VarTemplateDecl *D) {
1464  for (auto *SD : D->specializations()) {
1465    for (auto *RD : SD->redecls()) {
1466      switch (
1467          cast<VarTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
1468      case TSK_Undeclared:
1469      case TSK_ImplicitInstantiation:
1470        TRY_TO(TraverseDecl(RD));
1471        break;
1472
1473      case TSK_ExplicitInstantiationDeclaration:
1474      case TSK_ExplicitInstantiationDefinition:
1475      case TSK_ExplicitSpecialization:
1476        break;
1477      }
1478    }
1479  }
1480
1481  return true;
1482}
1483
1484// A helper method for traversing the instantiations of a
1485// function while skipping its specializations.
1486template <typename Derived>
1487bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
1488    FunctionTemplateDecl *D) {
1489  for (auto *FD : D->specializations()) {
1490    for (auto *RD : FD->redecls()) {
1491      switch (RD->getTemplateSpecializationKind()) {
1492      case TSK_Undeclared:
1493      case TSK_ImplicitInstantiation:
1494        // We don't know what kind of FunctionDecl this is.
1495        TRY_TO(TraverseDecl(RD));
1496        break;
1497
1498      // FIXME: For now traverse explicit instantiations here. Change that
1499      // once they are represented as dedicated nodes in the AST.
1500      case TSK_ExplicitInstantiationDeclaration:
1501      case TSK_ExplicitInstantiationDefinition:
1502        TRY_TO(TraverseDecl(RD));
1503        break;
1504
1505      case TSK_ExplicitSpecialization:
1506        break;
1507      }
1508    }
1509  }
1510
1511  return true;
1512}
1513
1514// This macro unifies the traversal of class, variable and function
1515// template declarations.
1516#define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND)                                   \
1517  DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, {                              \
1518    TRY_TO(TraverseDecl(D->getTemplatedDecl()));                             \
1519    TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \
1520                                                                             \
1521    /* By default, we do not traverse the instantiations of
1522       class templates since they do not appear in the user code. The
1523       following code optionally traverses them.
1524
1525       We only traverse the class instantiations when we see the canonical
1526       declaration of the template, to ensure we only visit them once. */    \
1527    if (getDerived().shouldVisitTemplateInstantiations() &&                  \
1528        D == D->getCanonicalDecl())                                          \
1529      TRY_TO(TraverseTemplateInstantiations(D));                             \
1530                                                                             \
1531    /* Note that getInstantiatedFromMemberTemplate() is just a link
1532       from a template instantiation back to the template from which
1533       it was instantiated, and thus should not be traversed. */             \
1534  })
1535
1536DEF_TRAVERSE_TMPL_DECL(Class)
1537DEF_TRAVERSE_TMPL_DECL(Var)
1538DEF_TRAVERSE_TMPL_DECL(Function)
1539
1540DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, {
1541  // D is the "T" in something like
1542  //   template <template <typename> class T> class container { };
1543  TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1544  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
1545    TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
1546  }
1547  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1548})
1549
1550DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
1551  // D is the "T" in something like "template<typename T> class vector;"
1552  if (D->getTypeForDecl())
1553    TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1554  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
1555    TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
1556})
1557
1558DEF_TRAVERSE_DECL(TypedefDecl, {
1559  TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1560  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1561  // declaring the typedef, not something that was written in the
1562  // source.
1563})
1564
1565DEF_TRAVERSE_DECL(TypeAliasDecl, {
1566  TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1567  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1568  // declaring the type alias, not something that was written in the
1569  // source.
1570})
1571
1572DEF_TRAVERSE_DECL(TypeAliasTemplateDecl, {
1573  TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1574  TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1575})
1576
1577DEF_TRAVERSE_DECL(UnresolvedUsingTypenameDecl, {
1578  // A dependent using declaration which was marked with 'typename'.
1579  //   template<class T> class A : public B<T> { using typename B<T>::foo; };
1580  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1581  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1582  // declaring the type, not something that was written in the
1583  // source.
1584})
1585
1586DEF_TRAVERSE_DECL(EnumDecl, {
1587  if (D->getTypeForDecl())
1588    TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1589
1590  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1591  // The enumerators are already traversed by
1592  // decls_begin()/decls_end().
1593})
1594
1595// Helper methods for RecordDecl and its children.
1596template <typename Derived>
1597bool RecursiveASTVisitor<Derived>::TraverseRecordHelper(RecordDecl *D) {
1598  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1599  // declaring the type, not something that was written in the source.
1600
1601  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1602  return true;
1603}
1604
1605template <typename Derived>
1606bool RecursiveASTVisitor<Derived>::TraverseCXXRecordHelper(CXXRecordDecl *D) {
1607  if (!TraverseRecordHelper(D))
1608    return false;
1609  if (D->isCompleteDefinition()) {
1610    for (const auto &I : D->bases()) {
1611      TRY_TO(TraverseTypeLoc(I.getTypeSourceInfo()->getTypeLoc()));
1612    }
1613    // We don't traverse the friends or the conversions, as they are
1614    // already in decls_begin()/decls_end().
1615  }
1616  return true;
1617}
1618
1619DEF_TRAVERSE_DECL(RecordDecl, { TRY_TO(TraverseRecordHelper(D)); })
1620
1621DEF_TRAVERSE_DECL(CXXRecordDecl, { TRY_TO(TraverseCXXRecordHelper(D)); })
1622
1623#define DEF_TRAVERSE_TMPL_SPEC_DECL(TMPLDECLKIND)                              \
1624  DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateSpecializationDecl, {                \
1625    /* For implicit instantiations ("set<int> x;"), we don't want to           \
1626       recurse at all, since the instatiated template isn't written in         \
1627       the source code anywhere.  (Note the instatiated *type* --              \
1628       set<int> -- is written, and will still get a callback of                \
1629       TemplateSpecializationType).  For explicit instantiations               \
1630       ("template set<int>;"), we do need a callback, since this               \
1631       is the only callback that's made for this instantiation.                \
1632       We use getTypeAsWritten() to distinguish. */                            \
1633    if (TypeSourceInfo *TSI = D->getTypeAsWritten())                           \
1634      TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));                              \
1635                                                                               \
1636    if (!getDerived().shouldVisitTemplateInstantiations() &&                   \
1637        D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)      \
1638      /* Returning from here skips traversing the                              \
1639         declaration context of the *TemplateSpecializationDecl                \
1640         (embedded in the DEF_TRAVERSE_DECL() macro)                           \
1641         which contains the instantiated members of the template. */           \
1642      return true;                                                             \
1643  })
1644
1645DEF_TRAVERSE_TMPL_SPEC_DECL(Class)
1646DEF_TRAVERSE_TMPL_SPEC_DECL(Var)
1647
1648template <typename Derived>
1649bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLocsHelper(
1650    const TemplateArgumentLoc *TAL, unsigned Count) {
1651  for (unsigned I = 0; I < Count; ++I) {
1652    TRY_TO(TraverseTemplateArgumentLoc(TAL[I]));
1653  }
1654  return true;
1655}
1656
1657#define DEF_TRAVERSE_TMPL_PART_SPEC_DECL(TMPLDECLKIND, DECLKIND)               \
1658  DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplatePartialSpecializationDecl, {         \
1659    /* The partial specialization. */                                        \
1660    if (TemplateParameterList *TPL = D->getTemplateParameters()) {           \
1661      for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end(); \
1662           I != E; ++I) {                                                    \
1663        TRY_TO(TraverseDecl(*I));                                            \
1664      }                                                                      \
1665    }                                                                        \
1666    /* The args that remains unspecialized. */                               \
1667    TRY_TO(TraverseTemplateArgumentLocsHelper(                               \
1668                      D->getTemplateArgsAsWritten()->getTemplateArgs(),      \
1669                      D->getTemplateArgsAsWritten()->NumTemplateArgs));      \
1670                                                                             \
1671    /* Don't need the *TemplatePartialSpecializationHelper, even
1672       though that's our parent class -- we already visit all the
1673       template args here. */                                                \
1674    TRY_TO(Traverse##DECLKIND##Helper(D));                                   \
1675                                                                             \
1676    /* Instantiations will have been visited with the primary template. */   \
1677  })
1678
1679DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Class, CXXRecord)
1680DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Var, Var)
1681
1682DEF_TRAVERSE_DECL(EnumConstantDecl, { TRY_TO(TraverseStmt(D->getInitExpr())); })
1683
1684DEF_TRAVERSE_DECL(UnresolvedUsingValueDecl, {
1685  // Like UnresolvedUsingTypenameDecl, but without the 'typename':
1686  //    template <class T> Class A : public Base<T> { using Base<T>::foo; };
1687  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1688  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1689})
1690
1691DEF_TRAVERSE_DECL(IndirectFieldDecl, {})
1692
1693template <typename Derived>
1694bool RecursiveASTVisitor<Derived>::TraverseDeclaratorHelper(DeclaratorDecl *D) {
1695  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1696  if (D->getTypeSourceInfo())
1697    TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1698  else
1699    TRY_TO(TraverseType(D->getType()));
1700  return true;
1701}
1702
1703DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })
1704
1705DEF_TRAVERSE_DECL(FieldDecl, {
1706  TRY_TO(TraverseDeclaratorHelper(D));
1707  if (D->isBitField())
1708    TRY_TO(TraverseStmt(D->getBitWidth()));
1709  else if (D->hasInClassInitializer())
1710    TRY_TO(TraverseStmt(D->getInClassInitializer()));
1711})
1712
1713DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
1714  TRY_TO(TraverseDeclaratorHelper(D));
1715  if (D->isBitField())
1716    TRY_TO(TraverseStmt(D->getBitWidth()));
1717  // FIXME: implement the rest.
1718})
1719
1720DEF_TRAVERSE_DECL(ObjCIvarDecl, {
1721  TRY_TO(TraverseDeclaratorHelper(D));
1722  if (D->isBitField())
1723    TRY_TO(TraverseStmt(D->getBitWidth()));
1724  // FIXME: implement the rest.
1725})
1726
1727template <typename Derived>
1728bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D) {
1729  TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
1730  TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
1731
1732  // If we're an explicit template specialization, iterate over the
1733  // template args that were explicitly specified.  If we were doing
1734  // this in typing order, we'd do it between the return type and
1735  // the function args, but both are handled by the FunctionTypeLoc
1736  // above, so we have to choose one side.  I've decided to do before.
1737  if (const FunctionTemplateSpecializationInfo *FTSI =
1738          D->getTemplateSpecializationInfo()) {
1739    if (FTSI->getTemplateSpecializationKind() != TSK_Undeclared &&
1740        FTSI->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
1741      // A specialization might not have explicit template arguments if it has
1742      // a templated return type and concrete arguments.
1743      if (const ASTTemplateArgumentListInfo *TALI =
1744              FTSI->TemplateArgumentsAsWritten) {
1745        TRY_TO(TraverseTemplateArgumentLocsHelper(TALI->getTemplateArgs(),
1746                                                  TALI->NumTemplateArgs));
1747      }
1748    }
1749  }
1750
1751  // Visit the function type itself, which can be either
1752  // FunctionNoProtoType or FunctionProtoType, or a typedef.  This
1753  // also covers the return type and the function parameters,
1754  // including exception specifications.
1755  if (TypeSourceInfo *TSI = D->getTypeSourceInfo()) {
1756    TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
1757  } else if (getDerived().shouldVisitImplicitCode()) {
1758    // Visit parameter variable declarations of the implicit function
1759    // if the traverser is visiting implicit code. Parameter variable
1760    // declarations do not have valid TypeSourceInfo, so to visit them
1761    // we need to traverse the declarations explicitly.
1762    for (FunctionDecl::param_const_iterator I = D->param_begin(),
1763                                            E = D->param_end();
1764         I != E; ++I)
1765      TRY_TO(TraverseDecl(*I));
1766  }
1767
1768  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1769    // Constructor initializers.
1770    for (auto *I : Ctor->inits()) {
1771      TRY_TO(TraverseConstructorInitializer(I));
1772    }
1773  }
1774
1775  if (D->isThisDeclarationADefinition()) {
1776    TRY_TO(TraverseStmt(D->getBody())); // Function body.
1777  }
1778  return true;
1779}
1780
1781DEF_TRAVERSE_DECL(FunctionDecl, {
1782  // We skip decls_begin/decls_end, which are already covered by
1783  // TraverseFunctionHelper().
1784  return TraverseFunctionHelper(D);
1785})
1786
1787DEF_TRAVERSE_DECL(CXXMethodDecl, {
1788  // We skip decls_begin/decls_end, which are already covered by
1789  // TraverseFunctionHelper().
1790  return TraverseFunctionHelper(D);
1791})
1792
1793DEF_TRAVERSE_DECL(CXXConstructorDecl, {
1794  // We skip decls_begin/decls_end, which are already covered by
1795  // TraverseFunctionHelper().
1796  return TraverseFunctionHelper(D);
1797})
1798
1799// CXXConversionDecl is the declaration of a type conversion operator.
1800// It's not a cast expression.
1801DEF_TRAVERSE_DECL(CXXConversionDecl, {
1802  // We skip decls_begin/decls_end, which are already covered by
1803  // TraverseFunctionHelper().
1804  return TraverseFunctionHelper(D);
1805})
1806
1807DEF_TRAVERSE_DECL(CXXDestructorDecl, {
1808  // We skip decls_begin/decls_end, which are already covered by
1809  // TraverseFunctionHelper().
1810  return TraverseFunctionHelper(D);
1811})
1812
1813template <typename Derived>
1814bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
1815  TRY_TO(TraverseDeclaratorHelper(D));
1816  // Default params are taken care of when we traverse the ParmVarDecl.
1817  if (!isa<ParmVarDecl>(D) &&
1818      (!D->isCXXForRangeDecl() || getDerived().shouldVisitImplicitCode()))
1819    TRY_TO(TraverseStmt(D->getInit()));
1820  return true;
1821}
1822
1823DEF_TRAVERSE_DECL(VarDecl, { TRY_TO(TraverseVarHelper(D)); })
1824
1825DEF_TRAVERSE_DECL(ImplicitParamDecl, { TRY_TO(TraverseVarHelper(D)); })
1826
1827DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, {
1828  // A non-type template parameter, e.g. "S" in template<int S> class Foo ...
1829  TRY_TO(TraverseDeclaratorHelper(D));
1830  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
1831    TRY_TO(TraverseStmt(D->getDefaultArgument()));
1832})
1833
1834DEF_TRAVERSE_DECL(ParmVarDecl, {
1835  TRY_TO(TraverseVarHelper(D));
1836
1837  if (D->hasDefaultArg() && D->hasUninstantiatedDefaultArg() &&
1838      !D->hasUnparsedDefaultArg())
1839    TRY_TO(TraverseStmt(D->getUninstantiatedDefaultArg()));
1840
1841  if (D->hasDefaultArg() && !D->hasUninstantiatedDefaultArg() &&
1842      !D->hasUnparsedDefaultArg())
1843    TRY_TO(TraverseStmt(D->getDefaultArg()));
1844})
1845
1846#undef DEF_TRAVERSE_DECL
1847
1848// ----------------- Stmt traversal -----------------
1849//
1850// For stmts, we automate (in the DEF_TRAVERSE_STMT macro) iterating
1851// over the children defined in children() (every stmt defines these,
1852// though sometimes the range is empty).  Each individual Traverse*
1853// method only needs to worry about children other than those.  To see
1854// what children() does for a given class, see, e.g.,
1855//   http://clang.llvm.org/doxygen/Stmt_8cpp_source.html
1856
1857// This macro makes available a variable S, the passed-in stmt.
1858#define DEF_TRAVERSE_STMT(STMT, CODE)                                          \
1859  template <typename Derived>                                                  \
1860  bool RecursiveASTVisitor<Derived>::Traverse##STMT(STMT *S) {                 \
1861    TRY_TO(WalkUpFrom##STMT(S));                                               \
1862    { CODE; }                                                                  \
1863    for (Stmt::child_range range = S->children(); range; ++range) {            \
1864      TRY_TO(TraverseStmt(*range));                                            \
1865    }                                                                          \
1866    return true;                                                               \
1867  }
1868
1869DEF_TRAVERSE_STMT(GCCAsmStmt, {
1870  TRY_TO(TraverseStmt(S->getAsmString()));
1871  for (unsigned I = 0, E = S->getNumInputs(); I < E; ++I) {
1872    TRY_TO(TraverseStmt(S->getInputConstraintLiteral(I)));
1873  }
1874  for (unsigned I = 0, E = S->getNumOutputs(); I < E; ++I) {
1875    TRY_TO(TraverseStmt(S->getOutputConstraintLiteral(I)));
1876  }
1877  for (unsigned I = 0, E = S->getNumClobbers(); I < E; ++I) {
1878    TRY_TO(TraverseStmt(S->getClobberStringLiteral(I)));
1879  }
1880  // children() iterates over inputExpr and outputExpr.
1881})
1882
1883DEF_TRAVERSE_STMT(
1884    MSAsmStmt,
1885    {// FIXME: MS Asm doesn't currently parse Constraints, Clobbers, etc.  Once
1886     // added this needs to be implemented.
1887    })
1888
1889DEF_TRAVERSE_STMT(CXXCatchStmt, {
1890  TRY_TO(TraverseDecl(S->getExceptionDecl()));
1891  // children() iterates over the handler block.
1892})
1893
1894DEF_TRAVERSE_STMT(DeclStmt, {
1895  for (auto *I : S->decls()) {
1896    TRY_TO(TraverseDecl(I));
1897  }
1898  // Suppress the default iteration over children() by
1899  // returning.  Here's why: A DeclStmt looks like 'type var [=
1900  // initializer]'.  The decls above already traverse over the
1901  // initializers, so we don't have to do it again (which
1902  // children() would do).
1903  return true;
1904})
1905
1906// These non-expr stmts (most of them), do not need any action except
1907// iterating over the children.
1908DEF_TRAVERSE_STMT(BreakStmt, {})
1909DEF_TRAVERSE_STMT(CXXTryStmt, {})
1910DEF_TRAVERSE_STMT(CaseStmt, {})
1911DEF_TRAVERSE_STMT(CompoundStmt, {})
1912DEF_TRAVERSE_STMT(ContinueStmt, {})
1913DEF_TRAVERSE_STMT(DefaultStmt, {})
1914DEF_TRAVERSE_STMT(DoStmt, {})
1915DEF_TRAVERSE_STMT(ForStmt, {})
1916DEF_TRAVERSE_STMT(GotoStmt, {})
1917DEF_TRAVERSE_STMT(IfStmt, {})
1918DEF_TRAVERSE_STMT(IndirectGotoStmt, {})
1919DEF_TRAVERSE_STMT(LabelStmt, {})
1920DEF_TRAVERSE_STMT(AttributedStmt, {})
1921DEF_TRAVERSE_STMT(NullStmt, {})
1922DEF_TRAVERSE_STMT(ObjCAtCatchStmt, {})
1923DEF_TRAVERSE_STMT(ObjCAtFinallyStmt, {})
1924DEF_TRAVERSE_STMT(ObjCAtSynchronizedStmt, {})
1925DEF_TRAVERSE_STMT(ObjCAtThrowStmt, {})
1926DEF_TRAVERSE_STMT(ObjCAtTryStmt, {})
1927DEF_TRAVERSE_STMT(ObjCForCollectionStmt, {})
1928DEF_TRAVERSE_STMT(ObjCAutoreleasePoolStmt, {})
1929DEF_TRAVERSE_STMT(CXXForRangeStmt, {
1930  if (!getDerived().shouldVisitImplicitCode()) {
1931    TRY_TO(TraverseStmt(S->getLoopVarStmt()));
1932    TRY_TO(TraverseStmt(S->getRangeInit()));
1933    TRY_TO(TraverseStmt(S->getBody()));
1934    // Visit everything else only if shouldVisitImplicitCode().
1935    return true;
1936  }
1937})
1938DEF_TRAVERSE_STMT(MSDependentExistsStmt, {
1939  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
1940  TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
1941})
1942DEF_TRAVERSE_STMT(ReturnStmt, {})
1943DEF_TRAVERSE_STMT(SwitchStmt, {})
1944DEF_TRAVERSE_STMT(WhileStmt, {})
1945
1946DEF_TRAVERSE_STMT(CXXDependentScopeMemberExpr, {
1947  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
1948  TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
1949  if (S->hasExplicitTemplateArgs()) {
1950    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
1951                                              S->getNumTemplateArgs()));
1952  }
1953})
1954
1955DEF_TRAVERSE_STMT(DeclRefExpr, {
1956  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
1957  TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
1958  TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
1959                                            S->getNumTemplateArgs()));
1960})
1961
1962DEF_TRAVERSE_STMT(DependentScopeDeclRefExpr, {
1963  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
1964  TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
1965  if (S->hasExplicitTemplateArgs()) {
1966    TRY_TO(TraverseTemplateArgumentLocsHelper(
1967        S->getExplicitTemplateArgs().getTemplateArgs(),
1968        S->getNumTemplateArgs()));
1969  }
1970})
1971
1972DEF_TRAVERSE_STMT(MemberExpr, {
1973  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
1974  TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
1975  TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
1976                                            S->getNumTemplateArgs()));
1977})
1978
1979DEF_TRAVERSE_STMT(
1980    ImplicitCastExpr,
1981    {// We don't traverse the cast type, as it's not written in the
1982     // source code.
1983    })
1984
1985DEF_TRAVERSE_STMT(CStyleCastExpr, {
1986  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
1987})
1988
1989DEF_TRAVERSE_STMT(CXXFunctionalCastExpr, {
1990  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
1991})
1992
1993DEF_TRAVERSE_STMT(CXXConstCastExpr, {
1994  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
1995})
1996
1997DEF_TRAVERSE_STMT(CXXDynamicCastExpr, {
1998  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
1999})
2000
2001DEF_TRAVERSE_STMT(CXXReinterpretCastExpr, {
2002  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2003})
2004
2005DEF_TRAVERSE_STMT(CXXStaticCastExpr, {
2006  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2007})
2008
2009// InitListExpr is a tricky one, because we want to do all our work on
2010// the syntactic form of the listexpr, but this method takes the
2011// semantic form by default.  We can't use the macro helper because it
2012// calls WalkUp*() on the semantic form, before our code can convert
2013// to the syntactic form.
2014template <typename Derived>
2015bool RecursiveASTVisitor<Derived>::TraverseInitListExpr(InitListExpr *S) {
2016  if (InitListExpr *Syn = S->getSyntacticForm())
2017    S = Syn;
2018  TRY_TO(WalkUpFromInitListExpr(S));
2019  // All we need are the default actions.  FIXME: use a helper function.
2020  for (Stmt::child_range range = S->children(); range; ++range) {
2021    TRY_TO(TraverseStmt(*range));
2022  }
2023  return true;
2024}
2025
2026// GenericSelectionExpr is a special case because the types and expressions
2027// are interleaved.  We also need to watch out for null types (default
2028// generic associations).
2029template <typename Derived>
2030bool RecursiveASTVisitor<Derived>::TraverseGenericSelectionExpr(
2031    GenericSelectionExpr *S) {
2032  TRY_TO(WalkUpFromGenericSelectionExpr(S));
2033  TRY_TO(TraverseStmt(S->getControllingExpr()));
2034  for (unsigned i = 0; i != S->getNumAssocs(); ++i) {
2035    if (TypeSourceInfo *TS = S->getAssocTypeSourceInfo(i))
2036      TRY_TO(TraverseTypeLoc(TS->getTypeLoc()));
2037    TRY_TO(TraverseStmt(S->getAssocExpr(i)));
2038  }
2039  return true;
2040}
2041
2042// PseudoObjectExpr is a special case because of the wierdness with
2043// syntactic expressions and opaque values.
2044template <typename Derived>
2045bool
2046RecursiveASTVisitor<Derived>::TraversePseudoObjectExpr(PseudoObjectExpr *S) {
2047  TRY_TO(WalkUpFromPseudoObjectExpr(S));
2048  TRY_TO(TraverseStmt(S->getSyntacticForm()));
2049  for (PseudoObjectExpr::semantics_iterator i = S->semantics_begin(),
2050                                            e = S->semantics_end();
2051       i != e; ++i) {
2052    Expr *sub = *i;
2053    if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
2054      sub = OVE->getSourceExpr();
2055    TRY_TO(TraverseStmt(sub));
2056  }
2057  return true;
2058}
2059
2060DEF_TRAVERSE_STMT(CXXScalarValueInitExpr, {
2061  // This is called for code like 'return T()' where T is a built-in
2062  // (i.e. non-class) type.
2063  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2064})
2065
2066DEF_TRAVERSE_STMT(CXXNewExpr, {
2067  // The child-iterator will pick up the other arguments.
2068  TRY_TO(TraverseTypeLoc(S->getAllocatedTypeSourceInfo()->getTypeLoc()));
2069})
2070
2071DEF_TRAVERSE_STMT(OffsetOfExpr, {
2072  // The child-iterator will pick up the expression representing
2073  // the field.
2074  // FIMXE: for code like offsetof(Foo, a.b.c), should we get
2075  // making a MemberExpr callbacks for Foo.a, Foo.a.b, and Foo.a.b.c?
2076  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2077})
2078
2079DEF_TRAVERSE_STMT(UnaryExprOrTypeTraitExpr, {
2080  // The child-iterator will pick up the arg if it's an expression,
2081  // but not if it's a type.
2082  if (S->isArgumentType())
2083    TRY_TO(TraverseTypeLoc(S->getArgumentTypeInfo()->getTypeLoc()));
2084})
2085
2086DEF_TRAVERSE_STMT(CXXTypeidExpr, {
2087  // The child-iterator will pick up the arg if it's an expression,
2088  // but not if it's a type.
2089  if (S->isTypeOperand())
2090    TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
2091})
2092
2093DEF_TRAVERSE_STMT(MSPropertyRefExpr, {
2094  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2095})
2096
2097DEF_TRAVERSE_STMT(CXXUuidofExpr, {
2098  // The child-iterator will pick up the arg if it's an expression,
2099  // but not if it's a type.
2100  if (S->isTypeOperand())
2101    TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
2102})
2103
2104DEF_TRAVERSE_STMT(TypeTraitExpr, {
2105  for (unsigned I = 0, N = S->getNumArgs(); I != N; ++I)
2106    TRY_TO(TraverseTypeLoc(S->getArg(I)->getTypeLoc()));
2107})
2108
2109DEF_TRAVERSE_STMT(ArrayTypeTraitExpr, {
2110  TRY_TO(TraverseTypeLoc(S->getQueriedTypeSourceInfo()->getTypeLoc()));
2111})
2112
2113DEF_TRAVERSE_STMT(ExpressionTraitExpr,
2114                  { TRY_TO(TraverseStmt(S->getQueriedExpression())); })
2115
2116DEF_TRAVERSE_STMT(VAArgExpr, {
2117  // The child-iterator will pick up the expression argument.
2118  TRY_TO(TraverseTypeLoc(S->getWrittenTypeInfo()->getTypeLoc()));
2119})
2120
2121DEF_TRAVERSE_STMT(CXXTemporaryObjectExpr, {
2122  // This is called for code like 'return T()' where T is a class type.
2123  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2124})
2125
2126// Walk only the visible parts of lambda expressions.
2127template <typename Derived>
2128bool RecursiveASTVisitor<Derived>::TraverseLambdaExpr(LambdaExpr *S) {
2129  TRY_TO(WalkUpFromLambdaExpr(S));
2130
2131  for (LambdaExpr::capture_iterator C = S->explicit_capture_begin(),
2132                                    CEnd = S->explicit_capture_end();
2133       C != CEnd; ++C) {
2134    TRY_TO(TraverseLambdaCapture(S, C));
2135  }
2136
2137  if (S->hasExplicitParameters() || S->hasExplicitResultType()) {
2138    TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
2139    if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
2140      // Visit the whole type.
2141      TRY_TO(TraverseTypeLoc(TL));
2142    } else if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
2143      if (S->hasExplicitParameters()) {
2144        // Visit parameters.
2145        for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
2146          TRY_TO(TraverseDecl(Proto.getParam(I)));
2147        }
2148      } else {
2149        TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
2150      }
2151    }
2152  }
2153
2154  TRY_TO(TraverseLambdaBody(S));
2155  return true;
2156}
2157
2158DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, {
2159  // This is called for code like 'T()', where T is a template argument.
2160  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2161})
2162
2163// These expressions all might take explicit template arguments.
2164// We traverse those if so.  FIXME: implement these.
2165DEF_TRAVERSE_STMT(CXXConstructExpr, {})
2166DEF_TRAVERSE_STMT(CallExpr, {})
2167DEF_TRAVERSE_STMT(CXXMemberCallExpr, {})
2168
2169// These exprs (most of them), do not need any action except iterating
2170// over the children.
2171DEF_TRAVERSE_STMT(AddrLabelExpr, {})
2172DEF_TRAVERSE_STMT(ArraySubscriptExpr, {})
2173DEF_TRAVERSE_STMT(BlockExpr, {
2174  TRY_TO(TraverseDecl(S->getBlockDecl()));
2175  return true; // no child statements to loop through.
2176})
2177DEF_TRAVERSE_STMT(ChooseExpr, {})
2178DEF_TRAVERSE_STMT(CompoundLiteralExpr, {
2179  TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
2180})
2181DEF_TRAVERSE_STMT(CXXBindTemporaryExpr, {})
2182DEF_TRAVERSE_STMT(CXXBoolLiteralExpr, {})
2183DEF_TRAVERSE_STMT(CXXDefaultArgExpr, {})
2184DEF_TRAVERSE_STMT(CXXDefaultInitExpr, {})
2185DEF_TRAVERSE_STMT(CXXDeleteExpr, {})
2186DEF_TRAVERSE_STMT(ExprWithCleanups, {})
2187DEF_TRAVERSE_STMT(CXXNullPtrLiteralExpr, {})
2188DEF_TRAVERSE_STMT(CXXStdInitializerListExpr, {})
2189DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, {
2190  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2191  if (TypeSourceInfo *ScopeInfo = S->getScopeTypeInfo())
2192    TRY_TO(TraverseTypeLoc(ScopeInfo->getTypeLoc()));
2193  if (TypeSourceInfo *DestroyedTypeInfo = S->getDestroyedTypeInfo())
2194    TRY_TO(TraverseTypeLoc(DestroyedTypeInfo->getTypeLoc()));
2195})
2196DEF_TRAVERSE_STMT(CXXThisExpr, {})
2197DEF_TRAVERSE_STMT(CXXThrowExpr, {})
2198DEF_TRAVERSE_STMT(UserDefinedLiteral, {})
2199DEF_TRAVERSE_STMT(DesignatedInitExpr, {})
2200DEF_TRAVERSE_STMT(ExtVectorElementExpr, {})
2201DEF_TRAVERSE_STMT(GNUNullExpr, {})
2202DEF_TRAVERSE_STMT(ImplicitValueInitExpr, {})
2203DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, {})
2204DEF_TRAVERSE_STMT(ObjCEncodeExpr, {
2205  if (TypeSourceInfo *TInfo = S->getEncodedTypeSourceInfo())
2206    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
2207})
2208DEF_TRAVERSE_STMT(ObjCIsaExpr, {})
2209DEF_TRAVERSE_STMT(ObjCIvarRefExpr, {})
2210DEF_TRAVERSE_STMT(ObjCMessageExpr, {
2211  if (TypeSourceInfo *TInfo = S->getClassReceiverTypeInfo())
2212    TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
2213})
2214DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, {})
2215DEF_TRAVERSE_STMT(ObjCSubscriptRefExpr, {})
2216DEF_TRAVERSE_STMT(ObjCProtocolExpr, {})
2217DEF_TRAVERSE_STMT(ObjCSelectorExpr, {})
2218DEF_TRAVERSE_STMT(ObjCIndirectCopyRestoreExpr, {})
2219DEF_TRAVERSE_STMT(ObjCBridgedCastExpr, {
2220  TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
2221})
2222DEF_TRAVERSE_STMT(ParenExpr, {})
2223DEF_TRAVERSE_STMT(ParenListExpr, {})
2224DEF_TRAVERSE_STMT(PredefinedExpr, {})
2225DEF_TRAVERSE_STMT(ShuffleVectorExpr, {})
2226DEF_TRAVERSE_STMT(ConvertVectorExpr, {})
2227DEF_TRAVERSE_STMT(StmtExpr, {})
2228DEF_TRAVERSE_STMT(UnresolvedLookupExpr, {
2229  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2230  if (S->hasExplicitTemplateArgs()) {
2231    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2232                                              S->getNumTemplateArgs()));
2233  }
2234})
2235
2236DEF_TRAVERSE_STMT(UnresolvedMemberExpr, {
2237  TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
2238  if (S->hasExplicitTemplateArgs()) {
2239    TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
2240                                              S->getNumTemplateArgs()));
2241  }
2242})
2243
2244DEF_TRAVERSE_STMT(SEHTryStmt, {})
2245DEF_TRAVERSE_STMT(SEHExceptStmt, {})
2246DEF_TRAVERSE_STMT(SEHFinallyStmt, {})
2247DEF_TRAVERSE_STMT(CapturedStmt, { TRY_TO(TraverseDecl(S->getCapturedDecl())); })
2248
2249DEF_TRAVERSE_STMT(CXXOperatorCallExpr, {})
2250DEF_TRAVERSE_STMT(OpaqueValueExpr, {})
2251DEF_TRAVERSE_STMT(CUDAKernelCallExpr, {})
2252
2253// These operators (all of them) do not need any action except
2254// iterating over the children.
2255DEF_TRAVERSE_STMT(BinaryConditionalOperator, {})
2256DEF_TRAVERSE_STMT(ConditionalOperator, {})
2257DEF_TRAVERSE_STMT(UnaryOperator, {})
2258DEF_TRAVERSE_STMT(BinaryOperator, {})
2259DEF_TRAVERSE_STMT(CompoundAssignOperator, {})
2260DEF_TRAVERSE_STMT(CXXNoexceptExpr, {})
2261DEF_TRAVERSE_STMT(PackExpansionExpr, {})
2262DEF_TRAVERSE_STMT(SizeOfPackExpr, {})
2263DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmPackExpr, {})
2264DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmExpr, {})
2265DEF_TRAVERSE_STMT(FunctionParmPackExpr, {})
2266DEF_TRAVERSE_STMT(MaterializeTemporaryExpr, {})
2267DEF_TRAVERSE_STMT(AtomicExpr, {})
2268
2269// These literals (all of them) do not need any action.
2270DEF_TRAVERSE_STMT(IntegerLiteral, {})
2271DEF_TRAVERSE_STMT(CharacterLiteral, {})
2272DEF_TRAVERSE_STMT(FloatingLiteral, {})
2273DEF_TRAVERSE_STMT(ImaginaryLiteral, {})
2274DEF_TRAVERSE_STMT(StringLiteral, {})
2275DEF_TRAVERSE_STMT(ObjCStringLiteral, {})
2276DEF_TRAVERSE_STMT(ObjCBoxedExpr, {})
2277DEF_TRAVERSE_STMT(ObjCArrayLiteral, {})
2278DEF_TRAVERSE_STMT(ObjCDictionaryLiteral, {})
2279
2280// Traverse OpenCL: AsType, Convert.
2281DEF_TRAVERSE_STMT(AsTypeExpr, {})
2282
2283// OpenMP directives.
2284template <typename Derived>
2285bool RecursiveASTVisitor<Derived>::TraverseOMPExecutableDirective(
2286    OMPExecutableDirective *S) {
2287  ArrayRef<OMPClause *> Clauses = S->clauses();
2288  for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
2289       I != E; ++I)
2290    if (!TraverseOMPClause(*I))
2291      return false;
2292  return true;
2293}
2294
2295DEF_TRAVERSE_STMT(OMPParallelDirective, {
2296  if (!TraverseOMPExecutableDirective(S))
2297    return false;
2298})
2299
2300DEF_TRAVERSE_STMT(OMPSimdDirective, {
2301  if (!TraverseOMPExecutableDirective(S))
2302    return false;
2303})
2304
2305// OpenMP clauses.
2306template <typename Derived>
2307bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
2308  if (!C)
2309    return true;
2310  switch (C->getClauseKind()) {
2311#define OPENMP_CLAUSE(Name, Class)                                             \
2312  case OMPC_##Name:                                                            \
2313    return getDerived().Visit##Class(static_cast<Class *>(C));
2314#include "clang/Basic/OpenMPKinds.def"
2315  default:
2316    break;
2317  }
2318  return true;
2319}
2320
2321template <typename Derived>
2322bool RecursiveASTVisitor<Derived>::VisitOMPIfClause(OMPIfClause *C) {
2323  TraverseStmt(C->getCondition());
2324  return true;
2325}
2326
2327template <typename Derived>
2328bool
2329RecursiveASTVisitor<Derived>::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
2330  TraverseStmt(C->getNumThreads());
2331  return true;
2332}
2333
2334template<typename Derived>
2335bool RecursiveASTVisitor<Derived>::VisitOMPSafelenClause(OMPSafelenClause *C) {
2336  TraverseStmt(C->getSafelen());
2337  return true;
2338}
2339
2340template <typename Derived>
2341bool RecursiveASTVisitor<Derived>::VisitOMPCollapseClause(OMPCollapseClause *C) {
2342  TraverseStmt(C->getNumForLoops());
2343  return true;
2344}
2345
2346template<typename Derived>
2347bool RecursiveASTVisitor<Derived>::VisitOMPDefaultClause(OMPDefaultClause *C) {
2348  return true;
2349}
2350
2351template <typename Derived>
2352bool
2353RecursiveASTVisitor<Derived>::VisitOMPProcBindClause(OMPProcBindClause *C) {
2354  return true;
2355}
2356
2357template <typename Derived>
2358template <typename T>
2359void RecursiveASTVisitor<Derived>::VisitOMPClauseList(T *Node) {
2360  for (auto *I : Node->varlists())
2361    TraverseStmt(I);
2362}
2363
2364template <typename Derived>
2365bool RecursiveASTVisitor<Derived>::VisitOMPPrivateClause(OMPPrivateClause *C) {
2366  VisitOMPClauseList(C);
2367  return true;
2368}
2369
2370template <typename Derived>
2371bool RecursiveASTVisitor<Derived>::VisitOMPFirstprivateClause(
2372    OMPFirstprivateClause *C) {
2373  VisitOMPClauseList(C);
2374  return true;
2375}
2376
2377template <typename Derived>
2378bool RecursiveASTVisitor<Derived>::VisitOMPSharedClause(OMPSharedClause *C) {
2379  VisitOMPClauseList(C);
2380  return true;
2381}
2382
2383template <typename Derived>
2384bool RecursiveASTVisitor<Derived>::VisitOMPLinearClause(OMPLinearClause *C) {
2385  VisitOMPClauseList(C);
2386  TraverseStmt(C->getStep());
2387  return true;
2388}
2389
2390template <typename Derived>
2391bool RecursiveASTVisitor<Derived>::VisitOMPCopyinClause(OMPCopyinClause *C) {
2392  VisitOMPClauseList(C);
2393  return true;
2394}
2395
2396// FIXME: look at the following tricky-seeming exprs to see if we
2397// need to recurse on anything.  These are ones that have methods
2398// returning decls or qualtypes or nestednamespecifier -- though I'm
2399// not sure if they own them -- or just seemed very complicated, or
2400// had lots of sub-types to explore.
2401//
2402// VisitOverloadExpr and its children: recurse on template args? etc?
2403
2404// FIXME: go through all the stmts and exprs again, and see which of them
2405// create new types, and recurse on the types (TypeLocs?) of those.
2406// Candidates:
2407//
2408//    http://clang.llvm.org/doxygen/classclang_1_1CXXTypeidExpr.html
2409//    http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html
2410//    http://clang.llvm.org/doxygen/classclang_1_1TypesCompatibleExpr.html
2411//    Every class that has getQualifier.
2412
2413#undef DEF_TRAVERSE_STMT
2414
2415#undef TRY_TO
2416
2417} // end namespace clang
2418
2419#endif // LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
2420