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