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