ASTMatchers.h revision 1a68afd5bbecd05a3bb22854954aa4e5448c4470
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>
1455hasOverloadedOperatorName(const StringRef Name) {
1456  return internal::PolymorphicMatcherWithParam1<
1457      internal::HasOverloadedOperatorNameMatcher, StringRef>(Name);
1458}
1459
1460/// \brief Matches C++ classes that are directly or indirectly derived from
1461/// a class matching \c Base.
1462///
1463/// Note that a class is not considered to be derived from itself.
1464///
1465/// Example matches Y, Z, C (Base == hasName("X"))
1466/// \code
1467///   class X;
1468///   class Y : public X {};  // directly derived
1469///   class Z : public Y {};  // indirectly derived
1470///   typedef X A;
1471///   typedef A B;
1472///   class C : public B {};  // derived from a typedef of X
1473/// \endcode
1474///
1475/// In the following example, Bar matches isDerivedFrom(hasName("X")):
1476/// \code
1477///   class Foo;
1478///   typedef Foo X;
1479///   class Bar : public Foo {};  // derived from a type that X is a typedef of
1480/// \endcode
1481AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1482              internal::Matcher<NamedDecl>, Base) {
1483  return Finder->classIsDerivedFrom(&Node, Base, Builder);
1484}
1485
1486/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1487inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
1488  assert(!BaseName.empty());
1489  return isDerivedFrom(hasName(BaseName));
1490}
1491
1492/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1493/// match \c Base.
1494inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1495    internal::Matcher<NamedDecl> Base) {
1496  return anyOf(Base, isDerivedFrom(Base));
1497}
1498
1499/// \brief Overloaded method as shortcut for
1500/// \c isSameOrDerivedFrom(hasName(...)).
1501inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1502    StringRef BaseName) {
1503  assert(!BaseName.empty());
1504  return isSameOrDerivedFrom(hasName(BaseName));
1505}
1506
1507/// \brief Matches the first method of a class or struct that satisfies \c
1508/// InnerMatcher.
1509///
1510/// Given:
1511/// \code
1512///   class A { void func(); };
1513///   class B { void member(); };
1514/// \code
1515///
1516/// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A
1517/// but not \c B.
1518AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1519              InnerMatcher) {
1520  return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
1521                                    Node.method_end(), Finder, Builder);
1522}
1523
1524/// \brief Matches AST nodes that have child AST nodes that match the
1525/// provided matcher.
1526///
1527/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1528/// \code
1529///   class X {};  // Matches X, because X::X is a class of name X inside X.
1530///   class Y { class X {}; };
1531///   class Z { class Y { class X {}; }; };  // Does not match Z.
1532/// \endcode
1533///
1534/// ChildT must be an AST base type.
1535///
1536/// Usable as: Any Matcher
1537template <typename ChildT>
1538internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
1539    const internal::Matcher<ChildT> &ChildMatcher) {
1540  return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
1541                                           ChildT>(ChildMatcher);
1542}
1543
1544/// \brief Matches AST nodes that have descendant AST nodes that match the
1545/// provided matcher.
1546///
1547/// Example matches X, Y, Z
1548///     (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1549/// \code
1550///   class X {};  // Matches X, because X::X is a class of name X inside X.
1551///   class Y { class X {}; };
1552///   class Z { class Y { class X {}; }; };
1553/// \endcode
1554///
1555/// DescendantT must be an AST base type.
1556///
1557/// Usable as: Any Matcher
1558template <typename DescendantT>
1559internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
1560hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1561  return internal::ArgumentAdaptingMatcher<
1562    internal::HasDescendantMatcher,
1563    DescendantT>(DescendantMatcher);
1564}
1565
1566/// \brief Matches AST nodes that have child AST nodes that match the
1567/// provided matcher.
1568///
1569/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1570/// \code
1571///   class X {};  // Matches X, because X::X is a class of name X inside X.
1572///   class Y { class X {}; };
1573///   class Z { class Y { class X {}; }; };  // Does not match Z.
1574/// \endcode
1575///
1576/// ChildT must be an AST base type.
1577///
1578/// As opposed to 'has', 'forEach' will cause a match for each result that
1579/// matches instead of only on the first one.
1580///
1581/// Usable as: Any Matcher
1582template <typename ChildT>
1583internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1584    const internal::Matcher<ChildT> &ChildMatcher) {
1585  return internal::ArgumentAdaptingMatcher<
1586    internal::ForEachMatcher,
1587    ChildT>(ChildMatcher);
1588}
1589
1590/// \brief Matches AST nodes that have descendant AST nodes that match the
1591/// provided matcher.
1592///
1593/// Example matches X, A, B, C
1594///     (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1595/// \code
1596///   class X {};  // Matches X, because X::X is a class of name X inside X.
1597///   class A { class X {}; };
1598///   class B { class C { class X {}; }; };
1599/// \endcode
1600///
1601/// DescendantT must be an AST base type.
1602///
1603/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1604/// each result that matches instead of only on the first one.
1605///
1606/// Note: Recursively combined ForEachDescendant can cause many matches:
1607///   recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1608/// will match 10 times (plus injected class name matches) on:
1609/// \code
1610///   class A { class B { class C { class D { class E {}; }; }; }; };
1611/// \endcode
1612///
1613/// Usable as: Any Matcher
1614template <typename DescendantT>
1615internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher,
1616                                  DescendantT>
1617forEachDescendant(
1618    const internal::Matcher<DescendantT> &DescendantMatcher) {
1619  return internal::ArgumentAdaptingMatcher<
1620    internal::ForEachDescendantMatcher,
1621    DescendantT>(DescendantMatcher);
1622}
1623
1624/// \brief Matches if the node or any descendant matches.
1625///
1626/// Generates results for each match.
1627///
1628/// For example, in:
1629/// \code
1630///   class A { class B {}; class C {}; };
1631/// \endcode
1632/// The matcher:
1633/// \code
1634///   recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1635/// \endcode
1636/// will generate results for \c A, \c B and \c C.
1637///
1638/// Usable as: Any Matcher
1639template <typename T>
1640internal::PolymorphicMatcherWithParam2<
1641    internal::EachOfMatcher, internal::Matcher<T>,
1642    internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> >
1643findAll(const internal::Matcher<T> &Matcher) {
1644  return eachOf(Matcher, forEachDescendant(Matcher));
1645}
1646
1647/// \brief Matches AST nodes that have a parent that matches the provided
1648/// matcher.
1649///
1650/// Given
1651/// \code
1652/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1653/// \endcode
1654/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1655///
1656/// Usable as: Any Matcher
1657template <typename ParentT>
1658internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT>
1659hasParent(const internal::Matcher<ParentT> &ParentMatcher) {
1660  return internal::ArgumentAdaptingMatcher<
1661    internal::HasParentMatcher,
1662    ParentT>(ParentMatcher);
1663}
1664
1665/// \brief Matches AST nodes that have an ancestor that matches the provided
1666/// matcher.
1667///
1668/// Given
1669/// \code
1670/// void f() { if (true) { int x = 42; } }
1671/// void g() { for (;;) { int x = 43; } }
1672/// \endcode
1673/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1674///
1675/// Usable as: Any Matcher
1676template <typename AncestorT>
1677internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT>
1678hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) {
1679  return internal::ArgumentAdaptingMatcher<
1680    internal::HasAncestorMatcher,
1681    AncestorT>(AncestorMatcher);
1682}
1683
1684/// \brief Matches if the provided matcher does not match.
1685///
1686/// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1687/// \code
1688///   class X {};
1689///   class Y {};
1690/// \endcode
1691///
1692/// Usable as: Any Matcher
1693template <typename M>
1694internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M>
1695unless(const M &InnerMatcher) {
1696  return internal::PolymorphicMatcherWithParam1<
1697    internal::NotMatcher, M>(InnerMatcher);
1698}
1699
1700/// \brief Matches a node if the declaration associated with that node
1701/// matches the given matcher.
1702///
1703/// The associated declaration is:
1704/// - for type nodes, the declaration of the underlying type
1705/// - for CallExpr, the declaration of the callee
1706/// - for MemberExpr, the declaration of the referenced member
1707/// - for CXXConstructExpr, the declaration of the constructor
1708///
1709/// Also usable as Matcher<T> for any T supporting the getDecl() member
1710/// function. e.g. various subtypes of clang::Type and various expressions.
1711/// FIXME: Add all node types for which this is matcher is usable due to
1712/// getDecl().
1713///
1714/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1715///   Matcher<MemberExpr>, Matcher<TypedefType>,
1716///   Matcher<TemplateSpecializationType>
1717inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1718                                     internal::Matcher<Decl> >
1719    hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1720  return internal::PolymorphicMatcherWithParam1<
1721    internal::HasDeclarationMatcher,
1722    internal::Matcher<Decl> >(InnerMatcher);
1723}
1724
1725/// \brief Matches on the implicit object argument of a member call expression.
1726///
1727/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1728/// \code
1729///   class Y { public: void x(); };
1730///   void z() { Y y; y.x(); }",
1731/// \endcode
1732///
1733/// FIXME: Overload to allow directly matching types?
1734AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1735              InnerMatcher) {
1736  const Expr *ExprNode = Node.getImplicitObjectArgument()
1737                            ->IgnoreParenImpCasts();
1738  return (ExprNode != NULL &&
1739          InnerMatcher.matches(*ExprNode, Finder, Builder));
1740}
1741
1742/// \brief Matches if the call expression's callee expression matches.
1743///
1744/// Given
1745/// \code
1746///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
1747///   void f() { f(); }
1748/// \endcode
1749/// callExpr(callee(expr()))
1750///   matches this->x(), x(), y.x(), f()
1751/// with callee(...)
1752///   matching this->x, x, y.x, f respectively
1753///
1754/// Note: Callee cannot take the more general internal::Matcher<Expr>
1755/// because this introduces ambiguous overloads with calls to Callee taking a
1756/// internal::Matcher<Decl>, as the matcher hierarchy is purely
1757/// implemented in terms of implicit casts.
1758AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1759              InnerMatcher) {
1760  const Expr *ExprNode = Node.getCallee();
1761  return (ExprNode != NULL &&
1762          InnerMatcher.matches(*ExprNode, Finder, Builder));
1763}
1764
1765/// \brief Matches if the call expression's callee's declaration matches the
1766/// given matcher.
1767///
1768/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1769/// \code
1770///   class Y { public: void x(); };
1771///   void z() { Y y; y.x();
1772/// \endcode
1773inline internal::Matcher<CallExpr> callee(
1774    const internal::Matcher<Decl> &InnerMatcher) {
1775  return callExpr(hasDeclaration(InnerMatcher));
1776}
1777
1778/// \brief Matches if the expression's or declaration's type matches a type
1779/// matcher.
1780///
1781/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1782///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1783/// \code
1784///  class X {};
1785///  void y(X &x) { x; X z; }
1786/// \endcode
1787AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1788                          InnerMatcher) {
1789  TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1790                          llvm::is_base_of<ValueDecl, NodeType>::value),
1791                         instantiated_with_wrong_types);
1792  return InnerMatcher.matches(Node.getType(), Finder, Builder);
1793}
1794
1795/// \brief Overloaded to match the declaration of the expression's or value
1796/// declaration's type.
1797///
1798/// In case of a value declaration (for example a variable declaration),
1799/// this resolves one layer of indirection. For example, in the value
1800/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1801/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1802/// of x."
1803///
1804/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1805///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1806/// \code
1807///  class X {};
1808///  void y(X &x) { x; X z; }
1809/// \endcode
1810///
1811/// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1812inline internal::PolymorphicMatcherWithParam1<
1813  internal::matcher_hasType0Matcher,
1814  internal::Matcher<QualType> >
1815hasType(const internal::Matcher<Decl> &InnerMatcher) {
1816  return hasType(qualType(hasDeclaration(InnerMatcher)));
1817}
1818
1819/// \brief Matches if the type location of the declarator decl's type matches
1820/// the inner matcher.
1821///
1822/// Given
1823/// \code
1824///   int x;
1825/// \endcode
1826/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
1827///   matches int x
1828AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
1829  if (!Node.getTypeSourceInfo())
1830    // This happens for example for implicit destructors.
1831    return false;
1832  return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
1833}
1834
1835/// \brief Matches if the matched type is represented by the given string.
1836///
1837/// Given
1838/// \code
1839///   class Y { public: void x(); };
1840///   void z() { Y* y; y->x(); }
1841/// \endcode
1842/// callExpr(on(hasType(asString("class Y *"))))
1843///   matches y->x()
1844AST_MATCHER_P(QualType, asString, std::string, Name) {
1845  return Name == Node.getAsString();
1846}
1847
1848/// \brief Matches if the matched type is a pointer type and the pointee type
1849/// matches the specified matcher.
1850///
1851/// Example matches y->x()
1852///     (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1853/// \code
1854///   class Y { public: void x(); };
1855///   void z() { Y *y; y->x(); }
1856/// \endcode
1857AST_MATCHER_P(
1858    QualType, pointsTo, internal::Matcher<QualType>,
1859    InnerMatcher) {
1860  return (!Node.isNull() && Node->isPointerType() &&
1861          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1862}
1863
1864/// \brief Overloaded to match the pointee type's declaration.
1865inline internal::Matcher<QualType> pointsTo(
1866    const internal::Matcher<Decl> &InnerMatcher) {
1867  return pointsTo(qualType(hasDeclaration(InnerMatcher)));
1868}
1869
1870/// \brief Matches if the matched type is a reference type and the referenced
1871/// type matches the specified matcher.
1872///
1873/// Example matches X &x and const X &y
1874///     (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1875/// \code
1876///   class X {
1877///     void a(X b) {
1878///       X &x = b;
1879///       const X &y = b;
1880///   };
1881/// \endcode
1882AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1883              InnerMatcher) {
1884  return (!Node.isNull() && Node->isReferenceType() &&
1885          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1886}
1887
1888/// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1889///
1890/// Given:
1891/// \code
1892///   typedef int &int_ref;
1893///   int a;
1894///   int_ref b = a;
1895/// \code
1896///
1897/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1898/// declaration of b but \c
1899/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1900AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1901              InnerMatcher) {
1902  if (Node.isNull())
1903    return false;
1904  return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1905}
1906
1907/// \brief Overloaded to match the referenced type's declaration.
1908inline internal::Matcher<QualType> references(
1909    const internal::Matcher<Decl> &InnerMatcher) {
1910  return references(qualType(hasDeclaration(InnerMatcher)));
1911}
1912
1913AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1914              internal::Matcher<Expr>, InnerMatcher) {
1915  const Expr *ExprNode = Node.getImplicitObjectArgument();
1916  return (ExprNode != NULL &&
1917          InnerMatcher.matches(*ExprNode, Finder, Builder));
1918}
1919
1920/// \brief Matches if the expression's type either matches the specified
1921/// matcher, or is a pointer to a type that matches the InnerMatcher.
1922inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1923    const internal::Matcher<QualType> &InnerMatcher) {
1924  return onImplicitObjectArgument(
1925      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1926}
1927
1928/// \brief Overloaded to match the type's declaration.
1929inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1930    const internal::Matcher<Decl> &InnerMatcher) {
1931  return onImplicitObjectArgument(
1932      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1933}
1934
1935/// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1936/// specified matcher.
1937///
1938/// Example matches x in if(x)
1939///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
1940/// \code
1941///   bool x;
1942///   if (x) {}
1943/// \endcode
1944AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1945              InnerMatcher) {
1946  const Decl *DeclNode = Node.getDecl();
1947  return (DeclNode != NULL &&
1948          InnerMatcher.matches(*DeclNode, Finder, Builder));
1949}
1950
1951/// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1952/// specific using shadow declaration.
1953///
1954/// FIXME: This currently only works for functions. Fix.
1955///
1956/// Given
1957/// \code
1958///   namespace a { void f() {} }
1959///   using a::f;
1960///   void g() {
1961///     f();     // Matches this ..
1962///     a::f();  // .. but not this.
1963///   }
1964/// \endcode
1965/// declRefExpr(throughUsingDeclaration(anything()))
1966///   matches \c f()
1967AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1968              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
1969  const NamedDecl *FoundDecl = Node.getFoundDecl();
1970  if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
1971    return InnerMatcher.matches(*UsingDecl, Finder, Builder);
1972  return false;
1973}
1974
1975/// \brief Matches the Decl of a DeclStmt which has a single declaration.
1976///
1977/// Given
1978/// \code
1979///   int a, b;
1980///   int c;
1981/// \endcode
1982/// declStmt(hasSingleDecl(anything()))
1983///   matches 'int c;' but not 'int a, b;'.
1984AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1985  if (Node.isSingleDecl()) {
1986    const Decl *FoundDecl = Node.getSingleDecl();
1987    return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1988  }
1989  return false;
1990}
1991
1992/// \brief Matches a variable declaration that has an initializer expression
1993/// that matches the given matcher.
1994///
1995/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
1996/// \code
1997///   bool y() { return true; }
1998///   bool x = y();
1999/// \endcode
2000AST_MATCHER_P(
2001    VarDecl, hasInitializer, internal::Matcher<Expr>,
2002    InnerMatcher) {
2003  const Expr *Initializer = Node.getAnyInitializer();
2004  return (Initializer != NULL &&
2005          InnerMatcher.matches(*Initializer, Finder, Builder));
2006}
2007
2008/// \brief Checks that a call expression or a constructor call expression has
2009/// a specific number of arguments (including absent default arguments).
2010///
2011/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2012/// \code
2013///   void f(int x, int y);
2014///   f(0, 0);
2015/// \endcode
2016AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
2017  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
2018                          llvm::is_base_of<CXXConstructExpr,
2019                                           NodeType>::value),
2020                         instantiated_with_wrong_types);
2021  return Node.getNumArgs() == N;
2022}
2023
2024/// \brief Matches the n'th argument of a call expression or a constructor
2025/// call expression.
2026///
2027/// Example matches y in x(y)
2028///     (matcher = callExpr(hasArgument(0, declRefExpr())))
2029/// \code
2030///   void x(int) { int y; x(y); }
2031/// \endcode
2032AST_POLYMORPHIC_MATCHER_P2(
2033    hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2034  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
2035                         llvm::is_base_of<CXXConstructExpr,
2036                                          NodeType>::value),
2037                         instantiated_with_wrong_types);
2038  return (N < Node.getNumArgs() &&
2039          InnerMatcher.matches(
2040              *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2041}
2042
2043/// \brief Matches declaration statements that contain a specific number of
2044/// declarations.
2045///
2046/// Example: Given
2047/// \code
2048///   int a, b;
2049///   int c;
2050///   int d = 2, e;
2051/// \endcode
2052/// declCountIs(2)
2053///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2054AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2055  return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2056}
2057
2058/// \brief Matches the n'th declaration of a declaration statement.
2059///
2060/// Note that this does not work for global declarations because the AST
2061/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2062/// DeclStmt's.
2063/// Example: Given non-global declarations
2064/// \code
2065///   int a, b = 0;
2066///   int c;
2067///   int d = 2, e;
2068/// \endcode
2069/// declStmt(containsDeclaration(
2070///       0, varDecl(hasInitializer(anything()))))
2071///   matches only 'int d = 2, e;', and
2072/// declStmt(containsDeclaration(1, varDecl()))
2073/// \code
2074///   matches 'int a, b = 0' as well as 'int d = 2, e;'
2075///   but 'int c;' is not matched.
2076/// \endcode
2077AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2078               internal::Matcher<Decl>, InnerMatcher) {
2079  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2080  if (N >= NumDecls)
2081    return false;
2082  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2083  std::advance(Iterator, N);
2084  return InnerMatcher.matches(**Iterator, Finder, Builder);
2085}
2086
2087/// \brief Matches a constructor initializer.
2088///
2089/// Given
2090/// \code
2091///   struct Foo {
2092///     Foo() : foo_(1) { }
2093///     int foo_;
2094///   };
2095/// \endcode
2096/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2097///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2098AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2099              internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2100  return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2101                                    Node.init_end(), Finder, Builder);
2102}
2103
2104/// \brief Matches the field declaration of a constructor initializer.
2105///
2106/// Given
2107/// \code
2108///   struct Foo {
2109///     Foo() : foo_(1) { }
2110///     int foo_;
2111///   };
2112/// \endcode
2113/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2114///     forField(hasName("foo_"))))))
2115///   matches Foo
2116/// with forField matching foo_
2117AST_MATCHER_P(CXXCtorInitializer, forField,
2118              internal::Matcher<FieldDecl>, InnerMatcher) {
2119  const FieldDecl *NodeAsDecl = Node.getMember();
2120  return (NodeAsDecl != NULL &&
2121      InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2122}
2123
2124/// \brief Matches the initializer expression of a constructor initializer.
2125///
2126/// Given
2127/// \code
2128///   struct Foo {
2129///     Foo() : foo_(1) { }
2130///     int foo_;
2131///   };
2132/// \endcode
2133/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2134///     withInitializer(integerLiteral(equals(1)))))))
2135///   matches Foo
2136/// with withInitializer matching (1)
2137AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2138              internal::Matcher<Expr>, InnerMatcher) {
2139  const Expr* NodeAsExpr = Node.getInit();
2140  return (NodeAsExpr != NULL &&
2141      InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2142}
2143
2144/// \brief Matches a contructor initializer if it is explicitly written in
2145/// code (as opposed to implicitly added by the compiler).
2146///
2147/// Given
2148/// \code
2149///   struct Foo {
2150///     Foo() { }
2151///     Foo(int) : foo_("A") { }
2152///     string foo_;
2153///   };
2154/// \endcode
2155/// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2156///   will match Foo(int), but not Foo()
2157AST_MATCHER(CXXCtorInitializer, isWritten) {
2158  return Node.isWritten();
2159}
2160
2161/// \brief Matches a constructor declaration that has been implicitly added
2162/// by the compiler (eg. implicit default/copy constructors).
2163AST_MATCHER(CXXConstructorDecl, isImplicit) {
2164  return Node.isImplicit();
2165}
2166
2167/// \brief Matches any argument of a call expression or a constructor call
2168/// expression.
2169///
2170/// Given
2171/// \code
2172///   void x(int, int, int) { int y; x(1, y, 42); }
2173/// \endcode
2174/// callExpr(hasAnyArgument(declRefExpr()))
2175///   matches x(1, y, 42)
2176/// with hasAnyArgument(...)
2177///   matching y
2178///
2179/// FIXME: Currently this will ignore parentheses and implicit casts on
2180/// the argument before applying the inner matcher. We'll want to remove
2181/// this to allow for greater control by the user once \c ignoreImplicit()
2182/// has been implemented.
2183AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
2184                          InnerMatcher) {
2185  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
2186                         llvm::is_base_of<CXXConstructExpr,
2187                                          NodeType>::value),
2188                         instantiated_with_wrong_types);
2189  for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2190    BoundNodesTreeBuilder Result(*Builder);
2191    if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
2192                             &Result)) {
2193      *Builder = Result;
2194      return true;
2195    }
2196  }
2197  return false;
2198}
2199
2200/// \brief Matches the n'th parameter of a function declaration.
2201///
2202/// Given
2203/// \code
2204///   class X { void f(int x) {} };
2205/// \endcode
2206/// methodDecl(hasParameter(0, hasType(varDecl())))
2207///   matches f(int x) {}
2208/// with hasParameter(...)
2209///   matching int x
2210AST_MATCHER_P2(FunctionDecl, hasParameter,
2211               unsigned, N, internal::Matcher<ParmVarDecl>,
2212               InnerMatcher) {
2213  return (N < Node.getNumParams() &&
2214          InnerMatcher.matches(
2215              *Node.getParamDecl(N), Finder, Builder));
2216}
2217
2218/// \brief Matches any parameter of a function declaration.
2219///
2220/// Does not match the 'this' parameter of a method.
2221///
2222/// Given
2223/// \code
2224///   class X { void f(int x, int y, int z) {} };
2225/// \endcode
2226/// methodDecl(hasAnyParameter(hasName("y")))
2227///   matches f(int x, int y, int z) {}
2228/// with hasAnyParameter(...)
2229///   matching int y
2230AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2231              internal::Matcher<ParmVarDecl>, InnerMatcher) {
2232  return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2233                                    Node.param_end(), Finder, Builder);
2234}
2235
2236/// \brief Matches \c FunctionDecls that have a specific parameter count.
2237///
2238/// Given
2239/// \code
2240///   void f(int i) {}
2241///   void g(int i, int j) {}
2242/// \endcode
2243/// functionDecl(parameterCountIs(2))
2244///   matches g(int i, int j) {}
2245AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2246  return Node.getNumParams() == N;
2247}
2248
2249/// \brief Matches the return type of a function declaration.
2250///
2251/// Given:
2252/// \code
2253///   class X { int f() { return 1; } };
2254/// \endcode
2255/// methodDecl(returns(asString("int")))
2256///   matches int f() { return 1; }
2257AST_MATCHER_P(FunctionDecl, returns,
2258              internal::Matcher<QualType>, InnerMatcher) {
2259  return InnerMatcher.matches(Node.getResultType(), Finder, Builder);
2260}
2261
2262/// \brief Matches extern "C" function declarations.
2263///
2264/// Given:
2265/// \code
2266///   extern "C" void f() {}
2267///   extern "C" { void g() {} }
2268///   void h() {}
2269/// \endcode
2270/// functionDecl(isExternC())
2271///   matches the declaration of f and g, but not the declaration h
2272AST_MATCHER(FunctionDecl, isExternC) {
2273  return Node.isExternC();
2274}
2275
2276/// \brief Matches the condition expression of an if statement, for loop,
2277/// or conditional operator.
2278///
2279/// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2280/// \code
2281///   if (true) {}
2282/// \endcode
2283AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
2284                          InnerMatcher) {
2285  TOOLING_COMPILE_ASSERT(
2286    (llvm::is_base_of<IfStmt, NodeType>::value) ||
2287    (llvm::is_base_of<ForStmt, NodeType>::value) ||
2288    (llvm::is_base_of<WhileStmt, NodeType>::value) ||
2289    (llvm::is_base_of<DoStmt, NodeType>::value) ||
2290    (llvm::is_base_of<ConditionalOperator, NodeType>::value),
2291    has_condition_requires_if_statement_conditional_operator_or_loop);
2292  const Expr *const Condition = Node.getCond();
2293  return (Condition != NULL &&
2294          InnerMatcher.matches(*Condition, Finder, Builder));
2295}
2296
2297/// \brief Matches the condition variable statement in an if statement.
2298///
2299/// Given
2300/// \code
2301///   if (A* a = GetAPointer()) {}
2302/// \endcode
2303/// hasConditionVariableStatment(...)
2304///   matches 'A* a = GetAPointer()'.
2305AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2306              internal::Matcher<DeclStmt>, InnerMatcher) {
2307  const DeclStmt* const DeclarationStatement =
2308    Node.getConditionVariableDeclStmt();
2309  return DeclarationStatement != NULL &&
2310         InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2311}
2312
2313/// \brief Matches the index expression of an array subscript expression.
2314///
2315/// Given
2316/// \code
2317///   int i[5];
2318///   void f() { i[1] = 42; }
2319/// \endcode
2320/// arraySubscriptExpression(hasIndex(integerLiteral()))
2321///   matches \c i[1] with the \c integerLiteral() matching \c 1
2322AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2323              internal::Matcher<Expr>, InnerMatcher) {
2324  if (const Expr* Expression = Node.getIdx())
2325    return InnerMatcher.matches(*Expression, Finder, Builder);
2326  return false;
2327}
2328
2329/// \brief Matches the base expression of an array subscript expression.
2330///
2331/// Given
2332/// \code
2333///   int i[5];
2334///   void f() { i[1] = 42; }
2335/// \endcode
2336/// arraySubscriptExpression(hasBase(implicitCastExpr(
2337///     hasSourceExpression(declRefExpr()))))
2338///   matches \c i[1] with the \c declRefExpr() matching \c i
2339AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2340              internal::Matcher<Expr>, InnerMatcher) {
2341  if (const Expr* Expression = Node.getBase())
2342    return InnerMatcher.matches(*Expression, Finder, Builder);
2343  return false;
2344}
2345
2346/// \brief Matches a 'for', 'while', or 'do while' statement that has
2347/// a given body.
2348///
2349/// Given
2350/// \code
2351///   for (;;) {}
2352/// \endcode
2353/// hasBody(compoundStmt())
2354///   matches 'for (;;) {}'
2355/// with compoundStmt()
2356///   matching '{}'
2357AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
2358                          InnerMatcher) {
2359  TOOLING_COMPILE_ASSERT(
2360      (llvm::is_base_of<DoStmt, NodeType>::value) ||
2361      (llvm::is_base_of<ForStmt, NodeType>::value) ||
2362      (llvm::is_base_of<WhileStmt, NodeType>::value),
2363      has_body_requires_for_while_or_do_statement);
2364  const Stmt *const Statement = Node.getBody();
2365  return (Statement != NULL &&
2366          InnerMatcher.matches(*Statement, Finder, Builder));
2367}
2368
2369/// \brief Matches compound statements where at least one substatement matches
2370/// a given matcher.
2371///
2372/// Given
2373/// \code
2374///   { {}; 1+2; }
2375/// \endcode
2376/// hasAnySubstatement(compoundStmt())
2377///   matches '{ {}; 1+2; }'
2378/// with compoundStmt()
2379///   matching '{}'
2380AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2381              internal::Matcher<Stmt>, InnerMatcher) {
2382  return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
2383                                    Node.body_end(), Finder, Builder);
2384}
2385
2386/// \brief Checks that a compound statement contains a specific number of
2387/// child statements.
2388///
2389/// Example: Given
2390/// \code
2391///   { for (;;) {} }
2392/// \endcode
2393/// compoundStmt(statementCountIs(0)))
2394///   matches '{}'
2395///   but does not match the outer compound statement.
2396AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2397  return Node.size() == N;
2398}
2399
2400/// \brief Matches literals that are equal to the given value.
2401///
2402/// Example matches true (matcher = boolLiteral(equals(true)))
2403/// \code
2404///   true
2405/// \endcode
2406///
2407/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2408///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2409template <typename ValueT>
2410internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2411equals(const ValueT &Value) {
2412  return internal::PolymorphicMatcherWithParam1<
2413    internal::ValueEqualsMatcher,
2414    ValueT>(Value);
2415}
2416
2417/// \brief Matches the operator Name of operator expressions (binary or
2418/// unary).
2419///
2420/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2421/// \code
2422///   !(a || b)
2423/// \endcode
2424AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
2425  TOOLING_COMPILE_ASSERT(
2426    (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
2427    (llvm::is_base_of<UnaryOperator, NodeType>::value),
2428    has_condition_requires_if_statement_or_conditional_operator);
2429  return Name == Node.getOpcodeStr(Node.getOpcode());
2430}
2431
2432/// \brief Matches the left hand side of binary operator expressions.
2433///
2434/// Example matches a (matcher = binaryOperator(hasLHS()))
2435/// \code
2436///   a || b
2437/// \endcode
2438AST_MATCHER_P(BinaryOperator, hasLHS,
2439              internal::Matcher<Expr>, InnerMatcher) {
2440  Expr *LeftHandSide = Node.getLHS();
2441  return (LeftHandSide != NULL &&
2442          InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2443}
2444
2445/// \brief Matches the right hand side of binary operator expressions.
2446///
2447/// Example matches b (matcher = binaryOperator(hasRHS()))
2448/// \code
2449///   a || b
2450/// \endcode
2451AST_MATCHER_P(BinaryOperator, hasRHS,
2452              internal::Matcher<Expr>, InnerMatcher) {
2453  Expr *RightHandSide = Node.getRHS();
2454  return (RightHandSide != NULL &&
2455          InnerMatcher.matches(*RightHandSide, Finder, Builder));
2456}
2457
2458/// \brief Matches if either the left hand side or the right hand side of a
2459/// binary operator matches.
2460inline internal::Matcher<BinaryOperator> hasEitherOperand(
2461    const internal::Matcher<Expr> &InnerMatcher) {
2462  return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2463}
2464
2465/// \brief Matches if the operand of a unary operator matches.
2466///
2467/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2468/// \code
2469///   !true
2470/// \endcode
2471AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2472              internal::Matcher<Expr>, InnerMatcher) {
2473  const Expr * const Operand = Node.getSubExpr();
2474  return (Operand != NULL &&
2475          InnerMatcher.matches(*Operand, Finder, Builder));
2476}
2477
2478/// \brief Matches if the cast's source expression matches the given matcher.
2479///
2480/// Example: matches "a string" (matcher =
2481///                                  hasSourceExpression(constructExpr()))
2482/// \code
2483/// class URL { URL(string); };
2484/// URL url = "a string";
2485AST_MATCHER_P(CastExpr, hasSourceExpression,
2486              internal::Matcher<Expr>, InnerMatcher) {
2487  const Expr* const SubExpression = Node.getSubExpr();
2488  return (SubExpression != NULL &&
2489          InnerMatcher.matches(*SubExpression, Finder, Builder));
2490}
2491
2492/// \brief Matches casts whose destination type matches a given matcher.
2493///
2494/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2495/// actual casts "explicit" casts.)
2496AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2497              internal::Matcher<QualType>, InnerMatcher) {
2498  const QualType NodeType = Node.getTypeAsWritten();
2499  return InnerMatcher.matches(NodeType, Finder, Builder);
2500}
2501
2502/// \brief Matches implicit casts whose destination type matches a given
2503/// matcher.
2504///
2505/// FIXME: Unit test this matcher
2506AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2507              internal::Matcher<QualType>, InnerMatcher) {
2508  return InnerMatcher.matches(Node.getType(), Finder, Builder);
2509}
2510
2511/// \brief Matches the true branch expression of a conditional operator.
2512///
2513/// Example matches a
2514/// \code
2515///   condition ? a : b
2516/// \endcode
2517AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2518              internal::Matcher<Expr>, InnerMatcher) {
2519  Expr *Expression = Node.getTrueExpr();
2520  return (Expression != NULL &&
2521          InnerMatcher.matches(*Expression, Finder, Builder));
2522}
2523
2524/// \brief Matches the false branch expression of a conditional operator.
2525///
2526/// Example matches b
2527/// \code
2528///   condition ? a : b
2529/// \endcode
2530AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2531              internal::Matcher<Expr>, InnerMatcher) {
2532  Expr *Expression = Node.getFalseExpr();
2533  return (Expression != NULL &&
2534          InnerMatcher.matches(*Expression, Finder, Builder));
2535}
2536
2537/// \brief Matches if a declaration has a body attached.
2538///
2539/// Example matches A, va, fa
2540/// \code
2541///   class A {};
2542///   class B;  // Doesn't match, as it has no body.
2543///   int va;
2544///   extern int vb;  // Doesn't match, as it doesn't define the variable.
2545///   void fa() {}
2546///   void fb();  // Doesn't match, as it has no body.
2547/// \endcode
2548///
2549/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2550AST_POLYMORPHIC_MATCHER(isDefinition) {
2551  TOOLING_COMPILE_ASSERT(
2552      (llvm::is_base_of<TagDecl, NodeType>::value) ||
2553      (llvm::is_base_of<VarDecl, NodeType>::value) ||
2554      (llvm::is_base_of<FunctionDecl, NodeType>::value),
2555      is_definition_requires_isThisDeclarationADefinition_method);
2556  return Node.isThisDeclarationADefinition();
2557}
2558
2559/// \brief Matches the class declaration that the given method declaration
2560/// belongs to.
2561///
2562/// FIXME: Generalize this for other kinds of declarations.
2563/// FIXME: What other kind of declarations would we need to generalize
2564/// this to?
2565///
2566/// Example matches A() in the last line
2567///     (matcher = constructExpr(hasDeclaration(methodDecl(
2568///         ofClass(hasName("A"))))))
2569/// \code
2570///   class A {
2571///    public:
2572///     A();
2573///   };
2574///   A a = A();
2575/// \endcode
2576AST_MATCHER_P(CXXMethodDecl, ofClass,
2577              internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2578  const CXXRecordDecl *Parent = Node.getParent();
2579  return (Parent != NULL &&
2580          InnerMatcher.matches(*Parent, Finder, Builder));
2581}
2582
2583/// \brief Matches if the given method declaration is virtual.
2584///
2585/// Given
2586/// \code
2587///   class A {
2588///    public:
2589///     virtual void x();
2590///   };
2591/// \endcode
2592///   matches A::x
2593AST_MATCHER(CXXMethodDecl, isVirtual) {
2594  return Node.isVirtual();
2595}
2596
2597/// \brief Matches if the given method declaration is const.
2598///
2599/// Given
2600/// \code
2601/// struct A {
2602///   void foo() const;
2603///   void bar();
2604/// };
2605/// \endcode
2606///
2607/// methodDecl(isConst()) matches A::foo() but not A::bar()
2608AST_MATCHER(CXXMethodDecl, isConst) {
2609  return Node.isConst();
2610}
2611
2612/// \brief Matches if the given method declaration overrides another method.
2613///
2614/// Given
2615/// \code
2616///   class A {
2617///    public:
2618///     virtual void x();
2619///   };
2620///   class B : public A {
2621///    public:
2622///     virtual void x();
2623///   };
2624/// \endcode
2625///   matches B::x
2626AST_MATCHER(CXXMethodDecl, isOverride) {
2627  return Node.size_overridden_methods() > 0;
2628}
2629
2630/// \brief Matches member expressions that are called with '->' as opposed
2631/// to '.'.
2632///
2633/// Member calls on the implicit this pointer match as called with '->'.
2634///
2635/// Given
2636/// \code
2637///   class Y {
2638///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2639///     int a;
2640///     static int b;
2641///   };
2642/// \endcode
2643/// memberExpr(isArrow())
2644///   matches this->x, x, y.x, a, this->b
2645AST_MATCHER(MemberExpr, isArrow) {
2646  return Node.isArrow();
2647}
2648
2649/// \brief Matches QualType nodes that are of integer type.
2650///
2651/// Given
2652/// \code
2653///   void a(int);
2654///   void b(long);
2655///   void c(double);
2656/// \endcode
2657/// functionDecl(hasAnyParameter(hasType(isInteger())))
2658/// matches "a(int)", "b(long)", but not "c(double)".
2659AST_MATCHER(QualType, isInteger) {
2660    return Node->isIntegerType();
2661}
2662
2663/// \brief Matches QualType nodes that are const-qualified, i.e., that
2664/// include "top-level" const.
2665///
2666/// Given
2667/// \code
2668///   void a(int);
2669///   void b(int const);
2670///   void c(const int);
2671///   void d(const int*);
2672///   void e(int const) {};
2673/// \endcode
2674/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2675///   matches "void b(int const)", "void c(const int)" and
2676///   "void e(int const) {}". It does not match d as there
2677///   is no top-level const on the parameter type "const int *".
2678AST_MATCHER(QualType, isConstQualified) {
2679  return Node.isConstQualified();
2680}
2681
2682/// \brief Matches QualType nodes that have local CV-qualifiers attached to
2683/// the node, not hidden within a typedef.
2684///
2685/// Given
2686/// \code
2687///   typedef const int const_int;
2688///   const_int i;
2689///   int *const j;
2690///   int *volatile k;
2691///   int m;
2692/// \endcode
2693/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2694/// \c i is const-qualified but the qualifier is not local.
2695AST_MATCHER(QualType, hasLocalQualifiers) {
2696  return Node.hasLocalQualifiers();
2697}
2698
2699/// \brief Matches a member expression where the member is matched by a
2700/// given matcher.
2701///
2702/// Given
2703/// \code
2704///   struct { int first, second; } first, second;
2705///   int i(second.first);
2706///   int j(first.second);
2707/// \endcode
2708/// memberExpr(member(hasName("first")))
2709///   matches second.first
2710///   but not first.second (because the member name there is "second").
2711AST_MATCHER_P(MemberExpr, member,
2712              internal::Matcher<ValueDecl>, InnerMatcher) {
2713  return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2714}
2715
2716/// \brief Matches a member expression where the object expression is
2717/// matched by a given matcher.
2718///
2719/// Given
2720/// \code
2721///   struct X { int m; };
2722///   void f(X x) { x.m; m; }
2723/// \endcode
2724/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2725///   matches "x.m" and "m"
2726/// with hasObjectExpression(...)
2727///   matching "x" and the implicit object expression of "m" which has type X*.
2728AST_MATCHER_P(MemberExpr, hasObjectExpression,
2729              internal::Matcher<Expr>, InnerMatcher) {
2730  return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2731}
2732
2733/// \brief Matches any using shadow declaration.
2734///
2735/// Given
2736/// \code
2737///   namespace X { void b(); }
2738///   using X::b;
2739/// \endcode
2740/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2741///   matches \code using X::b \endcode
2742AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2743              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2744  return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
2745                                    Node.shadow_end(), Finder, Builder);
2746}
2747
2748/// \brief Matches a using shadow declaration where the target declaration is
2749/// matched by the given matcher.
2750///
2751/// Given
2752/// \code
2753///   namespace X { int a; void b(); }
2754///   using X::a;
2755///   using X::b;
2756/// \endcode
2757/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2758///   matches \code using X::b \endcode
2759///   but not \code using X::a \endcode
2760AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2761              internal::Matcher<NamedDecl>, InnerMatcher) {
2762  return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2763}
2764
2765/// \brief Matches template instantiations of function, class, or static
2766/// member variable template instantiations.
2767///
2768/// Given
2769/// \code
2770///   template <typename T> class X {}; class A {}; X<A> x;
2771/// \endcode
2772/// or
2773/// \code
2774///   template <typename T> class X {}; class A {}; template class X<A>;
2775/// \endcode
2776/// recordDecl(hasName("::X"), isTemplateInstantiation())
2777///   matches the template instantiation of X<A>.
2778///
2779/// But given
2780/// \code
2781///   template <typename T>  class X {}; class A {};
2782///   template <> class X<A> {}; X<A> x;
2783/// \endcode
2784/// recordDecl(hasName("::X"), isTemplateInstantiation())
2785///   does not match, as X<A> is an explicit template specialization.
2786///
2787/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2788AST_POLYMORPHIC_MATCHER(isTemplateInstantiation) {
2789  TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2790                         (llvm::is_base_of<VarDecl, NodeType>::value) ||
2791                         (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2792                         requires_getTemplateSpecializationKind_method);
2793  return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2794          Node.getTemplateSpecializationKind() ==
2795          TSK_ExplicitInstantiationDefinition);
2796}
2797
2798/// \brief Matches explicit template specializations of function, class, or
2799/// static member variable template instantiations.
2800///
2801/// Given
2802/// \code
2803///   template<typename T> void A(T t) { }
2804///   template<> void A(int N) { }
2805/// \endcode
2806/// functionDecl(isExplicitTemplateSpecialization())
2807///   matches the specialization A<int>().
2808///
2809/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2810AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization) {
2811  TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2812                         (llvm::is_base_of<VarDecl, NodeType>::value) ||
2813                         (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2814                         requires_getTemplateSpecializationKind_method);
2815  return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2816}
2817
2818/// \brief Matches \c TypeLocs for which the given inner
2819/// QualType-matcher matches.
2820inline internal::BindableMatcher<TypeLoc> loc(
2821    const internal::Matcher<QualType> &InnerMatcher) {
2822  return internal::BindableMatcher<TypeLoc>(
2823      new internal::TypeLocTypeMatcher(InnerMatcher));
2824}
2825
2826/// \brief Matches builtin Types.
2827///
2828/// Given
2829/// \code
2830///   struct A {};
2831///   A a;
2832///   int b;
2833///   float c;
2834///   bool d;
2835/// \endcode
2836/// builtinType()
2837///   matches "int b", "float c" and "bool d"
2838AST_TYPE_MATCHER(BuiltinType, builtinType);
2839
2840/// \brief Matches all kinds of arrays.
2841///
2842/// Given
2843/// \code
2844///   int a[] = { 2, 3 };
2845///   int b[4];
2846///   void f() { int c[a[0]]; }
2847/// \endcode
2848/// arrayType()
2849///   matches "int a[]", "int b[4]" and "int c[a[0]]";
2850AST_TYPE_MATCHER(ArrayType, arrayType);
2851
2852/// \brief Matches C99 complex types.
2853///
2854/// Given
2855/// \code
2856///   _Complex float f;
2857/// \endcode
2858/// complexType()
2859///   matches "_Complex float f"
2860AST_TYPE_MATCHER(ComplexType, complexType);
2861
2862/// \brief Matches arrays and C99 complex types that have a specific element
2863/// type.
2864///
2865/// Given
2866/// \code
2867///   struct A {};
2868///   A a[7];
2869///   int b[7];
2870/// \endcode
2871/// arrayType(hasElementType(builtinType()))
2872///   matches "int b[7]"
2873///
2874/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
2875AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement);
2876
2877/// \brief Matches C arrays with a specified constant size.
2878///
2879/// Given
2880/// \code
2881///   void() {
2882///     int a[2];
2883///     int b[] = { 2, 3 };
2884///     int c[b[0]];
2885///   }
2886/// \endcode
2887/// constantArrayType()
2888///   matches "int a[2]"
2889AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
2890
2891/// \brief Matches \c ConstantArrayType nodes that have the specified size.
2892///
2893/// Given
2894/// \code
2895///   int a[42];
2896///   int b[2 * 21];
2897///   int c[41], d[43];
2898/// \endcode
2899/// constantArrayType(hasSize(42))
2900///   matches "int a[42]" and "int b[2 * 21]"
2901AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
2902  return Node.getSize() == N;
2903}
2904
2905/// \brief Matches C++ arrays whose size is a value-dependent expression.
2906///
2907/// Given
2908/// \code
2909///   template<typename T, int Size>
2910///   class array {
2911///     T data[Size];
2912///   };
2913/// \endcode
2914/// dependentSizedArrayType
2915///   matches "T data[Size]"
2916AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
2917
2918/// \brief Matches C arrays with unspecified size.
2919///
2920/// Given
2921/// \code
2922///   int a[] = { 2, 3 };
2923///   int b[42];
2924///   void f(int c[]) { int d[a[0]]; };
2925/// \endcode
2926/// incompleteArrayType()
2927///   matches "int a[]" and "int c[]"
2928AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
2929
2930/// \brief Matches C arrays with a specified size that is not an
2931/// integer-constant-expression.
2932///
2933/// Given
2934/// \code
2935///   void f() {
2936///     int a[] = { 2, 3 }
2937///     int b[42];
2938///     int c[a[0]];
2939/// \endcode
2940/// variableArrayType()
2941///   matches "int c[a[0]]"
2942AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
2943
2944/// \brief Matches \c VariableArrayType nodes that have a specific size
2945/// expression.
2946///
2947/// Given
2948/// \code
2949///   void f(int b) {
2950///     int a[b];
2951///   }
2952/// \endcode
2953/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
2954///   varDecl(hasName("b")))))))
2955///   matches "int a[b]"
2956AST_MATCHER_P(VariableArrayType, hasSizeExpr,
2957              internal::Matcher<Expr>, InnerMatcher) {
2958  return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
2959}
2960
2961/// \brief Matches atomic types.
2962///
2963/// Given
2964/// \code
2965///   _Atomic(int) i;
2966/// \endcode
2967/// atomicType()
2968///   matches "_Atomic(int) i"
2969AST_TYPE_MATCHER(AtomicType, atomicType);
2970
2971/// \brief Matches atomic types with a specific value type.
2972///
2973/// Given
2974/// \code
2975///   _Atomic(int) i;
2976///   _Atomic(float) f;
2977/// \endcode
2978/// atomicType(hasValueType(isInteger()))
2979///  matches "_Atomic(int) i"
2980///
2981/// Usable as: Matcher<AtomicType>
2982AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue);
2983
2984/// \brief Matches types nodes representing C++11 auto types.
2985///
2986/// Given:
2987/// \code
2988///   auto n = 4;
2989///   int v[] = { 2, 3 }
2990///   for (auto i : v) { }
2991/// \endcode
2992/// autoType()
2993///   matches "auto n" and "auto i"
2994AST_TYPE_MATCHER(AutoType, autoType);
2995
2996/// \brief Matches \c AutoType nodes where the deduced type is a specific type.
2997///
2998/// Note: There is no \c TypeLoc for the deduced type and thus no
2999/// \c getDeducedLoc() matcher.
3000///
3001/// Given
3002/// \code
3003///   auto a = 1;
3004///   auto b = 2.0;
3005/// \endcode
3006/// autoType(hasDeducedType(isInteger()))
3007///   matches "auto a"
3008///
3009/// Usable as: Matcher<AutoType>
3010AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType);
3011
3012/// \brief Matches \c FunctionType nodes.
3013///
3014/// Given
3015/// \code
3016///   int (*f)(int);
3017///   void g();
3018/// \endcode
3019/// functionType()
3020///   matches "int (*f)(int)" and the type of "g".
3021AST_TYPE_MATCHER(FunctionType, functionType);
3022
3023/// \brief Matches \c ParenType nodes.
3024///
3025/// Given
3026/// \code
3027///   int (*ptr_to_array)[4];
3028///   int *array_of_ptrs[4];
3029/// \endcode
3030///
3031/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3032/// \c array_of_ptrs.
3033AST_TYPE_MATCHER(ParenType, parenType);
3034
3035/// \brief Matches \c ParenType nodes where the inner type is a specific type.
3036///
3037/// Given
3038/// \code
3039///   int (*ptr_to_array)[4];
3040///   int (*ptr_to_func)(int);
3041/// \endcode
3042///
3043/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
3044/// \c ptr_to_func but not \c ptr_to_array.
3045///
3046/// Usable as: Matcher<ParenType>
3047AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType);
3048
3049/// \brief Matches block pointer types, i.e. types syntactically represented as
3050/// "void (^)(int)".
3051///
3052/// The \c pointee is always required to be a \c FunctionType.
3053AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
3054
3055/// \brief Matches member pointer types.
3056/// Given
3057/// \code
3058///   struct A { int i; }
3059///   A::* ptr = A::i;
3060/// \endcode
3061/// memberPointerType()
3062///   matches "A::* ptr"
3063AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3064
3065/// \brief Matches pointer types.
3066///
3067/// Given
3068/// \code
3069///   int *a;
3070///   int &b = *a;
3071///   int c = 5;
3072/// \endcode
3073/// pointerType()
3074///   matches "int *a"
3075AST_TYPE_MATCHER(PointerType, pointerType);
3076
3077/// \brief Matches both lvalue and rvalue reference types.
3078///
3079/// Given
3080/// \code
3081///   int *a;
3082///   int &b = *a;
3083///   int &&c = 1;
3084///   auto &d = b;
3085///   auto &&e = c;
3086///   auto &&f = 2;
3087///   int g = 5;
3088/// \endcode
3089///
3090/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3091AST_TYPE_MATCHER(ReferenceType, referenceType);
3092
3093/// \brief Matches lvalue reference types.
3094///
3095/// Given:
3096/// \code
3097///   int *a;
3098///   int &b = *a;
3099///   int &&c = 1;
3100///   auto &d = b;
3101///   auto &&e = c;
3102///   auto &&f = 2;
3103///   int g = 5;
3104/// \endcode
3105///
3106/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3107/// matched since the type is deduced as int& by reference collapsing rules.
3108AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3109
3110/// \brief Matches rvalue reference types.
3111///
3112/// Given:
3113/// \code
3114///   int *a;
3115///   int &b = *a;
3116///   int &&c = 1;
3117///   auto &d = b;
3118///   auto &&e = c;
3119///   auto &&f = 2;
3120///   int g = 5;
3121/// \endcode
3122///
3123/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3124/// matched as it is deduced to int& by reference collapsing rules.
3125AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3126
3127/// \brief Narrows PointerType (and similar) matchers to those where the
3128/// \c pointee matches a given matcher.
3129///
3130/// Given
3131/// \code
3132///   int *a;
3133///   int const *b;
3134///   float const *f;
3135/// \endcode
3136/// pointerType(pointee(isConstQualified(), isInteger()))
3137///   matches "int const *b"
3138///
3139/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3140///   Matcher<PointerType>, Matcher<ReferenceType>
3141AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee);
3142
3143/// \brief Matches typedef types.
3144///
3145/// Given
3146/// \code
3147///   typedef int X;
3148/// \endcode
3149/// typedefType()
3150///   matches "typedef int X"
3151AST_TYPE_MATCHER(TypedefType, typedefType);
3152
3153/// \brief Matches template specialization types.
3154///
3155/// Given
3156/// \code
3157///   template <typename T>
3158///   class C { };
3159///
3160///   template class C<int>;  // A
3161///   C<char> var;            // B
3162/// \code
3163///
3164/// \c templateSpecializationType() matches the type of the explicit
3165/// instantiation in \c A and the type of the variable declaration in \c B.
3166AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3167
3168/// \brief Matches record types (e.g. structs, classes).
3169///
3170/// Given
3171/// \code
3172///   class C {};
3173///   struct S {};
3174///
3175///   C c;
3176///   S s;
3177/// \code
3178///
3179/// \c recordType() matches the type of the variable declarations of both \c c
3180/// and \c s.
3181AST_TYPE_MATCHER(RecordType, recordType);
3182
3183/// \brief Matches types specified with an elaborated type keyword or with a
3184/// qualified name.
3185///
3186/// Given
3187/// \code
3188///   namespace N {
3189///     namespace M {
3190///       class D {};
3191///     }
3192///   }
3193///   class C {};
3194///
3195///   class C c;
3196///   N::M::D d;
3197/// \code
3198///
3199/// \c elaboratedType() matches the type of the variable declarations of both
3200/// \c c and \c d.
3201AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3202
3203/// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3204/// matches \c InnerMatcher if the qualifier exists.
3205///
3206/// Given
3207/// \code
3208///   namespace N {
3209///     namespace M {
3210///       class D {};
3211///     }
3212///   }
3213///   N::M::D d;
3214/// \code
3215///
3216/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3217/// matches the type of the variable declaration of \c d.
3218AST_MATCHER_P(ElaboratedType, hasQualifier,
3219              internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3220  if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3221    return InnerMatcher.matches(*Qualifier, Finder, Builder);
3222
3223  return false;
3224}
3225
3226/// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3227///
3228/// Given
3229/// \code
3230///   namespace N {
3231///     namespace M {
3232///       class D {};
3233///     }
3234///   }
3235///   N::M::D d;
3236/// \code
3237///
3238/// \c elaboratedType(namesType(recordType(
3239/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3240/// declaration of \c d.
3241AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3242              InnerMatcher) {
3243  return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3244}
3245
3246/// \brief Matches declarations whose declaration context, interpreted as a
3247/// Decl, matches \c InnerMatcher.
3248///
3249/// Given
3250/// \code
3251///   namespace N {
3252///     namespace M {
3253///       class D {};
3254///     }
3255///   }
3256/// \code
3257///
3258/// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3259/// declaration of \c class \c D.
3260AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3261  return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3262                              Finder, Builder);
3263}
3264
3265/// \brief Matches nested name specifiers.
3266///
3267/// Given
3268/// \code
3269///   namespace ns {
3270///     struct A { static void f(); };
3271///     void A::f() {}
3272///     void g() { A::f(); }
3273///   }
3274///   ns::A a;
3275/// \endcode
3276/// nestedNameSpecifier()
3277///   matches "ns::" and both "A::"
3278const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3279
3280/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3281const internal::VariadicAllOfMatcher<
3282  NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3283
3284/// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3285/// NestedNameSpecifier-matcher matches.
3286inline internal::BindableMatcher<NestedNameSpecifierLoc> loc(
3287    const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
3288  return internal::BindableMatcher<NestedNameSpecifierLoc>(
3289      new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3290          InnerMatcher));
3291}
3292
3293/// \brief Matches nested name specifiers that specify a type matching the
3294/// given \c QualType matcher without qualifiers.
3295///
3296/// Given
3297/// \code
3298///   struct A { struct B { struct C {}; }; };
3299///   A::B::C c;
3300/// \endcode
3301/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3302///   matches "A::"
3303AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3304              internal::Matcher<QualType>, InnerMatcher) {
3305  if (Node.getAsType() == NULL)
3306    return false;
3307  return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3308}
3309
3310/// \brief Matches nested name specifier locs that specify a type matching the
3311/// given \c TypeLoc.
3312///
3313/// Given
3314/// \code
3315///   struct A { struct B { struct C {}; }; };
3316///   A::B::C c;
3317/// \endcode
3318/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3319///   hasDeclaration(recordDecl(hasName("A")))))))
3320///   matches "A::"
3321AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3322              internal::Matcher<TypeLoc>, InnerMatcher) {
3323  return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3324}
3325
3326/// \brief Matches on the prefix of a \c NestedNameSpecifier.
3327///
3328/// Given
3329/// \code
3330///   struct A { struct B { struct C {}; }; };
3331///   A::B::C c;
3332/// \endcode
3333/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3334///   matches "A::"
3335AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3336                       internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3337                       0) {
3338  NestedNameSpecifier *NextNode = Node.getPrefix();
3339  if (NextNode == NULL)
3340    return false;
3341  return InnerMatcher.matches(*NextNode, Finder, Builder);
3342}
3343
3344/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3345///
3346/// Given
3347/// \code
3348///   struct A { struct B { struct C {}; }; };
3349///   A::B::C c;
3350/// \endcode
3351/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3352///   matches "A::"
3353AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3354                       internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3355                       1) {
3356  NestedNameSpecifierLoc NextNode = Node.getPrefix();
3357  if (!NextNode)
3358    return false;
3359  return InnerMatcher.matches(NextNode, Finder, Builder);
3360}
3361
3362/// \brief Matches nested name specifiers that specify a namespace matching the
3363/// given namespace matcher.
3364///
3365/// Given
3366/// \code
3367///   namespace ns { struct A {}; }
3368///   ns::A a;
3369/// \endcode
3370/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3371///   matches "ns::"
3372AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3373              internal::Matcher<NamespaceDecl>, InnerMatcher) {
3374  if (Node.getAsNamespace() == NULL)
3375    return false;
3376  return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3377}
3378
3379/// \brief Overloads for the \c equalsNode matcher.
3380/// FIXME: Implement for other node types.
3381/// @{
3382
3383/// \brief Matches if a node equals another node.
3384///
3385/// \c Decl has pointer identity in the AST.
3386AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) {
3387  return &Node == Other;
3388}
3389/// \brief Matches if a node equals another node.
3390///
3391/// \c Stmt has pointer identity in the AST.
3392///
3393AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) {
3394  return &Node == Other;
3395}
3396
3397/// @}
3398
3399/// \brief Matches each case or default statement belonging to the given switch
3400/// statement. This matcher may produce multiple matches.
3401///
3402/// Given
3403/// \code
3404///   switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
3405/// \endcode
3406/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
3407///   matches four times, with "c" binding each of "case 1:", "case 2:",
3408/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
3409/// "switch (1)", "switch (2)" and "switch (2)".
3410AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
3411              InnerMatcher) {
3412  BoundNodesTreeBuilder Result;
3413  // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
3414  // iteration order. We should use the more general iterating matchers once
3415  // they are capable of expressing this matcher (for example, it should ignore
3416  // case statements belonging to nested switch statements).
3417  bool Matched = false;
3418  for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
3419       SC = SC->getNextSwitchCase()) {
3420    BoundNodesTreeBuilder CaseBuilder(*Builder);
3421    bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
3422    if (CaseMatched) {
3423      Matched = true;
3424      Result.addMatch(CaseBuilder);
3425    }
3426  }
3427  *Builder = Result;
3428  return Matched;
3429}
3430
3431/// \brief If the given case statement does not use the GNU case range
3432/// extension, matches the constant given in the statement.
3433///
3434/// Given
3435/// \code
3436///   switch (1) { case 1: case 1+1: case 3 ... 4: ; }
3437/// \endcode
3438/// caseStmt(hasCaseConstant(integerLiteral()))
3439///   matches "case 1:"
3440AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
3441              InnerMatcher) {
3442  if (Node.getRHS())
3443    return false;
3444
3445  return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
3446}
3447
3448} // end namespace ast_matchers
3449} // end namespace clang
3450
3451#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
3452