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