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