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