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