ASTMatchers.h revision 425f41b370a8795fbca9ffc3b35e9b0ccbb15d97
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//    record(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//    record(hasName("MyClass"), hasChild(id("child", record())))
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 adding id(...) matchers into the
61/// match expression around the matchers for the nodes we want to access later.
62///
63/// The instances of BoundNodes are created by 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 'ID'.
68  /// Returns NULL if there was no node bound to 'ID' or if there is a node but
69  /// it cannot be converted to the specified type.
70  /// FIXME: We'll need one of those for every base type.
71  /// @{
72  template <typename T>
73  const T *getDeclAs(StringRef ID) const {
74    return getNodeAs<T>(DeclBindings, ID);
75  }
76  template <typename T>
77  const T *getStmtAs(StringRef ID) const {
78    return getNodeAs<T>(StmtBindings, ID);
79  }
80  /// @}
81
82private:
83  /// \brief Create BoundNodes from a pre-filled map of bindings.
84  BoundNodes(const std::map<std::string, const Decl*> &DeclBindings,
85             const std::map<std::string, const Stmt*> &StmtBindings)
86      : DeclBindings(DeclBindings), StmtBindings(StmtBindings) {}
87
88  template <typename T, typename MapT>
89  const T *getNodeAs(const MapT &Bindings, StringRef ID) const {
90    typename MapT::const_iterator It = Bindings.find(ID);
91    if (It == Bindings.end()) {
92      return NULL;
93    }
94    return llvm::dyn_cast<T>(It->second);
95  }
96
97  std::map<std::string, const Decl*> DeclBindings;
98  std::map<std::string, const Stmt*> StmtBindings;
99
100  friend class internal::BoundNodesTree;
101};
102
103/// \brief If the provided matcher matches a node, binds the node to 'ID'.
104///
105/// FIXME: Add example for accessing it.
106template <typename T>
107internal::Matcher<T> id(const std::string &ID,
108                        const internal::BindableMatcher<T> &InnerMatcher) {
109  return InnerMatcher.bind(ID);
110}
111
112/// \brief Types of matchers for the top-level classes in the AST class
113/// hierarchy.
114/// @{
115typedef internal::Matcher<Decl> DeclarationMatcher;
116typedef internal::Matcher<QualType> TypeMatcher;
117typedef internal::Matcher<Stmt> StatementMatcher;
118/// @}
119
120/// \brief Matches any node.
121///
122/// Useful when another matcher requires a child matcher, but there's no
123/// additional constraint. This will often be used with an explicit conversion
124/// to a internal::Matcher<> type such as TypeMatcher.
125///
126/// Example: DeclarationMatcher(anything()) matches all declarations, e.g.,
127/// "int* p" and "void f()" in
128///   int* p;
129///   void f();
130inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() {
131  return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
132}
133
134/// \brief Matches declarations.
135///
136/// Examples matches \c X, \c C, and the friend declaration inside \c C;
137/// \code
138///   void X();
139///   class C {
140///     friend X;
141///   };
142/// \endcode
143const internal::VariadicDynCastAllOfMatcher<Decl, Decl> decl;
144
145/// \brief Matches a declaration of anything that could have a name.
146///
147/// Example matches X, S, the anonymous union type, i, and U;
148///   typedef int X;
149///   struct S {
150///     union {
151///       int i;
152///     } U;
153///   };
154const internal::VariadicDynCastAllOfMatcher<
155  Decl,
156  NamedDecl> nameableDeclaration;
157
158/// \brief Matches C++ class declarations.
159///
160/// Example matches X, Z
161///   class X;
162///   template<class T> class Z {};
163const internal::VariadicDynCastAllOfMatcher<
164  Decl,
165  CXXRecordDecl> record;
166
167/// \brief Matches C++ class template specializations.
168///
169/// Given
170///   template<typename T> class A {};
171///   template<> class A<double> {};
172///   A<int> a;
173/// classTemplateSpecialization()
174///   matches the specializations \c A<int> and \c A<double>
175const internal::VariadicDynCastAllOfMatcher<
176  Decl,
177  ClassTemplateSpecializationDecl> classTemplateSpecialization;
178
179/// \brief Matches classTemplateSpecializations that have at least one
180/// TemplateArgument matching the given Matcher.
181///
182/// Given
183///   template<typename T> class A {};
184///   template<> class A<double> {};
185///   A<int> a;
186/// classTemplateSpecialization(hasAnyTemplateArgument(
187///     refersToType(asString("int"))))
188///   matches the specialization \c A<int>
189AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
190              internal::Matcher<TemplateArgument>, Matcher) {
191  const TemplateArgumentList &List = Node.getTemplateArgs();
192  for (unsigned i = 0; i < List.size(); ++i) {
193    if (Matcher.matches(List.get(i), Finder, Builder))
194      return true;
195  }
196  return false;
197}
198
199/// \brief Matches expressions that match InnerMatcher after any implicit casts
200/// are stripped off.
201///
202/// Parentheses and explicit casts are not discarded.
203/// Given
204///   int arr[5];
205///   int a = 0;
206///   char b = 0;
207///   const int c = a;
208///   int *d = arr;
209///   long e = (long) 0l;
210/// The matchers
211///    variable(hasInitializer(ignoringImpCasts(integerLiteral())))
212///    variable(hasInitializer(ignoringImpCasts(declarationReference())))
213/// would match the declarations for a, b, c, and d, but not e.
214/// while
215///    variable(hasInitializer(integerLiteral()))
216///    variable(hasInitializer(declarationReference()))
217/// only match the declarations for b, c, and d.
218AST_MATCHER_P(Expr, ignoringImpCasts,
219              internal::Matcher<Expr>, InnerMatcher) {
220  return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
221}
222
223/// \brief Matches expressions that match InnerMatcher after parentheses and
224/// casts are stripped off.
225///
226/// Implicit and non-C Style casts are also discarded.
227/// Given
228///   int a = 0;
229///   char b = (0);
230///   void* c = reinterpret_cast<char*>(0);
231///   char d = char(0);
232/// The matcher
233///    variable(hasInitializer(ignoringParenCasts(integerLiteral())))
234/// would match the declarations for a, b, c, and d.
235/// while
236///    variable(hasInitializer(integerLiteral()))
237/// only match the declaration for a.
238AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
239  return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
240}
241
242/// \brief Matches expressions that match InnerMatcher after implicit casts and
243/// parentheses are stripped off.
244///
245/// Explicit casts are not discarded.
246/// Given
247///   int arr[5];
248///   int a = 0;
249///   char b = (0);
250///   const int c = a;
251///   int *d = (arr);
252///   long e = ((long) 0l);
253/// The matchers
254///    variable(hasInitializer(ignoringParenImpCasts(
255///       integerLiteral())))
256///    variable(hasInitializer(ignoringParenImpCasts(
257///       declarationReference())))
258/// would match the declarations for a, b, c, and d, but not e.
259/// while
260///    variable(hasInitializer(integerLiteral()))
261///    variable(hasInitializer(declarationReference()))
262/// would only match the declaration for a.
263AST_MATCHER_P(Expr, ignoringParenImpCasts,
264              internal::Matcher<Expr>, InnerMatcher) {
265  return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
266}
267
268/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
269/// matches the given Matcher.
270///
271/// Given
272///   template<typename T, typename U> class A {};
273///   A<bool, int> b;
274///   A<int, bool> c;
275/// classTemplateSpecialization(hasTemplateArgument(
276///     1, refersToType(asString("int"))))
277///   matches the specialization \c A<bool, int>
278AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
279               unsigned, N, internal::Matcher<TemplateArgument>, Matcher) {
280  const TemplateArgumentList &List = Node.getTemplateArgs();
281  if (List.size() <= N)
282    return false;
283  return Matcher.matches(List.get(N), Finder, Builder);
284}
285
286/// \brief Matches a TemplateArgument that refers to a certain type.
287///
288/// Given
289///   struct X {};
290///   template<typename T> struct A {};
291///   A<X> a;
292/// classTemplateSpecialization(hasAnyTemplateArgument(
293///     refersToType(class(hasName("X")))))
294///   matches the specialization \c A<X>
295AST_MATCHER_P(TemplateArgument, refersToType,
296              internal::Matcher<QualType>, Matcher) {
297  if (Node.getKind() != TemplateArgument::Type)
298    return false;
299  return Matcher.matches(Node.getAsType(), Finder, Builder);
300}
301
302/// \brief Matches a TemplateArgument that refers to a certain declaration.
303///
304/// Given
305///   template<typename T> struct A {};
306///   struct B { B* next; };
307///   A<&B::next> a;
308/// classTemplateSpecialization(hasAnyTemplateArgument(
309///     refersToDeclaration(field(hasName("next"))))
310///   matches the specialization \c A<&B::next> with \c field(...) matching
311///     \c B::next
312AST_MATCHER_P(TemplateArgument, refersToDeclaration,
313              internal::Matcher<Decl>, Matcher) {
314  if (const Decl *Declaration = Node.getAsDecl())
315    return Matcher.matches(*Declaration, Finder, Builder);
316  return false;
317}
318
319/// \brief Matches C++ constructor declarations.
320///
321/// Example matches Foo::Foo() and Foo::Foo(int)
322///   class Foo {
323///    public:
324///     Foo();
325///     Foo(int);
326///     int DoSomething();
327///   };
328const internal::VariadicDynCastAllOfMatcher<
329  Decl,
330  CXXConstructorDecl> constructor;
331
332/// \brief Matches explicit C++ destructor declarations.
333///
334/// Example matches Foo::~Foo()
335///   class Foo {
336///    public:
337///     virtual ~Foo();
338///   };
339const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> destructor;
340
341/// \brief Matches enum declarations.
342///
343/// Example matches X
344///   enum X {
345///     A, B, C
346///   };
347const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
348
349/// \brief Matches enum constants.
350///
351/// Example matches A, B, C
352///   enum X {
353///     A, B, C
354///   };
355const internal::VariadicDynCastAllOfMatcher<
356  Decl,
357  EnumConstantDecl> enumConstant;
358
359/// \brief Matches method declarations.
360///
361/// Example matches y
362///   class X { void y() };
363const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> method;
364
365/// \brief Matches variable declarations.
366///
367/// Note: this does not match declarations of member variables, which are
368/// "field" declarations in Clang parlance.
369///
370/// Example matches a
371///   int a;
372const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> variable;
373
374/// \brief Matches field declarations.
375///
376/// Given
377///   class X { int m; };
378/// field()
379///   matches 'm'.
380const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> field;
381
382/// \brief Matches function declarations.
383///
384/// Example matches f
385///   void f();
386const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> function;
387
388
389/// \brief Matches statements.
390///
391/// Given
392///   { ++a; }
393/// statement()
394///   matches both the compound statement '{ ++a; }' and '++a'.
395const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> statement;
396
397/// \brief Matches declaration statements.
398///
399/// Given
400///   int a;
401/// declarationStatement()
402///   matches 'int a'.
403const internal::VariadicDynCastAllOfMatcher<
404  Stmt,
405  DeclStmt> declarationStatement;
406
407/// \brief Matches member expressions.
408///
409/// Given
410///   class Y {
411///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
412///     int a; static int b;
413///   };
414/// memberExpression()
415///   matches this->x, x, y.x, a, this->b
416const internal::VariadicDynCastAllOfMatcher<
417  Stmt,
418  MemberExpr> memberExpression;
419
420/// \brief Matches call expressions.
421///
422/// Example matches x.y() and y()
423///   X x;
424///   x.y();
425///   y();
426const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> call;
427
428/// \brief Matches member call expressions.
429///
430/// Example matches x.y()
431///   X x;
432///   x.y();
433const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr> memberCall;
434
435/// \brief Matches init list expressions.
436///
437/// Given
438///   int a[] = { 1, 2 };
439///   struct B { int x, y; };
440///   B b = { 5, 6 };
441/// initList()
442///   matches "{ 1, 2 }" and "{ 5, 6 }"
443const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
444
445/// \brief Matches using declarations.
446///
447/// Given
448///   namespace X { int x; }
449///   using X::x;
450/// usingDecl()
451///   matches \code using X::x \endcode
452const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
453
454/// \brief Matches constructor call expressions (including implicit ones).
455///
456/// Example matches string(ptr, n) and ptr within arguments of f
457///     (matcher = constructorCall())
458///   void f(const string &a, const string &b);
459///   char *ptr;
460///   int n;
461///   f(string(ptr, n), ptr);
462const internal::VariadicDynCastAllOfMatcher<
463  Stmt,
464  CXXConstructExpr> constructorCall;
465
466/// \brief Matches nodes where temporaries are created.
467///
468/// Example matches FunctionTakesString(GetStringByValue())
469///     (matcher = bindTemporaryExpression())
470///   FunctionTakesString(GetStringByValue());
471///   FunctionTakesStringByPointer(GetStringPointer());
472const internal::VariadicDynCastAllOfMatcher<
473  Stmt,
474  CXXBindTemporaryExpr> bindTemporaryExpression;
475
476/// \brief Matches new expressions.
477///
478/// Given
479///   new X;
480/// newExpression()
481///   matches 'new X'.
482const internal::VariadicDynCastAllOfMatcher<
483  Stmt,
484  CXXNewExpr> newExpression;
485
486/// \brief Matches delete expressions.
487///
488/// Given
489///   delete X;
490/// deleteExpression()
491///   matches 'delete X'.
492const internal::VariadicDynCastAllOfMatcher<
493  Stmt,
494  CXXDeleteExpr> deleteExpression;
495
496/// \brief Matches array subscript expressions.
497///
498/// Given
499///   int i = a[1];
500/// arraySubscriptExpr()
501///   matches "a[1]"
502const internal::VariadicDynCastAllOfMatcher<
503  Stmt,
504  ArraySubscriptExpr> arraySubscriptExpr;
505
506/// \brief Matches the value of a default argument at the call site.
507///
508/// Example matches the CXXDefaultArgExpr placeholder inserted for the
509///     default value of the second parameter in the call expression f(42)
510///     (matcher = defaultArgument())
511///   void f(int x, int y = 0);
512///   f(42);
513const internal::VariadicDynCastAllOfMatcher<
514  Stmt,
515  CXXDefaultArgExpr> defaultArgument;
516
517/// \brief Matches overloaded operator calls.
518///
519/// Note that if an operator isn't overloaded, it won't match. Instead, use
520/// binaryOperator matcher.
521/// Currently it does not match operators such as new delete.
522/// FIXME: figure out why these do not match?
523///
524/// Example matches both operator<<((o << b), c) and operator<<(o, b)
525///     (matcher = overloadedOperatorCall())
526///   ostream &operator<< (ostream &out, int i) { };
527///   ostream &o; int b = 1, c = 1;
528///   o << b << c;
529const internal::VariadicDynCastAllOfMatcher<
530  Stmt,
531  CXXOperatorCallExpr> overloadedOperatorCall;
532
533/// \brief Matches expressions.
534///
535/// Example matches x()
536///   void f() { x(); }
537const internal::VariadicDynCastAllOfMatcher<
538  Stmt,
539  Expr> expression;
540
541/// \brief Matches expressions that refer to declarations.
542///
543/// Example matches x in if (x)
544///   bool x;
545///   if (x) {}
546const internal::VariadicDynCastAllOfMatcher<
547  Stmt,
548  DeclRefExpr> declarationReference;
549
550/// \brief Matches if statements.
551///
552/// Example matches 'if (x) {}'
553///   if (x) {}
554const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
555
556/// \brief Matches for statements.
557///
558/// Example matches 'for (;;) {}'
559///   for (;;) {}
560const internal::VariadicDynCastAllOfMatcher<
561  Stmt, ForStmt> forStmt;
562
563/// \brief Matches the increment statement of a for loop.
564///
565/// Example:
566///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
567/// matches '++x' in
568///     for (x; x < N; ++x) { }
569AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
570              InnerMatcher) {
571  const Stmt *const Increment = Node.getInc();
572  return (Increment != NULL &&
573          InnerMatcher.matches(*Increment, Finder, Builder));
574}
575
576/// \brief Matches the initialization statement of a for loop.
577///
578/// Example:
579///     forStmt(hasLoopInit(declarationStatement()))
580/// matches 'int x = 0' in
581///     for (int x = 0; x < N; ++x) { }
582AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
583              InnerMatcher) {
584  const Stmt *const Init = Node.getInit();
585  return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
586}
587
588/// \brief Matches while statements.
589///
590/// Given
591///   while (true) {}
592/// whileStmt()
593///   matches 'while (true) {}'.
594const internal::VariadicDynCastAllOfMatcher<
595  Stmt,
596  WhileStmt> whileStmt;
597
598/// \brief Matches do statements.
599///
600/// Given
601///   do {} while (true);
602/// doStmt()
603///   matches 'do {} while(true)'
604const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
605
606/// \brief Matches case and default statements inside switch statements.
607///
608/// Given
609///   switch(a) { case 42: break; default: break; }
610/// switchCase()
611///   matches 'case 42: break;' and 'default: break;'.
612const internal::VariadicDynCastAllOfMatcher<
613  Stmt,
614  SwitchCase> switchCase;
615
616/// \brief Matches compound statements.
617///
618/// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
619///   for (;;) {{}}
620const internal::VariadicDynCastAllOfMatcher<
621  Stmt,
622  CompoundStmt> compoundStatement;
623
624/// \brief Matches bool literals.
625///
626/// Example matches true
627///   true
628const internal::VariadicDynCastAllOfMatcher<
629  Expr,
630  CXXBoolLiteralExpr> boolLiteral;
631
632/// \brief Matches string literals (also matches wide string literals).
633///
634/// Example matches "abcd", L"abcd"
635///   char *s = "abcd"; wchar_t *ws = L"abcd"
636const internal::VariadicDynCastAllOfMatcher<
637  Expr,
638  StringLiteral> stringLiteral;
639
640/// \brief Matches character literals (also matches wchar_t).
641///
642/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
643/// though.
644///
645/// Example matches 'a', L'a'
646///   char ch = 'a'; wchar_t chw = L'a';
647const internal::VariadicDynCastAllOfMatcher<
648  Expr,
649  CharacterLiteral> characterLiteral;
650
651/// \brief Matches integer literals of all sizes / encodings.
652///
653/// Not matching character-encoded integers such as L'a'.
654///
655/// Example matches 1, 1L, 0x1, 1U
656const internal::VariadicDynCastAllOfMatcher<
657  Expr,
658  IntegerLiteral> integerLiteral;
659
660/// \brief Matches binary operator expressions.
661///
662/// Example matches a || b
663///   !(a || b)
664const internal::VariadicDynCastAllOfMatcher<
665  Stmt,
666  BinaryOperator> binaryOperator;
667
668/// \brief Matches unary operator expressions.
669///
670/// Example matches !a
671///   !a || b
672const internal::VariadicDynCastAllOfMatcher<
673  Stmt,
674  UnaryOperator> unaryOperator;
675
676/// \brief Matches conditional operator expressions.
677///
678/// Example matches a ? b : c
679///   (a ? b : c) + 42
680const internal::VariadicDynCastAllOfMatcher<
681  Stmt,
682  ConditionalOperator> conditionalOperator;
683
684/// \brief Matches a reinterpret_cast expression.
685///
686/// Either the source expression or the destination type can be matched
687/// using has(), but hasDestinationType() is more specific and can be
688/// more readable.
689///
690/// Example matches reinterpret_cast<char*>(&p) in
691///   void* p = reinterpret_cast<char*>(&p);
692const internal::VariadicDynCastAllOfMatcher<
693  Expr,
694  CXXReinterpretCastExpr> reinterpretCast;
695
696/// \brief Matches a C++ static_cast expression.
697///
698/// \see hasDestinationType
699/// \see reinterpretCast
700///
701/// Example:
702///   staticCast()
703/// matches
704///   static_cast<long>(8)
705/// in
706///   long eight(static_cast<long>(8));
707const internal::VariadicDynCastAllOfMatcher<
708  Expr,
709  CXXStaticCastExpr> staticCast;
710
711/// \brief Matches a dynamic_cast expression.
712///
713/// Example:
714///   dynamicCast()
715/// matches
716///   dynamic_cast<D*>(&b);
717/// in
718///   struct B { virtual ~B() {} }; struct D : B {};
719///   B b;
720///   D* p = dynamic_cast<D*>(&b);
721const internal::VariadicDynCastAllOfMatcher<
722  Expr,
723  CXXDynamicCastExpr> dynamicCast;
724
725/// \brief Matches a const_cast expression.
726///
727/// Example: Matches const_cast<int*>(&r) in
728///   int n = 42;
729///   const int& r(n);
730///   int* p = const_cast<int*>(&r);
731const internal::VariadicDynCastAllOfMatcher<
732  Expr,
733  CXXConstCastExpr> constCast;
734
735/// \brief Matches explicit cast expressions.
736///
737/// Matches any cast expression written in user code, whether it be a
738/// C-style cast, a functional-style cast, or a keyword cast.
739///
740/// Does not match implicit conversions.
741///
742/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
743/// Clang uses the term "cast" to apply to implicit conversions as well as to
744/// actual cast expressions.
745///
746/// \see hasDestinationType.
747///
748/// Example: matches all five of the casts in
749///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
750/// but does not match the implicit conversion in
751///   long ell = 42;
752const internal::VariadicDynCastAllOfMatcher<
753  Expr,
754  ExplicitCastExpr> explicitCast;
755
756/// \brief Matches the implicit cast nodes of Clang's AST.
757///
758/// This matches many different places, including function call return value
759/// eliding, as well as any type conversions.
760const internal::VariadicDynCastAllOfMatcher<
761  Expr,
762  ImplicitCastExpr> implicitCast;
763
764/// \brief Matches any cast nodes of Clang's AST.
765///
766/// Example: castExpr() matches each of the following:
767///   (int) 3;
768///   const_cast<Expr *>(SubExpr);
769///   char c = 0;
770/// but does not match
771///   int i = (0);
772///   int k = 0;
773const internal::VariadicDynCastAllOfMatcher<
774  Expr,
775  CastExpr> castExpr;
776
777/// \brief Matches functional cast expressions
778///
779/// Example: Matches Foo(bar);
780///   Foo f = bar;
781///   Foo g = (Foo) bar;
782///   Foo h = Foo(bar);
783const internal::VariadicDynCastAllOfMatcher<
784  Expr,
785  CXXFunctionalCastExpr> functionalCast;
786
787/// \brief Various overloads for the anyOf matcher.
788/// @{
789template<typename C1, typename C2>
790internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, C2>
791anyOf(const C1 &P1, const C2 &P2) {
792  return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
793                                                C1, C2 >(P1, P2);
794}
795template<typename C1, typename C2, typename C3>
796internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
797    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, C3> >
798anyOf(const C1 &P1, const C2 &P2, const C3 &P3) {
799  return anyOf(P1, anyOf(P2, P3));
800}
801template<typename C1, typename C2, typename C3, typename C4>
802internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
803    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2,
804        internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
805                                               C3, C4> > >
806anyOf(const C1 &P1, const C2 &P2, const C3 &P3, const C4 &P4) {
807  return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
808}
809template<typename C1, typename C2, typename C3, typename C4, typename C5>
810internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
811    internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2,
812        internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C3,
813            internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
814                                                   C4, C5> > > >
815anyOf(const C1& P1, const C2& P2, const C3& P3, const C4& P4, const C5& P5) {
816  return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
817}
818/// @}
819
820/// \brief Various overloads for the allOf matcher.
821/// @{
822template<typename C1, typename C2>
823internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, C2>
824allOf(const C1 &P1, const C2 &P2) {
825  return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher,
826                                                C1, C2>(P1, P2);
827}
828template<typename C1, typename C2, typename C3>
829internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1,
830    internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C2, C3> >
831allOf(const C1& P1, const C2& P2, const C3& P3) {
832  return allOf(P1, allOf(P2, P3));
833}
834/// @}
835
836/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
837///
838/// Given
839///   Foo x = bar;
840///   int y = sizeof(x) + alignof(x);
841/// unaryExprOrTypeTraitExpr()
842///   matches \c sizeof(x) and \c alignof(x)
843const internal::VariadicDynCastAllOfMatcher<
844  Stmt,
845  UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
846
847/// \brief Matches unary expressions that have a specific type of argument.
848///
849/// Given
850///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
851/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
852///   matches \c sizeof(a) and \c alignof(c)
853AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
854              internal::Matcher<QualType>, Matcher) {
855  const QualType ArgumentType = Node.getTypeOfArgument();
856  return Matcher.matches(ArgumentType, Finder, Builder);
857}
858
859/// \brief Matches unary expressions of a certain kind.
860///
861/// Given
862///   int x;
863///   int s = sizeof(x) + alignof(x)
864/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
865///   matches \c sizeof(x)
866AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
867  return Node.getKind() == Kind;
868}
869
870/// \brief Same as unaryExprOrTypeTraitExpr, but only matching
871/// alignof.
872inline internal::Matcher<Stmt> alignOfExpr(
873    const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) {
874  return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
875      ofKind(UETT_AlignOf), Matcher)));
876}
877
878/// \brief Same as unaryExprOrTypeTraitExpr, but only matching
879/// sizeof.
880inline internal::Matcher<Stmt> sizeOfExpr(
881    const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) {
882  return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
883      ofKind(UETT_SizeOf), Matcher)));
884}
885
886/// \brief Matches NamedDecl nodes that have the specified name.
887///
888/// Supports specifying enclosing namespaces or classes by prefixing the name
889/// with '<enclosing>::'.
890/// Does not match typedefs of an underlying type with the given name.
891///
892/// Example matches X (Name == "X")
893///   class X;
894///
895/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
896/// namespace a { namespace b { class X; } }
897AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
898  assert(!Name.empty());
899  const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
900  const llvm::StringRef FullName = FullNameString;
901  const llvm::StringRef Pattern = Name;
902  if (Pattern.startswith("::")) {
903    return FullName == Pattern;
904  } else {
905    return FullName.endswith(("::" + Pattern).str());
906  }
907}
908
909/// \brief Matches NamedDecl nodes whose full names partially match the
910/// given RegExp.
911///
912/// Supports specifying enclosing namespaces or classes by
913/// prefixing the name with '<enclosing>::'.  Does not match typedefs
914/// of an underlying type with the given name.
915///
916/// Example matches X (regexp == "::X")
917///   class X;
918///
919/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
920/// namespace foo { namespace bar { class X; } }
921AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
922  assert(!RegExp.empty());
923  std::string FullNameString = "::" + Node.getQualifiedNameAsString();
924  llvm::Regex RE(RegExp);
925  return RE.match(FullNameString);
926}
927
928/// \brief Matches overloaded operator names.
929///
930/// Matches overloaded operator names specified in strings without the
931/// "operator" prefix, such as "<<", for OverloadedOperatorCall's.
932///
933/// Example matches a << b
934///     (matcher == overloadedOperatorCall(hasOverloadedOperatorName("<<")))
935///   a << b;
936///   c && d;  // assuming both operator<<
937///            // and operator&& are overloaded somewhere.
938AST_MATCHER_P(CXXOperatorCallExpr,
939              hasOverloadedOperatorName, std::string, Name) {
940  return getOperatorSpelling(Node.getOperator()) == Name;
941}
942
943/// \brief Matches C++ classes that are directly or indirectly derived from
944/// a class matching \c Base.
945///
946/// Note that a class is considered to be also derived from itself.
947///
948/// Example matches X, Y, Z, C (Base == hasName("X"))
949///   class X;                // A class is considered to be derived from itself
950///   class Y : public X {};  // directly derived
951///   class Z : public Y {};  // indirectly derived
952///   typedef X A;
953///   typedef A B;
954///   class C : public B {};  // derived from a typedef of X
955///
956/// In the following example, Bar matches isDerivedFrom(hasName("X")):
957///   class Foo;
958///   typedef Foo X;
959///   class Bar : public Foo {};  // derived from a type that X is a typedef of
960AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
961              internal::Matcher<NamedDecl>, Base) {
962  return Finder->classIsDerivedFrom(&Node, Base, Builder);
963}
964
965/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
966inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
967  assert(!BaseName.empty());
968  return isDerivedFrom(hasName(BaseName));
969}
970
971/// \brief Matches AST nodes that have child AST nodes that match the
972/// provided matcher.
973///
974/// Example matches X, Y (matcher = record(has(record(hasName("X")))
975///   class X {};  // Matches X, because X::X is a class of name X inside X.
976///   class Y { class X {}; };
977///   class Z { class Y { class X {}; }; };  // Does not match Z.
978///
979/// ChildT must be an AST base type.
980template <typename ChildT>
981internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
982    const internal::Matcher<ChildT> &ChildMatcher) {
983  return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
984                                           ChildT>(ChildMatcher);
985}
986
987/// \brief Matches AST nodes that have descendant AST nodes that match the
988/// provided matcher.
989///
990/// Example matches X, Y, Z
991///     (matcher = record(hasDescendant(record(hasName("X")))))
992///   class X {};  // Matches X, because X::X is a class of name X inside X.
993///   class Y { class X {}; };
994///   class Z { class Y { class X {}; }; };
995///
996/// DescendantT must be an AST base type.
997template <typename DescendantT>
998internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
999hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1000  return internal::ArgumentAdaptingMatcher<
1001    internal::HasDescendantMatcher,
1002    DescendantT>(DescendantMatcher);
1003}
1004
1005
1006/// \brief Matches AST nodes that have child AST nodes that match the
1007/// provided matcher.
1008///
1009/// Example matches X, Y (matcher = record(forEach(record(hasName("X")))
1010///   class X {};  // Matches X, because X::X is a class of name X inside X.
1011///   class Y { class X {}; };
1012///   class Z { class Y { class X {}; }; };  // Does not match Z.
1013///
1014/// ChildT must be an AST base type.
1015///
1016/// As opposed to 'has', 'forEach' will cause a match for each result that
1017/// matches instead of only on the first one.
1018template <typename ChildT>
1019internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1020    const internal::Matcher<ChildT>& ChildMatcher) {
1021  return internal::ArgumentAdaptingMatcher<
1022    internal::ForEachMatcher,
1023    ChildT>(ChildMatcher);
1024}
1025
1026/// \brief Matches AST nodes that have descendant AST nodes that match the
1027/// provided matcher.
1028///
1029/// Example matches X, A, B, C
1030///     (matcher = record(forEachDescendant(record(hasName("X")))))
1031///   class X {};  // Matches X, because X::X is a class of name X inside X.
1032///   class A { class X {}; };
1033///   class B { class C { class X {}; }; };
1034///
1035/// DescendantT must be an AST base type.
1036///
1037/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1038/// each result that matches instead of only on the first one.
1039///
1040/// Note: Recursively combined ForEachDescendant can cause many matches:
1041///   record(forEachDescendant(record(forEachDescendant(record()))))
1042/// will match 10 times (plus injected class name matches) on:
1043///   class A { class B { class C { class D { class E {}; }; }; }; };
1044template <typename DescendantT>
1045internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT>
1046forEachDescendant(
1047    const internal::Matcher<DescendantT>& DescendantMatcher) {
1048  return internal::ArgumentAdaptingMatcher<
1049    internal::ForEachDescendantMatcher,
1050    DescendantT>(DescendantMatcher);
1051}
1052
1053/// \brief Matches if the provided matcher does not match.
1054///
1055/// Example matches Y (matcher = record(unless(hasName("X"))))
1056///   class X {};
1057///   class Y {};
1058template <typename M>
1059internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> unless(const M &InnerMatcher) {
1060  return internal::PolymorphicMatcherWithParam1<
1061    internal::NotMatcher, M>(InnerMatcher);
1062}
1063
1064/// \brief Matches a type if the declaration of the type matches the given
1065/// matcher.
1066///
1067/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>
1068inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1069                                     internal::Matcher<Decl> >
1070    hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1071  return internal::PolymorphicMatcherWithParam1<
1072    internal::HasDeclarationMatcher,
1073    internal::Matcher<Decl> >(InnerMatcher);
1074}
1075
1076/// \brief Matches on the implicit object argument of a member call expression.
1077///
1078/// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y"))))))
1079///   class Y { public: void x(); };
1080///   void z() { Y y; y.x(); }",
1081///
1082/// FIXME: Overload to allow directly matching types?
1083AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1084              InnerMatcher) {
1085  const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node)
1086      .getImplicitObjectArgument()
1087      ->IgnoreParenImpCasts();
1088  return (ExprNode != NULL &&
1089          InnerMatcher.matches(*ExprNode, Finder, Builder));
1090}
1091
1092/// \brief Matches if the call expression's callee expression matches.
1093///
1094/// Given
1095///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
1096///   void f() { f(); }
1097/// call(callee(expression()))
1098///   matches this->x(), x(), y.x(), f()
1099/// with callee(...)
1100///   matching this->x, x, y.x, f respectively
1101///
1102/// Note: Callee cannot take the more general internal::Matcher<Expr>
1103/// because this introduces ambiguous overloads with calls to Callee taking a
1104/// internal::Matcher<Decl>, as the matcher hierarchy is purely
1105/// implemented in terms of implicit casts.
1106AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1107              InnerMatcher) {
1108  const Expr *ExprNode = Node.getCallee();
1109  return (ExprNode != NULL &&
1110          InnerMatcher.matches(*ExprNode, Finder, Builder));
1111}
1112
1113/// \brief Matches if the call expression's callee's declaration matches the
1114/// given matcher.
1115///
1116/// Example matches y.x() (matcher = call(callee(method(hasName("x")))))
1117///   class Y { public: void x(); };
1118///   void z() { Y y; y.x();
1119inline internal::Matcher<CallExpr> callee(
1120    const internal::Matcher<Decl> &InnerMatcher) {
1121  return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher));
1122}
1123
1124/// \brief Matches if the expression's or declaration's type matches a type
1125/// matcher.
1126///
1127/// Example matches x (matcher = expression(hasType(
1128///                        hasDeclaration(record(hasName("X"))))))
1129///             and z (matcher = variable(hasType(
1130///                        hasDeclaration(record(hasName("X"))))))
1131///  class X {};
1132///  void y(X &x) { x; X z; }
1133AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1134                          InnerMatcher) {
1135  TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1136                          llvm::is_base_of<ValueDecl, NodeType>::value),
1137                         instantiated_with_wrong_types);
1138  return InnerMatcher.matches(Node.getType(), Finder, Builder);
1139}
1140
1141/// \brief Overloaded to match the declaration of the expression's or value
1142/// declaration's type.
1143///
1144/// In case of a value declaration (for example a variable declaration),
1145/// this resolves one layer of indirection. For example, in the value
1146/// declaration "X x;", record(hasName("X")) matches the declaration of X,
1147/// while variable(hasType(record(hasName("X")))) matches the declaration
1148/// of x."
1149///
1150/// Example matches x (matcher = expression(hasType(record(hasName("X")))))
1151///             and z (matcher = variable(hasType(record(hasName("X")))))
1152///  class X {};
1153///  void y(X &x) { x; X z; }
1154///
1155/// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1156inline internal::PolymorphicMatcherWithParam1<
1157  internal::matcher_hasTypeMatcher,
1158  internal::Matcher<QualType> >
1159hasType(const internal::Matcher<Decl> &InnerMatcher) {
1160  return hasType(internal::Matcher<QualType>(
1161    hasDeclaration(InnerMatcher)));
1162}
1163
1164/// \brief Matches if the matched type is represented by the given string.
1165///
1166/// Given
1167///   class Y { public: void x(); };
1168///   void z() { Y* y; y->x(); }
1169/// call(on(hasType(asString("class Y *"))))
1170///   matches y->x()
1171AST_MATCHER_P(QualType, asString, std::string, Name) {
1172  return Name == Node.getAsString();
1173}
1174
1175/// \brief Matches if the matched type is a pointer type and the pointee type
1176/// matches the specified matcher.
1177///
1178/// Example matches y->x()
1179///     (matcher = call(on(hasType(pointsTo(record(hasName("Y")))))))
1180///   class Y { public: void x(); };
1181///   void z() { Y *y; y->x(); }
1182AST_MATCHER_P(
1183    QualType, pointsTo, internal::Matcher<QualType>,
1184    InnerMatcher) {
1185  return (!Node.isNull() && Node->isPointerType() &&
1186          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1187}
1188
1189/// \brief Overloaded to match the pointee type's declaration.
1190inline internal::Matcher<QualType> pointsTo(
1191    const internal::Matcher<Decl> &InnerMatcher) {
1192  return pointsTo(internal::Matcher<QualType>(
1193    hasDeclaration(InnerMatcher)));
1194}
1195
1196/// \brief Matches if the matched type is a reference type and the referenced
1197/// type matches the specified matcher.
1198///
1199/// Example matches X &x and const X &y
1200///     (matcher = variable(hasType(references(record(hasName("X"))))))
1201///   class X {
1202///     void a(X b) {
1203///       X &x = b;
1204///       const X &y = b;
1205///   };
1206AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1207              InnerMatcher) {
1208  return (!Node.isNull() && Node->isReferenceType() &&
1209          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1210}
1211
1212/// \brief Overloaded to match the referenced type's declaration.
1213inline internal::Matcher<QualType> references(
1214    const internal::Matcher<Decl> &InnerMatcher) {
1215  return references(internal::Matcher<QualType>(
1216    hasDeclaration(InnerMatcher)));
1217}
1218
1219AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1220              internal::Matcher<Expr>, InnerMatcher) {
1221  const Expr *ExprNode =
1222      const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument();
1223  return (ExprNode != NULL &&
1224          InnerMatcher.matches(*ExprNode, Finder, Builder));
1225}
1226
1227/// \brief Matches if the expression's type either matches the specified
1228/// matcher, or is a pointer to a type that matches the InnerMatcher.
1229inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1230    const internal::Matcher<QualType> &InnerMatcher) {
1231  return onImplicitObjectArgument(
1232      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1233}
1234
1235/// \brief Overloaded to match the type's declaration.
1236inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1237    const internal::Matcher<Decl> &InnerMatcher) {
1238  return onImplicitObjectArgument(
1239      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1240}
1241
1242/// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1243/// specified matcher.
1244///
1245/// Example matches x in if(x)
1246///     (matcher = declarationReference(to(variable(hasName("x")))))
1247///   bool x;
1248///   if (x) {}
1249AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1250              InnerMatcher) {
1251  const Decl *DeclNode = Node.getDecl();
1252  return (DeclNode != NULL &&
1253          InnerMatcher.matches(*DeclNode, Finder, Builder));
1254}
1255
1256/// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1257/// specific using shadow declaration.
1258///
1259/// FIXME: This currently only works for functions. Fix.
1260///
1261/// Given
1262///   namespace a { void f() {} }
1263///   using a::f;
1264///   void g() {
1265///     f();     // Matches this ..
1266///     a::f();  // .. but not this.
1267///   }
1268/// declarationReference(throughUsingDeclaration(anything()))
1269///   matches \c f()
1270AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1271              internal::Matcher<UsingShadowDecl>, Matcher) {
1272  const NamedDecl *FoundDecl = Node.getFoundDecl();
1273  if (const UsingShadowDecl *UsingDecl =
1274      llvm::dyn_cast<UsingShadowDecl>(FoundDecl))
1275    return Matcher.matches(*UsingDecl, Finder, Builder);
1276  return false;
1277}
1278
1279/// \brief Matches the Decl of a DeclStmt which has a single declaration.
1280///
1281/// Given
1282///   int a, b;
1283///   int c;
1284/// declarationStatement(hasSingleDecl(anything()))
1285///   matches 'int c;' but not 'int a, b;'.
1286AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1287  if (Node.isSingleDecl()) {
1288    const Decl *FoundDecl = Node.getSingleDecl();
1289    return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1290  }
1291  return false;
1292}
1293
1294/// \brief Matches a variable declaration that has an initializer expression
1295/// that matches the given matcher.
1296///
1297/// Example matches x (matcher = variable(hasInitializer(call())))
1298///   bool y() { return true; }
1299///   bool x = y();
1300AST_MATCHER_P(
1301    VarDecl, hasInitializer, internal::Matcher<Expr>,
1302    InnerMatcher) {
1303  const Expr *Initializer = Node.getAnyInitializer();
1304  return (Initializer != NULL &&
1305          InnerMatcher.matches(*Initializer, Finder, Builder));
1306}
1307
1308/// \brief Checks that a call expression or a constructor call expression has
1309/// a specific number of arguments (including absent default arguments).
1310///
1311/// Example matches f(0, 0) (matcher = call(argumentCountIs(2)))
1312///   void f(int x, int y);
1313///   f(0, 0);
1314AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1315  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1316                          llvm::is_base_of<CXXConstructExpr,
1317                                           NodeType>::value),
1318                         instantiated_with_wrong_types);
1319  return Node.getNumArgs() == N;
1320}
1321
1322/// \brief Matches the n'th argument of a call expression or a constructor
1323/// call expression.
1324///
1325/// Example matches y in x(y)
1326///     (matcher = call(hasArgument(0, declarationReference())))
1327///   void x(int) { int y; x(y); }
1328AST_POLYMORPHIC_MATCHER_P2(
1329    hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1330  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1331                         llvm::is_base_of<CXXConstructExpr,
1332                                          NodeType>::value),
1333                         instantiated_with_wrong_types);
1334  return (N < Node.getNumArgs() &&
1335          InnerMatcher.matches(
1336              *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1337}
1338
1339/// \brief Matches declaration statements that contain a specific number of
1340/// declarations.
1341///
1342/// Example: Given
1343///   int a, b;
1344///   int c;
1345///   int d = 2, e;
1346/// declCountIs(2)
1347///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
1348AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
1349  return std::distance(Node.decl_begin(), Node.decl_end()) == N;
1350}
1351
1352/// \brief Matches the n'th declaration of a declaration statement.
1353///
1354/// Note that this does not work for global declarations because the AST
1355/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
1356/// DeclStmt's.
1357/// Example: Given non-global declarations
1358///   int a, b = 0;
1359///   int c;
1360///   int d = 2, e;
1361/// declarationStatement(containsDeclaration(
1362///       0, variable(hasInitializer(anything()))))
1363///   matches only 'int d = 2, e;', and
1364/// declarationStatement(containsDeclaration(1, variable()))
1365///   matches 'int a, b = 0' as well as 'int d = 2, e;'
1366///   but 'int c;' is not matched.
1367AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
1368               internal::Matcher<Decl>, InnerMatcher) {
1369  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
1370  if (N >= NumDecls)
1371    return false;
1372  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
1373  std::advance(Iterator, N);
1374  return InnerMatcher.matches(**Iterator, Finder, Builder);
1375}
1376
1377/// \brief Matches a constructor initializer.
1378///
1379/// Given
1380///   struct Foo {
1381///     Foo() : foo_(1) { }
1382///     int foo_;
1383///   };
1384/// record(has(constructor(hasAnyConstructorInitializer(anything()))))
1385///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
1386AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
1387              internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
1388  for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
1389       I != Node.init_end(); ++I) {
1390    if (InnerMatcher.matches(**I, Finder, Builder)) {
1391      return true;
1392    }
1393  }
1394  return false;
1395}
1396
1397/// \brief Matches the field declaration of a constructor initializer.
1398///
1399/// Given
1400///   struct Foo {
1401///     Foo() : foo_(1) { }
1402///     int foo_;
1403///   };
1404/// record(has(constructor(hasAnyConstructorInitializer(
1405///     forField(hasName("foo_"))))))
1406///   matches Foo
1407/// with forField matching foo_
1408AST_MATCHER_P(CXXCtorInitializer, forField,
1409              internal::Matcher<FieldDecl>, InnerMatcher) {
1410  const FieldDecl *NodeAsDecl = Node.getMember();
1411  return (NodeAsDecl != NULL &&
1412      InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
1413}
1414
1415/// \brief Matches the initializer expression of a constructor initializer.
1416///
1417/// Given
1418///   struct Foo {
1419///     Foo() : foo_(1) { }
1420///     int foo_;
1421///   };
1422/// record(has(constructor(hasAnyConstructorInitializer(
1423///     withInitializer(integerLiteral(equals(1)))))))
1424///   matches Foo
1425/// with withInitializer matching (1)
1426AST_MATCHER_P(CXXCtorInitializer, withInitializer,
1427              internal::Matcher<Expr>, InnerMatcher) {
1428  const Expr* NodeAsExpr = Node.getInit();
1429  return (NodeAsExpr != NULL &&
1430      InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
1431}
1432
1433/// \brief Matches a contructor initializer if it is explicitly written in
1434/// code (as opposed to implicitly added by the compiler).
1435///
1436/// Given
1437///   struct Foo {
1438///     Foo() { }
1439///     Foo(int) : foo_("A") { }
1440///     string foo_;
1441///   };
1442/// constructor(hasAnyConstructorInitializer(isWritten()))
1443///   will match Foo(int), but not Foo()
1444AST_MATCHER(CXXCtorInitializer, isWritten) {
1445  return Node.isWritten();
1446}
1447
1448/// \brief Matches a constructor declaration that has been implicitly added
1449/// by the compiler (eg. implicit default/copy constructors).
1450AST_MATCHER(CXXConstructorDecl, isImplicit) {
1451  return Node.isImplicit();
1452}
1453
1454/// \brief Matches any argument of a call expression or a constructor call
1455/// expression.
1456///
1457/// Given
1458///   void x(int, int, int) { int y; x(1, y, 42); }
1459/// call(hasAnyArgument(declarationReference()))
1460///   matches x(1, y, 42)
1461/// with hasAnyArgument(...)
1462///   matching y
1463AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
1464                          InnerMatcher) {
1465  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1466                         llvm::is_base_of<CXXConstructExpr,
1467                                          NodeType>::value),
1468                         instantiated_with_wrong_types);
1469  for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
1470    if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
1471                             Finder, Builder)) {
1472      return true;
1473    }
1474  }
1475  return false;
1476}
1477
1478/// \brief Matches the n'th parameter of a function declaration.
1479///
1480/// Given
1481///   class X { void f(int x) {} };
1482/// method(hasParameter(0, hasType(variable())))
1483///   matches f(int x) {}
1484/// with hasParameter(...)
1485///   matching int x
1486AST_MATCHER_P2(FunctionDecl, hasParameter,
1487               unsigned, N, internal::Matcher<ParmVarDecl>,
1488               InnerMatcher) {
1489  return (N < Node.getNumParams() &&
1490          InnerMatcher.matches(
1491              *Node.getParamDecl(N), Finder, Builder));
1492}
1493
1494/// \brief Matches any parameter of a function declaration.
1495///
1496/// Does not match the 'this' parameter of a method.
1497///
1498/// Given
1499///   class X { void f(int x, int y, int z) {} };
1500/// method(hasAnyParameter(hasName("y")))
1501///   matches f(int x, int y, int z) {}
1502/// with hasAnyParameter(...)
1503///   matching int y
1504AST_MATCHER_P(FunctionDecl, hasAnyParameter,
1505              internal::Matcher<ParmVarDecl>, InnerMatcher) {
1506  for (unsigned I = 0; I < Node.getNumParams(); ++I) {
1507    if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
1508      return true;
1509    }
1510  }
1511  return false;
1512}
1513
1514/// \brief Matches the return type of a function declaration.
1515///
1516/// Given:
1517///   class X { int f() { return 1; } };
1518/// method(returns(asString("int")))
1519///   matches int f() { return 1; }
1520AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, Matcher) {
1521  return Matcher.matches(Node.getResultType(), Finder, Builder);
1522}
1523
1524/// \brief Matches extern "C" function declarations.
1525///
1526/// Given:
1527///   extern "C" void f() {}
1528///   extern "C" { void g() {} }
1529///   void h() {}
1530/// function(isExternC())
1531///   matches the declaration of f and g, but not the declaration h
1532AST_MATCHER(FunctionDecl, isExternC) {
1533  return Node.isExternC();
1534}
1535
1536/// \brief Matches the condition expression of an if statement, for loop,
1537/// or conditional operator.
1538///
1539/// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
1540///   if (true) {}
1541AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
1542                          InnerMatcher) {
1543  TOOLING_COMPILE_ASSERT(
1544    (llvm::is_base_of<IfStmt, NodeType>::value) ||
1545    (llvm::is_base_of<ForStmt, NodeType>::value) ||
1546    (llvm::is_base_of<WhileStmt, NodeType>::value) ||
1547    (llvm::is_base_of<DoStmt, NodeType>::value) ||
1548    (llvm::is_base_of<ConditionalOperator, NodeType>::value),
1549    has_condition_requires_if_statement_conditional_operator_or_loop);
1550  const Expr *const Condition = Node.getCond();
1551  return (Condition != NULL &&
1552          InnerMatcher.matches(*Condition, Finder, Builder));
1553}
1554
1555/// \brief Matches the condition variable statement in an if statement.
1556///
1557/// Given
1558///   if (A* a = GetAPointer()) {}
1559/// hasConditionVariableStatment(...)
1560///   matches 'A* a = GetAPointer()'.
1561AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
1562              internal::Matcher<DeclStmt>, InnerMatcher) {
1563  const DeclStmt* const DeclarationStatement =
1564    Node.getConditionVariableDeclStmt();
1565  return DeclarationStatement != NULL &&
1566         InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
1567}
1568
1569/// \brief Matches the index expression of an array subscript expression.
1570///
1571/// Given
1572///   int i[5];
1573///   void f() { i[1] = 42; }
1574/// arraySubscriptExpression(hasIndex(integerLiteral()))
1575///   matches \c i[1] with the \c integerLiteral() matching \c 1
1576AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
1577              internal::Matcher<Expr>, matcher) {
1578  if (const Expr* Expression = Node.getIdx())
1579    return matcher.matches(*Expression, Finder, Builder);
1580  return false;
1581}
1582
1583/// \brief Matches the base expression of an array subscript expression.
1584///
1585/// Given
1586///   int i[5];
1587///   void f() { i[1] = 42; }
1588/// arraySubscriptExpression(hasBase(implicitCast(
1589///     hasSourceExpression(declarationReference()))))
1590///   matches \c i[1] with the \c declarationReference() matching \c i
1591AST_MATCHER_P(ArraySubscriptExpr, hasBase,
1592              internal::Matcher<Expr>, matcher) {
1593  if (const Expr* Expression = Node.getBase())
1594    return matcher.matches(*Expression, Finder, Builder);
1595  return false;
1596}
1597
1598/// \brief Matches a 'for', 'while', or 'do while' statement that has
1599/// a given body.
1600///
1601/// Given
1602///   for (;;) {}
1603/// hasBody(compoundStatement())
1604///   matches 'for (;;) {}'
1605/// with compoundStatement()
1606///   matching '{}'
1607AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
1608                          InnerMatcher) {
1609  TOOLING_COMPILE_ASSERT(
1610      (llvm::is_base_of<DoStmt, NodeType>::value) ||
1611      (llvm::is_base_of<ForStmt, NodeType>::value) ||
1612      (llvm::is_base_of<WhileStmt, NodeType>::value),
1613      has_body_requires_for_while_or_do_statement);
1614  const Stmt *const Statement = Node.getBody();
1615  return (Statement != NULL &&
1616          InnerMatcher.matches(*Statement, Finder, Builder));
1617}
1618
1619/// \brief Matches compound statements where at least one substatement matches
1620/// a given matcher.
1621///
1622/// Given
1623///   { {}; 1+2; }
1624/// hasAnySubstatement(compoundStatement())
1625///   matches '{ {}; 1+2; }'
1626/// with compoundStatement()
1627///   matching '{}'
1628AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
1629              internal::Matcher<Stmt>, InnerMatcher) {
1630  for (CompoundStmt::const_body_iterator It = Node.body_begin();
1631       It != Node.body_end();
1632       ++It) {
1633    if (InnerMatcher.matches(**It, Finder, Builder)) return true;
1634  }
1635  return false;
1636}
1637
1638/// \brief Checks that a compound statement contains a specific number of
1639/// child statements.
1640///
1641/// Example: Given
1642///   { for (;;) {} }
1643/// compoundStatement(statementCountIs(0)))
1644///   matches '{}'
1645///   but does not match the outer compound statement.
1646AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
1647  return Node.size() == N;
1648}
1649
1650/// \brief Matches literals that are equal to the given value.
1651///
1652/// Example matches true (matcher = boolLiteral(equals(true)))
1653///   true
1654///
1655/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
1656///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
1657template <typename ValueT>
1658internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
1659equals(const ValueT &Value) {
1660  return internal::PolymorphicMatcherWithParam1<
1661    internal::ValueEqualsMatcher,
1662    ValueT>(Value);
1663}
1664
1665/// \brief Matches the operator Name of operator expressions (binary or
1666/// unary).
1667///
1668/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
1669///   !(a || b)
1670AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
1671  TOOLING_COMPILE_ASSERT(
1672    (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
1673    (llvm::is_base_of<UnaryOperator, NodeType>::value),
1674    has_condition_requires_if_statement_or_conditional_operator);
1675  return Name == Node.getOpcodeStr(Node.getOpcode());
1676}
1677
1678/// \brief Matches the left hand side of binary operator expressions.
1679///
1680/// Example matches a (matcher = binaryOperator(hasLHS()))
1681///   a || b
1682AST_MATCHER_P(BinaryOperator, hasLHS,
1683              internal::Matcher<Expr>, InnerMatcher) {
1684  Expr *LeftHandSide = Node.getLHS();
1685  return (LeftHandSide != NULL &&
1686          InnerMatcher.matches(*LeftHandSide, Finder, Builder));
1687}
1688
1689/// \brief Matches the right hand side of binary operator expressions.
1690///
1691/// Example matches b (matcher = binaryOperator(hasRHS()))
1692///   a || b
1693AST_MATCHER_P(BinaryOperator, hasRHS,
1694              internal::Matcher<Expr>, InnerMatcher) {
1695  Expr *RightHandSide = Node.getRHS();
1696  return (RightHandSide != NULL &&
1697          InnerMatcher.matches(*RightHandSide, Finder, Builder));
1698}
1699
1700/// \brief Matches if either the left hand side or the right hand side of a
1701/// binary operator matches.
1702inline internal::Matcher<BinaryOperator> hasEitherOperand(
1703    const internal::Matcher<Expr> &InnerMatcher) {
1704  return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
1705}
1706
1707/// \brief Matches if the operand of a unary operator matches.
1708///
1709/// Example matches true (matcher = hasOperand(boolLiteral(equals(true))))
1710///   !true
1711AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
1712              internal::Matcher<Expr>, InnerMatcher) {
1713  const Expr * const Operand = Node.getSubExpr();
1714  return (Operand != NULL &&
1715          InnerMatcher.matches(*Operand, Finder, Builder));
1716}
1717
1718/// \brief Matches if the cast's source expression matches the given matcher.
1719///
1720/// Example: matches "a string" (matcher =
1721///                                  hasSourceExpression(constructorCall()))
1722///
1723/// class URL { URL(string); };
1724/// URL url = "a string";
1725AST_MATCHER_P(CastExpr, hasSourceExpression,
1726              internal::Matcher<Expr>, InnerMatcher) {
1727  const Expr* const SubExpression = Node.getSubExpr();
1728  return (SubExpression != NULL &&
1729          InnerMatcher.matches(*SubExpression, Finder, Builder));
1730}
1731
1732/// \brief Matches casts whose destination type matches a given matcher.
1733///
1734/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
1735/// actual casts "explicit" casts.)
1736AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
1737              internal::Matcher<QualType>, InnerMatcher) {
1738  const QualType NodeType = Node.getTypeAsWritten();
1739  return InnerMatcher.matches(NodeType, Finder, Builder);
1740}
1741
1742/// \brief Matches implicit casts whose destination type matches a given
1743/// matcher.
1744///
1745/// FIXME: Unit test this matcher
1746AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
1747              internal::Matcher<QualType>, InnerMatcher) {
1748  return InnerMatcher.matches(Node.getType(), Finder, Builder);
1749}
1750
1751/// \brief Matches the true branch expression of a conditional operator.
1752///
1753/// Example matches a
1754///   condition ? a : b
1755AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
1756              internal::Matcher<Expr>, InnerMatcher) {
1757  Expr *Expression = Node.getTrueExpr();
1758  return (Expression != NULL &&
1759          InnerMatcher.matches(*Expression, Finder, Builder));
1760}
1761
1762/// \brief Matches the false branch expression of a conditional operator.
1763///
1764/// Example matches b
1765///   condition ? a : b
1766AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
1767              internal::Matcher<Expr>, InnerMatcher) {
1768  Expr *Expression = Node.getFalseExpr();
1769  return (Expression != NULL &&
1770          InnerMatcher.matches(*Expression, Finder, Builder));
1771}
1772
1773/// \brief Matches if a declaration has a body attached.
1774///
1775/// Example matches A, va, fa
1776///   class A {};
1777///   class B;  // Doesn't match, as it has no body.
1778///   int va;
1779///   extern int vb;  // Doesn't match, as it doesn't define the variable.
1780///   void fa() {}
1781///   void fb();  // Doesn't match, as it has no body.
1782///
1783/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
1784inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher>
1785isDefinition() {
1786  return internal::PolymorphicMatcherWithParam0<
1787    internal::IsDefinitionMatcher>();
1788}
1789
1790/// \brief Matches the class declaration that the given method declaration
1791/// belongs to.
1792///
1793/// FIXME: Generalize this for other kinds of declarations.
1794/// FIXME: What other kind of declarations would we need to generalize
1795/// this to?
1796///
1797/// Example matches A() in the last line
1798///     (matcher = constructorCall(hasDeclaration(method(
1799///         ofClass(hasName("A"))))))
1800///   class A {
1801///    public:
1802///     A();
1803///   };
1804///   A a = A();
1805AST_MATCHER_P(CXXMethodDecl, ofClass,
1806              internal::Matcher<CXXRecordDecl>, InnerMatcher) {
1807  const CXXRecordDecl *Parent = Node.getParent();
1808  return (Parent != NULL &&
1809          InnerMatcher.matches(*Parent, Finder, Builder));
1810}
1811
1812/// \brief Matches member expressions that are called with '->' as opposed
1813/// to '.'.
1814///
1815/// Member calls on the implicit this pointer match as called with '->'.
1816///
1817/// Given
1818///   class Y {
1819///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1820///     int a;
1821///     static int b;
1822///   };
1823/// memberExpression(isArrow())
1824///   matches this->x, x, y.x, a, this->b
1825inline internal::Matcher<MemberExpr> isArrow() {
1826  return makeMatcher(new internal::IsArrowMatcher());
1827}
1828
1829/// \brief Matches QualType nodes that are of integer type.
1830///
1831/// Given
1832///   void a(int);
1833///   void b(long);
1834///   void c(double);
1835/// function(hasAnyParameter(hasType(isInteger())))
1836/// matches "a(int)", "b(long)", but not "c(double)".
1837AST_MATCHER(QualType, isInteger) {
1838    return Node->isIntegerType();
1839}
1840
1841/// \brief Matches QualType nodes that are const-qualified, i.e., that
1842/// include "top-level" const.
1843///
1844/// Given
1845///   void a(int);
1846///   void b(int const);
1847///   void c(const int);
1848///   void d(const int*);
1849///   void e(int const) {};
1850/// function(hasAnyParameter(hasType(isConstQualified())))
1851///   matches "void b(int const)", "void c(const int)" and
1852///   "void e(int const) {}". It does not match d as there
1853///   is no top-level const on the parameter type "const int *".
1854inline internal::Matcher<QualType> isConstQualified() {
1855  return makeMatcher(new internal::IsConstQualifiedMatcher());
1856}
1857
1858/// \brief Matches a member expression where the member is matched by a
1859/// given matcher.
1860///
1861/// Given
1862///   struct { int first, second; } first, second;
1863///   int i(second.first);
1864///   int j(first.second);
1865/// memberExpression(member(hasName("first")))
1866///   matches second.first
1867///   but not first.second (because the member name there is "second").
1868AST_MATCHER_P(MemberExpr, member,
1869              internal::Matcher<ValueDecl>, InnerMatcher) {
1870  return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
1871}
1872
1873/// \brief Matches a member expression where the object expression is
1874/// matched by a given matcher.
1875///
1876/// Given
1877///   struct X { int m; };
1878///   void f(X x) { x.m; m; }
1879/// memberExpression(hasObjectExpression(hasType(record(hasName("X")))))))
1880///   matches "x.m" and "m"
1881/// with hasObjectExpression(...)
1882///   matching "x" and the implicit object expression of "m" which has type X*.
1883AST_MATCHER_P(MemberExpr, hasObjectExpression,
1884              internal::Matcher<Expr>, InnerMatcher) {
1885  return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
1886}
1887
1888/// \brief Matches any using shadow declaration.
1889///
1890/// Given
1891///   namespace X { void b(); }
1892///   using X::b;
1893/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
1894///   matches \code using X::b \endcode
1895AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
1896              internal::Matcher<UsingShadowDecl>, Matcher) {
1897  for (UsingDecl::shadow_iterator II = Node.shadow_begin();
1898       II != Node.shadow_end(); ++II) {
1899    if (Matcher.matches(**II, Finder, Builder))
1900      return true;
1901  }
1902  return false;
1903}
1904
1905/// \brief Matches a using shadow declaration where the target declaration is
1906/// matched by the given matcher.
1907///
1908/// Given
1909///   namespace X { int a; void b(); }
1910///   using X::a;
1911///   using X::b;
1912/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(function())))
1913///   matches \code using X::b \endcode
1914///   but not \code using X::a \endcode
1915AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
1916              internal::Matcher<NamedDecl>, Matcher) {
1917  return Matcher.matches(*Node.getTargetDecl(), Finder, Builder);
1918}
1919
1920/// \brief Matches template instantiations of function, class, or static
1921/// member variable template instantiations.
1922///
1923/// Given
1924///   template <typename T> class X {}; class A {}; X<A> x;
1925/// or
1926///   template <typename T> class X {}; class A {}; template class X<A>;
1927/// record(hasName("::X"), isTemplateInstantiation())
1928///   matches the template instantiation of X<A>.
1929///
1930/// But given
1931///   template <typename T> class X {}; class A {};
1932///   template <> class X<A> {}; X<A> x;
1933/// record(hasName("::X"), isTemplateInstantiation())
1934///   does not match, as X<A> is an explicit template specialization.
1935///
1936/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
1937inline internal::PolymorphicMatcherWithParam0<
1938  internal::IsTemplateInstantiationMatcher>
1939isTemplateInstantiation() {
1940  return internal::PolymorphicMatcherWithParam0<
1941    internal::IsTemplateInstantiationMatcher>();
1942}
1943
1944} // end namespace ast_matchers
1945} // end namespace clang
1946
1947#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
1948