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