RecursiveASTVisitor.h revision ac45ad57f0641b0d556ca27d19a59930925d6add
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/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/Stmt.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.h"
29#include "clang/AST/TemplateBase.h"
30#include "clang/AST/TemplateName.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
33
34// The following three macros are used for meta programming.  The code
35// using them is responsible for defining macro OPERATOR().
36
37// All unary operators.
38#define UNARYOP_LIST()                          \
39  OPERATOR(PostInc)   OPERATOR(PostDec)         \
40  OPERATOR(PreInc)    OPERATOR(PreDec)          \
41  OPERATOR(AddrOf)    OPERATOR(Deref)           \
42  OPERATOR(Plus)      OPERATOR(Minus)           \
43  OPERATOR(Not)       OPERATOR(LNot)            \
44  OPERATOR(Real)      OPERATOR(Imag)            \
45  OPERATOR(Extension)
46
47// All binary operators (excluding compound assign operators).
48#define BINOP_LIST() \
49  OPERATOR(PtrMemD)              OPERATOR(PtrMemI)    \
50  OPERATOR(Mul)   OPERATOR(Div)  OPERATOR(Rem)        \
51  OPERATOR(Add)   OPERATOR(Sub)  OPERATOR(Shl)        \
52  OPERATOR(Shr)                                       \
53                                                      \
54  OPERATOR(LT)    OPERATOR(GT)   OPERATOR(LE)         \
55  OPERATOR(GE)    OPERATOR(EQ)   OPERATOR(NE)         \
56  OPERATOR(And)   OPERATOR(Xor)  OPERATOR(Or)         \
57  OPERATOR(LAnd)  OPERATOR(LOr)                       \
58                                                      \
59  OPERATOR(Assign)                                    \
60  OPERATOR(Comma)
61
62// All compound assign operators.
63#define CAO_LIST()                                                      \
64  OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) \
65  OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or)  OPERATOR(Xor)
66
67namespace clang {
68
69// A helper macro to implement short-circuiting when recursing.  It
70// invokes CALL_EXPR, which must be a method call, on the derived
71// object (s.t. a user of RecursiveASTVisitor can override the method
72// in CALL_EXPR).
73#define TRY_TO(CALL_EXPR) \
74  do { if (!getDerived().CALL_EXPR) return false; } while (0)
75
76/// \brief A class that does preorder depth-first traversal on the
77/// entire Clang AST and visits each node.
78///
79/// This class performs three distinct tasks:
80///   1. traverse the AST (i.e. go to each node);
81///   2. at a given node, walk up the class hierarchy, starting from
82///      the node's dynamic type, until the top-most class (e.g. Stmt,
83///      Decl, or Type) is reached.
84///   3. given a (node, class) combination, where 'class' is some base
85///      class of the dynamic type of 'node', call a user-overridable
86///      function to actually visit the node.
87///
88/// These tasks are done by three groups of methods, respectively:
89///   1. TraverseDecl(Decl *x) does task #1.  It is the entry point
90///      for traversing an AST rooted at x.  This method simply
91///      dispatches (i.e. forwards) to TraverseFoo(Foo *x) where Foo
92///      is the dynamic type of *x, which calls WalkUpFromFoo(x) and
93///      then recursively visits the child nodes of x.
94///      TraverseStmt(Stmt *x) and TraverseType(QualType x) work
95///      similarly.
96///   2. WalkUpFromFoo(Foo *x) does task #2.  It does not try to visit
97///      any child node of x.  Instead, it first calls WalkUpFromBar(x)
98///      where Bar is the direct parent class of Foo (unless Foo has
99///      no parent), and then calls VisitFoo(x) (see the next list item).
100///   3. VisitFoo(Foo *x) does task #3.
101///
102/// These three method groups are tiered (Traverse* > WalkUpFrom* >
103/// Visit*).  A method (e.g. Traverse*) may call methods from the same
104/// tier (e.g. other Traverse*) or one tier lower (e.g. WalkUpFrom*).
105/// It may not call methods from a higher tier.
106///
107/// Note that since WalkUpFromFoo() calls WalkUpFromBar() (where Bar
108/// is Foo's super class) before calling VisitFoo(), the result is
109/// that the Visit*() methods for a given node are called in the
110/// top-down order (e.g. for a node of type NamedDecl, the order will
111/// be VisitDecl(), VisitNamedDecl(), and then VisitNamespaceDecl()).
112///
113/// This scheme guarantees that all Visit*() calls for the same AST
114/// node are grouped together.  In other words, Visit*() methods for
115/// different nodes are never interleaved.
116///
117/// Clients of this visitor should subclass the visitor (providing
118/// themselves as the template argument, using the curiously recurring
119/// template pattern) and override any of the Traverse*, WalkUpFrom*,
120/// and Visit* methods for declarations, types, statements,
121/// expressions, or other AST nodes where the visitor should customize
122/// behavior.  Most users only need to override Visit*.  Advanced
123/// users may override Traverse* and WalkUpFrom* to implement custom
124/// traversal strategies.  Returning false from one of these overridden
125/// functions will abort the entire traversal.
126///
127/// By default, this visitor tries to visit every part of the explicit
128/// source code exactly once.  The default policy towards templates
129/// is to descend into the 'pattern' class or function body, not any
130/// explicit or implicit instantiations.  Explicit specializations
131/// are still visited, and the patterns of partial specializations
132/// are visited separately.  This behavior can be changed by
133/// overriding shouldVisitTemplateInstantiations() in the derived class
134/// to return true, in which case all known implicit and explicit
135/// instantiations will be visited at the same time as the pattern
136/// from which they were produced.
137template<typename Derived>
138class RecursiveASTVisitor {
139public:
140  /// \brief Return a reference to the derived class.
141  Derived &getDerived() { return *static_cast<Derived*>(this); }
142
143  /// \brief Return whether this visitor should recurse into
144  /// template instantiations.
145  bool shouldVisitTemplateInstantiations() const { return false; }
146
147  /// \brief Recursively visit a statement or expression, by
148  /// dispatching to Traverse*() based on the argument's dynamic type.
149  ///
150  /// \returns false if the visitation was terminated early, true
151  /// otherwise (including when the argument is NULL).
152  bool TraverseStmt(Stmt *S);
153
154  /// \brief Recursively visit a type, by dispatching to
155  /// Traverse*Type() based on the argument's getTypeClass() property.
156  ///
157  /// \returns false if the visitation was terminated early, true
158  /// otherwise (including when the argument is a Null type).
159  bool TraverseType(QualType T);
160
161  /// \brief Recursively visit a type with location, by dispatching to
162  /// Traverse*TypeLoc() based on the argument type's getTypeClass() property.
163  ///
164  /// \returns false if the visitation was terminated early, true
165  /// otherwise (including when the argument is a Null type location).
166  bool TraverseTypeLoc(TypeLoc TL);
167
168  /// \brief Recursively visit a declaration, by dispatching to
169  /// Traverse*Decl() based on the argument's dynamic type.
170  ///
171  /// \returns false if the visitation was terminated early, true
172  /// otherwise (including when the argument is NULL).
173  bool TraverseDecl(Decl *D);
174
175  /// \brief Recursively visit a C++ nested-name-specifier.
176  ///
177  /// \returns false if the visitation was terminated early, true otherwise.
178  bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
179
180  /// \brief Recursively visit a template name and dispatch to the
181  /// appropriate method.
182  ///
183  /// \returns false if the visitation was terminated early, true otherwise.
184  bool TraverseTemplateName(TemplateName Template);
185
186  /// \brief Recursively visit a template argument and dispatch to the
187  /// appropriate method for the argument type.
188  ///
189  /// \returns false if the visitation was terminated early, true otherwise.
190  // FIXME: migrate callers to TemplateArgumentLoc instead.
191  bool TraverseTemplateArgument(const TemplateArgument &Arg);
192
193  /// \brief Recursively visit a template argument location and dispatch to the
194  /// appropriate method for the argument type.
195  ///
196  /// \returns false if the visitation was terminated early, true otherwise.
197  bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc);
198
199  /// \brief Recursively visit a set of template arguments.
200  /// This can be overridden by a subclass, but it's not expected that
201  /// will be needed -- this visitor always dispatches to another.
202  ///
203  /// \returns false if the visitation was terminated early, true otherwise.
204  // FIXME: take a TemplateArgumentLoc* (or TemplateArgumentListInfo) instead.
205  bool TraverseTemplateArguments(const TemplateArgument *Args,
206                                 unsigned NumArgs);
207
208  /// \brief Recursively visit a constructor initializer.  This
209  /// automatically dispatches to another visitor for the initializer
210  /// expression, but not for the name of the initializer, so may
211  /// be overridden for clients that need access to the name.
212  ///
213  /// \returns false if the visitation was terminated early, true otherwise.
214  bool TraverseConstructorInitializer(CXXBaseOrMemberInitializer *Init);
215
216  // ---- Methods on Stmts ----
217
218  // Declare Traverse*() for all concrete Stmt classes.
219#define ABSTRACT_STMT(STMT)
220#define STMT(CLASS, PARENT)                                     \
221  bool Traverse##CLASS(CLASS *S);
222#include "clang/AST/StmtNodes.inc"
223  // The above header #undefs ABSTRACT_STMT and STMT upon exit.
224
225  // Define WalkUpFrom*() and empty Visit*() for all Stmt classes.
226  bool WalkUpFromStmt(Stmt *S) { return getDerived().VisitStmt(S); }
227  bool VisitStmt(Stmt *S) { return true; }
228#define STMT(CLASS, PARENT)                                     \
229  bool WalkUpFrom##CLASS(CLASS *S) {                            \
230    TRY_TO(WalkUpFrom##PARENT(S));                              \
231    TRY_TO(Visit##CLASS(S));                                    \
232    return true;                                                \
233  }                                                             \
234  bool Visit##CLASS(CLASS *S) { return true; }
235#include "clang/AST/StmtNodes.inc"
236
237  // Define Traverse*(), WalkUpFrom*(), and Visit*() for unary
238  // operator methods.  Unary operators are not classes in themselves
239  // (they're all opcodes in UnaryOperator) but do have visitors.
240#define OPERATOR(NAME)                                           \
241  bool TraverseUnary##NAME(UnaryOperator *S) {                  \
242    TRY_TO(WalkUpFromUnary##NAME(S));                           \
243    TRY_TO(TraverseStmt(S->getSubExpr()));                      \
244    return true;                                                \
245  }                                                             \
246  bool WalkUpFromUnary##NAME(UnaryOperator *S) {                \
247    TRY_TO(WalkUpFromUnaryOperator(S));                         \
248    TRY_TO(VisitUnary##NAME(S));                                \
249    return true;                                                \
250  }                                                             \
251  bool VisitUnary##NAME(UnaryOperator *S) { return true; }
252
253  UNARYOP_LIST()
254#undef OPERATOR
255
256  // Define Traverse*(), WalkUpFrom*(), and Visit*() for binary
257  // operator methods.  Binary operators are not classes in themselves
258  // (they're all opcodes in BinaryOperator) but do have visitors.
259#define GENERAL_BINOP_FALLBACK(NAME, BINOP_TYPE)                \
260  bool TraverseBin##NAME(BINOP_TYPE *S) {                       \
261    TRY_TO(WalkUpFromBin##NAME(S));                             \
262    TRY_TO(TraverseStmt(S->getLHS()));                          \
263    TRY_TO(TraverseStmt(S->getRHS()));                          \
264    return true;                                                \
265  }                                                             \
266  bool WalkUpFromBin##NAME(BINOP_TYPE *S) {                     \
267    TRY_TO(WalkUpFrom##BINOP_TYPE(S));                          \
268    TRY_TO(VisitBin##NAME(S));                                  \
269    return true;                                                \
270  }                                                             \
271  bool VisitBin##NAME(BINOP_TYPE *S) { return true; }
272
273#define OPERATOR(NAME) GENERAL_BINOP_FALLBACK(NAME, BinaryOperator)
274  BINOP_LIST()
275#undef OPERATOR
276
277  // Define Traverse*(), WalkUpFrom*(), and Visit*() for compound
278  // assignment methods.  Compound assignment operators are not
279  // classes in themselves (they're all opcodes in
280  // CompoundAssignOperator) but do have visitors.
281#define OPERATOR(NAME) \
282  GENERAL_BINOP_FALLBACK(NAME##Assign, CompoundAssignOperator)
283
284  CAO_LIST()
285#undef OPERATOR
286#undef GENERAL_BINOP_FALLBACK
287
288  // ---- Methods on Types ----
289  // FIXME: revamp to take TypeLoc's rather than Types.
290
291  // Declare Traverse*() for all concrete Type classes.
292#define ABSTRACT_TYPE(CLASS, BASE)
293#define TYPE(CLASS, BASE) \
294  bool Traverse##CLASS##Type(CLASS##Type *T);
295#include "clang/AST/TypeNodes.def"
296  // The above header #undefs ABSTRACT_TYPE and TYPE upon exit.
297
298  // Define WalkUpFrom*() and empty Visit*() for all Type classes.
299  bool WalkUpFromType(Type *T) { return getDerived().VisitType(T); }
300  bool VisitType(Type *T) { return true; }
301#define TYPE(CLASS, BASE)                                       \
302  bool WalkUpFrom##CLASS##Type(CLASS##Type *T) {                \
303    TRY_TO(WalkUpFrom##BASE(T));                                \
304    TRY_TO(Visit##CLASS##Type(T));                              \
305    return true;                                                \
306  }                                                             \
307  bool Visit##CLASS##Type(CLASS##Type *T) { return true; }
308#include "clang/AST/TypeNodes.def"
309
310  // ---- Methods on TypeLocs ----
311  // FIXME: this currently just calls the matching Type methods
312
313  // Declare Traverse*() for all concrete Type classes.
314#define ABSTRACT_TYPELOC(CLASS, BASE)
315#define TYPELOC(CLASS, BASE) \
316  bool Traverse##CLASS##TypeLoc(CLASS##TypeLoc TL);
317#include "clang/AST/TypeLocNodes.def"
318  // The above header #undefs ABSTRACT_TYPELOC and TYPELOC upon exit.
319
320  // Define WalkUpFrom*() and empty Visit*() for all TypeLoc classes.
321  bool WalkUpFromTypeLoc(TypeLoc TL) { return getDerived().VisitTypeLoc(TL); }
322  bool VisitTypeLoc(TypeLoc TL) { return true; }
323
324  // QualifiedTypeLoc and UnqualTypeLoc are not declared in
325  // TypeNodes.def and thus need to be handled specially.
326  bool WalkUpFromQualifiedTypeLoc(QualifiedTypeLoc TL) {
327    return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
328  }
329  bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return true; }
330  bool WalkUpFromUnqualTypeLoc(UnqualTypeLoc TL) {
331    return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
332  }
333  bool VisitUnqualTypeLoc(UnqualTypeLoc TL) { return true; }
334
335  // Note that BASE includes trailing 'Type' which CLASS doesn't.
336#define TYPE(CLASS, BASE)                                       \
337  bool WalkUpFrom##CLASS##TypeLoc(CLASS##TypeLoc TL) {          \
338    TRY_TO(WalkUpFrom##BASE##Loc(TL));                          \
339    TRY_TO(Visit##CLASS##TypeLoc(TL));                          \
340    return true;                                                \
341  }                                                             \
342  bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { return true; }
343#include "clang/AST/TypeNodes.def"
344
345  // ---- Methods on Decls ----
346
347  // Declare Traverse*() for all concrete Decl classes.
348#define ABSTRACT_DECL(DECL)
349#define DECL(CLASS, BASE) \
350  bool Traverse##CLASS##Decl(CLASS##Decl *D);
351#include "clang/AST/DeclNodes.inc"
352  // The above header #undefs ABSTRACT_DECL and DECL upon exit.
353
354  // Define WalkUpFrom*() and empty Visit*() for all Decl classes.
355  bool WalkUpFromDecl(Decl *D) { return getDerived().VisitDecl(D); }
356  bool VisitDecl(Decl *D) { return true; }
357#define DECL(CLASS, BASE)                                       \
358  bool WalkUpFrom##CLASS##Decl(CLASS##Decl *D) {                \
359    TRY_TO(WalkUpFrom##BASE(D));                                \
360    TRY_TO(Visit##CLASS##Decl(D));                              \
361    return true;                                                \
362  }                                                             \
363  bool Visit##CLASS##Decl(CLASS##Decl *D) { return true; }
364#include "clang/AST/DeclNodes.inc"
365
366private:
367  // These are helper methods used by more than one Traverse* method.
368  bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
369  bool TraverseClassInstantiations(ClassTemplateDecl* D, Decl *Pattern);
370  bool TraverseFunctionInstantiations(FunctionTemplateDecl* D) ;
371  bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL,
372                                          unsigned Count);
373  bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL);
374  bool TraverseRecordHelper(RecordDecl *D);
375  bool TraverseCXXRecordHelper(CXXRecordDecl *D);
376  bool TraverseDeclaratorHelper(DeclaratorDecl *D);
377  bool TraverseDeclContextHelper(DeclContext *DC);
378  bool TraverseFunctionHelper(FunctionDecl *D);
379  bool TraverseVarHelper(VarDecl *D);
380};
381
382#define DISPATCH(NAME, CLASS, VAR) \
383  return getDerived().Traverse##NAME(static_cast<CLASS*>(VAR))
384
385template<typename Derived>
386bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S) {
387  if (!S)
388    return true;
389
390  // If we have a binary expr, dispatch to the subcode of the binop.  A smart
391  // optimizer (e.g. LLVM) will fold this comparison into the switch stmt
392  // below.
393  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
394    switch (BinOp->getOpcode()) {
395#define OPERATOR(NAME) \
396    case BO_##NAME: DISPATCH(Bin##PtrMemD, BinaryOperator, S);
397
398    BINOP_LIST()
399#undef OPERATOR
400#undef BINOP_LIST
401
402#define OPERATOR(NAME)                                          \
403    case BO_##NAME##Assign:                          \
404      DISPATCH(Bin##NAME##Assign, CompoundAssignOperator, S);
405
406    CAO_LIST()
407#undef OPERATOR
408#undef CAO_LIST
409    }
410  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
411    switch (UnOp->getOpcode()) {
412#define OPERATOR(NAME)                                                  \
413    case UO_##NAME: DISPATCH(Unary##NAME, UnaryOperator, S);
414
415    UNARYOP_LIST()
416#undef OPERATOR
417#undef UNARYOP_LIST
418    }
419  }
420
421  // Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
422  switch (S->getStmtClass()) {
423  case Stmt::NoStmtClass: break;
424#define ABSTRACT_STMT(STMT)
425#define STMT(CLASS, PARENT) \
426  case Stmt::CLASS##Class: DISPATCH(CLASS, CLASS, S);
427#include "clang/AST/StmtNodes.inc"
428  }
429
430  return true;
431}
432
433template<typename Derived>
434bool RecursiveASTVisitor<Derived>::TraverseType(QualType T) {
435  if (T.isNull())
436    return true;
437
438  switch (T->getTypeClass()) {
439#define ABSTRACT_TYPE(CLASS, BASE)
440#define TYPE(CLASS, BASE) \
441  case Type::CLASS: DISPATCH(CLASS##Type, CLASS##Type, T.getTypePtr());
442#include "clang/AST/TypeNodes.def"
443  }
444
445  return true;
446}
447
448template<typename Derived>
449bool RecursiveASTVisitor<Derived>::TraverseTypeLoc(TypeLoc TL) {
450  if (TL.isNull())
451    return true;
452
453  switch (TL.getTypeLocClass()) {
454#define ABSTRACT_TYPELOC(CLASS, BASE)
455#define TYPELOC(CLASS, BASE) \
456  case TypeLoc::CLASS: \
457    return getDerived().Traverse##CLASS##TypeLoc(*cast<CLASS##TypeLoc>(&TL));
458#include "clang/AST/TypeLocNodes.def"
459  }
460
461  return true;
462}
463
464
465template<typename Derived>
466bool RecursiveASTVisitor<Derived>::TraverseDecl(Decl *D) {
467  if (!D)
468    return true;
469
470  // As a syntax visitor, we want to ignore declarations for
471  // implicitly-defined declarations (ones not typed explicitly by the
472  // user).
473  if (D->isImplicit())
474    return true;
475
476  switch (D->getKind()) {
477#define ABSTRACT_DECL(DECL)
478#define DECL(CLASS, BASE) \
479  case Decl::CLASS: DISPATCH(CLASS##Decl, CLASS##Decl, D);
480#include "clang/AST/DeclNodes.inc"
481 }
482
483  return true;
484}
485
486#undef DISPATCH
487
488template<typename Derived>
489bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifier(
490                                                    NestedNameSpecifier *NNS) {
491  if (!NNS)
492    return true;
493
494  if (NNS->getPrefix())
495    TRY_TO(TraverseNestedNameSpecifier(NNS->getPrefix()));
496
497  switch (NNS->getKind()) {
498  case NestedNameSpecifier::Identifier:
499  case NestedNameSpecifier::Namespace:
500  case NestedNameSpecifier::Global:
501    return true;
502
503  case NestedNameSpecifier::TypeSpec:
504  case NestedNameSpecifier::TypeSpecWithTemplate:
505    TRY_TO(TraverseType(QualType(NNS->getAsType(), 0)));
506  }
507
508  return true;
509}
510
511template<typename Derived>
512bool RecursiveASTVisitor<Derived>::TraverseTemplateName(TemplateName Template) {
513  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
514    TRY_TO(TraverseNestedNameSpecifier(DTN->getQualifier()));
515  else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
516    TRY_TO(TraverseNestedNameSpecifier(QTN->getQualifier()));
517
518  return true;
519}
520
521template<typename Derived>
522bool RecursiveASTVisitor<Derived>::TraverseTemplateArgument(
523                                                const TemplateArgument &Arg) {
524  switch (Arg.getKind()) {
525  case TemplateArgument::Null:
526  case TemplateArgument::Declaration:
527  case TemplateArgument::Integral:
528    return true;
529
530  case TemplateArgument::Type:
531    return getDerived().TraverseType(Arg.getAsType());
532
533  case TemplateArgument::Template:
534    return getDerived().TraverseTemplateName(Arg.getAsTemplate());
535
536  case TemplateArgument::Expression:
537    return getDerived().TraverseStmt(Arg.getAsExpr());
538
539  case TemplateArgument::Pack:
540    return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
541                                                  Arg.pack_size());
542  }
543
544  return true;
545}
546
547// FIXME: no template name location?
548// FIXME: no source locations for a template argument pack?
549template<typename Derived>
550bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLoc(
551                                           const TemplateArgumentLoc &ArgLoc) {
552  const TemplateArgument &Arg = ArgLoc.getArgument();
553
554  switch (Arg.getKind()) {
555  case TemplateArgument::Null:
556  case TemplateArgument::Declaration:
557  case TemplateArgument::Integral:
558    return true;
559
560  case TemplateArgument::Type: {
561    // FIXME: how can TSI ever be NULL?
562    if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo())
563      return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
564    else
565      return true;
566  }
567
568  case TemplateArgument::Template:
569    return getDerived().TraverseTemplateName(Arg.getAsTemplate());
570
571  case TemplateArgument::Expression:
572    return getDerived().TraverseStmt(ArgLoc.getSourceExpression());
573
574  case TemplateArgument::Pack:
575    return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
576                                                  Arg.pack_size());
577  }
578
579  return true;
580}
581
582template<typename Derived>
583bool RecursiveASTVisitor<Derived>::TraverseTemplateArguments(
584                                                  const TemplateArgument *Args,
585                                                            unsigned NumArgs) {
586  for (unsigned I = 0; I != NumArgs; ++I) {
587    TRY_TO(TraverseTemplateArgument(Args[I]));
588  }
589
590  return true;
591}
592
593template<typename Derived>
594bool RecursiveASTVisitor<Derived>::TraverseConstructorInitializer(
595                                            CXXBaseOrMemberInitializer *Init) {
596  // FIXME: recurse on TypeLoc of the base initializer if isBaseInitializer()?
597  if (Init->isWritten())
598    TRY_TO(TraverseStmt(Init->getInit()));
599  return true;
600}
601
602
603// ----------------- Type traversal -----------------
604
605// This macro makes available a variable T, the passed-in type.
606#define DEF_TRAVERSE_TYPE(TYPE, CODE)                     \
607  template<typename Derived>                                           \
608  bool RecursiveASTVisitor<Derived>::Traverse##TYPE (TYPE *T) {        \
609    TRY_TO(WalkUpFrom##TYPE (T));                                      \
610    { CODE; }                                                          \
611    return true;                                                       \
612  }
613
614DEF_TRAVERSE_TYPE(BuiltinType, { })
615
616DEF_TRAVERSE_TYPE(ComplexType, {
617    TRY_TO(TraverseType(T->getElementType()));
618  })
619
620DEF_TRAVERSE_TYPE(PointerType, {
621    TRY_TO(TraverseType(T->getPointeeType()));
622  })
623
624DEF_TRAVERSE_TYPE(BlockPointerType, {
625    TRY_TO(TraverseType(T->getPointeeType()));
626  })
627
628DEF_TRAVERSE_TYPE(LValueReferenceType, {
629    TRY_TO(TraverseType(T->getPointeeType()));
630  })
631
632DEF_TRAVERSE_TYPE(RValueReferenceType, {
633    TRY_TO(TraverseType(T->getPointeeType()));
634  })
635
636DEF_TRAVERSE_TYPE(MemberPointerType, {
637    TRY_TO(TraverseType(QualType(T->getClass(), 0)));
638    TRY_TO(TraverseType(T->getPointeeType()));
639  })
640
641DEF_TRAVERSE_TYPE(ConstantArrayType, {
642    TRY_TO(TraverseType(T->getElementType()));
643  })
644
645DEF_TRAVERSE_TYPE(IncompleteArrayType, {
646    TRY_TO(TraverseType(T->getElementType()));
647  })
648
649DEF_TRAVERSE_TYPE(VariableArrayType, {
650    TRY_TO(TraverseType(T->getElementType()));
651    TRY_TO(TraverseStmt(T->getSizeExpr()));
652  })
653
654DEF_TRAVERSE_TYPE(DependentSizedArrayType, {
655    TRY_TO(TraverseType(T->getElementType()));
656    if (T->getSizeExpr())
657      TRY_TO(TraverseStmt(T->getSizeExpr()));
658  })
659
660DEF_TRAVERSE_TYPE(DependentSizedExtVectorType, {
661    if (T->getSizeExpr())
662      TRY_TO(TraverseStmt(T->getSizeExpr()));
663    TRY_TO(TraverseType(T->getElementType()));
664  })
665
666DEF_TRAVERSE_TYPE(VectorType, {
667    TRY_TO(TraverseType(T->getElementType()));
668  })
669
670DEF_TRAVERSE_TYPE(ExtVectorType, {
671    TRY_TO(TraverseType(T->getElementType()));
672  })
673
674DEF_TRAVERSE_TYPE(FunctionNoProtoType, {
675    TRY_TO(TraverseType(T->getResultType()));
676  })
677
678DEF_TRAVERSE_TYPE(FunctionProtoType, {
679    TRY_TO(TraverseType(T->getResultType()));
680
681    for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
682                                           AEnd = T->arg_type_end();
683         A != AEnd; ++A) {
684      TRY_TO(TraverseType(*A));
685    }
686
687    for (FunctionProtoType::exception_iterator E = T->exception_begin(),
688                                            EEnd = T->exception_end();
689         E != EEnd; ++E) {
690      TRY_TO(TraverseType(*E));
691    }
692  })
693
694DEF_TRAVERSE_TYPE(UnresolvedUsingType, { })
695DEF_TRAVERSE_TYPE(TypedefType, { })
696
697DEF_TRAVERSE_TYPE(TypeOfExprType, {
698    TRY_TO(TraverseStmt(T->getUnderlyingExpr()));
699  })
700
701DEF_TRAVERSE_TYPE(TypeOfType, {
702    TRY_TO(TraverseType(T->getUnderlyingType()));
703  })
704
705DEF_TRAVERSE_TYPE(DecltypeType, {
706    TRY_TO(TraverseStmt(T->getUnderlyingExpr()));
707  })
708
709DEF_TRAVERSE_TYPE(RecordType, { })
710DEF_TRAVERSE_TYPE(EnumType, { })
711DEF_TRAVERSE_TYPE(TemplateTypeParmType, { })
712DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, { })
713
714DEF_TRAVERSE_TYPE(TemplateSpecializationType, {
715    TRY_TO(TraverseTemplateName(T->getTemplateName()));
716    TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
717  })
718
719DEF_TRAVERSE_TYPE(InjectedClassNameType, { })
720
721DEF_TRAVERSE_TYPE(ElaboratedType, {
722    if (T->getQualifier()) {
723      TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
724    }
725    TRY_TO(TraverseType(T->getNamedType()));
726  })
727
728DEF_TRAVERSE_TYPE(DependentNameType, {
729    TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
730  })
731
732DEF_TRAVERSE_TYPE(DependentTemplateSpecializationType, {
733    TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
734    TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
735  })
736
737DEF_TRAVERSE_TYPE(ObjCInterfaceType, { })
738
739DEF_TRAVERSE_TYPE(ObjCObjectType, {
740    // We have to watch out here because an ObjCInterfaceType's base
741    // type is itself.
742    if (T->getBaseType().getTypePtr() != T)
743      TRY_TO(TraverseType(T->getBaseType()));
744  })
745
746DEF_TRAVERSE_TYPE(ObjCObjectPointerType, {
747    TRY_TO(TraverseType(T->getPointeeType()));
748  })
749
750#undef DEF_TRAVERSE_TYPE
751
752// ----------------- TypeLoc traversal -----------------
753
754// This macro makes available a variable TL, the passed-in TypeLoc.
755// It calls WalkUpFrom* for the Type in the given TypeLoc, in addition
756// to WalkUpFrom* for the TypeLoc itself, such that existing clients
757// that override the WalkUpFrom*Type() and/or Visit*Type() methods
758// continue to work.
759#define DEF_TRAVERSE_TYPELOC(TYPE, CODE)                                \
760  template<typename Derived>                                            \
761  bool RecursiveASTVisitor<Derived>::Traverse##TYPE##Loc(TYPE##Loc TL) { \
762    TRY_TO(WalkUpFrom##TYPE(TL.getTypePtr()));                          \
763    TRY_TO(WalkUpFrom##TYPE##Loc(TL));                                  \
764    { CODE; }                                                           \
765    return true;                                                        \
766  }
767
768template<typename Derived>
769bool RecursiveASTVisitor<Derived>::TraverseQualifiedTypeLoc(
770    QualifiedTypeLoc TL) {
771  // Move this over to the 'main' typeloc tree.  Note that this is a
772  // move -- we pretend that we were really looking at the unqualified
773  // typeloc all along -- rather than a recursion, so we don't follow
774  // the normal CRTP plan of going through
775  // getDerived().TraverseTypeLoc.  If we did, we'd be traversing
776  // twice for the same type (once as a QualifiedTypeLoc version of
777  // the type, once as an UnqualifiedTypeLoc version of the type),
778  // which in effect means we'd call VisitTypeLoc twice with the
779  // 'same' type.  This solves that problem, at the cost of never
780  // seeing the qualified version of the type (unless the client
781  // subclasses TraverseQualifiedTypeLoc themselves).  It's not a
782  // perfect solution.  A perfect solution probably requires making
783  // QualifiedTypeLoc a wrapper around TypeLoc -- like QualType is a
784  // wrapper around Type* -- rather than being its own class in the
785  // type hierarchy.
786  return TraverseTypeLoc(TL.getUnqualifiedLoc());
787}
788
789DEF_TRAVERSE_TYPELOC(BuiltinType, { })
790
791// FIXME: ComplexTypeLoc is unfinished
792DEF_TRAVERSE_TYPELOC(ComplexType, {
793    TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
794  })
795
796DEF_TRAVERSE_TYPELOC(PointerType, {
797    TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
798  })
799
800DEF_TRAVERSE_TYPELOC(BlockPointerType, {
801    TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
802  })
803
804DEF_TRAVERSE_TYPELOC(LValueReferenceType, {
805    TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
806  })
807
808DEF_TRAVERSE_TYPELOC(RValueReferenceType, {
809    TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
810  })
811
812// FIXME: location of base class?
813// We traverse this in the type case as well, but how is it not reached through
814// the pointee type?
815DEF_TRAVERSE_TYPELOC(MemberPointerType, {
816    TRY_TO(TraverseType(QualType(TL.getTypePtr()->getClass(), 0)));
817    TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
818  })
819
820template<typename Derived>
821bool RecursiveASTVisitor<Derived>::TraverseArrayTypeLocHelper(ArrayTypeLoc TL) {
822  // This isn't available for ArrayType, but is for the ArrayTypeLoc.
823  TRY_TO(TraverseStmt(TL.getSizeExpr()));
824  return true;
825}
826
827DEF_TRAVERSE_TYPELOC(ConstantArrayType, {
828    TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
829    return TraverseArrayTypeLocHelper(TL);
830  })
831
832DEF_TRAVERSE_TYPELOC(IncompleteArrayType, {
833    TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
834    return TraverseArrayTypeLocHelper(TL);
835  })
836
837DEF_TRAVERSE_TYPELOC(VariableArrayType, {
838    TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
839    return TraverseArrayTypeLocHelper(TL);
840  })
841
842DEF_TRAVERSE_TYPELOC(DependentSizedArrayType, {
843    TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
844    return TraverseArrayTypeLocHelper(TL);
845  })
846
847// FIXME: order? why not size expr first?
848// FIXME: base VectorTypeLoc is unfinished
849DEF_TRAVERSE_TYPELOC(DependentSizedExtVectorType, {
850    if (TL.getTypePtr()->getSizeExpr())
851      TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
852    TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
853  })
854
855// FIXME: VectorTypeLoc is unfinished
856DEF_TRAVERSE_TYPELOC(VectorType, {
857    TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
858  })
859
860// FIXME: size and attributes
861// FIXME: base VectorTypeLoc is unfinished
862DEF_TRAVERSE_TYPELOC(ExtVectorType, {
863    TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
864  })
865
866DEF_TRAVERSE_TYPELOC(FunctionNoProtoType, {
867    TRY_TO(TraverseTypeLoc(TL.getResultLoc()));
868  })
869
870// FIXME: location of arguments, exception specifications (attributes?)
871// Note that we have the ParmVarDecl's here. Do we want to use them?
872DEF_TRAVERSE_TYPELOC(FunctionProtoType, {
873    TRY_TO(TraverseTypeLoc(TL.getResultLoc()));
874
875    FunctionProtoType *T = TL.getTypePtr();
876/*
877    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
878      TRY_TO(TraverseDecl(TL.getArg(I)));
879    }
880*/
881    for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
882                                           AEnd = T->arg_type_end();
883         A != AEnd; ++A) {
884      TRY_TO(TraverseType(*A));
885    }
886    for (FunctionProtoType::exception_iterator E = T->exception_begin(),
887                                            EEnd = T->exception_end();
888         E != EEnd; ++E) {
889      TRY_TO(TraverseType(*E));
890    }
891  })
892
893DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, { })
894DEF_TRAVERSE_TYPELOC(TypedefType, { })
895
896DEF_TRAVERSE_TYPELOC(TypeOfExprType, {
897    TRY_TO(TraverseStmt(TL.getUnderlyingExpr()));
898  })
899
900DEF_TRAVERSE_TYPELOC(TypeOfType, {
901    TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
902  })
903
904// FIXME: location of underlying expr
905DEF_TRAVERSE_TYPELOC(DecltypeType, {
906    TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr()));
907  })
908
909DEF_TRAVERSE_TYPELOC(RecordType, { })
910DEF_TRAVERSE_TYPELOC(EnumType, { })
911DEF_TRAVERSE_TYPELOC(TemplateTypeParmType, { })
912DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmType, { })
913
914// FIXME: use the loc for the template name?
915DEF_TRAVERSE_TYPELOC(TemplateSpecializationType, {
916    TRY_TO(TraverseTemplateName(TL.getTypePtr()->getTemplateName()));
917    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
918      TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
919    }
920  })
921
922DEF_TRAVERSE_TYPELOC(InjectedClassNameType, { })
923
924// FIXME: use the sourceloc on qualifier?
925DEF_TRAVERSE_TYPELOC(ElaboratedType, {
926    if (TL.getTypePtr()->getQualifier()) {
927      TRY_TO(TraverseNestedNameSpecifier(TL.getTypePtr()->getQualifier()));
928    }
929    TRY_TO(TraverseTypeLoc(TL.getNamedTypeLoc()));
930  })
931
932// FIXME: use the sourceloc on qualifier?
933DEF_TRAVERSE_TYPELOC(DependentNameType, {
934    TRY_TO(TraverseNestedNameSpecifier(TL.getTypePtr()->getQualifier()));
935  })
936
937DEF_TRAVERSE_TYPELOC(DependentTemplateSpecializationType, {
938    TRY_TO(TraverseNestedNameSpecifier(TL.getTypePtr()->getQualifier()));
939    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
940      TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
941    }
942  })
943
944DEF_TRAVERSE_TYPELOC(ObjCInterfaceType, { })
945
946DEF_TRAVERSE_TYPELOC(ObjCObjectType, {
947    // We have to watch out here because an ObjCInterfaceType's base
948    // type is itself.
949    if (TL.getTypePtr()->getBaseType().getTypePtr() != TL.getTypePtr())
950      TRY_TO(TraverseTypeLoc(TL.getBaseLoc()));
951  })
952
953DEF_TRAVERSE_TYPELOC(ObjCObjectPointerType, {
954    TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
955  })
956
957#undef DEF_TRAVERSE_TYPELOC
958
959// ----------------- Decl traversal -----------------
960//
961// For a Decl, we automate (in the DEF_TRAVERSE_DECL macro) traversing
962// the children that come from the DeclContext associated with it.
963// Therefore each Traverse* only needs to worry about children other
964// than those.
965
966template<typename Derived>
967bool RecursiveASTVisitor<Derived>::TraverseDeclContextHelper(DeclContext *DC) {
968  if (!DC)
969    return true;
970
971  for (DeclContext::decl_iterator Child = DC->decls_begin(),
972           ChildEnd = DC->decls_end();
973       Child != ChildEnd; ++Child) {
974    TRY_TO(TraverseDecl(*Child));
975  }
976
977  return true;
978}
979
980// This macro makes available a variable D, the passed-in decl.
981#define DEF_TRAVERSE_DECL(DECL, CODE)                           \
982template<typename Derived>                                      \
983bool RecursiveASTVisitor<Derived>::Traverse##DECL (DECL *D) {   \
984  TRY_TO(WalkUpFrom##DECL (D));                                 \
985  { CODE; }                                                     \
986  TRY_TO(TraverseDeclContextHelper(dyn_cast<DeclContext>(D)));  \
987  return true;                                                  \
988}
989
990DEF_TRAVERSE_DECL(AccessSpecDecl, { })
991
992DEF_TRAVERSE_DECL(BlockDecl, {
993    // We don't traverse nodes in param_begin()/param_end(), as they
994    // appear in decls_begin()/decls_end() and thus are handled by the
995    // DEF_TRAVERSE_DECL macro already.
996    TRY_TO(TraverseStmt(D->getBody()));
997  })
998
999DEF_TRAVERSE_DECL(FileScopeAsmDecl, {
1000    TRY_TO(TraverseStmt(D->getAsmString()));
1001  })
1002
1003DEF_TRAVERSE_DECL(FriendDecl, {
1004    TRY_TO(TraverseDecl(D->getFriendDecl()));
1005  })
1006
1007DEF_TRAVERSE_DECL(FriendTemplateDecl, {
1008    TRY_TO(TraverseDecl(D->getFriendDecl()));
1009    for (unsigned I = 0, E = D->getNumTemplateParameters(); I < E; ++I) {
1010      TemplateParameterList *TPL = D->getTemplateParameterList(I);
1011      for (TemplateParameterList::iterator ITPL = TPL->begin(),
1012                                           ETPL = TPL->end();
1013           ITPL != ETPL; ++ITPL) {
1014        TRY_TO(TraverseDecl(*ITPL));
1015      }
1016    }
1017  })
1018
1019DEF_TRAVERSE_DECL(LinkageSpecDecl, { })
1020
1021DEF_TRAVERSE_DECL(ObjCClassDecl, {
1022    // FIXME: implement this
1023  })
1024
1025DEF_TRAVERSE_DECL(ObjCForwardProtocolDecl, {
1026    // FIXME: implement this
1027  })
1028
1029DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {
1030    // FIXME: implement this
1031  })
1032
1033DEF_TRAVERSE_DECL(StaticAssertDecl, {
1034    TRY_TO(TraverseStmt(D->getAssertExpr()));
1035    TRY_TO(TraverseStmt(D->getMessage()));
1036  })
1037
1038DEF_TRAVERSE_DECL(TranslationUnitDecl, {
1039    // Code in an unnamed namespace shows up automatically in
1040    // decls_begin()/decls_end().  Thus we don't need to recurse on
1041    // D->getAnonymousNamespace().
1042  })
1043
1044DEF_TRAVERSE_DECL(NamespaceAliasDecl, {
1045    // We shouldn't traverse an aliased namespace, since it will be
1046    // defined (and, therefore, traversed) somewhere else.
1047    //
1048    // This return statement makes sure the traversal of nodes in
1049    // decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
1050    // is skipped - don't remove it.
1051    return true;
1052  })
1053
1054DEF_TRAVERSE_DECL(NamespaceDecl, {
1055    // Code in an unnamed namespace shows up automatically in
1056    // decls_begin()/decls_end().  Thus we don't need to recurse on
1057    // D->getAnonymousNamespace().
1058  })
1059
1060DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, {
1061    // FIXME: implement
1062  })
1063
1064DEF_TRAVERSE_DECL(ObjCCategoryDecl, {
1065    // FIXME: implement
1066  })
1067
1068DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, {
1069    // FIXME: implement
1070  })
1071
1072DEF_TRAVERSE_DECL(ObjCImplementationDecl, {
1073    // FIXME: implement
1074  })
1075
1076DEF_TRAVERSE_DECL(ObjCInterfaceDecl, {
1077    // FIXME: implement
1078  })
1079
1080DEF_TRAVERSE_DECL(ObjCProtocolDecl, {
1081    // FIXME: implement
1082  })
1083
1084DEF_TRAVERSE_DECL(ObjCMethodDecl, {
1085    // FIXME: implement
1086  })
1087
1088DEF_TRAVERSE_DECL(ObjCPropertyDecl, {
1089    // FIXME: implement
1090  })
1091
1092DEF_TRAVERSE_DECL(UsingDecl, {
1093    TRY_TO(TraverseNestedNameSpecifier(D->getTargetNestedNameDecl()));
1094  })
1095
1096DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
1097    TRY_TO(TraverseNestedNameSpecifier(D->getQualifier()));
1098  })
1099
1100DEF_TRAVERSE_DECL(UsingShadowDecl, { })
1101
1102// A helper method for TemplateDecl's children.
1103template<typename Derived>
1104bool RecursiveASTVisitor<Derived>::TraverseTemplateParameterListHelper(
1105    TemplateParameterList *TPL) {
1106  if (TPL) {
1107    for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();
1108         I != E; ++I) {
1109      TRY_TO(TraverseDecl(*I));
1110    }
1111  }
1112  return true;
1113}
1114
1115// A helper method for traversing the implicit instantiations of a
1116// class.
1117template<typename Derived>
1118bool RecursiveASTVisitor<Derived>::TraverseClassInstantiations(
1119  ClassTemplateDecl* D, Decl *Pattern) {
1120  assert(isa<ClassTemplateDecl>(Pattern) ||
1121         isa<ClassTemplatePartialSpecializationDecl>(Pattern));
1122
1123  ClassTemplateDecl::spec_iterator end = D->spec_end();
1124  for (ClassTemplateDecl::spec_iterator it = D->spec_begin(); it != end; ++it) {
1125    ClassTemplateSpecializationDecl* SD = *it;
1126
1127    switch (SD->getSpecializationKind()) {
1128    // Visit the implicit instantiations with the requested pattern.
1129    case TSK_ImplicitInstantiation: {
1130      llvm::PointerUnion<ClassTemplateDecl *,
1131                         ClassTemplatePartialSpecializationDecl *> U
1132        = SD->getInstantiatedFrom();
1133
1134      bool ShouldVisit;
1135      if (U.is<ClassTemplateDecl*>())
1136        ShouldVisit = (U.get<ClassTemplateDecl*>() == Pattern);
1137      else
1138        ShouldVisit
1139          = (U.get<ClassTemplatePartialSpecializationDecl*>() == Pattern);
1140
1141      if (ShouldVisit)
1142        TRY_TO(TraverseClassTemplateSpecializationDecl(SD));
1143      break;
1144    }
1145
1146    // We don't need to do anything on an explicit instantiation
1147    // or explicit specialization because there will be an explicit
1148    // node for it elsewhere.
1149    case TSK_ExplicitInstantiationDeclaration:
1150    case TSK_ExplicitInstantiationDefinition:
1151    case TSK_ExplicitSpecialization:
1152      break;
1153
1154    // We don't need to do anything for an uninstantiated
1155    // specialization.
1156    case TSK_Undeclared:
1157      break;
1158    }
1159  }
1160
1161  return true;
1162}
1163
1164DEF_TRAVERSE_DECL(ClassTemplateDecl, {
1165    CXXRecordDecl* TempDecl = D->getTemplatedDecl();
1166    TRY_TO(TraverseDecl(TempDecl));
1167    TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1168
1169    // By default, we do not traverse the instantiations of
1170    // class templates since they do not apprear in the user code. The
1171    // following code optionally traverses them.
1172    if (getDerived().shouldVisitTemplateInstantiations()) {
1173      // If this is the definition of the primary template, visit
1174      // instantiations which were formed from this pattern.
1175      if (D->isThisDeclarationADefinition())
1176        TRY_TO(TraverseClassInstantiations(D, D));
1177    }
1178
1179    // Note that getInstantiatedFromMemberTemplate() is just a link
1180    // from a template instantiation back to the template from which
1181    // it was instantiated, and thus should not be traversed.
1182  })
1183
1184// A helper method for traversing the instantiations of a
1185// function while skipping its specializations.
1186template<typename Derived>
1187bool RecursiveASTVisitor<Derived>::TraverseFunctionInstantiations(
1188  FunctionTemplateDecl* D) {
1189  FunctionTemplateDecl::spec_iterator end = D->spec_end();
1190  for (FunctionTemplateDecl::spec_iterator it = D->spec_begin(); it != end; ++it) {
1191    FunctionDecl* FD = *it;
1192    switch (FD->getTemplateSpecializationKind()) {
1193    case TSK_ImplicitInstantiation:
1194      // We don't know what kind of FunctionDecl this is.
1195      TRY_TO(TraverseDecl(FD));
1196      break;
1197
1198    // No need to visit explicit instantiations, we'll find the node
1199    // eventually.
1200    case TSK_ExplicitInstantiationDeclaration:
1201    case TSK_ExplicitInstantiationDefinition:
1202      break;
1203
1204    case TSK_Undeclared:           // Declaration of the template definition.
1205    case TSK_ExplicitSpecialization:
1206      break;
1207    default:
1208      assert(false && "Unknown specialization kind.");
1209    }
1210  }
1211
1212  return true;
1213}
1214
1215DEF_TRAVERSE_DECL(FunctionTemplateDecl, {
1216    TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1217    TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1218
1219    // By default, we do not traverse the instantiations of
1220    // function templates since they do not apprear in the user code. The
1221    // following code optionally traverses them.
1222    if (getDerived().shouldVisitTemplateInstantiations()) {
1223      // Explicit function specializations will be traversed from the
1224      // context of their declaration. There is therefore no need to
1225      // traverse them for here.
1226      //
1227      // In addition, we only traverse the function instantiations when
1228      // the function template is a function template definition.
1229      if (D->isThisDeclarationADefinition()) {
1230        TRY_TO(TraverseFunctionInstantiations(D));
1231      }
1232    }
1233  })
1234
1235DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, {
1236    // D is the "T" in something like
1237    //   template <template <typename> class T> class container { };
1238    TRY_TO(TraverseDecl(D->getTemplatedDecl()));
1239    if (D->hasDefaultArgument()) {
1240      TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
1241    }
1242    TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
1243  })
1244
1245DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
1246    // D is the "T" in something like "template<typename T> class vector;"
1247    if (D->getTypeForDecl())
1248      TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1249    if (D->hasDefaultArgument())
1250      TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
1251  })
1252
1253DEF_TRAVERSE_DECL(TypedefDecl, {
1254    TRY_TO(TraverseType(D->getUnderlyingType()));
1255    // We shouldn't traverse D->getTypeForDecl(); it's a result of
1256    // declaring the typedef, not something that was written in the
1257    // source.
1258  })
1259
1260DEF_TRAVERSE_DECL(UnresolvedUsingTypenameDecl, {
1261    // A dependent using declaration which was marked with 'typename'.
1262    //   template<class T> class A : public B<T> { using typename B<T>::foo; };
1263    TRY_TO(TraverseNestedNameSpecifier(D->getTargetNestedNameSpecifier()));
1264    // We shouldn't traverse D->getTypeForDecl(); it's a result of
1265    // declaring the type, not something that was written in the
1266    // source.
1267  })
1268
1269DEF_TRAVERSE_DECL(EnumDecl, {
1270    if (D->getTypeForDecl())
1271      TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
1272
1273    TRY_TO(TraverseNestedNameSpecifier(D->getQualifier()));
1274    // The enumerators are already traversed by
1275    // decls_begin()/decls_end().
1276  })
1277
1278
1279// Helper methods for RecordDecl and its children.
1280template<typename Derived>
1281bool RecursiveASTVisitor<Derived>::TraverseRecordHelper(
1282    RecordDecl *D) {
1283  // We shouldn't traverse D->getTypeForDecl(); it's a result of
1284  // declaring the type, not something that was written in the source.
1285  //
1286  // The anonymous struct or union object is the variable or field
1287  // whose type is the anonymous struct or union.  We shouldn't
1288  // traverse D->getAnonymousStructOrUnionObject(), as it's not
1289  // something that is explicitly written in the source.
1290  TRY_TO(TraverseNestedNameSpecifier(D->getQualifier()));
1291  return true;
1292}
1293
1294template<typename Derived>
1295bool RecursiveASTVisitor<Derived>::TraverseCXXRecordHelper(
1296    CXXRecordDecl *D) {
1297  if (!TraverseRecordHelper(D))
1298    return false;
1299  if (D->hasDefinition()) {
1300    for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1301                                            E = D->bases_end();
1302         I != E; ++I) {
1303      TRY_TO(TraverseTypeLoc(I->getTypeSourceInfo()->getTypeLoc()));
1304    }
1305    // We don't traverse the friends or the conversions, as they are
1306    // already in decls_begin()/decls_end().
1307  }
1308  return true;
1309}
1310
1311DEF_TRAVERSE_DECL(RecordDecl, {
1312    TRY_TO(TraverseRecordHelper(D));
1313  })
1314
1315DEF_TRAVERSE_DECL(CXXRecordDecl, {
1316    TRY_TO(TraverseCXXRecordHelper(D));
1317  })
1318
1319DEF_TRAVERSE_DECL(ClassTemplateSpecializationDecl, {
1320    // For implicit instantiations ("set<int> x;"), we don't want to
1321    // recurse at all, since the instatiated class isn't written in
1322    // the source code anywhere.  (Note the instatiated *type* --
1323    // set<int> -- is written, and will still get a callback of
1324    // TemplateSpecializationType).  For explicit instantiations
1325    // ("template set<int>;"), we do need a callback, since this
1326    // is the only callback that's made for this instantiation.
1327    // We use getTypeAsWritten() to distinguish.
1328    if (TypeSourceInfo *TSI = D->getTypeAsWritten())
1329      TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
1330
1331    if (!getDerived().shouldVisitTemplateInstantiations() &&
1332        D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1333      // Returning from here skips traversing the
1334      // declaration context of the ClassTemplateSpecializationDecl
1335      // (embedded in the DEF_TRAVERSE_DECL() macro)
1336      // which contains the instantiated members of the class.
1337      return true;
1338  })
1339
1340template <typename Derived>
1341bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLocsHelper(
1342    const TemplateArgumentLoc *TAL, unsigned Count) {
1343  for (unsigned I = 0; I < Count; ++I) {
1344    TRY_TO(TraverseTemplateArgumentLoc(TAL[I]));
1345  }
1346  return true;
1347}
1348
1349DEF_TRAVERSE_DECL(ClassTemplatePartialSpecializationDecl, {
1350    // The partial specialization.
1351    if (TemplateParameterList *TPL = D->getTemplateParameters()) {
1352      for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();
1353           I != E; ++I) {
1354        TRY_TO(TraverseDecl(*I));
1355      }
1356    }
1357    // The args that remains unspecialized.
1358    TRY_TO(TraverseTemplateArgumentLocsHelper(
1359        D->getTemplateArgsAsWritten(), D->getNumTemplateArgsAsWritten()));
1360
1361    // Don't need the ClassTemplatePartialSpecializationHelper, even
1362    // though that's our parent class -- we already visit all the
1363    // template args here.
1364    TRY_TO(TraverseCXXRecordHelper(D));
1365
1366    // If we're visiting instantiations, visit the instantiations of
1367    // this template now.
1368    if (getDerived().shouldVisitTemplateInstantiations() &&
1369        D->isThisDeclarationADefinition())
1370      TRY_TO(TraverseClassInstantiations(D->getSpecializedTemplate(), D));
1371  })
1372
1373DEF_TRAVERSE_DECL(EnumConstantDecl, {
1374    TRY_TO(TraverseStmt(D->getInitExpr()));
1375  })
1376
1377DEF_TRAVERSE_DECL(UnresolvedUsingValueDecl, {
1378    // Like UnresolvedUsingTypenameDecl, but without the 'typename':
1379    //    template <class T> Class A : public Base<T> { using Base<T>::foo; };
1380    TRY_TO(TraverseNestedNameSpecifier(D->getTargetNestedNameSpecifier()));
1381  })
1382
1383template<typename Derived>
1384bool RecursiveASTVisitor<Derived>::TraverseDeclaratorHelper(DeclaratorDecl *D) {
1385  TRY_TO(TraverseNestedNameSpecifier(D->getQualifier()));
1386  if (D->getTypeSourceInfo())
1387    TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
1388  return true;
1389}
1390
1391DEF_TRAVERSE_DECL(FieldDecl, {
1392    TRY_TO(TraverseDeclaratorHelper(D));
1393    if (D->isBitField())
1394      TRY_TO(TraverseStmt(D->getBitWidth()));
1395  })
1396
1397DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
1398    TRY_TO(TraverseDeclaratorHelper(D));
1399    if (D->isBitField())
1400      TRY_TO(TraverseStmt(D->getBitWidth()));
1401    // FIXME: implement the rest.
1402  })
1403
1404DEF_TRAVERSE_DECL(ObjCIvarDecl, {
1405    TRY_TO(TraverseDeclaratorHelper(D));
1406    if (D->isBitField())
1407      TRY_TO(TraverseStmt(D->getBitWidth()));
1408    // FIXME: implement the rest.
1409  })
1410
1411template<typename Derived>
1412bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D) {
1413  TRY_TO(TraverseNestedNameSpecifier(D->getQualifier()));
1414
1415  // Visit the function type itself, which can be either
1416  // FunctionNoProtoType or FunctionProtoType, or a typedef.  If it's
1417  // not a Function*ProtoType, then it can't have a body or arguments,
1418  // so we have to do less work.
1419  Type *FuncType = D->getType().getTypePtr();
1420  if (FunctionProtoType *FuncProto = dyn_cast<FunctionProtoType>(FuncType)) {
1421    if (D->isThisDeclarationADefinition()) {
1422      // Don't call Traverse*, or the result type and parameter types
1423      // will be double counted.
1424      TRY_TO(WalkUpFromFunctionProtoType(FuncProto));
1425    } else {
1426      // This works around a bug in Clang that does not add the parameters
1427      // to decls_begin/end for function declarations (as opposed to
1428      // definitions):
1429      //    http://llvm.org/PR7442
1430      // We work around this here by traversing the function type.
1431      // This isn't perfect because we don't traverse the default
1432      // values, if any.  It also may not interact great with
1433      // templates.  But it's the best we can do until the bug is
1434      // fixed.
1435      // FIXME: replace the entire 'if' statement with
1436      //   TRY_TO(WalkUpFromFunctionProtoType(FuncProto));
1437      // when the bug is fixed.
1438      TRY_TO(TraverseFunctionProtoType(FuncProto));
1439      return true;
1440    }
1441  } else if (FunctionNoProtoType *FuncNoProto =
1442      dyn_cast<FunctionNoProtoType>(FuncType)) {
1443    // Don't call Traverse*, or the result type will be double
1444    // counted.
1445    TRY_TO(WalkUpFromFunctionNoProtoType(FuncNoProto));
1446  } else {   // a typedef type, or who knows what
1447    assert(!D->isThisDeclarationADefinition() && "Unexpected function type");
1448    TRY_TO(TraverseType(D->getType()));
1449    return true;
1450  }
1451
1452  TRY_TO(TraverseType(D->getResultType()));
1453
1454  // If we're an explicit template specialization, iterate over the
1455  // template args that were explicitly specified.
1456  if (const FunctionTemplateSpecializationInfo *FTSI =
1457      D->getTemplateSpecializationInfo()) {
1458    if (FTSI->getTemplateSpecializationKind() != TSK_Undeclared &&
1459        FTSI->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
1460      // A specialization might not have explicit template arguments if it has
1461      // a templated return type and concrete arguments.
1462      if (const TemplateArgumentListInfo *TALI =
1463          FTSI->TemplateArgumentsAsWritten) {
1464        TRY_TO(TraverseTemplateArgumentLocsHelper(TALI->getArgumentArray(),
1465                                                  TALI->size()));
1466      }
1467    }
1468  }
1469
1470  for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end();
1471       I != E; ++I) {
1472    TRY_TO(TraverseDecl(*I));
1473  }
1474
1475  if (FunctionProtoType *FuncProto = dyn_cast<FunctionProtoType>(FuncType)) {
1476    if (D->isThisDeclarationADefinition()) {
1477      // This would be visited if we called TraverseType(D->getType())
1478      // above, but we don't (at least, not in the
1479      // declaration-is-a-definition case), in order to avoid duplicate
1480      // visiting for parameters.  (We need to check parameters here,
1481      // rather than letting D->getType() do it, so we visit default
1482      // parameter values).  So we need to re-do some of the work the
1483      // type would do.
1484      for (FunctionProtoType::exception_iterator
1485               E = FuncProto->exception_begin(),
1486               EEnd = FuncProto->exception_end();
1487           E != EEnd; ++E) {
1488        TRY_TO(TraverseType(*E));
1489      }
1490    }
1491  }
1492
1493  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1494    // Constructor initializers.
1495    for (CXXConstructorDecl::init_iterator I = Ctor->init_begin(),
1496                                           E = Ctor->init_end();
1497         I != E; ++I) {
1498      TRY_TO(TraverseConstructorInitializer(*I));
1499    }
1500  }
1501
1502  if (D->isThisDeclarationADefinition()) {
1503    TRY_TO(TraverseStmt(D->getBody()));  // Function body.
1504  }
1505  return true;
1506}
1507
1508DEF_TRAVERSE_DECL(FunctionDecl, {
1509    // We skip decls_begin/decls_end, which are already covered by
1510    // TraverseFunctionHelper().
1511    return TraverseFunctionHelper(D);
1512  })
1513
1514DEF_TRAVERSE_DECL(CXXMethodDecl, {
1515    // We skip decls_begin/decls_end, which are already covered by
1516    // TraverseFunctionHelper().
1517    return TraverseFunctionHelper(D);
1518  })
1519
1520DEF_TRAVERSE_DECL(CXXConstructorDecl, {
1521    // We skip decls_begin/decls_end, which are already covered by
1522    // TraverseFunctionHelper().
1523    return TraverseFunctionHelper(D);
1524  })
1525
1526// CXXConversionDecl is the declaration of a type conversion operator.
1527// It's not a cast expression.
1528DEF_TRAVERSE_DECL(CXXConversionDecl, {
1529    // We skip decls_begin/decls_end, which are already covered by
1530    // TraverseFunctionHelper().
1531    return TraverseFunctionHelper(D);
1532  })
1533
1534DEF_TRAVERSE_DECL(CXXDestructorDecl, {
1535    // We skip decls_begin/decls_end, which are already covered by
1536    // TraverseFunctionHelper().
1537    return TraverseFunctionHelper(D);
1538  })
1539
1540template<typename Derived>
1541bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
1542  TRY_TO(TraverseDeclaratorHelper(D));
1543  TRY_TO(TraverseStmt(D->getInit()));
1544  return true;
1545}
1546
1547DEF_TRAVERSE_DECL(VarDecl, {
1548    TRY_TO(TraverseVarHelper(D));
1549  })
1550
1551DEF_TRAVERSE_DECL(ImplicitParamDecl, {
1552    TRY_TO(TraverseVarHelper(D));
1553  })
1554
1555DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, {
1556    // A non-type template parameter, e.g. "S" in template<int S> class Foo ...
1557    TRY_TO(TraverseVarHelper(D));
1558    TRY_TO(TraverseStmt(D->getDefaultArgument()));
1559  })
1560
1561DEF_TRAVERSE_DECL(ParmVarDecl, {
1562    TRY_TO(TraverseVarHelper(D));
1563
1564    if (D->hasDefaultArg() &&
1565        D->hasUninstantiatedDefaultArg() &&
1566        !D->hasUnparsedDefaultArg())
1567      TRY_TO(TraverseStmt(D->getUninstantiatedDefaultArg()));
1568
1569    if (D->hasDefaultArg() &&
1570        !D->hasUninstantiatedDefaultArg() &&
1571        !D->hasUnparsedDefaultArg())
1572      TRY_TO(TraverseStmt(D->getDefaultArg()));
1573  })
1574
1575#undef DEF_TRAVERSE_DECL
1576
1577// ----------------- Stmt traversal -----------------
1578//
1579// For stmts, we automate (in the DEF_TRAVERSE_STMT macro) iterating
1580// over the children defined in child_begin/child_end (every stmt
1581// defines these, though sometimes the range is empty).  Each
1582// individual Traverse* method only needs to worry about children
1583// other than those.  To see what child_begin()/end() does for a given
1584// class, see, e.g.,
1585// http://clang.llvm.org/doxygen/Stmt_8cpp_source.html
1586
1587// This macro makes available a variable S, the passed-in stmt.
1588#define DEF_TRAVERSE_STMT(STMT, CODE)                                   \
1589template<typename Derived>                                              \
1590bool RecursiveASTVisitor<Derived>::Traverse##STMT (STMT *S) {           \
1591  TRY_TO(WalkUpFrom##STMT(S));                                          \
1592  { CODE; }                                                             \
1593  for (Stmt::child_iterator C = S->child_begin(), CEnd = S->child_end(); \
1594       C != CEnd; ++C) {                                                \
1595    TRY_TO(TraverseStmt(*C));                                           \
1596  }                                                                     \
1597  return true;                                                          \
1598}
1599
1600DEF_TRAVERSE_STMT(AsmStmt, {
1601    TRY_TO(TraverseStmt(S->getAsmString()));
1602    for (unsigned I = 0, E = S->getNumInputs(); I < E; ++I) {
1603      TRY_TO(TraverseStmt(S->getInputConstraintLiteral(I)));
1604    }
1605    for (unsigned I = 0, E = S->getNumOutputs(); I < E; ++I) {
1606      TRY_TO(TraverseStmt(S->getOutputConstraintLiteral(I)));
1607    }
1608    for (unsigned I = 0, E = S->getNumClobbers(); I < E; ++I) {
1609      TRY_TO(TraverseStmt(S->getClobber(I)));
1610    }
1611    // child_begin()/end() iterates over inputExpr and outputExpr.
1612  })
1613
1614DEF_TRAVERSE_STMT(CXXCatchStmt, {
1615    TRY_TO(TraverseDecl(S->getExceptionDecl()));
1616    // child_begin()/end() iterates over the handler block.
1617  })
1618
1619DEF_TRAVERSE_STMT(DeclStmt, {
1620    for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end();
1621         I != E; ++I) {
1622      TRY_TO(TraverseDecl(*I));
1623    }
1624    // Suppress the default iteration over child_begin/end by
1625    // returning.  Here's why: A DeclStmt looks like 'type var [=
1626    // initializer]'.  The decls above already traverse over the
1627    // initializers, so we don't have to do it again (which
1628    // child_begin/end would do).
1629    return true;
1630  })
1631
1632
1633// These non-expr stmts (most of them), do not need any action except
1634// iterating over the children.
1635DEF_TRAVERSE_STMT(BreakStmt, { })
1636DEF_TRAVERSE_STMT(CXXTryStmt, { })
1637DEF_TRAVERSE_STMT(CaseStmt, { })
1638DEF_TRAVERSE_STMT(CompoundStmt, { })
1639DEF_TRAVERSE_STMT(ContinueStmt, { })
1640DEF_TRAVERSE_STMT(DefaultStmt, { })
1641DEF_TRAVERSE_STMT(DoStmt, { })
1642DEF_TRAVERSE_STMT(ForStmt, { })
1643DEF_TRAVERSE_STMT(GotoStmt, { })
1644DEF_TRAVERSE_STMT(IfStmt, { })
1645DEF_TRAVERSE_STMT(IndirectGotoStmt, { })
1646DEF_TRAVERSE_STMT(LabelStmt, { })
1647DEF_TRAVERSE_STMT(NullStmt, { })
1648DEF_TRAVERSE_STMT(ObjCAtCatchStmt, { })
1649DEF_TRAVERSE_STMT(ObjCAtFinallyStmt, { })
1650DEF_TRAVERSE_STMT(ObjCAtSynchronizedStmt, { })
1651DEF_TRAVERSE_STMT(ObjCAtThrowStmt, { })
1652DEF_TRAVERSE_STMT(ObjCAtTryStmt, { })
1653DEF_TRAVERSE_STMT(ObjCForCollectionStmt, { })
1654DEF_TRAVERSE_STMT(ReturnStmt, { })
1655DEF_TRAVERSE_STMT(SwitchCase, { })
1656DEF_TRAVERSE_STMT(SwitchStmt, { })
1657DEF_TRAVERSE_STMT(WhileStmt, { })
1658
1659
1660DEF_TRAVERSE_STMT(CXXDependentScopeMemberExpr, {
1661    if (S->hasExplicitTemplateArgs()) {
1662      TRY_TO(TraverseTemplateArgumentLocsHelper(
1663          S->getTemplateArgs(), S->getNumTemplateArgs()));
1664    }
1665    TRY_TO(TraverseNestedNameSpecifier(S->getQualifier()));
1666  })
1667
1668DEF_TRAVERSE_STMT(DeclRefExpr, {
1669    TRY_TO(TraverseTemplateArgumentLocsHelper(
1670        S->getTemplateArgs(), S->getNumTemplateArgs()));
1671    // FIXME: Should we be recursing on the qualifier?
1672    TRY_TO(TraverseNestedNameSpecifier(S->getQualifier()));
1673  })
1674
1675DEF_TRAVERSE_STMT(DependentScopeDeclRefExpr, {
1676    // FIXME: Should we be recursing on these two things?
1677    if (S->hasExplicitTemplateArgs()) {
1678      TRY_TO(TraverseTemplateArgumentLocsHelper(
1679          S->getExplicitTemplateArgs().getTemplateArgs(),
1680          S->getNumTemplateArgs()));
1681    }
1682    TRY_TO(TraverseNestedNameSpecifier(S->getQualifier()));
1683  })
1684
1685DEF_TRAVERSE_STMT(MemberExpr, {
1686    TRY_TO(TraverseTemplateArgumentLocsHelper(
1687        S->getTemplateArgs(), S->getNumTemplateArgs()));
1688    // FIXME: Should we be recursing on the qualifier?
1689    TRY_TO(TraverseNestedNameSpecifier(S->getQualifier()));
1690  })
1691
1692DEF_TRAVERSE_STMT(ImplicitCastExpr, {
1693    // We don't traverse the cast type, as it's not written in the
1694    // source code.
1695  })
1696
1697DEF_TRAVERSE_STMT(CStyleCastExpr, {
1698    TRY_TO(TraverseType(S->getTypeAsWritten()));
1699  })
1700
1701DEF_TRAVERSE_STMT(CXXFunctionalCastExpr, {
1702    TRY_TO(TraverseType(S->getTypeAsWritten()));
1703  })
1704
1705DEF_TRAVERSE_STMT(CXXConstCastExpr, {
1706    TRY_TO(TraverseType(S->getTypeAsWritten()));
1707  })
1708
1709DEF_TRAVERSE_STMT(CXXDynamicCastExpr, {
1710    TRY_TO(TraverseType(S->getTypeAsWritten()));
1711  })
1712
1713DEF_TRAVERSE_STMT(CXXReinterpretCastExpr, {
1714    TRY_TO(TraverseType(S->getTypeAsWritten()));
1715  })
1716
1717DEF_TRAVERSE_STMT(CXXStaticCastExpr, {
1718    TRY_TO(TraverseType(S->getTypeAsWritten()));
1719  })
1720
1721// InitListExpr is a tricky one, because we want to do all our work on
1722// the syntactic form of the listexpr, but this method takes the
1723// semantic form by default.  We can't use the macro helper because it
1724// calls WalkUp*() on the semantic form, before our code can convert
1725// to the syntactic form.
1726template<typename Derived>
1727bool RecursiveASTVisitor<Derived>::TraverseInitListExpr(InitListExpr *S) {
1728  if (InitListExpr *Syn = S->getSyntacticForm())
1729    S = Syn;
1730  TRY_TO(WalkUpFromInitListExpr(S));
1731  // All we need are the default actions.  FIXME: use a helper function.
1732  for (Stmt::child_iterator C = S->child_begin(), CEnd = S->child_end();
1733       C != CEnd; ++C) {
1734    TRY_TO(TraverseStmt(*C));
1735  }
1736  return true;
1737}
1738
1739DEF_TRAVERSE_STMT(CXXScalarValueInitExpr, {
1740    // This is called for code like 'return T()' where T is a built-in
1741    // (i.e. non-class) type.
1742    TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
1743  })
1744
1745DEF_TRAVERSE_STMT(CXXNewExpr, {
1746  // The child-iterator will pick up the other arguments.
1747  TRY_TO(TraverseTypeLoc(S->getAllocatedTypeSourceInfo()->getTypeLoc()));
1748  })
1749
1750DEF_TRAVERSE_STMT(OffsetOfExpr, {
1751    // The child-iterator will pick up the expression representing
1752    // the field.
1753    // FIMXE: for code like offsetof(Foo, a.b.c), should we get
1754    // making a MemberExpr callbacks for Foo.a, Foo.a.b, and Foo.a.b.c?
1755    TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
1756  })
1757
1758DEF_TRAVERSE_STMT(SizeOfAlignOfExpr, {
1759    // The child-iterator will pick up the arg if it's an expression,
1760    // but not if it's a type.
1761    if (S->isArgumentType())
1762      TRY_TO(TraverseTypeLoc(S->getArgumentTypeInfo()->getTypeLoc()));
1763  })
1764
1765DEF_TRAVERSE_STMT(CXXTypeidExpr, {
1766    // The child-iterator will pick up the arg if it's an expression,
1767    // but not if it's a type.
1768    if (S->isTypeOperand())
1769      TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
1770  })
1771
1772DEF_TRAVERSE_STMT(CXXUuidofExpr, {
1773    // The child-iterator will pick up the arg if it's an expression,
1774    // but not if it's a type.
1775    if (S->isTypeOperand())
1776      TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
1777  })
1778
1779DEF_TRAVERSE_STMT(TypesCompatibleExpr, {
1780    TRY_TO(TraverseTypeLoc(S->getArgTInfo1()->getTypeLoc()));
1781    TRY_TO(TraverseTypeLoc(S->getArgTInfo2()->getTypeLoc()));
1782  })
1783
1784DEF_TRAVERSE_STMT(UnaryTypeTraitExpr, {
1785    TRY_TO(TraverseTypeLoc(S->getQueriedTypeSourceInfo()->getTypeLoc()));
1786  })
1787
1788DEF_TRAVERSE_STMT(VAArgExpr, {
1789    // The child-iterator will pick up the expression argument.
1790    TRY_TO(TraverseTypeLoc(S->getWrittenTypeInfo()->getTypeLoc()));
1791  })
1792
1793DEF_TRAVERSE_STMT(CXXTemporaryObjectExpr, {
1794    // This is called for code like 'return T()' where T is a class type.
1795    TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
1796  })
1797
1798DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, {
1799    // This is called for code like 'T()', where T is a template argument.
1800    TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
1801  })
1802
1803// These expressions all might take explicit template arguments.
1804// We traverse those if so.  FIXME: implement these.
1805DEF_TRAVERSE_STMT(CXXConstructExpr, { })
1806DEF_TRAVERSE_STMT(CallExpr, { })
1807DEF_TRAVERSE_STMT(CXXMemberCallExpr, { })
1808
1809// These exprs (most of them), do not need any action except iterating
1810// over the children.
1811DEF_TRAVERSE_STMT(AddrLabelExpr, { })
1812DEF_TRAVERSE_STMT(ArraySubscriptExpr, { })
1813DEF_TRAVERSE_STMT(BlockDeclRefExpr, { })
1814DEF_TRAVERSE_STMT(BlockExpr, { })
1815DEF_TRAVERSE_STMT(ChooseExpr, { })
1816DEF_TRAVERSE_STMT(CompoundLiteralExpr, { })
1817DEF_TRAVERSE_STMT(CXXBindTemporaryExpr, { })
1818DEF_TRAVERSE_STMT(CXXBoolLiteralExpr, { })
1819DEF_TRAVERSE_STMT(CXXDefaultArgExpr, { })
1820DEF_TRAVERSE_STMT(CXXDeleteExpr, { })
1821DEF_TRAVERSE_STMT(CXXExprWithTemporaries, { })
1822DEF_TRAVERSE_STMT(CXXNullPtrLiteralExpr, { })
1823DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, { })
1824DEF_TRAVERSE_STMT(CXXThisExpr, { })
1825DEF_TRAVERSE_STMT(CXXThrowExpr, { })
1826DEF_TRAVERSE_STMT(DesignatedInitExpr, { })
1827DEF_TRAVERSE_STMT(ExtVectorElementExpr, { })
1828DEF_TRAVERSE_STMT(GNUNullExpr, { })
1829DEF_TRAVERSE_STMT(ImplicitValueInitExpr, { })
1830DEF_TRAVERSE_STMT(ObjCEncodeExpr, { })
1831DEF_TRAVERSE_STMT(ObjCImplicitSetterGetterRefExpr, { })
1832DEF_TRAVERSE_STMT(ObjCIsaExpr, { })
1833DEF_TRAVERSE_STMT(ObjCIvarRefExpr, { })
1834DEF_TRAVERSE_STMT(ObjCMessageExpr, { })
1835DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, { })
1836DEF_TRAVERSE_STMT(ObjCProtocolExpr, { })
1837DEF_TRAVERSE_STMT(ObjCSelectorExpr, { })
1838DEF_TRAVERSE_STMT(ObjCSuperExpr, { })
1839DEF_TRAVERSE_STMT(ParenExpr, { })
1840DEF_TRAVERSE_STMT(ParenListExpr, { })
1841DEF_TRAVERSE_STMT(PredefinedExpr, { })
1842DEF_TRAVERSE_STMT(ShuffleVectorExpr, { })
1843DEF_TRAVERSE_STMT(StmtExpr, { })
1844DEF_TRAVERSE_STMT(UnresolvedLookupExpr, { })
1845DEF_TRAVERSE_STMT(UnresolvedMemberExpr, { })
1846DEF_TRAVERSE_STMT(CXXOperatorCallExpr, { })
1847
1848// These operators (all of them) do not need any action except
1849// iterating over the children.
1850DEF_TRAVERSE_STMT(ConditionalOperator, { })
1851DEF_TRAVERSE_STMT(UnaryOperator, { })
1852DEF_TRAVERSE_STMT(BinaryOperator, { })
1853DEF_TRAVERSE_STMT(CompoundAssignOperator, { })
1854DEF_TRAVERSE_STMT(CXXNoexceptExpr, { })
1855
1856// These literals (all of them) do not need any action.
1857DEF_TRAVERSE_STMT(IntegerLiteral, { })
1858DEF_TRAVERSE_STMT(CharacterLiteral, { })
1859DEF_TRAVERSE_STMT(FloatingLiteral, { })
1860DEF_TRAVERSE_STMT(ImaginaryLiteral, { })
1861DEF_TRAVERSE_STMT(StringLiteral, { })
1862DEF_TRAVERSE_STMT(ObjCStringLiteral, { })
1863
1864// FIXME: look at the following tricky-seeming exprs to see if we
1865// need to recurse on anything.  These are ones that have methods
1866// returning decls or qualtypes or nestednamespecifier -- though I'm
1867// not sure if they own them -- or just seemed very complicated, or
1868// had lots of sub-types to explore.
1869//
1870// VisitOverloadExpr and its children: recurse on template args? etc?
1871
1872// FIXME: go through all the stmts and exprs again, and see which of them
1873// create new types, and recurse on the types (TypeLocs?) of those.
1874// Candidates:
1875//
1876//    http://clang.llvm.org/doxygen/classclang_1_1CXXTypeidExpr.html
1877//    http://clang.llvm.org/doxygen/classclang_1_1SizeOfAlignOfExpr.html
1878//    http://clang.llvm.org/doxygen/classclang_1_1TypesCompatibleExpr.html
1879//    Every class that has getQualifier.
1880
1881#undef DEF_TRAVERSE_STMT
1882
1883#undef TRY_TO
1884
1885} // end namespace clang
1886
1887#endif // LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
1888