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