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