ASTMatchers.h revision 31bdf071afc18bb9551e4f4254be297333200c4a
1//===--- ASTMatchers.h - Structural query framework -------------*- 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 implements matchers to be used together with the MatchFinder to
11//  match AST nodes.
12//
13//  Matchers are created by generator functions, which can be combined in
14//  a functional in-language DSL to express queries over the C++ AST.
15//
16//  For example, to match a class with a certain name, one would call:
17//    recordDecl(hasName("MyClass"))
18//  which returns a matcher that can be used to find all AST nodes that declare
19//  a class named 'MyClass'.
20//
21//  For more complicated match expressions we're often interested in accessing
22//  multiple parts of the matched AST nodes once a match is found. In that case,
23//  use the id(...) matcher around the match expressions that match the nodes
24//  you want to access.
25//
26//  For example, when we're interested in child classes of a certain class, we
27//  would write:
28//    recordDecl(hasName("MyClass"), hasChild(id("child", recordDecl())))
29//  When the match is found via the MatchFinder, a user provided callback will
30//  be called with a BoundNodes instance that contains a mapping from the
31//  strings that we provided for the id(...) calls to the nodes that were
32//  matched.
33//  In the given example, each time our matcher finds a match we get a callback
34//  where "child" is bound to the CXXRecordDecl node of the matching child
35//  class declaration.
36//
37//  See ASTMatchersInternal.h for a more in-depth explanation of the
38//  implementation details of the matcher framework.
39//
40//  See ASTMatchFinder.h for how to use the generated matchers to run over
41//  an AST.
42//
43//===----------------------------------------------------------------------===//
44
45#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
46#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
47
48#include "clang/AST/DeclTemplate.h"
49#include "clang/ASTMatchers/ASTMatchersInternal.h"
50#include "clang/ASTMatchers/ASTMatchersMacros.h"
51#include "llvm/ADT/Twine.h"
52#include "llvm/Support/Regex.h"
53#include <iterator>
54
55namespace clang {
56namespace ast_matchers {
57
58/// \brief Maps string IDs to AST nodes matched by parts of a matcher.
59///
60/// The bound nodes are generated by calling \c bind("id") on the node matchers
61/// of the nodes we want to access later.
62///
63/// The instances of BoundNodes are created by \c MatchFinder when the user's
64/// callbacks are executed every time a match is found.
65class BoundNodes {
66public:
67  /// \brief Returns the AST node bound to \c ID.
68  ///
69  /// Returns NULL if there was no node bound to \c ID or if there is a node but
70  /// it cannot be converted to the specified type.
71  template <typename T>
72  const T *getNodeAs(StringRef ID) const {
73    return MyBoundNodes.getNodeAs<T>(ID);
74  }
75
76  /// \brief Deprecated. Please use \c getNodeAs instead.
77  /// @{
78  template <typename T>
79  const T *getDeclAs(StringRef ID) const {
80    return getNodeAs<T>(ID);
81  }
82  template <typename T>
83  const T *getStmtAs(StringRef ID) const {
84    return getNodeAs<T>(ID);
85  }
86  /// @}
87
88private:
89  /// \brief Create BoundNodes from a pre-filled map of bindings.
90  BoundNodes(internal::BoundNodesMap &MyBoundNodes)
91      : MyBoundNodes(MyBoundNodes) {}
92
93  internal::BoundNodesMap MyBoundNodes;
94
95  friend class internal::BoundNodesTree;
96};
97
98/// \brief If the provided matcher matches a node, binds the node to \c ID.
99///
100/// FIXME: Do we want to support this now that we have bind()?
101template <typename T>
102internal::Matcher<T> id(const std::string &ID,
103                        const internal::BindableMatcher<T> &InnerMatcher) {
104  return InnerMatcher.bind(ID);
105}
106
107/// \brief Types of matchers for the top-level classes in the AST class
108/// hierarchy.
109/// @{
110typedef internal::Matcher<Decl> DeclarationMatcher;
111typedef internal::Matcher<Stmt> StatementMatcher;
112typedef internal::Matcher<QualType> TypeMatcher;
113typedef internal::Matcher<TypeLoc> TypeLocMatcher;
114typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
115typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
116/// @}
117
118/// \brief Matches any node.
119///
120/// Useful when another matcher requires a child matcher, but there's no
121/// additional constraint. This will often be used with an explicit conversion
122/// to an \c internal::Matcher<> type such as \c TypeMatcher.
123///
124/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
125/// \code
126/// "int* p" and "void f()" in
127///   int* p;
128///   void f();
129/// \endcode
130///
131/// Usable as: Any Matcher
132inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() {
133  return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
134}
135
136/// \brief Matches declarations.
137///
138/// Examples matches \c X, \c C, and the friend declaration inside \c C;
139/// \code
140///   void X();
141///   class C {
142///     friend X;
143///   };
144/// \endcode
145const internal::VariadicDynCastAllOfMatcher<Decl, Decl> decl;
146
147/// \brief Matches a declaration of anything that could have a name.
148///
149/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
150/// \code
151///   typedef int X;
152///   struct S {
153///     union {
154///       int i;
155///     } U;
156///   };
157/// \endcode
158const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
159
160/// \brief Matches C++ class declarations.
161///
162/// Example matches \c X, \c Z
163/// \code
164///   class X;
165///   template<class T> class Z {};
166/// \endcode
167const internal::VariadicDynCastAllOfMatcher<
168  Decl,
169  CXXRecordDecl> recordDecl;
170
171/// \brief Matches C++ class template declarations.
172///
173/// Example matches \c Z
174/// \code
175///   template<class T> class Z {};
176/// \endcode
177const internal::VariadicDynCastAllOfMatcher<
178  Decl,
179  ClassTemplateDecl> classTemplateDecl;
180
181/// \brief Matches C++ class template specializations.
182///
183/// Given
184/// \code
185///   template<typename T> class A {};
186///   template<> class A<double> {};
187///   A<int> a;
188/// \endcode
189/// classTemplateSpecializationDecl()
190///   matches the specializations \c A<int> and \c A<double>
191const internal::VariadicDynCastAllOfMatcher<
192  Decl,
193  ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
194
195/// \brief Matches classTemplateSpecializations that have at least one
196/// TemplateArgument matching the given InnerMatcher.
197///
198/// Given
199/// \code
200///   template<typename T> class A {};
201///   template<> class A<double> {};
202///   A<int> a;
203/// \endcode
204/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
205///     refersToType(asString("int"))))
206///   matches the specialization \c A<int>
207AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
208              internal::Matcher<TemplateArgument>, InnerMatcher) {
209  const TemplateArgumentList &List = Node.getTemplateArgs();
210  for (unsigned i = 0; i < List.size(); ++i) {
211    if (InnerMatcher.matches(List.get(i), Finder, Builder))
212      return true;
213  }
214  return false;
215}
216
217/// \brief Matches expressions that match InnerMatcher after any implicit casts
218/// are stripped off.
219///
220/// Parentheses and explicit casts are not discarded.
221/// Given
222/// \code
223///   int arr[5];
224///   int a = 0;
225///   char b = 0;
226///   const int c = a;
227///   int *d = arr;
228///   long e = (long) 0l;
229/// \endcode
230/// The matchers
231/// \code
232///    varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
233///    varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
234/// \endcode
235/// would match the declarations for a, b, c, and d, but not e.
236/// While
237/// \code
238///    varDecl(hasInitializer(integerLiteral()))
239///    varDecl(hasInitializer(declRefExpr()))
240/// \endcode
241/// only match the declarations for b, c, and d.
242AST_MATCHER_P(Expr, ignoringImpCasts,
243              internal::Matcher<Expr>, InnerMatcher) {
244  return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
245}
246
247/// \brief Matches expressions that match InnerMatcher after parentheses and
248/// casts are stripped off.
249///
250/// Implicit and non-C Style casts are also discarded.
251/// Given
252/// \code
253///   int a = 0;
254///   char b = (0);
255///   void* c = reinterpret_cast<char*>(0);
256///   char d = char(0);
257/// \endcode
258/// The matcher
259///    varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
260/// would match the declarations for a, b, c, and d.
261/// while
262///    varDecl(hasInitializer(integerLiteral()))
263/// only match the declaration for a.
264AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
265  return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
266}
267
268/// \brief Matches expressions that match InnerMatcher after implicit casts and
269/// parentheses are stripped off.
270///
271/// Explicit casts are not discarded.
272/// Given
273/// \code
274///   int arr[5];
275///   int a = 0;
276///   char b = (0);
277///   const int c = a;
278///   int *d = (arr);
279///   long e = ((long) 0l);
280/// \endcode
281/// The matchers
282///    varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
283///    varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
284/// would match the declarations for a, b, c, and d, but not e.
285/// while
286///    varDecl(hasInitializer(integerLiteral()))
287///    varDecl(hasInitializer(declRefExpr()))
288/// would only match the declaration for a.
289AST_MATCHER_P(Expr, ignoringParenImpCasts,
290              internal::Matcher<Expr>, InnerMatcher) {
291  return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
292}
293
294/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
295/// matches the given InnerMatcher.
296///
297/// Given
298/// \code
299///   template<typename T, typename U> class A {};
300///   A<bool, int> b;
301///   A<int, bool> c;
302/// \endcode
303/// classTemplateSpecializationDecl(hasTemplateArgument(
304///     1, refersToType(asString("int"))))
305///   matches the specialization \c A<bool, int>
306AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
307               unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
308  const TemplateArgumentList &List = Node.getTemplateArgs();
309  if (List.size() <= N)
310    return false;
311  return InnerMatcher.matches(List.get(N), Finder, Builder);
312}
313
314/// \brief Matches a TemplateArgument that refers to a certain type.
315///
316/// Given
317/// \code
318///   struct X {};
319///   template<typename T> struct A {};
320///   A<X> a;
321/// \endcode
322/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
323///     refersToType(class(hasName("X")))))
324///   matches the specialization \c A<X>
325AST_MATCHER_P(TemplateArgument, refersToType,
326              internal::Matcher<QualType>, InnerMatcher) {
327  if (Node.getKind() != TemplateArgument::Type)
328    return false;
329  return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
330}
331
332/// \brief Matches a TemplateArgument that refers to a certain declaration.
333///
334/// Given
335/// \code
336///   template<typename T> struct A {};
337///   struct B { B* next; };
338///   A<&B::next> a;
339/// \endcode
340/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
341///     refersToDeclaration(fieldDecl(hasName("next"))))
342///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
343///     \c B::next
344AST_MATCHER_P(TemplateArgument, refersToDeclaration,
345              internal::Matcher<Decl>, InnerMatcher) {
346  if (Node.getKind() == TemplateArgument::Declaration)
347    return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
348  return false;
349}
350
351/// \brief Matches C++ constructor declarations.
352///
353/// Example matches Foo::Foo() and Foo::Foo(int)
354/// \code
355///   class Foo {
356///    public:
357///     Foo();
358///     Foo(int);
359///     int DoSomething();
360///   };
361/// \endcode
362const internal::VariadicDynCastAllOfMatcher<
363  Decl,
364  CXXConstructorDecl> constructorDecl;
365
366/// \brief Matches explicit C++ destructor declarations.
367///
368/// Example matches Foo::~Foo()
369/// \code
370///   class Foo {
371///    public:
372///     virtual ~Foo();
373///   };
374/// \endcode
375const internal::VariadicDynCastAllOfMatcher<
376  Decl,
377  CXXDestructorDecl> destructorDecl;
378
379/// \brief Matches enum declarations.
380///
381/// Example matches X
382/// \code
383///   enum X {
384///     A, B, C
385///   };
386/// \endcode
387const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
388
389/// \brief Matches enum constants.
390///
391/// Example matches A, B, C
392/// \code
393///   enum X {
394///     A, B, C
395///   };
396/// \endcode
397const internal::VariadicDynCastAllOfMatcher<
398  Decl,
399  EnumConstantDecl> enumConstantDecl;
400
401/// \brief Matches method declarations.
402///
403/// Example matches y
404/// \code
405///   class X { void y() };
406/// \endcode
407const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
408
409/// \brief Matches variable declarations.
410///
411/// Note: this does not match declarations of member variables, which are
412/// "field" declarations in Clang parlance.
413///
414/// Example matches a
415/// \code
416///   int a;
417/// \endcode
418const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
419
420/// \brief Matches field declarations.
421///
422/// Given
423/// \code
424///   class X { int m; };
425/// \endcode
426/// fieldDecl()
427///   matches 'm'.
428const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
429
430/// \brief Matches function declarations.
431///
432/// Example matches f
433/// \code
434///   void f();
435/// \endcode
436const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
437
438/// \brief Matches C++ function template declarations.
439///
440/// Example matches f
441/// \code
442///   template<class T> void f(T t) {}
443/// \endcode
444const internal::VariadicDynCastAllOfMatcher<
445  Decl,
446  FunctionTemplateDecl> functionTemplateDecl;
447
448/// \brief Matches statements.
449///
450/// Given
451/// \code
452///   { ++a; }
453/// \endcode
454/// stmt()
455///   matches both the compound statement '{ ++a; }' and '++a'.
456const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> stmt;
457
458/// \brief Matches declaration statements.
459///
460/// Given
461/// \code
462///   int a;
463/// \endcode
464/// declStmt()
465///   matches 'int a'.
466const internal::VariadicDynCastAllOfMatcher<
467  Stmt,
468  DeclStmt> declStmt;
469
470/// \brief Matches member expressions.
471///
472/// Given
473/// \code
474///   class Y {
475///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
476///     int a; static int b;
477///   };
478/// \endcode
479/// memberExpr()
480///   matches this->x, x, y.x, a, this->b
481const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
482
483/// \brief Matches call expressions.
484///
485/// Example matches x.y() and y()
486/// \code
487///   X x;
488///   x.y();
489///   y();
490/// \endcode
491const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
492
493/// \brief Matches lambda expressions.
494///
495/// Example matches [&](){return 5;}
496/// \code
497///   [&](){return 5;}
498/// \endcode
499const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
500
501/// \brief Matches member call expressions.
502///
503/// Example matches x.y()
504/// \code
505///   X x;
506///   x.y();
507/// \endcode
508const internal::VariadicDynCastAllOfMatcher<
509  Stmt,
510  CXXMemberCallExpr> memberCallExpr;
511
512/// \brief Matches init list expressions.
513///
514/// Given
515/// \code
516///   int a[] = { 1, 2 };
517///   struct B { int x, y; };
518///   B b = { 5, 6 };
519/// \endcode
520/// initList()
521///   matches "{ 1, 2 }" and "{ 5, 6 }"
522const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
523
524/// \brief Matches using declarations.
525///
526/// Given
527/// \code
528///   namespace X { int x; }
529///   using X::x;
530/// \endcode
531/// usingDecl()
532///   matches \code using X::x \endcode
533const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
534
535/// \brief Matches constructor call expressions (including implicit ones).
536///
537/// Example matches string(ptr, n) and ptr within arguments of f
538///     (matcher = constructExpr())
539/// \code
540///   void f(const string &a, const string &b);
541///   char *ptr;
542///   int n;
543///   f(string(ptr, n), ptr);
544/// \endcode
545const internal::VariadicDynCastAllOfMatcher<
546  Stmt,
547  CXXConstructExpr> constructExpr;
548
549/// \brief Matches implicit and explicit this expressions.
550///
551/// Example matches the implicit this expression in "return i".
552///     (matcher = thisExpr())
553/// \code
554/// struct foo {
555///   int i;
556///   int f() { return i; }
557/// };
558/// \endcode
559const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr;
560
561/// \brief Matches nodes where temporaries are created.
562///
563/// Example matches FunctionTakesString(GetStringByValue())
564///     (matcher = bindTemporaryExpr())
565/// \code
566///   FunctionTakesString(GetStringByValue());
567///   FunctionTakesStringByPointer(GetStringPointer());
568/// \endcode
569const internal::VariadicDynCastAllOfMatcher<
570  Stmt,
571  CXXBindTemporaryExpr> bindTemporaryExpr;
572
573/// \brief Matches nodes where temporaries are materialized.
574///
575/// Example: Given
576/// \code
577///   struct T {void func()};
578///   T f();
579///   void g(T);
580/// \endcode
581/// materializeTemporaryExpr() matches 'f()' in these statements
582/// \code
583///   T u(f());
584///   g(f());
585/// \endcode
586/// but does not match
587/// \code
588///   f();
589///   f().func();
590/// \endcode
591const internal::VariadicDynCastAllOfMatcher<
592  Stmt,
593  MaterializeTemporaryExpr> materializeTemporaryExpr;
594
595/// \brief Matches new expressions.
596///
597/// Given
598/// \code
599///   new X;
600/// \endcode
601/// newExpr()
602///   matches 'new X'.
603const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr;
604
605/// \brief Matches delete expressions.
606///
607/// Given
608/// \code
609///   delete X;
610/// \endcode
611/// deleteExpr()
612///   matches 'delete X'.
613const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr;
614
615/// \brief Matches array subscript expressions.
616///
617/// Given
618/// \code
619///   int i = a[1];
620/// \endcode
621/// arraySubscriptExpr()
622///   matches "a[1]"
623const internal::VariadicDynCastAllOfMatcher<
624  Stmt,
625  ArraySubscriptExpr> arraySubscriptExpr;
626
627/// \brief Matches the value of a default argument at the call site.
628///
629/// Example matches the CXXDefaultArgExpr placeholder inserted for the
630///     default value of the second parameter in the call expression f(42)
631///     (matcher = defaultArgExpr())
632/// \code
633///   void f(int x, int y = 0);
634///   f(42);
635/// \endcode
636const internal::VariadicDynCastAllOfMatcher<
637  Stmt,
638  CXXDefaultArgExpr> defaultArgExpr;
639
640/// \brief Matches overloaded operator calls.
641///
642/// Note that if an operator isn't overloaded, it won't match. Instead, use
643/// binaryOperator matcher.
644/// Currently it does not match operators such as new delete.
645/// FIXME: figure out why these do not match?
646///
647/// Example matches both operator<<((o << b), c) and operator<<(o, b)
648///     (matcher = operatorCallExpr())
649/// \code
650///   ostream &operator<< (ostream &out, int i) { };
651///   ostream &o; int b = 1, c = 1;
652///   o << b << c;
653/// \endcode
654const internal::VariadicDynCastAllOfMatcher<
655  Stmt,
656  CXXOperatorCallExpr> operatorCallExpr;
657
658/// \brief Matches expressions.
659///
660/// Example matches x()
661/// \code
662///   void f() { x(); }
663/// \endcode
664const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
665
666/// \brief Matches expressions that refer to declarations.
667///
668/// Example matches x in if (x)
669/// \code
670///   bool x;
671///   if (x) {}
672/// \endcode
673const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
674
675/// \brief Matches if statements.
676///
677/// Example matches 'if (x) {}'
678/// \code
679///   if (x) {}
680/// \endcode
681const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
682
683/// \brief Matches for statements.
684///
685/// Example matches 'for (;;) {}'
686/// \code
687///   for (;;) {}
688///   int i[] =  {1, 2, 3}; for (auto a : i);
689/// \endcode
690const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
691
692/// \brief Matches range-based for statements.
693///
694/// forRangeStmt() matches 'for (auto a : i)'
695/// \code
696///   int i[] =  {1, 2, 3}; for (auto a : i);
697///   for(int j = 0; j < 5; ++j);
698/// \endcode
699const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt;
700
701/// \brief Matches the increment statement of a for loop.
702///
703/// Example:
704///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
705/// matches '++x' in
706/// \code
707///     for (x; x < N; ++x) { }
708/// \endcode
709AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
710              InnerMatcher) {
711  const Stmt *const Increment = Node.getInc();
712  return (Increment != NULL &&
713          InnerMatcher.matches(*Increment, Finder, Builder));
714}
715
716/// \brief Matches the initialization statement of a for loop.
717///
718/// Example:
719///     forStmt(hasLoopInit(declStmt()))
720/// matches 'int x = 0' in
721/// \code
722///     for (int x = 0; x < N; ++x) { }
723/// \endcode
724AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
725              InnerMatcher) {
726  const Stmt *const Init = Node.getInit();
727  return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
728}
729
730/// \brief Matches while statements.
731///
732/// Given
733/// \code
734///   while (true) {}
735/// \endcode
736/// whileStmt()
737///   matches 'while (true) {}'.
738const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
739
740/// \brief Matches do statements.
741///
742/// Given
743/// \code
744///   do {} while (true);
745/// \endcode
746/// doStmt()
747///   matches 'do {} while(true)'
748const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
749
750/// \brief Matches break statements.
751///
752/// Given
753/// \code
754///   while (true) { break; }
755/// \endcode
756/// breakStmt()
757///   matches 'break'
758const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
759
760/// \brief Matches continue statements.
761///
762/// Given
763/// \code
764///   while (true) { continue; }
765/// \endcode
766/// continueStmt()
767///   matches 'continue'
768const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
769
770/// \brief Matches return statements.
771///
772/// Given
773/// \code
774///   return 1;
775/// \endcode
776/// returnStmt()
777///   matches 'return 1'
778const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
779
780/// \brief Matches goto statements.
781///
782/// Given
783/// \code
784///   goto FOO;
785///   FOO: bar();
786/// \endcode
787/// gotoStmt()
788///   matches 'goto FOO'
789const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
790
791/// \brief Matches label statements.
792///
793/// Given
794/// \code
795///   goto FOO;
796///   FOO: bar();
797/// \endcode
798/// labelStmt()
799///   matches 'FOO:'
800const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
801
802/// \brief Matches switch statements.
803///
804/// Given
805/// \code
806///   switch(a) { case 42: break; default: break; }
807/// \endcode
808/// switchStmt()
809///   matches 'switch(a)'.
810const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
811
812/// \brief Matches case and default statements inside switch statements.
813///
814/// Given
815/// \code
816///   switch(a) { case 42: break; default: break; }
817/// \endcode
818/// switchCase()
819///   matches 'case 42: break;' and 'default: break;'.
820const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
821
822/// \brief Matches compound statements.
823///
824/// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
825/// \code
826///   for (;;) {{}}
827/// \endcode
828const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
829
830/// \brief Matches catch statements.
831///
832/// \code
833///   try {} catch(int i) {}
834/// \endcode
835/// catchStmt()
836///   matches 'catch(int i)'
837const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt;
838
839/// \brief Matches try statements.
840///
841/// \code
842///   try {} catch(int i) {}
843/// \endcode
844/// tryStmt()
845///   matches 'try {}'
846const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt;
847
848/// \brief Matches throw expressions.
849///
850/// \code
851///   try { throw 5; } catch(int i) {}
852/// \endcode
853/// throwExpr()
854///   matches 'throw 5'
855const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr;
856
857/// \brief Matches null statements.
858///
859/// \code
860///   foo();;
861/// \endcode
862/// nullStmt()
863///   matches the second ';'
864const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
865
866/// \brief Matches asm statements.
867///
868/// \code
869///  int i = 100;
870///   __asm("mov al, 2");
871/// \endcode
872/// asmStmt()
873///   matches '__asm("mov al, 2")'
874const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
875
876/// \brief Matches bool literals.
877///
878/// Example matches true
879/// \code
880///   true
881/// \endcode
882const internal::VariadicDynCastAllOfMatcher<
883  Stmt,
884  CXXBoolLiteralExpr> boolLiteral;
885
886/// \brief Matches string literals (also matches wide string literals).
887///
888/// Example matches "abcd", L"abcd"
889/// \code
890///   char *s = "abcd"; wchar_t *ws = L"abcd"
891/// \endcode
892const internal::VariadicDynCastAllOfMatcher<
893  Stmt,
894  StringLiteral> stringLiteral;
895
896/// \brief Matches character literals (also matches wchar_t).
897///
898/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
899/// though.
900///
901/// Example matches 'a', L'a'
902/// \code
903///   char ch = 'a'; wchar_t chw = L'a';
904/// \endcode
905const internal::VariadicDynCastAllOfMatcher<
906  Stmt,
907  CharacterLiteral> characterLiteral;
908
909/// \brief Matches integer literals of all sizes / encodings.
910///
911/// Not matching character-encoded integers such as L'a'.
912///
913/// Example matches 1, 1L, 0x1, 1U
914const internal::VariadicDynCastAllOfMatcher<
915  Stmt,
916  IntegerLiteral> integerLiteral;
917
918/// \brief Matches user defined literal operator call.
919///
920/// Example match: "foo"_suffix
921const internal::VariadicDynCastAllOfMatcher<
922  Stmt,
923  UserDefinedLiteral> userDefinedLiteral;
924
925/// \brief Matches nullptr literal.
926const internal::VariadicDynCastAllOfMatcher<
927  Stmt,
928  CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
929
930/// \brief Matches binary operator expressions.
931///
932/// Example matches a || b
933/// \code
934///   !(a || b)
935/// \endcode
936const internal::VariadicDynCastAllOfMatcher<
937  Stmt,
938  BinaryOperator> binaryOperator;
939
940/// \brief Matches unary operator expressions.
941///
942/// Example matches !a
943/// \code
944///   !a || b
945/// \endcode
946const internal::VariadicDynCastAllOfMatcher<
947  Stmt,
948  UnaryOperator> unaryOperator;
949
950/// \brief Matches conditional operator expressions.
951///
952/// Example matches a ? b : c
953/// \code
954///   (a ? b : c) + 42
955/// \endcode
956const internal::VariadicDynCastAllOfMatcher<
957  Stmt,
958  ConditionalOperator> conditionalOperator;
959
960/// \brief Matches a reinterpret_cast expression.
961///
962/// Either the source expression or the destination type can be matched
963/// using has(), but hasDestinationType() is more specific and can be
964/// more readable.
965///
966/// Example matches reinterpret_cast<char*>(&p) in
967/// \code
968///   void* p = reinterpret_cast<char*>(&p);
969/// \endcode
970const internal::VariadicDynCastAllOfMatcher<
971  Stmt,
972  CXXReinterpretCastExpr> reinterpretCastExpr;
973
974/// \brief Matches a C++ static_cast expression.
975///
976/// \see hasDestinationType
977/// \see reinterpretCast
978///
979/// Example:
980///   staticCastExpr()
981/// matches
982///   static_cast<long>(8)
983/// in
984/// \code
985///   long eight(static_cast<long>(8));
986/// \endcode
987const internal::VariadicDynCastAllOfMatcher<
988  Stmt,
989  CXXStaticCastExpr> staticCastExpr;
990
991/// \brief Matches a dynamic_cast expression.
992///
993/// Example:
994///   dynamicCastExpr()
995/// matches
996///   dynamic_cast<D*>(&b);
997/// in
998/// \code
999///   struct B { virtual ~B() {} }; struct D : B {};
1000///   B b;
1001///   D* p = dynamic_cast<D*>(&b);
1002/// \endcode
1003const internal::VariadicDynCastAllOfMatcher<
1004  Stmt,
1005  CXXDynamicCastExpr> dynamicCastExpr;
1006
1007/// \brief Matches a const_cast expression.
1008///
1009/// Example: Matches const_cast<int*>(&r) in
1010/// \code
1011///   int n = 42;
1012///   const int &r(n);
1013///   int* p = const_cast<int*>(&r);
1014/// \endcode
1015const internal::VariadicDynCastAllOfMatcher<
1016  Stmt,
1017  CXXConstCastExpr> constCastExpr;
1018
1019/// \brief Matches a C-style cast expression.
1020///
1021/// Example: Matches (int*) 2.2f in
1022/// \code
1023///   int i = (int) 2.2f;
1024/// \endcode
1025const internal::VariadicDynCastAllOfMatcher<
1026  Stmt,
1027  CStyleCastExpr> cStyleCastExpr;
1028
1029/// \brief Matches explicit cast expressions.
1030///
1031/// Matches any cast expression written in user code, whether it be a
1032/// C-style cast, a functional-style cast, or a keyword cast.
1033///
1034/// Does not match implicit conversions.
1035///
1036/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1037/// Clang uses the term "cast" to apply to implicit conversions as well as to
1038/// actual cast expressions.
1039///
1040/// \see hasDestinationType.
1041///
1042/// Example: matches all five of the casts in
1043/// \code
1044///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1045/// \endcode
1046/// but does not match the implicit conversion in
1047/// \code
1048///   long ell = 42;
1049/// \endcode
1050const internal::VariadicDynCastAllOfMatcher<
1051  Stmt,
1052  ExplicitCastExpr> explicitCastExpr;
1053
1054/// \brief Matches the implicit cast nodes of Clang's AST.
1055///
1056/// This matches many different places, including function call return value
1057/// eliding, as well as any type conversions.
1058const internal::VariadicDynCastAllOfMatcher<
1059  Stmt,
1060  ImplicitCastExpr> implicitCastExpr;
1061
1062/// \brief Matches any cast nodes of Clang's AST.
1063///
1064/// Example: castExpr() matches each of the following:
1065/// \code
1066///   (int) 3;
1067///   const_cast<Expr *>(SubExpr);
1068///   char c = 0;
1069/// \endcode
1070/// but does not match
1071/// \code
1072///   int i = (0);
1073///   int k = 0;
1074/// \endcode
1075const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1076
1077/// \brief Matches functional cast expressions
1078///
1079/// Example: Matches Foo(bar);
1080/// \code
1081///   Foo f = bar;
1082///   Foo g = (Foo) bar;
1083///   Foo h = Foo(bar);
1084/// \endcode
1085const internal::VariadicDynCastAllOfMatcher<
1086  Stmt,
1087  CXXFunctionalCastExpr> functionalCastExpr;
1088
1089/// \brief Matches \c QualTypes in the clang AST.
1090const internal::VariadicAllOfMatcher<QualType> qualType;
1091
1092/// \brief Matches \c Types in the clang AST.
1093const internal::VariadicDynCastAllOfMatcher<Type, Type> type;
1094
1095/// \brief Matches \c TypeLocs in the clang AST.
1096const internal::VariadicDynCastAllOfMatcher<TypeLoc, TypeLoc> typeLoc;
1097
1098/// \brief Various overloads for the anyOf matcher.
1099/// @{
1100
1101/// \brief Matches if any of the given matchers matches.
1102///
1103/// Usable as: Any Matcher
1104template<typename M1, typename M2>
1105internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2>
1106anyOf(const M1 &P1, const M2 &P2) {
1107  return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1108                                                M1, M2 >(P1, P2);
1109}
1110template<typename M1, typename M2, typename M3>
1111internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1112    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> >
1113anyOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1114  return anyOf(P1, anyOf(P2, P3));
1115}
1116template<typename M1, typename M2, typename M3, typename M4>
1117internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1118    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1119        internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1120                                               M3, M4> > >
1121anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1122  return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
1123}
1124template<typename M1, typename M2, typename M3, typename M4, typename M5>
1125internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1126    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1127        internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3,
1128            internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1129                                                   M4, M5> > > >
1130anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1131  return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
1132}
1133
1134/// @}
1135
1136/// \brief Various overloads for the allOf matcher.
1137/// @{
1138
1139/// \brief Matches if all given matchers match.
1140///
1141/// Usable as: Any Matcher
1142template<typename M1, typename M2>
1143internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>
1144allOf(const M1 &P1, const M2 &P2) {
1145  return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher,
1146                                                M1, M2>(P1, P2);
1147}
1148template<typename M1, typename M2, typename M3>
1149internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1,
1150    internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> >
1151allOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1152  return allOf(P1, allOf(P2, P3));
1153}
1154
1155/// @}
1156
1157/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1158///
1159/// Given
1160/// \code
1161///   Foo x = bar;
1162///   int y = sizeof(x) + alignof(x);
1163/// \endcode
1164/// unaryExprOrTypeTraitExpr()
1165///   matches \c sizeof(x) and \c alignof(x)
1166const internal::VariadicDynCastAllOfMatcher<
1167  Stmt,
1168  UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1169
1170/// \brief Matches unary expressions that have a specific type of argument.
1171///
1172/// Given
1173/// \code
1174///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1175/// \endcode
1176/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1177///   matches \c sizeof(a) and \c alignof(c)
1178AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1179              internal::Matcher<QualType>, InnerMatcher) {
1180  const QualType ArgumentType = Node.getTypeOfArgument();
1181  return InnerMatcher.matches(ArgumentType, Finder, Builder);
1182}
1183
1184/// \brief Matches unary expressions of a certain kind.
1185///
1186/// Given
1187/// \code
1188///   int x;
1189///   int s = sizeof(x) + alignof(x)
1190/// \endcode
1191/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1192///   matches \c sizeof(x)
1193AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1194  return Node.getKind() == Kind;
1195}
1196
1197/// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1198/// alignof.
1199inline internal::Matcher<Stmt> alignOfExpr(
1200    const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1201  return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
1202      ofKind(UETT_AlignOf), InnerMatcher)));
1203}
1204
1205/// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1206/// sizeof.
1207inline internal::Matcher<Stmt> sizeOfExpr(
1208    const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1209  return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
1210      ofKind(UETT_SizeOf), InnerMatcher)));
1211}
1212
1213/// \brief Matches NamedDecl nodes that have the specified name.
1214///
1215/// Supports specifying enclosing namespaces or classes by prefixing the name
1216/// with '<enclosing>::'.
1217/// Does not match typedefs of an underlying type with the given name.
1218///
1219/// Example matches X (Name == "X")
1220/// \code
1221///   class X;
1222/// \endcode
1223///
1224/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1225/// \code
1226///   namespace a { namespace b { class X; } }
1227/// \endcode
1228AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1229  assert(!Name.empty());
1230  const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1231  const llvm::StringRef FullName = FullNameString;
1232  const llvm::StringRef Pattern = Name;
1233  if (Pattern.startswith("::")) {
1234    return FullName == Pattern;
1235  } else {
1236    return FullName.endswith(("::" + Pattern).str());
1237  }
1238}
1239
1240/// \brief Matches NamedDecl nodes whose fully qualified names contain
1241/// a substring matched by the given RegExp.
1242///
1243/// Supports specifying enclosing namespaces or classes by
1244/// prefixing the name with '<enclosing>::'.  Does not match typedefs
1245/// of an underlying type with the given name.
1246///
1247/// Example matches X (regexp == "::X")
1248/// \code
1249///   class X;
1250/// \endcode
1251///
1252/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1253/// \code
1254///   namespace foo { namespace bar { class X; } }
1255/// \endcode
1256AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1257  assert(!RegExp.empty());
1258  std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1259  llvm::Regex RE(RegExp);
1260  return RE.match(FullNameString);
1261}
1262
1263/// \brief Matches overloaded operator names.
1264///
1265/// Matches overloaded operator names specified in strings without the
1266/// "operator" prefix, such as "<<", for OverloadedOperatorCall's.
1267///
1268/// Example matches a << b
1269///     (matcher == operatorCallExpr(hasOverloadedOperatorName("<<")))
1270/// \code
1271///   a << b;
1272///   c && d;  // assuming both operator<<
1273///            // and operator&& are overloaded somewhere.
1274/// \endcode
1275AST_MATCHER_P(CXXOperatorCallExpr,
1276              hasOverloadedOperatorName, std::string, Name) {
1277  return getOperatorSpelling(Node.getOperator()) == Name;
1278}
1279
1280/// \brief Matches C++ classes that are directly or indirectly derived from
1281/// a class matching \c Base.
1282///
1283/// Note that a class is not considered to be derived from itself.
1284///
1285/// Example matches Y, Z, C (Base == hasName("X"))
1286/// \code
1287///   class X;
1288///   class Y : public X {};  // directly derived
1289///   class Z : public Y {};  // indirectly derived
1290///   typedef X A;
1291///   typedef A B;
1292///   class C : public B {};  // derived from a typedef of X
1293/// \endcode
1294///
1295/// In the following example, Bar matches isDerivedFrom(hasName("X")):
1296/// \code
1297///   class Foo;
1298///   typedef Foo X;
1299///   class Bar : public Foo {};  // derived from a type that X is a typedef of
1300/// \endcode
1301AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1302              internal::Matcher<NamedDecl>, Base) {
1303  return Finder->classIsDerivedFrom(&Node, Base, Builder);
1304}
1305
1306/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1307inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
1308  assert(!BaseName.empty());
1309  return isDerivedFrom(hasName(BaseName));
1310}
1311
1312/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1313/// match \c Base.
1314inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1315    internal::Matcher<NamedDecl> Base) {
1316  return anyOf(Base, isDerivedFrom(Base));
1317}
1318
1319/// \brief Overloaded method as shortcut for
1320/// \c isSameOrDerivedFrom(hasName(...)).
1321inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1322    StringRef BaseName) {
1323  assert(!BaseName.empty());
1324  return isSameOrDerivedFrom(hasName(BaseName));
1325}
1326
1327/// \brief Matches AST nodes that have child AST nodes that match the
1328/// provided matcher.
1329///
1330/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1331/// \code
1332///   class X {};  // Matches X, because X::X is a class of name X inside X.
1333///   class Y { class X {}; };
1334///   class Z { class Y { class X {}; }; };  // Does not match Z.
1335/// \endcode
1336///
1337/// ChildT must be an AST base type.
1338///
1339/// Usable as: Any Matcher
1340template <typename ChildT>
1341internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
1342    const internal::Matcher<ChildT> &ChildMatcher) {
1343  return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
1344                                           ChildT>(ChildMatcher);
1345}
1346
1347/// \brief Matches AST nodes that have descendant AST nodes that match the
1348/// provided matcher.
1349///
1350/// Example matches X, Y, Z
1351///     (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1352/// \code
1353///   class X {};  // Matches X, because X::X is a class of name X inside X.
1354///   class Y { class X {}; };
1355///   class Z { class Y { class X {}; }; };
1356/// \endcode
1357///
1358/// DescendantT must be an AST base type.
1359///
1360/// Usable as: Any Matcher
1361template <typename DescendantT>
1362internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
1363hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1364  return internal::ArgumentAdaptingMatcher<
1365    internal::HasDescendantMatcher,
1366    DescendantT>(DescendantMatcher);
1367}
1368
1369/// \brief Matches AST nodes that have child AST nodes that match the
1370/// provided matcher.
1371///
1372/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1373/// \code
1374///   class X {};  // Matches X, because X::X is a class of name X inside X.
1375///   class Y { class X {}; };
1376///   class Z { class Y { class X {}; }; };  // Does not match Z.
1377/// \endcode
1378///
1379/// ChildT must be an AST base type.
1380///
1381/// As opposed to 'has', 'forEach' will cause a match for each result that
1382/// matches instead of only on the first one.
1383///
1384/// Usable as: Any Matcher
1385template <typename ChildT>
1386internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1387    const internal::Matcher<ChildT> &ChildMatcher) {
1388  return internal::ArgumentAdaptingMatcher<
1389    internal::ForEachMatcher,
1390    ChildT>(ChildMatcher);
1391}
1392
1393/// \brief Matches AST nodes that have descendant AST nodes that match the
1394/// provided matcher.
1395///
1396/// Example matches X, A, B, C
1397///     (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1398/// \code
1399///   class X {};  // Matches X, because X::X is a class of name X inside X.
1400///   class A { class X {}; };
1401///   class B { class C { class X {}; }; };
1402/// \endcode
1403///
1404/// DescendantT must be an AST base type.
1405///
1406/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1407/// each result that matches instead of only on the first one.
1408///
1409/// Note: Recursively combined ForEachDescendant can cause many matches:
1410///   recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1411/// will match 10 times (plus injected class name matches) on:
1412/// \code
1413///   class A { class B { class C { class D { class E {}; }; }; }; };
1414/// \endcode
1415///
1416/// Usable as: Any Matcher
1417template <typename DescendantT>
1418internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher,
1419                                  DescendantT>
1420forEachDescendant(
1421    const internal::Matcher<DescendantT> &DescendantMatcher) {
1422  return internal::ArgumentAdaptingMatcher<
1423    internal::ForEachDescendantMatcher,
1424    DescendantT>(DescendantMatcher);
1425}
1426
1427/// \brief Matches AST nodes that have a parent that matches the provided
1428/// matcher.
1429///
1430/// Given
1431/// \code
1432/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1433/// \endcode
1434/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1435///
1436/// Usable as: Any Matcher
1437template <typename ParentT>
1438internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT>
1439hasParent(const internal::Matcher<ParentT> &ParentMatcher) {
1440  return internal::ArgumentAdaptingMatcher<
1441    internal::HasParentMatcher,
1442    ParentT>(ParentMatcher);
1443}
1444
1445/// \brief Matches AST nodes that have an ancestor that matches the provided
1446/// matcher.
1447///
1448/// Given
1449/// \code
1450/// void f() { if (true) { int x = 42; } }
1451/// void g() { for (;;) { int x = 43; } }
1452/// \endcode
1453/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1454///
1455/// Usable as: Any Matcher
1456template <typename AncestorT>
1457internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT>
1458hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) {
1459  return internal::ArgumentAdaptingMatcher<
1460    internal::HasAncestorMatcher,
1461    AncestorT>(AncestorMatcher);
1462}
1463
1464/// \brief Matches if the provided matcher does not match.
1465///
1466/// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1467/// \code
1468///   class X {};
1469///   class Y {};
1470/// \endcode
1471///
1472/// Usable as: Any Matcher
1473template <typename M>
1474internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M>
1475unless(const M &InnerMatcher) {
1476  return internal::PolymorphicMatcherWithParam1<
1477    internal::NotMatcher, M>(InnerMatcher);
1478}
1479
1480/// \brief Matches a type if the declaration of the type matches the given
1481/// matcher.
1482///
1483/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1484///   Matcher<MemberExpr>
1485inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1486                                     internal::Matcher<Decl> >
1487    hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1488  return internal::PolymorphicMatcherWithParam1<
1489    internal::HasDeclarationMatcher,
1490    internal::Matcher<Decl> >(InnerMatcher);
1491}
1492
1493/// \brief Matches on the implicit object argument of a member call expression.
1494///
1495/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1496/// \code
1497///   class Y { public: void x(); };
1498///   void z() { Y y; y.x(); }",
1499/// \endcode
1500///
1501/// FIXME: Overload to allow directly matching types?
1502AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1503              InnerMatcher) {
1504  const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node)
1505      .getImplicitObjectArgument()
1506      ->IgnoreParenImpCasts();
1507  return (ExprNode != NULL &&
1508          InnerMatcher.matches(*ExprNode, Finder, Builder));
1509}
1510
1511/// \brief Matches if the call expression's callee expression matches.
1512///
1513/// Given
1514/// \code
1515///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
1516///   void f() { f(); }
1517/// \endcode
1518/// callExpr(callee(expr()))
1519///   matches this->x(), x(), y.x(), f()
1520/// with callee(...)
1521///   matching this->x, x, y.x, f respectively
1522///
1523/// Note: Callee cannot take the more general internal::Matcher<Expr>
1524/// because this introduces ambiguous overloads with calls to Callee taking a
1525/// internal::Matcher<Decl>, as the matcher hierarchy is purely
1526/// implemented in terms of implicit casts.
1527AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1528              InnerMatcher) {
1529  const Expr *ExprNode = Node.getCallee();
1530  return (ExprNode != NULL &&
1531          InnerMatcher.matches(*ExprNode, Finder, Builder));
1532}
1533
1534/// \brief Matches if the call expression's callee's declaration matches the
1535/// given matcher.
1536///
1537/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1538/// \code
1539///   class Y { public: void x(); };
1540///   void z() { Y y; y.x();
1541/// \endcode
1542inline internal::Matcher<CallExpr> callee(
1543    const internal::Matcher<Decl> &InnerMatcher) {
1544  return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher));
1545}
1546
1547/// \brief Matches if the expression's or declaration's type matches a type
1548/// matcher.
1549///
1550/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1551///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1552/// \code
1553///  class X {};
1554///  void y(X &x) { x; X z; }
1555/// \endcode
1556AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1557                          InnerMatcher) {
1558  TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1559                          llvm::is_base_of<ValueDecl, NodeType>::value),
1560                         instantiated_with_wrong_types);
1561  return InnerMatcher.matches(Node.getType(), Finder, Builder);
1562}
1563
1564/// \brief Overloaded to match the declaration of the expression's or value
1565/// declaration's type.
1566///
1567/// In case of a value declaration (for example a variable declaration),
1568/// this resolves one layer of indirection. For example, in the value
1569/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1570/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1571/// of x."
1572///
1573/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1574///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1575/// \code
1576///  class X {};
1577///  void y(X &x) { x; X z; }
1578/// \endcode
1579///
1580/// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1581inline internal::PolymorphicMatcherWithParam1<
1582  internal::matcher_hasTypeMatcher,
1583  internal::Matcher<QualType> >
1584hasType(const internal::Matcher<Decl> &InnerMatcher) {
1585  return hasType(internal::Matcher<QualType>(
1586    hasDeclaration(InnerMatcher)));
1587}
1588
1589/// \brief Matches if the matched type is represented by the given string.
1590///
1591/// Given
1592/// \code
1593///   class Y { public: void x(); };
1594///   void z() { Y* y; y->x(); }
1595/// \endcode
1596/// callExpr(on(hasType(asString("class Y *"))))
1597///   matches y->x()
1598AST_MATCHER_P(QualType, asString, std::string, Name) {
1599  return Name == Node.getAsString();
1600}
1601
1602/// \brief Matches if the matched type is a pointer type and the pointee type
1603/// matches the specified matcher.
1604///
1605/// Example matches y->x()
1606///     (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1607/// \code
1608///   class Y { public: void x(); };
1609///   void z() { Y *y; y->x(); }
1610/// \endcode
1611AST_MATCHER_P(
1612    QualType, pointsTo, internal::Matcher<QualType>,
1613    InnerMatcher) {
1614  return (!Node.isNull() && Node->isPointerType() &&
1615          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1616}
1617
1618/// \brief Overloaded to match the pointee type's declaration.
1619inline internal::Matcher<QualType> pointsTo(
1620    const internal::Matcher<Decl> &InnerMatcher) {
1621  return pointsTo(internal::Matcher<QualType>(
1622    hasDeclaration(InnerMatcher)));
1623}
1624
1625/// \brief Matches if the matched type is a reference type and the referenced
1626/// type matches the specified matcher.
1627///
1628/// Example matches X &x and const X &y
1629///     (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1630/// \code
1631///   class X {
1632///     void a(X b) {
1633///       X &x = b;
1634///       const X &y = b;
1635///   };
1636/// \endcode
1637AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1638              InnerMatcher) {
1639  return (!Node.isNull() && Node->isReferenceType() &&
1640          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1641}
1642
1643/// \brief Overloaded to match the referenced type's declaration.
1644inline internal::Matcher<QualType> references(
1645    const internal::Matcher<Decl> &InnerMatcher) {
1646  return references(internal::Matcher<QualType>(
1647    hasDeclaration(InnerMatcher)));
1648}
1649
1650AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1651              internal::Matcher<Expr>, InnerMatcher) {
1652  const Expr *ExprNode =
1653      const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument();
1654  return (ExprNode != NULL &&
1655          InnerMatcher.matches(*ExprNode, Finder, Builder));
1656}
1657
1658/// \brief Matches if the expression's type either matches the specified
1659/// matcher, or is a pointer to a type that matches the InnerMatcher.
1660inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1661    const internal::Matcher<QualType> &InnerMatcher) {
1662  return onImplicitObjectArgument(
1663      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1664}
1665
1666/// \brief Overloaded to match the type's declaration.
1667inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1668    const internal::Matcher<Decl> &InnerMatcher) {
1669  return onImplicitObjectArgument(
1670      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1671}
1672
1673/// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1674/// specified matcher.
1675///
1676/// Example matches x in if(x)
1677///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
1678/// \code
1679///   bool x;
1680///   if (x) {}
1681/// \endcode
1682AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1683              InnerMatcher) {
1684  const Decl *DeclNode = Node.getDecl();
1685  return (DeclNode != NULL &&
1686          InnerMatcher.matches(*DeclNode, Finder, Builder));
1687}
1688
1689/// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1690/// specific using shadow declaration.
1691///
1692/// FIXME: This currently only works for functions. Fix.
1693///
1694/// Given
1695/// \code
1696///   namespace a { void f() {} }
1697///   using a::f;
1698///   void g() {
1699///     f();     // Matches this ..
1700///     a::f();  // .. but not this.
1701///   }
1702/// \endcode
1703/// declRefExpr(throughUsingDeclaration(anything()))
1704///   matches \c f()
1705AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1706              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
1707  const NamedDecl *FoundDecl = Node.getFoundDecl();
1708  if (const UsingShadowDecl *UsingDecl =
1709      llvm::dyn_cast<UsingShadowDecl>(FoundDecl))
1710    return InnerMatcher.matches(*UsingDecl, Finder, Builder);
1711  return false;
1712}
1713
1714/// \brief Matches the Decl of a DeclStmt which has a single declaration.
1715///
1716/// Given
1717/// \code
1718///   int a, b;
1719///   int c;
1720/// \endcode
1721/// declStmt(hasSingleDecl(anything()))
1722///   matches 'int c;' but not 'int a, b;'.
1723AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1724  if (Node.isSingleDecl()) {
1725    const Decl *FoundDecl = Node.getSingleDecl();
1726    return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1727  }
1728  return false;
1729}
1730
1731/// \brief Matches a variable declaration that has an initializer expression
1732/// that matches the given matcher.
1733///
1734/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
1735/// \code
1736///   bool y() { return true; }
1737///   bool x = y();
1738/// \endcode
1739AST_MATCHER_P(
1740    VarDecl, hasInitializer, internal::Matcher<Expr>,
1741    InnerMatcher) {
1742  const Expr *Initializer = Node.getAnyInitializer();
1743  return (Initializer != NULL &&
1744          InnerMatcher.matches(*Initializer, Finder, Builder));
1745}
1746
1747/// \brief Checks that a call expression or a constructor call expression has
1748/// a specific number of arguments (including absent default arguments).
1749///
1750/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
1751/// \code
1752///   void f(int x, int y);
1753///   f(0, 0);
1754/// \endcode
1755AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1756  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1757                          llvm::is_base_of<CXXConstructExpr,
1758                                           NodeType>::value),
1759                         instantiated_with_wrong_types);
1760  return Node.getNumArgs() == N;
1761}
1762
1763/// \brief Matches the n'th argument of a call expression or a constructor
1764/// call expression.
1765///
1766/// Example matches y in x(y)
1767///     (matcher = callExpr(hasArgument(0, declRefExpr())))
1768/// \code
1769///   void x(int) { int y; x(y); }
1770/// \endcode
1771AST_POLYMORPHIC_MATCHER_P2(
1772    hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1773  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1774                         llvm::is_base_of<CXXConstructExpr,
1775                                          NodeType>::value),
1776                         instantiated_with_wrong_types);
1777  return (N < Node.getNumArgs() &&
1778          InnerMatcher.matches(
1779              *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1780}
1781
1782/// \brief Matches declaration statements that contain a specific number of
1783/// declarations.
1784///
1785/// Example: Given
1786/// \code
1787///   int a, b;
1788///   int c;
1789///   int d = 2, e;
1790/// \endcode
1791/// declCountIs(2)
1792///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
1793AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
1794  return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
1795}
1796
1797/// \brief Matches the n'th declaration of a declaration statement.
1798///
1799/// Note that this does not work for global declarations because the AST
1800/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
1801/// DeclStmt's.
1802/// Example: Given non-global declarations
1803/// \code
1804///   int a, b = 0;
1805///   int c;
1806///   int d = 2, e;
1807/// \endcode
1808/// declStmt(containsDeclaration(
1809///       0, varDecl(hasInitializer(anything()))))
1810///   matches only 'int d = 2, e;', and
1811/// declStmt(containsDeclaration(1, varDecl()))
1812/// \code
1813///   matches 'int a, b = 0' as well as 'int d = 2, e;'
1814///   but 'int c;' is not matched.
1815/// \endcode
1816AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
1817               internal::Matcher<Decl>, InnerMatcher) {
1818  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
1819  if (N >= NumDecls)
1820    return false;
1821  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
1822  std::advance(Iterator, N);
1823  return InnerMatcher.matches(**Iterator, Finder, Builder);
1824}
1825
1826/// \brief Matches a constructor initializer.
1827///
1828/// Given
1829/// \code
1830///   struct Foo {
1831///     Foo() : foo_(1) { }
1832///     int foo_;
1833///   };
1834/// \endcode
1835/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
1836///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
1837AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
1838              internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
1839  for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
1840       I != Node.init_end(); ++I) {
1841    if (InnerMatcher.matches(**I, Finder, Builder)) {
1842      return true;
1843    }
1844  }
1845  return false;
1846}
1847
1848/// \brief Matches the field declaration of a constructor initializer.
1849///
1850/// Given
1851/// \code
1852///   struct Foo {
1853///     Foo() : foo_(1) { }
1854///     int foo_;
1855///   };
1856/// \endcode
1857/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
1858///     forField(hasName("foo_"))))))
1859///   matches Foo
1860/// with forField matching foo_
1861AST_MATCHER_P(CXXCtorInitializer, forField,
1862              internal::Matcher<FieldDecl>, InnerMatcher) {
1863  const FieldDecl *NodeAsDecl = Node.getMember();
1864  return (NodeAsDecl != NULL &&
1865      InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
1866}
1867
1868/// \brief Matches the initializer expression of a constructor initializer.
1869///
1870/// Given
1871/// \code
1872///   struct Foo {
1873///     Foo() : foo_(1) { }
1874///     int foo_;
1875///   };
1876/// \endcode
1877/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
1878///     withInitializer(integerLiteral(equals(1)))))))
1879///   matches Foo
1880/// with withInitializer matching (1)
1881AST_MATCHER_P(CXXCtorInitializer, withInitializer,
1882              internal::Matcher<Expr>, InnerMatcher) {
1883  const Expr* NodeAsExpr = Node.getInit();
1884  return (NodeAsExpr != NULL &&
1885      InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
1886}
1887
1888/// \brief Matches a contructor initializer if it is explicitly written in
1889/// code (as opposed to implicitly added by the compiler).
1890///
1891/// Given
1892/// \code
1893///   struct Foo {
1894///     Foo() { }
1895///     Foo(int) : foo_("A") { }
1896///     string foo_;
1897///   };
1898/// \endcode
1899/// constructorDecl(hasAnyConstructorInitializer(isWritten()))
1900///   will match Foo(int), but not Foo()
1901AST_MATCHER(CXXCtorInitializer, isWritten) {
1902  return Node.isWritten();
1903}
1904
1905/// \brief Matches a constructor declaration that has been implicitly added
1906/// by the compiler (eg. implicit default/copy constructors).
1907AST_MATCHER(CXXConstructorDecl, isImplicit) {
1908  return Node.isImplicit();
1909}
1910
1911/// \brief Matches any argument of a call expression or a constructor call
1912/// expression.
1913///
1914/// Given
1915/// \code
1916///   void x(int, int, int) { int y; x(1, y, 42); }
1917/// \endcode
1918/// callExpr(hasAnyArgument(declRefExpr()))
1919///   matches x(1, y, 42)
1920/// with hasAnyArgument(...)
1921///   matching y
1922AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
1923                          InnerMatcher) {
1924  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1925                         llvm::is_base_of<CXXConstructExpr,
1926                                          NodeType>::value),
1927                         instantiated_with_wrong_types);
1928  for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
1929    if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
1930                             Finder, Builder)) {
1931      return true;
1932    }
1933  }
1934  return false;
1935}
1936
1937/// \brief Matches the n'th parameter of a function declaration.
1938///
1939/// Given
1940/// \code
1941///   class X { void f(int x) {} };
1942/// \endcode
1943/// methodDecl(hasParameter(0, hasType(varDecl())))
1944///   matches f(int x) {}
1945/// with hasParameter(...)
1946///   matching int x
1947AST_MATCHER_P2(FunctionDecl, hasParameter,
1948               unsigned, N, internal::Matcher<ParmVarDecl>,
1949               InnerMatcher) {
1950  return (N < Node.getNumParams() &&
1951          InnerMatcher.matches(
1952              *Node.getParamDecl(N), Finder, Builder));
1953}
1954
1955/// \brief Matches any parameter of a function declaration.
1956///
1957/// Does not match the 'this' parameter of a method.
1958///
1959/// Given
1960/// \code
1961///   class X { void f(int x, int y, int z) {} };
1962/// \endcode
1963/// methodDecl(hasAnyParameter(hasName("y")))
1964///   matches f(int x, int y, int z) {}
1965/// with hasAnyParameter(...)
1966///   matching int y
1967AST_MATCHER_P(FunctionDecl, hasAnyParameter,
1968              internal::Matcher<ParmVarDecl>, InnerMatcher) {
1969  for (unsigned I = 0; I < Node.getNumParams(); ++I) {
1970    if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
1971      return true;
1972    }
1973  }
1974  return false;
1975}
1976
1977/// \brief Matches \c FunctionDecls that have a specific parameter count.
1978///
1979/// Given
1980/// \code
1981///   void f(int i) {}
1982///   void g(int i, int j) {}
1983/// \endcode
1984/// functionDecl(parameterCountIs(2))
1985///   matches g(int i, int j) {}
1986AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
1987  return Node.getNumParams() == N;
1988}
1989
1990/// \brief Matches the return type of a function declaration.
1991///
1992/// Given:
1993/// \code
1994///   class X { int f() { return 1; } };
1995/// \endcode
1996/// methodDecl(returns(asString("int")))
1997///   matches int f() { return 1; }
1998AST_MATCHER_P(FunctionDecl, returns,
1999              internal::Matcher<QualType>, InnerMatcher) {
2000  return InnerMatcher.matches(Node.getResultType(), Finder, Builder);
2001}
2002
2003/// \brief Matches extern "C" function declarations.
2004///
2005/// Given:
2006/// \code
2007///   extern "C" void f() {}
2008///   extern "C" { void g() {} }
2009///   void h() {}
2010/// \endcode
2011/// functionDecl(isExternC())
2012///   matches the declaration of f and g, but not the declaration h
2013AST_MATCHER(FunctionDecl, isExternC) {
2014  return Node.isExternC();
2015}
2016
2017/// \brief Matches the condition expression of an if statement, for loop,
2018/// or conditional operator.
2019///
2020/// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2021/// \code
2022///   if (true) {}
2023/// \endcode
2024AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
2025                          InnerMatcher) {
2026  TOOLING_COMPILE_ASSERT(
2027    (llvm::is_base_of<IfStmt, NodeType>::value) ||
2028    (llvm::is_base_of<ForStmt, NodeType>::value) ||
2029    (llvm::is_base_of<WhileStmt, NodeType>::value) ||
2030    (llvm::is_base_of<DoStmt, NodeType>::value) ||
2031    (llvm::is_base_of<ConditionalOperator, NodeType>::value),
2032    has_condition_requires_if_statement_conditional_operator_or_loop);
2033  const Expr *const Condition = Node.getCond();
2034  return (Condition != NULL &&
2035          InnerMatcher.matches(*Condition, Finder, Builder));
2036}
2037
2038/// \brief Matches the condition variable statement in an if statement.
2039///
2040/// Given
2041/// \code
2042///   if (A* a = GetAPointer()) {}
2043/// \endcode
2044/// hasConditionVariableStatment(...)
2045///   matches 'A* a = GetAPointer()'.
2046AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2047              internal::Matcher<DeclStmt>, InnerMatcher) {
2048  const DeclStmt* const DeclarationStatement =
2049    Node.getConditionVariableDeclStmt();
2050  return DeclarationStatement != NULL &&
2051         InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2052}
2053
2054/// \brief Matches the index expression of an array subscript expression.
2055///
2056/// Given
2057/// \code
2058///   int i[5];
2059///   void f() { i[1] = 42; }
2060/// \endcode
2061/// arraySubscriptExpression(hasIndex(integerLiteral()))
2062///   matches \c i[1] with the \c integerLiteral() matching \c 1
2063AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2064              internal::Matcher<Expr>, InnerMatcher) {
2065  if (const Expr* Expression = Node.getIdx())
2066    return InnerMatcher.matches(*Expression, Finder, Builder);
2067  return false;
2068}
2069
2070/// \brief Matches the base expression of an array subscript expression.
2071///
2072/// Given
2073/// \code
2074///   int i[5];
2075///   void f() { i[1] = 42; }
2076/// \endcode
2077/// arraySubscriptExpression(hasBase(implicitCastExpr(
2078///     hasSourceExpression(declRefExpr()))))
2079///   matches \c i[1] with the \c declRefExpr() matching \c i
2080AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2081              internal::Matcher<Expr>, InnerMatcher) {
2082  if (const Expr* Expression = Node.getBase())
2083    return InnerMatcher.matches(*Expression, Finder, Builder);
2084  return false;
2085}
2086
2087/// \brief Matches a 'for', 'while', or 'do while' statement that has
2088/// a given body.
2089///
2090/// Given
2091/// \code
2092///   for (;;) {}
2093/// \endcode
2094/// hasBody(compoundStmt())
2095///   matches 'for (;;) {}'
2096/// with compoundStmt()
2097///   matching '{}'
2098AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
2099                          InnerMatcher) {
2100  TOOLING_COMPILE_ASSERT(
2101      (llvm::is_base_of<DoStmt, NodeType>::value) ||
2102      (llvm::is_base_of<ForStmt, NodeType>::value) ||
2103      (llvm::is_base_of<WhileStmt, NodeType>::value),
2104      has_body_requires_for_while_or_do_statement);
2105  const Stmt *const Statement = Node.getBody();
2106  return (Statement != NULL &&
2107          InnerMatcher.matches(*Statement, Finder, Builder));
2108}
2109
2110/// \brief Matches compound statements where at least one substatement matches
2111/// a given matcher.
2112///
2113/// Given
2114/// \code
2115///   { {}; 1+2; }
2116/// \endcode
2117/// hasAnySubstatement(compoundStmt())
2118///   matches '{ {}; 1+2; }'
2119/// with compoundStmt()
2120///   matching '{}'
2121AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2122              internal::Matcher<Stmt>, InnerMatcher) {
2123  for (CompoundStmt::const_body_iterator It = Node.body_begin();
2124       It != Node.body_end();
2125       ++It) {
2126    if (InnerMatcher.matches(**It, Finder, Builder)) return true;
2127  }
2128  return false;
2129}
2130
2131/// \brief Checks that a compound statement contains a specific number of
2132/// child statements.
2133///
2134/// Example: Given
2135/// \code
2136///   { for (;;) {} }
2137/// \endcode
2138/// compoundStmt(statementCountIs(0)))
2139///   matches '{}'
2140///   but does not match the outer compound statement.
2141AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2142  return Node.size() == N;
2143}
2144
2145/// \brief Matches literals that are equal to the given value.
2146///
2147/// Example matches true (matcher = boolLiteral(equals(true)))
2148/// \code
2149///   true
2150/// \endcode
2151///
2152/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2153///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2154template <typename ValueT>
2155internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2156equals(const ValueT &Value) {
2157  return internal::PolymorphicMatcherWithParam1<
2158    internal::ValueEqualsMatcher,
2159    ValueT>(Value);
2160}
2161
2162/// \brief Matches the operator Name of operator expressions (binary or
2163/// unary).
2164///
2165/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2166/// \code
2167///   !(a || b)
2168/// \endcode
2169AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
2170  TOOLING_COMPILE_ASSERT(
2171    (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
2172    (llvm::is_base_of<UnaryOperator, NodeType>::value),
2173    has_condition_requires_if_statement_or_conditional_operator);
2174  return Name == Node.getOpcodeStr(Node.getOpcode());
2175}
2176
2177/// \brief Matches the left hand side of binary operator expressions.
2178///
2179/// Example matches a (matcher = binaryOperator(hasLHS()))
2180/// \code
2181///   a || b
2182/// \endcode
2183AST_MATCHER_P(BinaryOperator, hasLHS,
2184              internal::Matcher<Expr>, InnerMatcher) {
2185  Expr *LeftHandSide = Node.getLHS();
2186  return (LeftHandSide != NULL &&
2187          InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2188}
2189
2190/// \brief Matches the right hand side of binary operator expressions.
2191///
2192/// Example matches b (matcher = binaryOperator(hasRHS()))
2193/// \code
2194///   a || b
2195/// \endcode
2196AST_MATCHER_P(BinaryOperator, hasRHS,
2197              internal::Matcher<Expr>, InnerMatcher) {
2198  Expr *RightHandSide = Node.getRHS();
2199  return (RightHandSide != NULL &&
2200          InnerMatcher.matches(*RightHandSide, Finder, Builder));
2201}
2202
2203/// \brief Matches if either the left hand side or the right hand side of a
2204/// binary operator matches.
2205inline internal::Matcher<BinaryOperator> hasEitherOperand(
2206    const internal::Matcher<Expr> &InnerMatcher) {
2207  return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2208}
2209
2210/// \brief Matches if the operand of a unary operator matches.
2211///
2212/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2213/// \code
2214///   !true
2215/// \endcode
2216AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2217              internal::Matcher<Expr>, InnerMatcher) {
2218  const Expr * const Operand = Node.getSubExpr();
2219  return (Operand != NULL &&
2220          InnerMatcher.matches(*Operand, Finder, Builder));
2221}
2222
2223/// \brief Matches if the cast's source expression matches the given matcher.
2224///
2225/// Example: matches "a string" (matcher =
2226///                                  hasSourceExpression(constructExpr()))
2227/// \code
2228/// class URL { URL(string); };
2229/// URL url = "a string";
2230AST_MATCHER_P(CastExpr, hasSourceExpression,
2231              internal::Matcher<Expr>, InnerMatcher) {
2232  const Expr* const SubExpression = Node.getSubExpr();
2233  return (SubExpression != NULL &&
2234          InnerMatcher.matches(*SubExpression, Finder, Builder));
2235}
2236
2237/// \brief Matches casts whose destination type matches a given matcher.
2238///
2239/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2240/// actual casts "explicit" casts.)
2241AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2242              internal::Matcher<QualType>, InnerMatcher) {
2243  const QualType NodeType = Node.getTypeAsWritten();
2244  return InnerMatcher.matches(NodeType, Finder, Builder);
2245}
2246
2247/// \brief Matches implicit casts whose destination type matches a given
2248/// matcher.
2249///
2250/// FIXME: Unit test this matcher
2251AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2252              internal::Matcher<QualType>, InnerMatcher) {
2253  return InnerMatcher.matches(Node.getType(), Finder, Builder);
2254}
2255
2256/// \brief Matches the true branch expression of a conditional operator.
2257///
2258/// Example matches a
2259/// \code
2260///   condition ? a : b
2261/// \endcode
2262AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2263              internal::Matcher<Expr>, InnerMatcher) {
2264  Expr *Expression = Node.getTrueExpr();
2265  return (Expression != NULL &&
2266          InnerMatcher.matches(*Expression, Finder, Builder));
2267}
2268
2269/// \brief Matches the false branch expression of a conditional operator.
2270///
2271/// Example matches b
2272/// \code
2273///   condition ? a : b
2274/// \endcode
2275AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2276              internal::Matcher<Expr>, InnerMatcher) {
2277  Expr *Expression = Node.getFalseExpr();
2278  return (Expression != NULL &&
2279          InnerMatcher.matches(*Expression, Finder, Builder));
2280}
2281
2282/// \brief Matches if a declaration has a body attached.
2283///
2284/// Example matches A, va, fa
2285/// \code
2286///   class A {};
2287///   class B;  // Doesn't match, as it has no body.
2288///   int va;
2289///   extern int vb;  // Doesn't match, as it doesn't define the variable.
2290///   void fa() {}
2291///   void fb();  // Doesn't match, as it has no body.
2292/// \endcode
2293///
2294/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2295inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher>
2296isDefinition() {
2297  return internal::PolymorphicMatcherWithParam0<
2298    internal::IsDefinitionMatcher>();
2299}
2300
2301/// \brief Matches the class declaration that the given method declaration
2302/// belongs to.
2303///
2304/// FIXME: Generalize this for other kinds of declarations.
2305/// FIXME: What other kind of declarations would we need to generalize
2306/// this to?
2307///
2308/// Example matches A() in the last line
2309///     (matcher = constructExpr(hasDeclaration(methodDecl(
2310///         ofClass(hasName("A"))))))
2311/// \code
2312///   class A {
2313///    public:
2314///     A();
2315///   };
2316///   A a = A();
2317/// \endcode
2318AST_MATCHER_P(CXXMethodDecl, ofClass,
2319              internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2320  const CXXRecordDecl *Parent = Node.getParent();
2321  return (Parent != NULL &&
2322          InnerMatcher.matches(*Parent, Finder, Builder));
2323}
2324
2325/// \brief Matches member expressions that are called with '->' as opposed
2326/// to '.'.
2327///
2328/// Member calls on the implicit this pointer match as called with '->'.
2329///
2330/// Given
2331/// \code
2332///   class Y {
2333///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2334///     int a;
2335///     static int b;
2336///   };
2337/// \endcode
2338/// memberExpr(isArrow())
2339///   matches this->x, x, y.x, a, this->b
2340inline internal::Matcher<MemberExpr> isArrow() {
2341  return makeMatcher(new internal::IsArrowMatcher());
2342}
2343
2344/// \brief Matches QualType nodes that are of integer type.
2345///
2346/// Given
2347/// \code
2348///   void a(int);
2349///   void b(long);
2350///   void c(double);
2351/// \endcode
2352/// functionDecl(hasAnyParameter(hasType(isInteger())))
2353/// matches "a(int)", "b(long)", but not "c(double)".
2354AST_MATCHER(QualType, isInteger) {
2355    return Node->isIntegerType();
2356}
2357
2358/// \brief Matches QualType nodes that are const-qualified, i.e., that
2359/// include "top-level" const.
2360///
2361/// Given
2362/// \code
2363///   void a(int);
2364///   void b(int const);
2365///   void c(const int);
2366///   void d(const int*);
2367///   void e(int const) {};
2368/// \endcode
2369/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2370///   matches "void b(int const)", "void c(const int)" and
2371///   "void e(int const) {}". It does not match d as there
2372///   is no top-level const on the parameter type "const int *".
2373inline internal::Matcher<QualType> isConstQualified() {
2374  return makeMatcher(new internal::IsConstQualifiedMatcher());
2375}
2376
2377/// \brief Matches a member expression where the member is matched by a
2378/// given matcher.
2379///
2380/// Given
2381/// \code
2382///   struct { int first, second; } first, second;
2383///   int i(second.first);
2384///   int j(first.second);
2385/// \endcode
2386/// memberExpr(member(hasName("first")))
2387///   matches second.first
2388///   but not first.second (because the member name there is "second").
2389AST_MATCHER_P(MemberExpr, member,
2390              internal::Matcher<ValueDecl>, InnerMatcher) {
2391  return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2392}
2393
2394/// \brief Matches a member expression where the object expression is
2395/// matched by a given matcher.
2396///
2397/// Given
2398/// \code
2399///   struct X { int m; };
2400///   void f(X x) { x.m; m; }
2401/// \endcode
2402/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2403///   matches "x.m" and "m"
2404/// with hasObjectExpression(...)
2405///   matching "x" and the implicit object expression of "m" which has type X*.
2406AST_MATCHER_P(MemberExpr, hasObjectExpression,
2407              internal::Matcher<Expr>, InnerMatcher) {
2408  return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2409}
2410
2411/// \brief Matches any using shadow declaration.
2412///
2413/// Given
2414/// \code
2415///   namespace X { void b(); }
2416///   using X::b;
2417/// \endcode
2418/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2419///   matches \code using X::b \endcode
2420AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2421              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2422  for (UsingDecl::shadow_iterator II = Node.shadow_begin();
2423       II != Node.shadow_end(); ++II) {
2424    if (InnerMatcher.matches(**II, Finder, Builder))
2425      return true;
2426  }
2427  return false;
2428}
2429
2430/// \brief Matches a using shadow declaration where the target declaration is
2431/// matched by the given matcher.
2432///
2433/// Given
2434/// \code
2435///   namespace X { int a; void b(); }
2436///   using X::a;
2437///   using X::b;
2438/// \endcode
2439/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2440///   matches \code using X::b \endcode
2441///   but not \code using X::a \endcode
2442AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2443              internal::Matcher<NamedDecl>, InnerMatcher) {
2444  return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2445}
2446
2447/// \brief Matches template instantiations of function, class, or static
2448/// member variable template instantiations.
2449///
2450/// Given
2451/// \code
2452///   template <typename T> class X {}; class A {}; X<A> x;
2453/// \endcode
2454/// or
2455/// \code
2456///   template <typename T> class X {}; class A {}; template class X<A>;
2457/// \endcode
2458/// recordDecl(hasName("::X"), isTemplateInstantiation())
2459///   matches the template instantiation of X<A>.
2460///
2461/// But given
2462/// \code
2463///   template <typename T>  class X {}; class A {};
2464///   template <> class X<A> {}; X<A> x;
2465/// \endcode
2466/// recordDecl(hasName("::X"), isTemplateInstantiation())
2467///   does not match, as X<A> is an explicit template specialization.
2468///
2469/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2470inline internal::PolymorphicMatcherWithParam0<
2471  internal::IsTemplateInstantiationMatcher>
2472isTemplateInstantiation() {
2473  return internal::PolymorphicMatcherWithParam0<
2474    internal::IsTemplateInstantiationMatcher>();
2475}
2476
2477/// \brief Matches explicit template specializations of function, class, or
2478/// static member variable template instantiations.
2479///
2480/// Given
2481/// \code
2482///   template<typename T> void A(T t) { }
2483///   template<> void A(int N) { }
2484/// \endcode
2485/// functionDecl(isExplicitTemplateSpecialization())
2486///   matches the specialization A<int>().
2487///
2488/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2489inline internal::PolymorphicMatcherWithParam0<
2490  internal::IsExplicitTemplateSpecializationMatcher>
2491isExplicitTemplateSpecialization() {
2492  return internal::PolymorphicMatcherWithParam0<
2493    internal::IsExplicitTemplateSpecializationMatcher>();
2494}
2495
2496/// \brief Matches \c TypeLocs for which the given inner
2497/// QualType-matcher matches.
2498inline internal::BindableMatcher<TypeLoc> loc(
2499    const internal::Matcher<QualType> &InnerMatcher) {
2500  return internal::BindableMatcher<TypeLoc>(
2501      new internal::TypeLocTypeMatcher(InnerMatcher));
2502}
2503
2504/// \brief Matches builtin Types.
2505///
2506/// Given
2507/// \code
2508///   struct A {};
2509///   A a;
2510///   int b;
2511///   float c;
2512///   bool d;
2513/// \endcode
2514/// builtinType()
2515///   matches "int b", "float c" and "bool d"
2516AST_TYPE_MATCHER(BuiltinType, builtinType);
2517
2518/// \brief Matches all kinds of arrays.
2519///
2520/// Given
2521/// \code
2522///   int a[] = { 2, 3 };
2523///   int b[4];
2524///   void f() { int c[a[0]]; }
2525/// \endcode
2526/// arrayType()
2527///   matches "int a[]", "int b[4]" and "int c[a[0]]";
2528AST_TYPE_MATCHER(ArrayType, arrayType);
2529
2530/// \brief Matches C99 complex types.
2531///
2532/// Given
2533/// \code
2534///   _Complex float f;
2535/// \endcode
2536/// complexType()
2537///   matches "_Complex float f"
2538AST_TYPE_MATCHER(ComplexType, complexType);
2539
2540/// \brief Matches arrays and C99 complex types that have a specific element
2541/// type.
2542///
2543/// Given
2544/// \code
2545///   struct A {};
2546///   A a[7];
2547///   int b[7];
2548/// \endcode
2549/// arrayType(hasElementType(builtinType()))
2550///   matches "int b[7]"
2551///
2552/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
2553AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement);
2554
2555/// \brief Matches C arrays with a specified constant size.
2556///
2557/// Given
2558/// \code
2559///   void() {
2560///     int a[2];
2561///     int b[] = { 2, 3 };
2562///     int c[b[0]];
2563///   }
2564/// \endcode
2565/// constantArrayType()
2566///   matches "int a[2]"
2567AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
2568
2569/// \brief Matches \c ConstantArrayType nodes that have the specified size.
2570///
2571/// Given
2572/// \code
2573///   int a[42];
2574///   int b[2 * 21];
2575///   int c[41], d[43];
2576/// \endcode
2577/// constantArrayType(hasSize(42))
2578///   matches "int a[42]" and "int b[2 * 21]"
2579AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
2580  return Node.getSize() == N;
2581}
2582
2583/// \brief Matches C++ arrays whose size is a value-dependent expression.
2584///
2585/// Given
2586/// \code
2587///   template<typename T, int Size>
2588///   class array {
2589///     T data[Size];
2590///   };
2591/// \endcode
2592/// dependentSizedArrayType
2593///   matches "T data[Size]"
2594AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
2595
2596/// \brief Matches C arrays with unspecified size.
2597///
2598/// Given
2599/// \code
2600///   int a[] = { 2, 3 };
2601///   int b[42];
2602///   void f(int c[]) { int d[a[0]]; };
2603/// \endcode
2604/// incompleteArrayType()
2605///   matches "int a[]" and "int c[]"
2606AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
2607
2608/// \brief Matches C arrays with a specified size that is not an
2609/// integer-constant-expression.
2610///
2611/// Given
2612/// \code
2613///   void f() {
2614///     int a[] = { 2, 3 }
2615///     int b[42];
2616///     int c[a[0]];
2617/// \endcode
2618/// variableArrayType()
2619///   matches "int c[a[0]]"
2620AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
2621
2622/// \brief Matches \c VariableArrayType nodes that have a specific size
2623/// expression.
2624///
2625/// Given
2626/// \code
2627///   void f(int b) {
2628///     int a[b];
2629///   }
2630/// \endcode
2631/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
2632///   varDecl(hasName("b")))))))
2633///   matches "int a[b]"
2634AST_MATCHER_P(VariableArrayType, hasSizeExpr,
2635              internal::Matcher<Expr>, InnerMatcher) {
2636  return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
2637}
2638
2639/// \brief Matches atomic types.
2640///
2641/// Given
2642/// \code
2643///   _Atomic(int) i;
2644/// \endcode
2645/// atomicType()
2646///   matches "_Atomic(int) i"
2647AST_TYPE_MATCHER(AtomicType, atomicType);
2648
2649/// \brief Matches atomic types with a specific value type.
2650///
2651/// Given
2652/// \code
2653///   _Atomic(int) i;
2654///   _Atomic(float) f;
2655/// \endcode
2656/// atomicType(hasValueType(isInteger()))
2657///  matches "_Atomic(int) i"
2658///
2659/// Usable as: Matcher<AtomicType>
2660AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue);
2661
2662/// \brief Matches types nodes representing C++11 auto types.
2663///
2664/// Given:
2665/// \code
2666///   auto n = 4;
2667///   int v[] = { 2, 3 }
2668///   for (auto i : v) { }
2669/// \endcode
2670/// autoType()
2671///   matches "auto n" and "auto i"
2672AST_TYPE_MATCHER(AutoType, autoType);
2673
2674/// \brief Matches \c AutoType nodes where the deduced type is a specific type.
2675///
2676/// Note: There is no \c TypeLoc for the deduced type and thus no
2677/// \c getDeducedLoc() matcher.
2678///
2679/// Given
2680/// \code
2681///   auto a = 1;
2682///   auto b = 2.0;
2683/// \endcode
2684/// autoType(hasDeducedType(isInteger()))
2685///   matches "auto a"
2686///
2687/// Usable as: Matcher<AutoType>
2688AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType);
2689
2690/// \brief Matches \c FunctionType nodes.
2691///
2692/// Given
2693/// \code
2694///   int (*f)(int);
2695///   void g();
2696/// \endcode
2697/// functionType()
2698///   matches "int (*f)(int)" and the type of "g".
2699AST_TYPE_MATCHER(FunctionType, functionType);
2700
2701/// \brief Matches block pointer types, i.e. types syntactically represented as
2702/// "void (^)(int)".
2703///
2704/// The \c pointee is always required to be a \c FunctionType.
2705AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
2706
2707/// \brief Matches member pointer types.
2708/// Given
2709/// \code
2710///   struct A { int i; }
2711///   A::* ptr = A::i;
2712/// \endcode
2713/// memberPointerType()
2714///   matches "A::* ptr"
2715AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
2716
2717/// \brief Matches pointer types.
2718///
2719/// Given
2720/// \code
2721///   int *a;
2722///   int &b = *a;
2723///   int c = 5;
2724/// \endcode
2725/// pointerType()
2726///   matches "int *a"
2727AST_TYPE_MATCHER(PointerType, pointerType);
2728
2729/// \brief Matches reference types.
2730///
2731/// Given
2732/// \code
2733///   int *a;
2734///   int &b = *a;
2735///   int c = 5;
2736/// \endcode
2737/// pointerType()
2738///   matches "int &b"
2739AST_TYPE_MATCHER(ReferenceType, referenceType);
2740
2741/// \brief Narrows PointerType (and similar) matchers to those where the
2742/// \c pointee matches a given matcher.
2743///
2744/// Given
2745/// \code
2746///   int *a;
2747///   int const *b;
2748///   float const *f;
2749/// \endcode
2750/// pointerType(pointee(isConstQualified(), isInteger()))
2751///   matches "int const *b"
2752///
2753/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
2754///   Matcher<PointerType>, Matcher<ReferenceType>
2755AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee);
2756
2757/// \brief Matches typedef types.
2758///
2759/// Given
2760/// \code
2761///   typedef int X;
2762/// \endcode
2763/// typedefType()
2764///   matches "typedef int X"
2765AST_TYPE_MATCHER(TypedefType, typedefType);
2766
2767/// \brief Matches \c TypedefTypes referring to a specific
2768/// \c TypedefNameDecl.
2769AST_MATCHER_P(TypedefType, hasDecl,
2770              internal::Matcher<TypedefNameDecl>, InnerMatcher) {
2771  return InnerMatcher.matches(*Node.getDecl(), Finder, Builder);
2772}
2773
2774/// \brief Matches nested name specifiers.
2775///
2776/// Given
2777/// \code
2778///   namespace ns {
2779///     struct A { static void f(); };
2780///     void A::f() {}
2781///     void g() { A::f(); }
2782///   }
2783///   ns::A a;
2784/// \endcode
2785/// nestedNameSpecifier()
2786///   matches "ns::" and both "A::"
2787const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
2788
2789/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
2790const internal::VariadicAllOfMatcher<
2791  NestedNameSpecifierLoc> nestedNameSpecifierLoc;
2792
2793/// \brief Matches \c NestedNameSpecifierLocs for which the given inner
2794/// NestedNameSpecifier-matcher matches.
2795inline internal::BindableMatcher<NestedNameSpecifierLoc> loc(
2796    const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
2797  return internal::BindableMatcher<NestedNameSpecifierLoc>(
2798      new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
2799          InnerMatcher));
2800}
2801
2802/// \brief Matches nested name specifiers that specify a type matching the
2803/// given \c QualType matcher without qualifiers.
2804///
2805/// Given
2806/// \code
2807///   struct A { struct B { struct C {}; }; };
2808///   A::B::C c;
2809/// \endcode
2810/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
2811///   matches "A::"
2812AST_MATCHER_P(NestedNameSpecifier, specifiesType,
2813              internal::Matcher<QualType>, InnerMatcher) {
2814  if (Node.getAsType() == NULL)
2815    return false;
2816  return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
2817}
2818
2819/// \brief Matches nested name specifier locs that specify a type matching the
2820/// given \c TypeLoc.
2821///
2822/// Given
2823/// \code
2824///   struct A { struct B { struct C {}; }; };
2825///   A::B::C c;
2826/// \endcode
2827/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
2828///   hasDeclaration(recordDecl(hasName("A")))))))
2829///   matches "A::"
2830AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
2831              internal::Matcher<TypeLoc>, InnerMatcher) {
2832  return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
2833}
2834
2835/// \brief Matches on the prefix of a \c NestedNameSpecifier.
2836///
2837/// Given
2838/// \code
2839///   struct A { struct B { struct C {}; }; };
2840///   A::B::C c;
2841/// \endcode
2842/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
2843///   matches "A::"
2844inline internal::Matcher<NestedNameSpecifier> hasPrefix(
2845    const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
2846  return internal::makeMatcher(
2847    new internal::NestedNameSpecifierPrefixMatcher(InnerMatcher));
2848}
2849
2850/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
2851///
2852/// Given
2853/// \code
2854///   struct A { struct B { struct C {}; }; };
2855///   A::B::C c;
2856/// \endcode
2857/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
2858///   matches "A::"
2859inline internal::Matcher<NestedNameSpecifierLoc> hasPrefix(
2860    const internal::Matcher<NestedNameSpecifierLoc> &InnerMatcher) {
2861  return internal::makeMatcher(
2862    new internal::NestedNameSpecifierLocPrefixMatcher(InnerMatcher));
2863}
2864
2865/// \brief Matches nested name specifiers that specify a namespace matching the
2866/// given namespace matcher.
2867///
2868/// Given
2869/// \code
2870///   namespace ns { struct A {}; }
2871///   ns::A a;
2872/// \endcode
2873/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
2874///   matches "ns::"
2875AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
2876              internal::Matcher<NamespaceDecl>, InnerMatcher) {
2877  if (Node.getAsNamespace() == NULL)
2878    return false;
2879  return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
2880}
2881
2882} // end namespace ast_matchers
2883} // end namespace clang
2884
2885#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
2886