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