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