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