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