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