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