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