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