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