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