ASTMatchers.h revision 523806028d812a7f29636c59a8bc0e7e3d3fd9ae
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::VariadicAllOfMatcher<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::VariadicAllOfMatcher<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 compound (i.e. non-scalar) literals
926///
927/// Example match: {1}, (1, 2)
928/// \code
929///   int array[4] = {1}; vector int myvec = (vector int)(1, 2);
930/// \endcode
931const internal::VariadicDynCastAllOfMatcher<
932  Stmt,
933  CompoundLiteralExpr> compoundLiteralExpr;
934
935/// \brief Matches nullptr literal.
936const internal::VariadicDynCastAllOfMatcher<
937  Stmt,
938  CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
939
940/// \brief Matches binary operator expressions.
941///
942/// Example matches a || b
943/// \code
944///   !(a || b)
945/// \endcode
946const internal::VariadicDynCastAllOfMatcher<
947  Stmt,
948  BinaryOperator> binaryOperator;
949
950/// \brief Matches unary operator expressions.
951///
952/// Example matches !a
953/// \code
954///   !a || b
955/// \endcode
956const internal::VariadicDynCastAllOfMatcher<
957  Stmt,
958  UnaryOperator> unaryOperator;
959
960/// \brief Matches conditional operator expressions.
961///
962/// Example matches a ? b : c
963/// \code
964///   (a ? b : c) + 42
965/// \endcode
966const internal::VariadicDynCastAllOfMatcher<
967  Stmt,
968  ConditionalOperator> conditionalOperator;
969
970/// \brief Matches a reinterpret_cast expression.
971///
972/// Either the source expression or the destination type can be matched
973/// using has(), but hasDestinationType() is more specific and can be
974/// more readable.
975///
976/// Example matches reinterpret_cast<char*>(&p) in
977/// \code
978///   void* p = reinterpret_cast<char*>(&p);
979/// \endcode
980const internal::VariadicDynCastAllOfMatcher<
981  Stmt,
982  CXXReinterpretCastExpr> reinterpretCastExpr;
983
984/// \brief Matches a C++ static_cast expression.
985///
986/// \see hasDestinationType
987/// \see reinterpretCast
988///
989/// Example:
990///   staticCastExpr()
991/// matches
992///   static_cast<long>(8)
993/// in
994/// \code
995///   long eight(static_cast<long>(8));
996/// \endcode
997const internal::VariadicDynCastAllOfMatcher<
998  Stmt,
999  CXXStaticCastExpr> staticCastExpr;
1000
1001/// \brief Matches a dynamic_cast expression.
1002///
1003/// Example:
1004///   dynamicCastExpr()
1005/// matches
1006///   dynamic_cast<D*>(&b);
1007/// in
1008/// \code
1009///   struct B { virtual ~B() {} }; struct D : B {};
1010///   B b;
1011///   D* p = dynamic_cast<D*>(&b);
1012/// \endcode
1013const internal::VariadicDynCastAllOfMatcher<
1014  Stmt,
1015  CXXDynamicCastExpr> dynamicCastExpr;
1016
1017/// \brief Matches a const_cast expression.
1018///
1019/// Example: Matches const_cast<int*>(&r) in
1020/// \code
1021///   int n = 42;
1022///   const int &r(n);
1023///   int* p = const_cast<int*>(&r);
1024/// \endcode
1025const internal::VariadicDynCastAllOfMatcher<
1026  Stmt,
1027  CXXConstCastExpr> constCastExpr;
1028
1029/// \brief Matches a C-style cast expression.
1030///
1031/// Example: Matches (int*) 2.2f in
1032/// \code
1033///   int i = (int) 2.2f;
1034/// \endcode
1035const internal::VariadicDynCastAllOfMatcher<
1036  Stmt,
1037  CStyleCastExpr> cStyleCastExpr;
1038
1039/// \brief Matches explicit cast expressions.
1040///
1041/// Matches any cast expression written in user code, whether it be a
1042/// C-style cast, a functional-style cast, or a keyword cast.
1043///
1044/// Does not match implicit conversions.
1045///
1046/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1047/// Clang uses the term "cast" to apply to implicit conversions as well as to
1048/// actual cast expressions.
1049///
1050/// \see hasDestinationType.
1051///
1052/// Example: matches all five of the casts in
1053/// \code
1054///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1055/// \endcode
1056/// but does not match the implicit conversion in
1057/// \code
1058///   long ell = 42;
1059/// \endcode
1060const internal::VariadicDynCastAllOfMatcher<
1061  Stmt,
1062  ExplicitCastExpr> explicitCastExpr;
1063
1064/// \brief Matches the implicit cast nodes of Clang's AST.
1065///
1066/// This matches many different places, including function call return value
1067/// eliding, as well as any type conversions.
1068const internal::VariadicDynCastAllOfMatcher<
1069  Stmt,
1070  ImplicitCastExpr> implicitCastExpr;
1071
1072/// \brief Matches any cast nodes of Clang's AST.
1073///
1074/// Example: castExpr() matches each of the following:
1075/// \code
1076///   (int) 3;
1077///   const_cast<Expr *>(SubExpr);
1078///   char c = 0;
1079/// \endcode
1080/// but does not match
1081/// \code
1082///   int i = (0);
1083///   int k = 0;
1084/// \endcode
1085const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1086
1087/// \brief Matches functional cast expressions
1088///
1089/// Example: Matches Foo(bar);
1090/// \code
1091///   Foo f = bar;
1092///   Foo g = (Foo) bar;
1093///   Foo h = Foo(bar);
1094/// \endcode
1095const internal::VariadicDynCastAllOfMatcher<
1096  Stmt,
1097  CXXFunctionalCastExpr> functionalCastExpr;
1098
1099/// \brief Matches \c QualTypes in the clang AST.
1100const internal::VariadicAllOfMatcher<QualType> qualType;
1101
1102/// \brief Matches \c Types in the clang AST.
1103const internal::VariadicAllOfMatcher<Type> type;
1104
1105/// \brief Matches \c TypeLocs in the clang AST.
1106const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1107
1108/// \brief Matches if any of the given matchers matches.
1109///
1110/// Unlike \c anyOf, \c eachOf will generate a match result for each
1111/// matching submatcher.
1112///
1113/// For example, in:
1114/// \code
1115///   class A { int a; int b; };
1116/// \endcode
1117/// The matcher:
1118/// \code
1119///   recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1120///                     has(fieldDecl(hasName("b")).bind("v"))))
1121/// \endcode
1122/// will generate two results binding "v", the first of which binds
1123/// the field declaration of \c a, the second the field declaration of
1124/// \c b.
1125///
1126/// Usable as: Any Matcher
1127template <typename M1, typename M2>
1128internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, M2>
1129eachOf(const M1 &P1, const M2 &P2) {
1130  return internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1,
1131                                                M2>(P1, P2);
1132}
1133
1134/// \brief Various overloads for the anyOf matcher.
1135/// @{
1136
1137/// \brief Matches if any of the given matchers matches.
1138///
1139/// Usable as: Any Matcher
1140template<typename M1, typename M2>
1141internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2>
1142anyOf(const M1 &P1, const M2 &P2) {
1143  return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1144                                                M1, M2 >(P1, P2);
1145}
1146template<typename M1, typename M2, typename M3>
1147internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1148    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> >
1149anyOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1150  return anyOf(P1, anyOf(P2, P3));
1151}
1152template<typename M1, typename M2, typename M3, typename M4>
1153internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1154    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1155        internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1156                                               M3, M4> > >
1157anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1158  return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
1159}
1160template<typename M1, typename M2, typename M3, typename M4, typename M5>
1161internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1162    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1163        internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3,
1164            internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1165                                                   M4, M5> > > >
1166anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1167  return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
1168}
1169
1170/// @}
1171
1172/// \brief Various overloads for the allOf matcher.
1173/// @{
1174
1175/// \brief Matches if all given matchers match.
1176///
1177/// Usable as: Any Matcher
1178template <typename M1, typename M2>
1179internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>
1180allOf(const M1 &P1, const M2 &P2) {
1181  return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>(
1182      P1, P2);
1183}
1184template <typename M1, typename M2, typename M3>
1185internal::PolymorphicMatcherWithParam2<
1186    internal::AllOfMatcher, M1,
1187    internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> >
1188allOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1189  return allOf(P1, allOf(P2, P3));
1190}
1191template <typename M1, typename M2, typename M3, typename M4>
1192internal::PolymorphicMatcherWithParam2<
1193    internal::AllOfMatcher, M1,
1194    internal::PolymorphicMatcherWithParam2<
1195        internal::AllOfMatcher, M2, internal::PolymorphicMatcherWithParam2<
1196                                        internal::AllOfMatcher, M3, M4> > >
1197allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1198  return allOf(P1, allOf(P2, P3, P4));
1199}
1200template <typename M1, typename M2, typename M3, typename M4, typename M5>
1201internal::PolymorphicMatcherWithParam2<
1202    internal::AllOfMatcher, M1,
1203    internal::PolymorphicMatcherWithParam2<
1204        internal::AllOfMatcher, M2,
1205        internal::PolymorphicMatcherWithParam2<
1206            internal::AllOfMatcher, M3,
1207            internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M4,
1208                                                   M5> > > >
1209allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1210  return allOf(P1, allOf(P2, P3, P4, P5));
1211}
1212
1213/// @}
1214
1215/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1216///
1217/// Given
1218/// \code
1219///   Foo x = bar;
1220///   int y = sizeof(x) + alignof(x);
1221/// \endcode
1222/// unaryExprOrTypeTraitExpr()
1223///   matches \c sizeof(x) and \c alignof(x)
1224const internal::VariadicDynCastAllOfMatcher<
1225  Stmt,
1226  UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1227
1228/// \brief Matches unary expressions that have a specific type of argument.
1229///
1230/// Given
1231/// \code
1232///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1233/// \endcode
1234/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1235///   matches \c sizeof(a) and \c alignof(c)
1236AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1237              internal::Matcher<QualType>, InnerMatcher) {
1238  const QualType ArgumentType = Node.getTypeOfArgument();
1239  return InnerMatcher.matches(ArgumentType, Finder, Builder);
1240}
1241
1242/// \brief Matches unary expressions of a certain kind.
1243///
1244/// Given
1245/// \code
1246///   int x;
1247///   int s = sizeof(x) + alignof(x)
1248/// \endcode
1249/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1250///   matches \c sizeof(x)
1251AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1252  return Node.getKind() == Kind;
1253}
1254
1255/// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1256/// alignof.
1257inline internal::Matcher<Stmt> alignOfExpr(
1258    const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1259  return stmt(unaryExprOrTypeTraitExpr(allOf(
1260      ofKind(UETT_AlignOf), InnerMatcher)));
1261}
1262
1263/// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1264/// sizeof.
1265inline internal::Matcher<Stmt> sizeOfExpr(
1266    const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1267  return stmt(unaryExprOrTypeTraitExpr(
1268      allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1269}
1270
1271/// \brief Matches NamedDecl nodes that have the specified name.
1272///
1273/// Supports specifying enclosing namespaces or classes by prefixing the name
1274/// with '<enclosing>::'.
1275/// Does not match typedefs of an underlying type with the given name.
1276///
1277/// Example matches X (Name == "X")
1278/// \code
1279///   class X;
1280/// \endcode
1281///
1282/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1283/// \code
1284///   namespace a { namespace b { class X; } }
1285/// \endcode
1286AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1287  assert(!Name.empty());
1288  const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1289  const StringRef FullName = FullNameString;
1290  const StringRef Pattern = Name;
1291  if (Pattern.startswith("::")) {
1292    return FullName == Pattern;
1293  } else {
1294    return FullName.endswith(("::" + Pattern).str());
1295  }
1296}
1297
1298/// \brief Matches NamedDecl nodes whose fully qualified names contain
1299/// a substring matched by the given RegExp.
1300///
1301/// Supports specifying enclosing namespaces or classes by
1302/// prefixing the name with '<enclosing>::'.  Does not match typedefs
1303/// of an underlying type with the given name.
1304///
1305/// Example matches X (regexp == "::X")
1306/// \code
1307///   class X;
1308/// \endcode
1309///
1310/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1311/// \code
1312///   namespace foo { namespace bar { class X; } }
1313/// \endcode
1314AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1315  assert(!RegExp.empty());
1316  std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1317  llvm::Regex RE(RegExp);
1318  return RE.match(FullNameString);
1319}
1320
1321/// \brief Matches overloaded operator names.
1322///
1323/// Matches overloaded operator names specified in strings without the
1324/// "operator" prefix, such as "<<", for OverloadedOperatorCall's.
1325///
1326/// Example matches a << b
1327///     (matcher == operatorCallExpr(hasOverloadedOperatorName("<<")))
1328/// \code
1329///   a << b;
1330///   c && d;  // assuming both operator<<
1331///            // and operator&& are overloaded somewhere.
1332/// \endcode
1333AST_MATCHER_P(CXXOperatorCallExpr,
1334              hasOverloadedOperatorName, std::string, Name) {
1335  return getOperatorSpelling(Node.getOperator()) == Name;
1336}
1337
1338/// \brief Matches C++ classes that are directly or indirectly derived from
1339/// a class matching \c Base.
1340///
1341/// Note that a class is not considered to be derived from itself.
1342///
1343/// Example matches Y, Z, C (Base == hasName("X"))
1344/// \code
1345///   class X;
1346///   class Y : public X {};  // directly derived
1347///   class Z : public Y {};  // indirectly derived
1348///   typedef X A;
1349///   typedef A B;
1350///   class C : public B {};  // derived from a typedef of X
1351/// \endcode
1352///
1353/// In the following example, Bar matches isDerivedFrom(hasName("X")):
1354/// \code
1355///   class Foo;
1356///   typedef Foo X;
1357///   class Bar : public Foo {};  // derived from a type that X is a typedef of
1358/// \endcode
1359AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1360              internal::Matcher<NamedDecl>, Base) {
1361  return Finder->classIsDerivedFrom(&Node, Base, Builder);
1362}
1363
1364/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1365inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
1366  assert(!BaseName.empty());
1367  return isDerivedFrom(hasName(BaseName));
1368}
1369
1370/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1371/// match \c Base.
1372inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1373    internal::Matcher<NamedDecl> Base) {
1374  return anyOf(Base, isDerivedFrom(Base));
1375}
1376
1377/// \brief Overloaded method as shortcut for
1378/// \c isSameOrDerivedFrom(hasName(...)).
1379inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1380    StringRef BaseName) {
1381  assert(!BaseName.empty());
1382  return isSameOrDerivedFrom(hasName(BaseName));
1383}
1384
1385/// \brief Matches AST nodes that have child AST nodes that match the
1386/// provided matcher.
1387///
1388/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1389/// \code
1390///   class X {};  // Matches X, because X::X is a class of name X inside X.
1391///   class Y { class X {}; };
1392///   class Z { class Y { class X {}; }; };  // Does not match Z.
1393/// \endcode
1394///
1395/// ChildT must be an AST base type.
1396///
1397/// Usable as: Any Matcher
1398template <typename ChildT>
1399internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
1400    const internal::Matcher<ChildT> &ChildMatcher) {
1401  return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
1402                                           ChildT>(ChildMatcher);
1403}
1404
1405/// \brief Matches AST nodes that have descendant AST nodes that match the
1406/// provided matcher.
1407///
1408/// Example matches X, Y, Z
1409///     (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1410/// \code
1411///   class X {};  // Matches X, because X::X is a class of name X inside X.
1412///   class Y { class X {}; };
1413///   class Z { class Y { class X {}; }; };
1414/// \endcode
1415///
1416/// DescendantT must be an AST base type.
1417///
1418/// Usable as: Any Matcher
1419template <typename DescendantT>
1420internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
1421hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1422  return internal::ArgumentAdaptingMatcher<
1423    internal::HasDescendantMatcher,
1424    DescendantT>(DescendantMatcher);
1425}
1426
1427/// \brief Matches AST nodes that have child AST nodes that match the
1428/// provided matcher.
1429///
1430/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1431/// \code
1432///   class X {};  // Matches X, because X::X is a class of name X inside X.
1433///   class Y { class X {}; };
1434///   class Z { class Y { class X {}; }; };  // Does not match Z.
1435/// \endcode
1436///
1437/// ChildT must be an AST base type.
1438///
1439/// As opposed to 'has', 'forEach' will cause a match for each result that
1440/// matches instead of only on the first one.
1441///
1442/// Usable as: Any Matcher
1443template <typename ChildT>
1444internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1445    const internal::Matcher<ChildT> &ChildMatcher) {
1446  return internal::ArgumentAdaptingMatcher<
1447    internal::ForEachMatcher,
1448    ChildT>(ChildMatcher);
1449}
1450
1451/// \brief Matches AST nodes that have descendant AST nodes that match the
1452/// provided matcher.
1453///
1454/// Example matches X, A, B, C
1455///     (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1456/// \code
1457///   class X {};  // Matches X, because X::X is a class of name X inside X.
1458///   class A { class X {}; };
1459///   class B { class C { class X {}; }; };
1460/// \endcode
1461///
1462/// DescendantT must be an AST base type.
1463///
1464/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1465/// each result that matches instead of only on the first one.
1466///
1467/// Note: Recursively combined ForEachDescendant can cause many matches:
1468///   recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1469/// will match 10 times (plus injected class name matches) on:
1470/// \code
1471///   class A { class B { class C { class D { class E {}; }; }; }; };
1472/// \endcode
1473///
1474/// Usable as: Any Matcher
1475template <typename DescendantT>
1476internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher,
1477                                  DescendantT>
1478forEachDescendant(
1479    const internal::Matcher<DescendantT> &DescendantMatcher) {
1480  return internal::ArgumentAdaptingMatcher<
1481    internal::ForEachDescendantMatcher,
1482    DescendantT>(DescendantMatcher);
1483}
1484
1485/// \brief Matches if the node or any descendant matches.
1486///
1487/// Generates results for each match.
1488///
1489/// For example, in:
1490/// \code
1491///   class A { class B {}; class C {}; };
1492/// \endcode
1493/// The matcher:
1494/// \code
1495///   recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1496/// \endcode
1497/// will generate results for \c A, \c B and \c C.
1498///
1499/// Usable as: Any Matcher
1500template <typename T>
1501internal::PolymorphicMatcherWithParam2<
1502    internal::EachOfMatcher, internal::Matcher<T>,
1503    internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> >
1504findAll(const internal::Matcher<T> &Matcher) {
1505  return eachOf(Matcher, forEachDescendant(Matcher));
1506}
1507
1508/// \brief Matches AST nodes that have a parent that matches the provided
1509/// matcher.
1510///
1511/// Given
1512/// \code
1513/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1514/// \endcode
1515/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1516///
1517/// Usable as: Any Matcher
1518template <typename ParentT>
1519internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT>
1520hasParent(const internal::Matcher<ParentT> &ParentMatcher) {
1521  return internal::ArgumentAdaptingMatcher<
1522    internal::HasParentMatcher,
1523    ParentT>(ParentMatcher);
1524}
1525
1526/// \brief Matches AST nodes that have an ancestor that matches the provided
1527/// matcher.
1528///
1529/// Given
1530/// \code
1531/// void f() { if (true) { int x = 42; } }
1532/// void g() { for (;;) { int x = 43; } }
1533/// \endcode
1534/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1535///
1536/// Usable as: Any Matcher
1537template <typename AncestorT>
1538internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT>
1539hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) {
1540  return internal::ArgumentAdaptingMatcher<
1541    internal::HasAncestorMatcher,
1542    AncestorT>(AncestorMatcher);
1543}
1544
1545/// \brief Matches if the provided matcher does not match.
1546///
1547/// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1548/// \code
1549///   class X {};
1550///   class Y {};
1551/// \endcode
1552///
1553/// Usable as: Any Matcher
1554template <typename M>
1555internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M>
1556unless(const M &InnerMatcher) {
1557  return internal::PolymorphicMatcherWithParam1<
1558    internal::NotMatcher, M>(InnerMatcher);
1559}
1560
1561/// \brief Matches a type if the declaration of the type matches the given
1562/// matcher.
1563///
1564/// In addition to being usable as Matcher<TypedefType>, also usable as
1565/// Matcher<T> for any T supporting the getDecl() member function. e.g. various
1566/// subtypes of clang::Type.
1567///
1568/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1569///   Matcher<MemberExpr>, Matcher<TypedefType>
1570inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1571                                     internal::Matcher<Decl> >
1572    hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1573  return internal::PolymorphicMatcherWithParam1<
1574    internal::HasDeclarationMatcher,
1575    internal::Matcher<Decl> >(InnerMatcher);
1576}
1577
1578/// \brief Matches on the implicit object argument of a member call expression.
1579///
1580/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1581/// \code
1582///   class Y { public: void x(); };
1583///   void z() { Y y; y.x(); }",
1584/// \endcode
1585///
1586/// FIXME: Overload to allow directly matching types?
1587AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1588              InnerMatcher) {
1589  const Expr *ExprNode = Node.getImplicitObjectArgument()
1590                            ->IgnoreParenImpCasts();
1591  return (ExprNode != NULL &&
1592          InnerMatcher.matches(*ExprNode, Finder, Builder));
1593}
1594
1595/// \brief Matches if the call expression's callee expression matches.
1596///
1597/// Given
1598/// \code
1599///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
1600///   void f() { f(); }
1601/// \endcode
1602/// callExpr(callee(expr()))
1603///   matches this->x(), x(), y.x(), f()
1604/// with callee(...)
1605///   matching this->x, x, y.x, f respectively
1606///
1607/// Note: Callee cannot take the more general internal::Matcher<Expr>
1608/// because this introduces ambiguous overloads with calls to Callee taking a
1609/// internal::Matcher<Decl>, as the matcher hierarchy is purely
1610/// implemented in terms of implicit casts.
1611AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1612              InnerMatcher) {
1613  const Expr *ExprNode = Node.getCallee();
1614  return (ExprNode != NULL &&
1615          InnerMatcher.matches(*ExprNode, Finder, Builder));
1616}
1617
1618/// \brief Matches if the call expression's callee's declaration matches the
1619/// given matcher.
1620///
1621/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1622/// \code
1623///   class Y { public: void x(); };
1624///   void z() { Y y; y.x();
1625/// \endcode
1626inline internal::Matcher<CallExpr> callee(
1627    const internal::Matcher<Decl> &InnerMatcher) {
1628  return callExpr(hasDeclaration(InnerMatcher));
1629}
1630
1631/// \brief Matches if the expression's or declaration's type matches a type
1632/// matcher.
1633///
1634/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1635///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1636/// \code
1637///  class X {};
1638///  void y(X &x) { x; X z; }
1639/// \endcode
1640AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1641                          InnerMatcher) {
1642  TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1643                          llvm::is_base_of<ValueDecl, NodeType>::value),
1644                         instantiated_with_wrong_types);
1645  return InnerMatcher.matches(Node.getType(), Finder, Builder);
1646}
1647
1648/// \brief Overloaded to match the declaration of the expression's or value
1649/// declaration's type.
1650///
1651/// In case of a value declaration (for example a variable declaration),
1652/// this resolves one layer of indirection. For example, in the value
1653/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1654/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1655/// of x."
1656///
1657/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1658///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1659/// \code
1660///  class X {};
1661///  void y(X &x) { x; X z; }
1662/// \endcode
1663///
1664/// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1665inline internal::PolymorphicMatcherWithParam1<
1666  internal::matcher_hasType0Matcher,
1667  internal::Matcher<QualType> >
1668hasType(const internal::Matcher<Decl> &InnerMatcher) {
1669  return hasType(qualType(hasDeclaration(InnerMatcher)));
1670}
1671
1672/// \brief Matches if the matched type is represented by the given string.
1673///
1674/// Given
1675/// \code
1676///   class Y { public: void x(); };
1677///   void z() { Y* y; y->x(); }
1678/// \endcode
1679/// callExpr(on(hasType(asString("class Y *"))))
1680///   matches y->x()
1681AST_MATCHER_P(QualType, asString, std::string, Name) {
1682  return Name == Node.getAsString();
1683}
1684
1685/// \brief Matches if the matched type is a pointer type and the pointee type
1686/// matches the specified matcher.
1687///
1688/// Example matches y->x()
1689///     (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1690/// \code
1691///   class Y { public: void x(); };
1692///   void z() { Y *y; y->x(); }
1693/// \endcode
1694AST_MATCHER_P(
1695    QualType, pointsTo, internal::Matcher<QualType>,
1696    InnerMatcher) {
1697  return (!Node.isNull() && Node->isPointerType() &&
1698          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1699}
1700
1701/// \brief Overloaded to match the pointee type's declaration.
1702inline internal::Matcher<QualType> pointsTo(
1703    const internal::Matcher<Decl> &InnerMatcher) {
1704  return pointsTo(qualType(hasDeclaration(InnerMatcher)));
1705}
1706
1707/// \brief Matches if the matched type is a reference type and the referenced
1708/// type matches the specified matcher.
1709///
1710/// Example matches X &x and const X &y
1711///     (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1712/// \code
1713///   class X {
1714///     void a(X b) {
1715///       X &x = b;
1716///       const X &y = b;
1717///   };
1718/// \endcode
1719AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1720              InnerMatcher) {
1721  return (!Node.isNull() && Node->isReferenceType() &&
1722          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1723}
1724
1725/// \brief Overloaded to match the referenced type's declaration.
1726inline internal::Matcher<QualType> references(
1727    const internal::Matcher<Decl> &InnerMatcher) {
1728  return references(qualType(hasDeclaration(InnerMatcher)));
1729}
1730
1731AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1732              internal::Matcher<Expr>, InnerMatcher) {
1733  const Expr *ExprNode = Node.getImplicitObjectArgument();
1734  return (ExprNode != NULL &&
1735          InnerMatcher.matches(*ExprNode, Finder, Builder));
1736}
1737
1738/// \brief Matches if the expression's type either matches the specified
1739/// matcher, or is a pointer to a type that matches the InnerMatcher.
1740inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1741    const internal::Matcher<QualType> &InnerMatcher) {
1742  return onImplicitObjectArgument(
1743      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1744}
1745
1746/// \brief Overloaded to match the type's declaration.
1747inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1748    const internal::Matcher<Decl> &InnerMatcher) {
1749  return onImplicitObjectArgument(
1750      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1751}
1752
1753/// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1754/// specified matcher.
1755///
1756/// Example matches x in if(x)
1757///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
1758/// \code
1759///   bool x;
1760///   if (x) {}
1761/// \endcode
1762AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1763              InnerMatcher) {
1764  const Decl *DeclNode = Node.getDecl();
1765  return (DeclNode != NULL &&
1766          InnerMatcher.matches(*DeclNode, Finder, Builder));
1767}
1768
1769/// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1770/// specific using shadow declaration.
1771///
1772/// FIXME: This currently only works for functions. Fix.
1773///
1774/// Given
1775/// \code
1776///   namespace a { void f() {} }
1777///   using a::f;
1778///   void g() {
1779///     f();     // Matches this ..
1780///     a::f();  // .. but not this.
1781///   }
1782/// \endcode
1783/// declRefExpr(throughUsingDeclaration(anything()))
1784///   matches \c f()
1785AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1786              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
1787  const NamedDecl *FoundDecl = Node.getFoundDecl();
1788  if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
1789    return InnerMatcher.matches(*UsingDecl, Finder, Builder);
1790  return false;
1791}
1792
1793/// \brief Matches the Decl of a DeclStmt which has a single declaration.
1794///
1795/// Given
1796/// \code
1797///   int a, b;
1798///   int c;
1799/// \endcode
1800/// declStmt(hasSingleDecl(anything()))
1801///   matches 'int c;' but not 'int a, b;'.
1802AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1803  if (Node.isSingleDecl()) {
1804    const Decl *FoundDecl = Node.getSingleDecl();
1805    return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1806  }
1807  return false;
1808}
1809
1810/// \brief Matches a variable declaration that has an initializer expression
1811/// that matches the given matcher.
1812///
1813/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
1814/// \code
1815///   bool y() { return true; }
1816///   bool x = y();
1817/// \endcode
1818AST_MATCHER_P(
1819    VarDecl, hasInitializer, internal::Matcher<Expr>,
1820    InnerMatcher) {
1821  const Expr *Initializer = Node.getAnyInitializer();
1822  return (Initializer != NULL &&
1823          InnerMatcher.matches(*Initializer, Finder, Builder));
1824}
1825
1826/// \brief Checks that a call expression or a constructor call expression has
1827/// a specific number of arguments (including absent default arguments).
1828///
1829/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
1830/// \code
1831///   void f(int x, int y);
1832///   f(0, 0);
1833/// \endcode
1834AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1835  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1836                          llvm::is_base_of<CXXConstructExpr,
1837                                           NodeType>::value),
1838                         instantiated_with_wrong_types);
1839  return Node.getNumArgs() == N;
1840}
1841
1842/// \brief Matches the n'th argument of a call expression or a constructor
1843/// call expression.
1844///
1845/// Example matches y in x(y)
1846///     (matcher = callExpr(hasArgument(0, declRefExpr())))
1847/// \code
1848///   void x(int) { int y; x(y); }
1849/// \endcode
1850AST_POLYMORPHIC_MATCHER_P2(
1851    hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1852  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1853                         llvm::is_base_of<CXXConstructExpr,
1854                                          NodeType>::value),
1855                         instantiated_with_wrong_types);
1856  return (N < Node.getNumArgs() &&
1857          InnerMatcher.matches(
1858              *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1859}
1860
1861/// \brief Matches declaration statements that contain a specific number of
1862/// declarations.
1863///
1864/// Example: Given
1865/// \code
1866///   int a, b;
1867///   int c;
1868///   int d = 2, e;
1869/// \endcode
1870/// declCountIs(2)
1871///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
1872AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
1873  return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
1874}
1875
1876/// \brief Matches the n'th declaration of a declaration statement.
1877///
1878/// Note that this does not work for global declarations because the AST
1879/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
1880/// DeclStmt's.
1881/// Example: Given non-global declarations
1882/// \code
1883///   int a, b = 0;
1884///   int c;
1885///   int d = 2, e;
1886/// \endcode
1887/// declStmt(containsDeclaration(
1888///       0, varDecl(hasInitializer(anything()))))
1889///   matches only 'int d = 2, e;', and
1890/// declStmt(containsDeclaration(1, varDecl()))
1891/// \code
1892///   matches 'int a, b = 0' as well as 'int d = 2, e;'
1893///   but 'int c;' is not matched.
1894/// \endcode
1895AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
1896               internal::Matcher<Decl>, InnerMatcher) {
1897  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
1898  if (N >= NumDecls)
1899    return false;
1900  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
1901  std::advance(Iterator, N);
1902  return InnerMatcher.matches(**Iterator, Finder, Builder);
1903}
1904
1905/// \brief Matches a constructor initializer.
1906///
1907/// Given
1908/// \code
1909///   struct Foo {
1910///     Foo() : foo_(1) { }
1911///     int foo_;
1912///   };
1913/// \endcode
1914/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
1915///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
1916AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
1917              internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
1918  for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
1919       I != Node.init_end(); ++I) {
1920    if (InnerMatcher.matches(**I, Finder, Builder)) {
1921      return true;
1922    }
1923  }
1924  return false;
1925}
1926
1927/// \brief Matches the field declaration of a constructor initializer.
1928///
1929/// Given
1930/// \code
1931///   struct Foo {
1932///     Foo() : foo_(1) { }
1933///     int foo_;
1934///   };
1935/// \endcode
1936/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
1937///     forField(hasName("foo_"))))))
1938///   matches Foo
1939/// with forField matching foo_
1940AST_MATCHER_P(CXXCtorInitializer, forField,
1941              internal::Matcher<FieldDecl>, InnerMatcher) {
1942  const FieldDecl *NodeAsDecl = Node.getMember();
1943  return (NodeAsDecl != NULL &&
1944      InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
1945}
1946
1947/// \brief Matches the initializer expression of a constructor initializer.
1948///
1949/// Given
1950/// \code
1951///   struct Foo {
1952///     Foo() : foo_(1) { }
1953///     int foo_;
1954///   };
1955/// \endcode
1956/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
1957///     withInitializer(integerLiteral(equals(1)))))))
1958///   matches Foo
1959/// with withInitializer matching (1)
1960AST_MATCHER_P(CXXCtorInitializer, withInitializer,
1961              internal::Matcher<Expr>, InnerMatcher) {
1962  const Expr* NodeAsExpr = Node.getInit();
1963  return (NodeAsExpr != NULL &&
1964      InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
1965}
1966
1967/// \brief Matches a contructor initializer if it is explicitly written in
1968/// code (as opposed to implicitly added by the compiler).
1969///
1970/// Given
1971/// \code
1972///   struct Foo {
1973///     Foo() { }
1974///     Foo(int) : foo_("A") { }
1975///     string foo_;
1976///   };
1977/// \endcode
1978/// constructorDecl(hasAnyConstructorInitializer(isWritten()))
1979///   will match Foo(int), but not Foo()
1980AST_MATCHER(CXXCtorInitializer, isWritten) {
1981  return Node.isWritten();
1982}
1983
1984/// \brief Matches a constructor declaration that has been implicitly added
1985/// by the compiler (eg. implicit default/copy constructors).
1986AST_MATCHER(CXXConstructorDecl, isImplicit) {
1987  return Node.isImplicit();
1988}
1989
1990/// \brief Matches any argument of a call expression or a constructor call
1991/// expression.
1992///
1993/// Given
1994/// \code
1995///   void x(int, int, int) { int y; x(1, y, 42); }
1996/// \endcode
1997/// callExpr(hasAnyArgument(declRefExpr()))
1998///   matches x(1, y, 42)
1999/// with hasAnyArgument(...)
2000///   matching y
2001AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
2002                          InnerMatcher) {
2003  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
2004                         llvm::is_base_of<CXXConstructExpr,
2005                                          NodeType>::value),
2006                         instantiated_with_wrong_types);
2007  for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2008    if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
2009                             Finder, Builder)) {
2010      return true;
2011    }
2012  }
2013  return false;
2014}
2015
2016/// \brief Matches the n'th parameter of a function declaration.
2017///
2018/// Given
2019/// \code
2020///   class X { void f(int x) {} };
2021/// \endcode
2022/// methodDecl(hasParameter(0, hasType(varDecl())))
2023///   matches f(int x) {}
2024/// with hasParameter(...)
2025///   matching int x
2026AST_MATCHER_P2(FunctionDecl, hasParameter,
2027               unsigned, N, internal::Matcher<ParmVarDecl>,
2028               InnerMatcher) {
2029  return (N < Node.getNumParams() &&
2030          InnerMatcher.matches(
2031              *Node.getParamDecl(N), Finder, Builder));
2032}
2033
2034/// \brief Matches any parameter of a function declaration.
2035///
2036/// Does not match the 'this' parameter of a method.
2037///
2038/// Given
2039/// \code
2040///   class X { void f(int x, int y, int z) {} };
2041/// \endcode
2042/// methodDecl(hasAnyParameter(hasName("y")))
2043///   matches f(int x, int y, int z) {}
2044/// with hasAnyParameter(...)
2045///   matching int y
2046AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2047              internal::Matcher<ParmVarDecl>, InnerMatcher) {
2048  for (unsigned I = 0; I < Node.getNumParams(); ++I) {
2049    if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
2050      return true;
2051    }
2052  }
2053  return false;
2054}
2055
2056/// \brief Matches \c FunctionDecls that have a specific parameter count.
2057///
2058/// Given
2059/// \code
2060///   void f(int i) {}
2061///   void g(int i, int j) {}
2062/// \endcode
2063/// functionDecl(parameterCountIs(2))
2064///   matches g(int i, int j) {}
2065AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2066  return Node.getNumParams() == N;
2067}
2068
2069/// \brief Matches the return type of a function declaration.
2070///
2071/// Given:
2072/// \code
2073///   class X { int f() { return 1; } };
2074/// \endcode
2075/// methodDecl(returns(asString("int")))
2076///   matches int f() { return 1; }
2077AST_MATCHER_P(FunctionDecl, returns,
2078              internal::Matcher<QualType>, InnerMatcher) {
2079  return InnerMatcher.matches(Node.getResultType(), Finder, Builder);
2080}
2081
2082/// \brief Matches extern "C" function declarations.
2083///
2084/// Given:
2085/// \code
2086///   extern "C" void f() {}
2087///   extern "C" { void g() {} }
2088///   void h() {}
2089/// \endcode
2090/// functionDecl(isExternC())
2091///   matches the declaration of f and g, but not the declaration h
2092AST_MATCHER(FunctionDecl, isExternC) {
2093  return Node.isExternC();
2094}
2095
2096/// \brief Matches the condition expression of an if statement, for loop,
2097/// or conditional operator.
2098///
2099/// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2100/// \code
2101///   if (true) {}
2102/// \endcode
2103AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
2104                          InnerMatcher) {
2105  TOOLING_COMPILE_ASSERT(
2106    (llvm::is_base_of<IfStmt, NodeType>::value) ||
2107    (llvm::is_base_of<ForStmt, NodeType>::value) ||
2108    (llvm::is_base_of<WhileStmt, NodeType>::value) ||
2109    (llvm::is_base_of<DoStmt, NodeType>::value) ||
2110    (llvm::is_base_of<ConditionalOperator, NodeType>::value),
2111    has_condition_requires_if_statement_conditional_operator_or_loop);
2112  const Expr *const Condition = Node.getCond();
2113  return (Condition != NULL &&
2114          InnerMatcher.matches(*Condition, Finder, Builder));
2115}
2116
2117/// \brief Matches the condition variable statement in an if statement.
2118///
2119/// Given
2120/// \code
2121///   if (A* a = GetAPointer()) {}
2122/// \endcode
2123/// hasConditionVariableStatment(...)
2124///   matches 'A* a = GetAPointer()'.
2125AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2126              internal::Matcher<DeclStmt>, InnerMatcher) {
2127  const DeclStmt* const DeclarationStatement =
2128    Node.getConditionVariableDeclStmt();
2129  return DeclarationStatement != NULL &&
2130         InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2131}
2132
2133/// \brief Matches the index expression of an array subscript expression.
2134///
2135/// Given
2136/// \code
2137///   int i[5];
2138///   void f() { i[1] = 42; }
2139/// \endcode
2140/// arraySubscriptExpression(hasIndex(integerLiteral()))
2141///   matches \c i[1] with the \c integerLiteral() matching \c 1
2142AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2143              internal::Matcher<Expr>, InnerMatcher) {
2144  if (const Expr* Expression = Node.getIdx())
2145    return InnerMatcher.matches(*Expression, Finder, Builder);
2146  return false;
2147}
2148
2149/// \brief Matches the base expression of an array subscript expression.
2150///
2151/// Given
2152/// \code
2153///   int i[5];
2154///   void f() { i[1] = 42; }
2155/// \endcode
2156/// arraySubscriptExpression(hasBase(implicitCastExpr(
2157///     hasSourceExpression(declRefExpr()))))
2158///   matches \c i[1] with the \c declRefExpr() matching \c i
2159AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2160              internal::Matcher<Expr>, InnerMatcher) {
2161  if (const Expr* Expression = Node.getBase())
2162    return InnerMatcher.matches(*Expression, Finder, Builder);
2163  return false;
2164}
2165
2166/// \brief Matches a 'for', 'while', or 'do while' statement that has
2167/// a given body.
2168///
2169/// Given
2170/// \code
2171///   for (;;) {}
2172/// \endcode
2173/// hasBody(compoundStmt())
2174///   matches 'for (;;) {}'
2175/// with compoundStmt()
2176///   matching '{}'
2177AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
2178                          InnerMatcher) {
2179  TOOLING_COMPILE_ASSERT(
2180      (llvm::is_base_of<DoStmt, NodeType>::value) ||
2181      (llvm::is_base_of<ForStmt, NodeType>::value) ||
2182      (llvm::is_base_of<WhileStmt, NodeType>::value),
2183      has_body_requires_for_while_or_do_statement);
2184  const Stmt *const Statement = Node.getBody();
2185  return (Statement != NULL &&
2186          InnerMatcher.matches(*Statement, Finder, Builder));
2187}
2188
2189/// \brief Matches compound statements where at least one substatement matches
2190/// a given matcher.
2191///
2192/// Given
2193/// \code
2194///   { {}; 1+2; }
2195/// \endcode
2196/// hasAnySubstatement(compoundStmt())
2197///   matches '{ {}; 1+2; }'
2198/// with compoundStmt()
2199///   matching '{}'
2200AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2201              internal::Matcher<Stmt>, InnerMatcher) {
2202  for (CompoundStmt::const_body_iterator It = Node.body_begin();
2203       It != Node.body_end();
2204       ++It) {
2205    if (InnerMatcher.matches(**It, Finder, Builder)) return true;
2206  }
2207  return false;
2208}
2209
2210/// \brief Checks that a compound statement contains a specific number of
2211/// child statements.
2212///
2213/// Example: Given
2214/// \code
2215///   { for (;;) {} }
2216/// \endcode
2217/// compoundStmt(statementCountIs(0)))
2218///   matches '{}'
2219///   but does not match the outer compound statement.
2220AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2221  return Node.size() == N;
2222}
2223
2224/// \brief Matches literals that are equal to the given value.
2225///
2226/// Example matches true (matcher = boolLiteral(equals(true)))
2227/// \code
2228///   true
2229/// \endcode
2230///
2231/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2232///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2233template <typename ValueT>
2234internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2235equals(const ValueT &Value) {
2236  return internal::PolymorphicMatcherWithParam1<
2237    internal::ValueEqualsMatcher,
2238    ValueT>(Value);
2239}
2240
2241/// \brief Matches the operator Name of operator expressions (binary or
2242/// unary).
2243///
2244/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2245/// \code
2246///   !(a || b)
2247/// \endcode
2248AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
2249  TOOLING_COMPILE_ASSERT(
2250    (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
2251    (llvm::is_base_of<UnaryOperator, NodeType>::value),
2252    has_condition_requires_if_statement_or_conditional_operator);
2253  return Name == Node.getOpcodeStr(Node.getOpcode());
2254}
2255
2256/// \brief Matches the left hand side of binary operator expressions.
2257///
2258/// Example matches a (matcher = binaryOperator(hasLHS()))
2259/// \code
2260///   a || b
2261/// \endcode
2262AST_MATCHER_P(BinaryOperator, hasLHS,
2263              internal::Matcher<Expr>, InnerMatcher) {
2264  Expr *LeftHandSide = Node.getLHS();
2265  return (LeftHandSide != NULL &&
2266          InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2267}
2268
2269/// \brief Matches the right hand side of binary operator expressions.
2270///
2271/// Example matches b (matcher = binaryOperator(hasRHS()))
2272/// \code
2273///   a || b
2274/// \endcode
2275AST_MATCHER_P(BinaryOperator, hasRHS,
2276              internal::Matcher<Expr>, InnerMatcher) {
2277  Expr *RightHandSide = Node.getRHS();
2278  return (RightHandSide != NULL &&
2279          InnerMatcher.matches(*RightHandSide, Finder, Builder));
2280}
2281
2282/// \brief Matches if either the left hand side or the right hand side of a
2283/// binary operator matches.
2284inline internal::Matcher<BinaryOperator> hasEitherOperand(
2285    const internal::Matcher<Expr> &InnerMatcher) {
2286  return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2287}
2288
2289/// \brief Matches if the operand of a unary operator matches.
2290///
2291/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2292/// \code
2293///   !true
2294/// \endcode
2295AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2296              internal::Matcher<Expr>, InnerMatcher) {
2297  const Expr * const Operand = Node.getSubExpr();
2298  return (Operand != NULL &&
2299          InnerMatcher.matches(*Operand, Finder, Builder));
2300}
2301
2302/// \brief Matches if the cast's source expression matches the given matcher.
2303///
2304/// Example: matches "a string" (matcher =
2305///                                  hasSourceExpression(constructExpr()))
2306/// \code
2307/// class URL { URL(string); };
2308/// URL url = "a string";
2309AST_MATCHER_P(CastExpr, hasSourceExpression,
2310              internal::Matcher<Expr>, InnerMatcher) {
2311  const Expr* const SubExpression = Node.getSubExpr();
2312  return (SubExpression != NULL &&
2313          InnerMatcher.matches(*SubExpression, Finder, Builder));
2314}
2315
2316/// \brief Matches casts whose destination type matches a given matcher.
2317///
2318/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2319/// actual casts "explicit" casts.)
2320AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2321              internal::Matcher<QualType>, InnerMatcher) {
2322  const QualType NodeType = Node.getTypeAsWritten();
2323  return InnerMatcher.matches(NodeType, Finder, Builder);
2324}
2325
2326/// \brief Matches implicit casts whose destination type matches a given
2327/// matcher.
2328///
2329/// FIXME: Unit test this matcher
2330AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2331              internal::Matcher<QualType>, InnerMatcher) {
2332  return InnerMatcher.matches(Node.getType(), Finder, Builder);
2333}
2334
2335/// \brief Matches the true branch expression of a conditional operator.
2336///
2337/// Example matches a
2338/// \code
2339///   condition ? a : b
2340/// \endcode
2341AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2342              internal::Matcher<Expr>, InnerMatcher) {
2343  Expr *Expression = Node.getTrueExpr();
2344  return (Expression != NULL &&
2345          InnerMatcher.matches(*Expression, Finder, Builder));
2346}
2347
2348/// \brief Matches the false branch expression of a conditional operator.
2349///
2350/// Example matches b
2351/// \code
2352///   condition ? a : b
2353/// \endcode
2354AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2355              internal::Matcher<Expr>, InnerMatcher) {
2356  Expr *Expression = Node.getFalseExpr();
2357  return (Expression != NULL &&
2358          InnerMatcher.matches(*Expression, Finder, Builder));
2359}
2360
2361/// \brief Matches if a declaration has a body attached.
2362///
2363/// Example matches A, va, fa
2364/// \code
2365///   class A {};
2366///   class B;  // Doesn't match, as it has no body.
2367///   int va;
2368///   extern int vb;  // Doesn't match, as it doesn't define the variable.
2369///   void fa() {}
2370///   void fb();  // Doesn't match, as it has no body.
2371/// \endcode
2372///
2373/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2374AST_POLYMORPHIC_MATCHER(isDefinition) {
2375  TOOLING_COMPILE_ASSERT(
2376      (llvm::is_base_of<TagDecl, NodeType>::value) ||
2377      (llvm::is_base_of<VarDecl, NodeType>::value) ||
2378      (llvm::is_base_of<FunctionDecl, NodeType>::value),
2379      is_definition_requires_isThisDeclarationADefinition_method);
2380  return Node.isThisDeclarationADefinition();
2381}
2382
2383/// \brief Matches the class declaration that the given method declaration
2384/// belongs to.
2385///
2386/// FIXME: Generalize this for other kinds of declarations.
2387/// FIXME: What other kind of declarations would we need to generalize
2388/// this to?
2389///
2390/// Example matches A() in the last line
2391///     (matcher = constructExpr(hasDeclaration(methodDecl(
2392///         ofClass(hasName("A"))))))
2393/// \code
2394///   class A {
2395///    public:
2396///     A();
2397///   };
2398///   A a = A();
2399/// \endcode
2400AST_MATCHER_P(CXXMethodDecl, ofClass,
2401              internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2402  const CXXRecordDecl *Parent = Node.getParent();
2403  return (Parent != NULL &&
2404          InnerMatcher.matches(*Parent, Finder, Builder));
2405}
2406
2407/// \brief Matches member expressions that are called with '->' as opposed
2408/// to '.'.
2409///
2410/// Member calls on the implicit this pointer match as called with '->'.
2411///
2412/// Given
2413/// \code
2414///   class Y {
2415///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2416///     int a;
2417///     static int b;
2418///   };
2419/// \endcode
2420/// memberExpr(isArrow())
2421///   matches this->x, x, y.x, a, this->b
2422AST_MATCHER(MemberExpr, isArrow) {
2423  return Node.isArrow();
2424}
2425
2426/// \brief Matches QualType nodes that are of integer type.
2427///
2428/// Given
2429/// \code
2430///   void a(int);
2431///   void b(long);
2432///   void c(double);
2433/// \endcode
2434/// functionDecl(hasAnyParameter(hasType(isInteger())))
2435/// matches "a(int)", "b(long)", but not "c(double)".
2436AST_MATCHER(QualType, isInteger) {
2437    return Node->isIntegerType();
2438}
2439
2440/// \brief Matches QualType nodes that are const-qualified, i.e., that
2441/// include "top-level" const.
2442///
2443/// Given
2444/// \code
2445///   void a(int);
2446///   void b(int const);
2447///   void c(const int);
2448///   void d(const int*);
2449///   void e(int const) {};
2450/// \endcode
2451/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2452///   matches "void b(int const)", "void c(const int)" and
2453///   "void e(int const) {}". It does not match d as there
2454///   is no top-level const on the parameter type "const int *".
2455AST_MATCHER(QualType, isConstQualified) {
2456  return Node.isConstQualified();
2457}
2458
2459/// \brief Matches a member expression where the member is matched by a
2460/// given matcher.
2461///
2462/// Given
2463/// \code
2464///   struct { int first, second; } first, second;
2465///   int i(second.first);
2466///   int j(first.second);
2467/// \endcode
2468/// memberExpr(member(hasName("first")))
2469///   matches second.first
2470///   but not first.second (because the member name there is "second").
2471AST_MATCHER_P(MemberExpr, member,
2472              internal::Matcher<ValueDecl>, InnerMatcher) {
2473  return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2474}
2475
2476/// \brief Matches a member expression where the object expression is
2477/// matched by a given matcher.
2478///
2479/// Given
2480/// \code
2481///   struct X { int m; };
2482///   void f(X x) { x.m; m; }
2483/// \endcode
2484/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2485///   matches "x.m" and "m"
2486/// with hasObjectExpression(...)
2487///   matching "x" and the implicit object expression of "m" which has type X*.
2488AST_MATCHER_P(MemberExpr, hasObjectExpression,
2489              internal::Matcher<Expr>, InnerMatcher) {
2490  return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2491}
2492
2493/// \brief Matches any using shadow declaration.
2494///
2495/// Given
2496/// \code
2497///   namespace X { void b(); }
2498///   using X::b;
2499/// \endcode
2500/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2501///   matches \code using X::b \endcode
2502AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2503              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2504  for (UsingDecl::shadow_iterator II = Node.shadow_begin();
2505       II != Node.shadow_end(); ++II) {
2506    if (InnerMatcher.matches(**II, Finder, Builder))
2507      return true;
2508  }
2509  return false;
2510}
2511
2512/// \brief Matches a using shadow declaration where the target declaration is
2513/// matched by the given matcher.
2514///
2515/// Given
2516/// \code
2517///   namespace X { int a; void b(); }
2518///   using X::a;
2519///   using X::b;
2520/// \endcode
2521/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2522///   matches \code using X::b \endcode
2523///   but not \code using X::a \endcode
2524AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2525              internal::Matcher<NamedDecl>, InnerMatcher) {
2526  return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2527}
2528
2529/// \brief Matches template instantiations of function, class, or static
2530/// member variable template instantiations.
2531///
2532/// Given
2533/// \code
2534///   template <typename T> class X {}; class A {}; X<A> x;
2535/// \endcode
2536/// or
2537/// \code
2538///   template <typename T> class X {}; class A {}; template class X<A>;
2539/// \endcode
2540/// recordDecl(hasName("::X"), isTemplateInstantiation())
2541///   matches the template instantiation of X<A>.
2542///
2543/// But given
2544/// \code
2545///   template <typename T>  class X {}; class A {};
2546///   template <> class X<A> {}; X<A> x;
2547/// \endcode
2548/// recordDecl(hasName("::X"), isTemplateInstantiation())
2549///   does not match, as X<A> is an explicit template specialization.
2550///
2551/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2552AST_POLYMORPHIC_MATCHER(isTemplateInstantiation) {
2553  TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2554                         (llvm::is_base_of<VarDecl, NodeType>::value) ||
2555                         (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2556                         requires_getTemplateSpecializationKind_method);
2557  return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2558          Node.getTemplateSpecializationKind() ==
2559          TSK_ExplicitInstantiationDefinition);
2560}
2561
2562/// \brief Matches explicit template specializations of function, class, or
2563/// static member variable template instantiations.
2564///
2565/// Given
2566/// \code
2567///   template<typename T> void A(T t) { }
2568///   template<> void A(int N) { }
2569/// \endcode
2570/// functionDecl(isExplicitTemplateSpecialization())
2571///   matches the specialization A<int>().
2572///
2573/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2574AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization) {
2575  TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2576                         (llvm::is_base_of<VarDecl, NodeType>::value) ||
2577                         (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2578                         requires_getTemplateSpecializationKind_method);
2579  return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2580}
2581
2582/// \brief Matches \c TypeLocs for which the given inner
2583/// QualType-matcher matches.
2584inline internal::BindableMatcher<TypeLoc> loc(
2585    const internal::Matcher<QualType> &InnerMatcher) {
2586  return internal::BindableMatcher<TypeLoc>(
2587      new internal::TypeLocTypeMatcher(InnerMatcher));
2588}
2589
2590/// \brief Matches builtin Types.
2591///
2592/// Given
2593/// \code
2594///   struct A {};
2595///   A a;
2596///   int b;
2597///   float c;
2598///   bool d;
2599/// \endcode
2600/// builtinType()
2601///   matches "int b", "float c" and "bool d"
2602AST_TYPE_MATCHER(BuiltinType, builtinType);
2603
2604/// \brief Matches all kinds of arrays.
2605///
2606/// Given
2607/// \code
2608///   int a[] = { 2, 3 };
2609///   int b[4];
2610///   void f() { int c[a[0]]; }
2611/// \endcode
2612/// arrayType()
2613///   matches "int a[]", "int b[4]" and "int c[a[0]]";
2614AST_TYPE_MATCHER(ArrayType, arrayType);
2615
2616/// \brief Matches C99 complex types.
2617///
2618/// Given
2619/// \code
2620///   _Complex float f;
2621/// \endcode
2622/// complexType()
2623///   matches "_Complex float f"
2624AST_TYPE_MATCHER(ComplexType, complexType);
2625
2626/// \brief Matches arrays and C99 complex types that have a specific element
2627/// type.
2628///
2629/// Given
2630/// \code
2631///   struct A {};
2632///   A a[7];
2633///   int b[7];
2634/// \endcode
2635/// arrayType(hasElementType(builtinType()))
2636///   matches "int b[7]"
2637///
2638/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
2639AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement);
2640
2641/// \brief Matches C arrays with a specified constant size.
2642///
2643/// Given
2644/// \code
2645///   void() {
2646///     int a[2];
2647///     int b[] = { 2, 3 };
2648///     int c[b[0]];
2649///   }
2650/// \endcode
2651/// constantArrayType()
2652///   matches "int a[2]"
2653AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
2654
2655/// \brief Matches \c ConstantArrayType nodes that have the specified size.
2656///
2657/// Given
2658/// \code
2659///   int a[42];
2660///   int b[2 * 21];
2661///   int c[41], d[43];
2662/// \endcode
2663/// constantArrayType(hasSize(42))
2664///   matches "int a[42]" and "int b[2 * 21]"
2665AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
2666  return Node.getSize() == N;
2667}
2668
2669/// \brief Matches C++ arrays whose size is a value-dependent expression.
2670///
2671/// Given
2672/// \code
2673///   template<typename T, int Size>
2674///   class array {
2675///     T data[Size];
2676///   };
2677/// \endcode
2678/// dependentSizedArrayType
2679///   matches "T data[Size]"
2680AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
2681
2682/// \brief Matches C arrays with unspecified size.
2683///
2684/// Given
2685/// \code
2686///   int a[] = { 2, 3 };
2687///   int b[42];
2688///   void f(int c[]) { int d[a[0]]; };
2689/// \endcode
2690/// incompleteArrayType()
2691///   matches "int a[]" and "int c[]"
2692AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
2693
2694/// \brief Matches C arrays with a specified size that is not an
2695/// integer-constant-expression.
2696///
2697/// Given
2698/// \code
2699///   void f() {
2700///     int a[] = { 2, 3 }
2701///     int b[42];
2702///     int c[a[0]];
2703/// \endcode
2704/// variableArrayType()
2705///   matches "int c[a[0]]"
2706AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
2707
2708/// \brief Matches \c VariableArrayType nodes that have a specific size
2709/// expression.
2710///
2711/// Given
2712/// \code
2713///   void f(int b) {
2714///     int a[b];
2715///   }
2716/// \endcode
2717/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
2718///   varDecl(hasName("b")))))))
2719///   matches "int a[b]"
2720AST_MATCHER_P(VariableArrayType, hasSizeExpr,
2721              internal::Matcher<Expr>, InnerMatcher) {
2722  return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
2723}
2724
2725/// \brief Matches atomic types.
2726///
2727/// Given
2728/// \code
2729///   _Atomic(int) i;
2730/// \endcode
2731/// atomicType()
2732///   matches "_Atomic(int) i"
2733AST_TYPE_MATCHER(AtomicType, atomicType);
2734
2735/// \brief Matches atomic types with a specific value type.
2736///
2737/// Given
2738/// \code
2739///   _Atomic(int) i;
2740///   _Atomic(float) f;
2741/// \endcode
2742/// atomicType(hasValueType(isInteger()))
2743///  matches "_Atomic(int) i"
2744///
2745/// Usable as: Matcher<AtomicType>
2746AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue);
2747
2748/// \brief Matches types nodes representing C++11 auto types.
2749///
2750/// Given:
2751/// \code
2752///   auto n = 4;
2753///   int v[] = { 2, 3 }
2754///   for (auto i : v) { }
2755/// \endcode
2756/// autoType()
2757///   matches "auto n" and "auto i"
2758AST_TYPE_MATCHER(AutoType, autoType);
2759
2760/// \brief Matches \c AutoType nodes where the deduced type is a specific type.
2761///
2762/// Note: There is no \c TypeLoc for the deduced type and thus no
2763/// \c getDeducedLoc() matcher.
2764///
2765/// Given
2766/// \code
2767///   auto a = 1;
2768///   auto b = 2.0;
2769/// \endcode
2770/// autoType(hasDeducedType(isInteger()))
2771///   matches "auto a"
2772///
2773/// Usable as: Matcher<AutoType>
2774AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType);
2775
2776/// \brief Matches \c FunctionType nodes.
2777///
2778/// Given
2779/// \code
2780///   int (*f)(int);
2781///   void g();
2782/// \endcode
2783/// functionType()
2784///   matches "int (*f)(int)" and the type of "g".
2785AST_TYPE_MATCHER(FunctionType, functionType);
2786
2787/// \brief Matches block pointer types, i.e. types syntactically represented as
2788/// "void (^)(int)".
2789///
2790/// The \c pointee is always required to be a \c FunctionType.
2791AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
2792
2793/// \brief Matches member pointer types.
2794/// Given
2795/// \code
2796///   struct A { int i; }
2797///   A::* ptr = A::i;
2798/// \endcode
2799/// memberPointerType()
2800///   matches "A::* ptr"
2801AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
2802
2803/// \brief Matches pointer types.
2804///
2805/// Given
2806/// \code
2807///   int *a;
2808///   int &b = *a;
2809///   int c = 5;
2810/// \endcode
2811/// pointerType()
2812///   matches "int *a"
2813AST_TYPE_MATCHER(PointerType, pointerType);
2814
2815/// \brief Matches reference types.
2816///
2817/// Given
2818/// \code
2819///   int *a;
2820///   int &b = *a;
2821///   int c = 5;
2822/// \endcode
2823/// pointerType()
2824///   matches "int &b"
2825AST_TYPE_MATCHER(ReferenceType, referenceType);
2826
2827/// \brief Narrows PointerType (and similar) matchers to those where the
2828/// \c pointee matches a given matcher.
2829///
2830/// Given
2831/// \code
2832///   int *a;
2833///   int const *b;
2834///   float const *f;
2835/// \endcode
2836/// pointerType(pointee(isConstQualified(), isInteger()))
2837///   matches "int const *b"
2838///
2839/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
2840///   Matcher<PointerType>, Matcher<ReferenceType>
2841AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee);
2842
2843/// \brief Matches typedef types.
2844///
2845/// Given
2846/// \code
2847///   typedef int X;
2848/// \endcode
2849/// typedefType()
2850///   matches "typedef int X"
2851AST_TYPE_MATCHER(TypedefType, typedefType);
2852
2853/// \brief Matches nested name specifiers.
2854///
2855/// Given
2856/// \code
2857///   namespace ns {
2858///     struct A { static void f(); };
2859///     void A::f() {}
2860///     void g() { A::f(); }
2861///   }
2862///   ns::A a;
2863/// \endcode
2864/// nestedNameSpecifier()
2865///   matches "ns::" and both "A::"
2866const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
2867
2868/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
2869const internal::VariadicAllOfMatcher<
2870  NestedNameSpecifierLoc> nestedNameSpecifierLoc;
2871
2872/// \brief Matches \c NestedNameSpecifierLocs for which the given inner
2873/// NestedNameSpecifier-matcher matches.
2874inline internal::BindableMatcher<NestedNameSpecifierLoc> loc(
2875    const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
2876  return internal::BindableMatcher<NestedNameSpecifierLoc>(
2877      new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
2878          InnerMatcher));
2879}
2880
2881/// \brief Matches nested name specifiers that specify a type matching the
2882/// given \c QualType matcher without qualifiers.
2883///
2884/// Given
2885/// \code
2886///   struct A { struct B { struct C {}; }; };
2887///   A::B::C c;
2888/// \endcode
2889/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
2890///   matches "A::"
2891AST_MATCHER_P(NestedNameSpecifier, specifiesType,
2892              internal::Matcher<QualType>, InnerMatcher) {
2893  if (Node.getAsType() == NULL)
2894    return false;
2895  return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
2896}
2897
2898/// \brief Matches nested name specifier locs that specify a type matching the
2899/// given \c TypeLoc.
2900///
2901/// Given
2902/// \code
2903///   struct A { struct B { struct C {}; }; };
2904///   A::B::C c;
2905/// \endcode
2906/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
2907///   hasDeclaration(recordDecl(hasName("A")))))))
2908///   matches "A::"
2909AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
2910              internal::Matcher<TypeLoc>, InnerMatcher) {
2911  return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
2912}
2913
2914/// \brief Matches on the prefix of a \c NestedNameSpecifier.
2915///
2916/// Given
2917/// \code
2918///   struct A { struct B { struct C {}; }; };
2919///   A::B::C c;
2920/// \endcode
2921/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
2922///   matches "A::"
2923AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
2924                       internal::Matcher<NestedNameSpecifier>, InnerMatcher,
2925                       0) {
2926  NestedNameSpecifier *NextNode = Node.getPrefix();
2927  if (NextNode == NULL)
2928    return false;
2929  return InnerMatcher.matches(*NextNode, Finder, Builder);
2930}
2931
2932/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
2933///
2934/// Given
2935/// \code
2936///   struct A { struct B { struct C {}; }; };
2937///   A::B::C c;
2938/// \endcode
2939/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
2940///   matches "A::"
2941AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
2942                       internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
2943                       1) {
2944  NestedNameSpecifierLoc NextNode = Node.getPrefix();
2945  if (!NextNode)
2946    return false;
2947  return InnerMatcher.matches(NextNode, Finder, Builder);
2948}
2949
2950/// \brief Matches nested name specifiers that specify a namespace matching the
2951/// given namespace matcher.
2952///
2953/// Given
2954/// \code
2955///   namespace ns { struct A {}; }
2956///   ns::A a;
2957/// \endcode
2958/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
2959///   matches "ns::"
2960AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
2961              internal::Matcher<NamespaceDecl>, InnerMatcher) {
2962  if (Node.getAsNamespace() == NULL)
2963    return false;
2964  return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
2965}
2966
2967/// \brief Overloads for the \c equalsNode matcher.
2968/// FIXME: Implement for other node types.
2969/// @{
2970
2971/// \brief Matches if a node equals another node.
2972///
2973/// \c Decl has pointer identity in the AST.
2974AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) {
2975  return &Node == Other;
2976}
2977/// \brief Matches if a node equals another node.
2978///
2979/// \c Stmt has pointer identity in the AST.
2980///
2981AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) {
2982  return &Node == Other;
2983}
2984
2985/// @}
2986
2987} // end namespace ast_matchers
2988} // end namespace clang
2989
2990#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
2991