]> granicus.if.org Git - clang/blob - include/clang/ASTMatchers/ASTMatchers.h
fc15454c45223316990cef641ec9bf18a99eb7fd
[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 ///   };
1957 /// \endcode
1958 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1959               InnerMatcher) {
1960   return (!Node.isNull() && Node->isReferenceType() &&
1961           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1962 }
1963
1964 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1965 ///
1966 /// Given:
1967 /// \code
1968 ///   typedef int &int_ref;
1969 ///   int a;
1970 ///   int_ref b = a;
1971 /// \code
1972 ///
1973 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1974 /// declaration of b but \c
1975 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1976 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1977               InnerMatcher) {
1978   if (Node.isNull())
1979     return false;
1980   return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1981 }
1982
1983 /// \brief Overloaded to match the referenced type's declaration.
1984 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
1985                        InnerMatcher, 1) {
1986   return references(qualType(hasDeclaration(InnerMatcher)))
1987       .matches(Node, Finder, Builder);
1988 }
1989
1990 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1991               internal::Matcher<Expr>, InnerMatcher) {
1992   const Expr *ExprNode = Node.getImplicitObjectArgument();
1993   return (ExprNode != nullptr &&
1994           InnerMatcher.matches(*ExprNode, Finder, Builder));
1995 }
1996
1997 /// \brief Matches if the expression's type either matches the specified
1998 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1999 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2000                        internal::Matcher<QualType>, InnerMatcher, 0) {
2001   return onImplicitObjectArgument(
2002       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2003       .matches(Node, Finder, Builder);
2004 }
2005
2006 /// \brief Overloaded to match the type's declaration.
2007 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2008                        internal::Matcher<Decl>, InnerMatcher, 1) {
2009   return onImplicitObjectArgument(
2010       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2011       .matches(Node, Finder, Builder);
2012 }
2013
2014 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2015 /// specified matcher.
2016 ///
2017 /// Example matches x in if(x)
2018 ///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
2019 /// \code
2020 ///   bool x;
2021 ///   if (x) {}
2022 /// \endcode
2023 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2024               InnerMatcher) {
2025   const Decl *DeclNode = Node.getDecl();
2026   return (DeclNode != nullptr &&
2027           InnerMatcher.matches(*DeclNode, Finder, Builder));
2028 }
2029
2030 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2031 /// specific using shadow declaration.
2032 ///
2033 /// FIXME: This currently only works for functions. Fix.
2034 ///
2035 /// Given
2036 /// \code
2037 ///   namespace a { void f() {} }
2038 ///   using a::f;
2039 ///   void g() {
2040 ///     f();     // Matches this ..
2041 ///     a::f();  // .. but not this.
2042 ///   }
2043 /// \endcode
2044 /// declRefExpr(throughUsingDeclaration(anything()))
2045 ///   matches \c f()
2046 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2047               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2048   const NamedDecl *FoundDecl = Node.getFoundDecl();
2049   if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2050     return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2051   return false;
2052 }
2053
2054 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2055 ///
2056 /// Given
2057 /// \code
2058 ///   int a, b;
2059 ///   int c;
2060 /// \endcode
2061 /// declStmt(hasSingleDecl(anything()))
2062 ///   matches 'int c;' but not 'int a, b;'.
2063 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2064   if (Node.isSingleDecl()) {
2065     const Decl *FoundDecl = Node.getSingleDecl();
2066     return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2067   }
2068   return false;
2069 }
2070
2071 /// \brief Matches a variable declaration that has an initializer expression
2072 /// that matches the given matcher.
2073 ///
2074 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2075 /// \code
2076 ///   bool y() { return true; }
2077 ///   bool x = y();
2078 /// \endcode
2079 AST_MATCHER_P(
2080     VarDecl, hasInitializer, internal::Matcher<Expr>,
2081     InnerMatcher) {
2082   const Expr *Initializer = Node.getAnyInitializer();
2083   return (Initializer != nullptr &&
2084           InnerMatcher.matches(*Initializer, Finder, Builder));
2085 }
2086
2087 /// \brief Matches a variable declaration that has function scope and is a
2088 /// non-static local variable.
2089 ///
2090 /// Example matches x (matcher = varDecl(hasLocalStorage())
2091 /// \code
2092 /// void f() {
2093 ///   int x;
2094 ///   static int y;
2095 /// }
2096 /// int z;
2097 /// \endcode
2098 AST_MATCHER(VarDecl, hasLocalStorage) {
2099   return Node.hasLocalStorage();
2100 }
2101
2102 /// \brief Matches a variable declaration that does not have local storage.
2103 ///
2104 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2105 /// \code
2106 /// void f() {
2107 ///   int x;
2108 ///   static int y;
2109 /// }
2110 /// int z;
2111 /// \endcode
2112 AST_MATCHER(VarDecl, hasGlobalStorage) {
2113   return Node.hasGlobalStorage();
2114 }
2115
2116 /// \brief Checks that a call expression or a constructor call expression has
2117 /// a specific number of arguments (including absent default arguments).
2118 ///
2119 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2120 /// \code
2121 ///   void f(int x, int y);
2122 ///   f(0, 0);
2123 /// \endcode
2124 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2125                                                CallExpr, CXXConstructExpr),
2126                           unsigned, N) {
2127   return Node.getNumArgs() == N;
2128 }
2129
2130 /// \brief Matches the n'th argument of a call expression or a constructor
2131 /// call expression.
2132 ///
2133 /// Example matches y in x(y)
2134 ///     (matcher = callExpr(hasArgument(0, declRefExpr())))
2135 /// \code
2136 ///   void x(int) { int y; x(y); }
2137 /// \endcode
2138 AST_POLYMORPHIC_MATCHER_P2(
2139     hasArgument,
2140     AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr),
2141     unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2142   return (N < Node.getNumArgs() &&
2143           InnerMatcher.matches(
2144               *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2145 }
2146
2147 /// \brief Matches declaration statements that contain a specific number of
2148 /// declarations.
2149 ///
2150 /// Example: Given
2151 /// \code
2152 ///   int a, b;
2153 ///   int c;
2154 ///   int d = 2, e;
2155 /// \endcode
2156 /// declCountIs(2)
2157 ///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2158 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2159   return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2160 }
2161
2162 /// \brief Matches the n'th declaration of a declaration statement.
2163 ///
2164 /// Note that this does not work for global declarations because the AST
2165 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2166 /// DeclStmt's.
2167 /// Example: Given non-global declarations
2168 /// \code
2169 ///   int a, b = 0;
2170 ///   int c;
2171 ///   int d = 2, e;
2172 /// \endcode
2173 /// declStmt(containsDeclaration(
2174 ///       0, varDecl(hasInitializer(anything()))))
2175 ///   matches only 'int d = 2, e;', and
2176 /// declStmt(containsDeclaration(1, varDecl()))
2177 /// \code
2178 ///   matches 'int a, b = 0' as well as 'int d = 2, e;'
2179 ///   but 'int c;' is not matched.
2180 /// \endcode
2181 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2182                internal::Matcher<Decl>, InnerMatcher) {
2183   const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2184   if (N >= NumDecls)
2185     return false;
2186   DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2187   std::advance(Iterator, N);
2188   return InnerMatcher.matches(**Iterator, Finder, Builder);
2189 }
2190
2191 /// \brief Matches a constructor initializer.
2192 ///
2193 /// Given
2194 /// \code
2195 ///   struct Foo {
2196 ///     Foo() : foo_(1) { }
2197 ///     int foo_;
2198 ///   };
2199 /// \endcode
2200 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2201 ///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2202 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2203               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2204   return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2205                                     Node.init_end(), Finder, Builder);
2206 }
2207
2208 /// \brief Matches the field declaration of a constructor initializer.
2209 ///
2210 /// Given
2211 /// \code
2212 ///   struct Foo {
2213 ///     Foo() : foo_(1) { }
2214 ///     int foo_;
2215 ///   };
2216 /// \endcode
2217 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2218 ///     forField(hasName("foo_"))))))
2219 ///   matches Foo
2220 /// with forField matching foo_
2221 AST_MATCHER_P(CXXCtorInitializer, forField,
2222               internal::Matcher<FieldDecl>, InnerMatcher) {
2223   const FieldDecl *NodeAsDecl = Node.getMember();
2224   return (NodeAsDecl != nullptr &&
2225       InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2226 }
2227
2228 /// \brief Matches the initializer expression of a constructor initializer.
2229 ///
2230 /// Given
2231 /// \code
2232 ///   struct Foo {
2233 ///     Foo() : foo_(1) { }
2234 ///     int foo_;
2235 ///   };
2236 /// \endcode
2237 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2238 ///     withInitializer(integerLiteral(equals(1)))))))
2239 ///   matches Foo
2240 /// with withInitializer matching (1)
2241 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2242               internal::Matcher<Expr>, InnerMatcher) {
2243   const Expr* NodeAsExpr = Node.getInit();
2244   return (NodeAsExpr != nullptr &&
2245       InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2246 }
2247
2248 /// \brief Matches a constructor initializer if it is explicitly written in
2249 /// code (as opposed to implicitly added by the compiler).
2250 ///
2251 /// Given
2252 /// \code
2253 ///   struct Foo {
2254 ///     Foo() { }
2255 ///     Foo(int) : foo_("A") { }
2256 ///     string foo_;
2257 ///   };
2258 /// \endcode
2259 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2260 ///   will match Foo(int), but not Foo()
2261 AST_MATCHER(CXXCtorInitializer, isWritten) {
2262   return Node.isWritten();
2263 }
2264
2265 /// \brief Matches any argument of a call expression or a constructor call
2266 /// expression.
2267 ///
2268 /// Given
2269 /// \code
2270 ///   void x(int, int, int) { int y; x(1, y, 42); }
2271 /// \endcode
2272 /// callExpr(hasAnyArgument(declRefExpr()))
2273 ///   matches x(1, y, 42)
2274 /// with hasAnyArgument(...)
2275 ///   matching y
2276 ///
2277 /// FIXME: Currently this will ignore parentheses and implicit casts on
2278 /// the argument before applying the inner matcher. We'll want to remove
2279 /// this to allow for greater control by the user once \c ignoreImplicit()
2280 /// has been implemented.
2281 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2282                                               CallExpr, CXXConstructExpr),
2283                           internal::Matcher<Expr>, InnerMatcher) {
2284   for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2285     BoundNodesTreeBuilder Result(*Builder);
2286     if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
2287                              &Result)) {
2288       *Builder = Result;
2289       return true;
2290     }
2291   }
2292   return false;
2293 }
2294
2295 /// \brief Matches a constructor call expression which uses list initialization.
2296 AST_MATCHER(CXXConstructExpr, isListInitialization) {
2297   return Node.isListInitialization();
2298 }
2299
2300 /// \brief Matches the n'th parameter of a function declaration.
2301 ///
2302 /// Given
2303 /// \code
2304 ///   class X { void f(int x) {} };
2305 /// \endcode
2306 /// methodDecl(hasParameter(0, hasType(varDecl())))
2307 ///   matches f(int x) {}
2308 /// with hasParameter(...)
2309 ///   matching int x
2310 AST_MATCHER_P2(FunctionDecl, hasParameter,
2311                unsigned, N, internal::Matcher<ParmVarDecl>,
2312                InnerMatcher) {
2313   return (N < Node.getNumParams() &&
2314           InnerMatcher.matches(
2315               *Node.getParamDecl(N), Finder, Builder));
2316 }
2317
2318 /// \brief Matches any parameter of a function declaration.
2319 ///
2320 /// Does not match the 'this' parameter of a method.
2321 ///
2322 /// Given
2323 /// \code
2324 ///   class X { void f(int x, int y, int z) {} };
2325 /// \endcode
2326 /// methodDecl(hasAnyParameter(hasName("y")))
2327 ///   matches f(int x, int y, int z) {}
2328 /// with hasAnyParameter(...)
2329 ///   matching int y
2330 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2331               internal::Matcher<ParmVarDecl>, InnerMatcher) {
2332   return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2333                                     Node.param_end(), Finder, Builder);
2334 }
2335
2336 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2337 ///
2338 /// Given
2339 /// \code
2340 ///   void f(int i) {}
2341 ///   void g(int i, int j) {}
2342 /// \endcode
2343 /// functionDecl(parameterCountIs(2))
2344 ///   matches g(int i, int j) {}
2345 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2346   return Node.getNumParams() == N;
2347 }
2348
2349 /// \brief Matches the return type of a function declaration.
2350 ///
2351 /// Given:
2352 /// \code
2353 ///   class X { int f() { return 1; } };
2354 /// \endcode
2355 /// methodDecl(returns(asString("int")))
2356 ///   matches int f() { return 1; }
2357 AST_MATCHER_P(FunctionDecl, returns,
2358               internal::Matcher<QualType>, InnerMatcher) {
2359   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
2360 }
2361
2362 /// \brief Matches extern "C" function declarations.
2363 ///
2364 /// Given:
2365 /// \code
2366 ///   extern "C" void f() {}
2367 ///   extern "C" { void g() {} }
2368 ///   void h() {}
2369 /// \endcode
2370 /// functionDecl(isExternC())
2371 ///   matches the declaration of f and g, but not the declaration h
2372 AST_MATCHER(FunctionDecl, isExternC) {
2373   return Node.isExternC();
2374 }
2375
2376 /// \brief Matches the condition expression of an if statement, for loop,
2377 /// or conditional operator.
2378 ///
2379 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2380 /// \code
2381 ///   if (true) {}
2382 /// \endcode
2383 AST_POLYMORPHIC_MATCHER_P(
2384     hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5(
2385                       IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator),
2386     internal::Matcher<Expr>, InnerMatcher) {
2387   const Expr *const Condition = Node.getCond();
2388   return (Condition != nullptr &&
2389           InnerMatcher.matches(*Condition, Finder, Builder));
2390 }
2391
2392 /// \brief Matches the then-statement of an if statement.
2393 ///
2394 /// Examples matches the if statement
2395 ///   (matcher = ifStmt(hasThen(boolLiteral(equals(true)))))
2396 /// \code
2397 ///   if (false) true; else false;
2398 /// \endcode
2399 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
2400   const Stmt *const Then = Node.getThen();
2401   return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
2402 }
2403
2404 /// \brief Matches the else-statement of an if statement.
2405 ///
2406 /// Examples matches the if statement
2407 ///   (matcher = ifStmt(hasElse(boolLiteral(equals(true)))))
2408 /// \code
2409 ///   if (false) false; else true;
2410 /// \endcode
2411 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
2412   const Stmt *const Else = Node.getElse();
2413   return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
2414 }
2415
2416 /// \brief Matches if a node equals a previously bound node.
2417 ///
2418 /// Matches a node if it equals the node previously bound to \p ID.
2419 ///
2420 /// Given
2421 /// \code
2422 ///   class X { int a; int b; };
2423 /// \endcode
2424 /// recordDecl(
2425 ///     has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2426 ///     has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
2427 ///   matches the class \c X, as \c a and \c b have the same type.
2428 ///
2429 /// Note that when multiple matches are involved via \c forEach* matchers,
2430 /// \c equalsBoundNodes acts as a filter.
2431 /// For example:
2432 /// compoundStmt(
2433 ///     forEachDescendant(varDecl().bind("d")),
2434 ///     forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
2435 /// will trigger a match for each combination of variable declaration
2436 /// and reference to that variable declaration within a compound statement.
2437 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4(
2438                                                Stmt, Decl, Type, QualType),
2439                           std::string, ID) {
2440   // FIXME: Figure out whether it makes sense to allow this
2441   // on any other node types.
2442   // For *Loc it probably does not make sense, as those seem
2443   // unique. For NestedNameSepcifier it might make sense, as
2444   // those also have pointer identity, but I'm not sure whether
2445   // they're ever reused.
2446   internal::NotEqualsBoundNodePredicate Predicate;
2447   Predicate.ID = ID;
2448   Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
2449   return Builder->removeBindings(Predicate);
2450 }
2451
2452 /// \brief Matches the condition variable statement in an if statement.
2453 ///
2454 /// Given
2455 /// \code
2456 ///   if (A* a = GetAPointer()) {}
2457 /// \endcode
2458 /// hasConditionVariableStatement(...)
2459 ///   matches 'A* a = GetAPointer()'.
2460 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2461               internal::Matcher<DeclStmt>, InnerMatcher) {
2462   const DeclStmt* const DeclarationStatement =
2463     Node.getConditionVariableDeclStmt();
2464   return DeclarationStatement != nullptr &&
2465          InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2466 }
2467
2468 /// \brief Matches the index expression of an array subscript expression.
2469 ///
2470 /// Given
2471 /// \code
2472 ///   int i[5];
2473 ///   void f() { i[1] = 42; }
2474 /// \endcode
2475 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2476 ///   matches \c i[1] with the \c integerLiteral() matching \c 1
2477 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2478               internal::Matcher<Expr>, InnerMatcher) {
2479   if (const Expr* Expression = Node.getIdx())
2480     return InnerMatcher.matches(*Expression, Finder, Builder);
2481   return false;
2482 }
2483
2484 /// \brief Matches the base expression of an array subscript expression.
2485 ///
2486 /// Given
2487 /// \code
2488 ///   int i[5];
2489 ///   void f() { i[1] = 42; }
2490 /// \endcode
2491 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2492 ///     hasSourceExpression(declRefExpr()))))
2493 ///   matches \c i[1] with the \c declRefExpr() matching \c i
2494 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2495               internal::Matcher<Expr>, InnerMatcher) {
2496   if (const Expr* Expression = Node.getBase())
2497     return InnerMatcher.matches(*Expression, Finder, Builder);
2498   return false;
2499 }
2500
2501 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2502 /// a given body.
2503 ///
2504 /// Given
2505 /// \code
2506 ///   for (;;) {}
2507 /// \endcode
2508 /// hasBody(compoundStmt())
2509 ///   matches 'for (;;) {}'
2510 /// with compoundStmt()
2511 ///   matching '{}'
2512 AST_POLYMORPHIC_MATCHER_P(hasBody,
2513                           AST_POLYMORPHIC_SUPPORTED_TYPES_4(DoStmt, ForStmt,
2514                                                             WhileStmt,
2515                                                             CXXForRangeStmt),
2516                           internal::Matcher<Stmt>, InnerMatcher) {
2517   const Stmt *const Statement = Node.getBody();
2518   return (Statement != nullptr &&
2519           InnerMatcher.matches(*Statement, Finder, Builder));
2520 }
2521
2522 /// \brief Matches compound statements where at least one substatement matches
2523 /// a given matcher.
2524 ///
2525 /// Given
2526 /// \code
2527 ///   { {}; 1+2; }
2528 /// \endcode
2529 /// hasAnySubstatement(compoundStmt())
2530 ///   matches '{ {}; 1+2; }'
2531 /// with compoundStmt()
2532 ///   matching '{}'
2533 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2534               internal::Matcher<Stmt>, InnerMatcher) {
2535   return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
2536                                     Node.body_end(), Finder, Builder);
2537 }
2538
2539 /// \brief Checks that a compound statement contains a specific number of
2540 /// child statements.
2541 ///
2542 /// Example: Given
2543 /// \code
2544 ///   { for (;;) {} }
2545 /// \endcode
2546 /// compoundStmt(statementCountIs(0)))
2547 ///   matches '{}'
2548 ///   but does not match the outer compound statement.
2549 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2550   return Node.size() == N;
2551 }
2552
2553 /// \brief Matches literals that are equal to the given value.
2554 ///
2555 /// Example matches true (matcher = boolLiteral(equals(true)))
2556 /// \code
2557 ///   true
2558 /// \endcode
2559 ///
2560 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2561 ///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2562 template <typename ValueT>
2563 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2564 equals(const ValueT &Value) {
2565   return internal::PolymorphicMatcherWithParam1<
2566     internal::ValueEqualsMatcher,
2567     ValueT>(Value);
2568 }
2569
2570 /// \brief Matches the operator Name of operator expressions (binary or
2571 /// unary).
2572 ///
2573 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2574 /// \code
2575 ///   !(a || b)
2576 /// \endcode
2577 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2578                                                BinaryOperator, UnaryOperator),
2579                           std::string, Name) {
2580   return Name == Node.getOpcodeStr(Node.getOpcode());
2581 }
2582
2583 /// \brief Matches the left hand side of binary operator expressions.
2584 ///
2585 /// Example matches a (matcher = binaryOperator(hasLHS()))
2586 /// \code
2587 ///   a || b
2588 /// \endcode
2589 AST_MATCHER_P(BinaryOperator, hasLHS,
2590               internal::Matcher<Expr>, InnerMatcher) {
2591   Expr *LeftHandSide = Node.getLHS();
2592   return (LeftHandSide != nullptr &&
2593           InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2594 }
2595
2596 /// \brief Matches the right hand side of binary operator expressions.
2597 ///
2598 /// Example matches b (matcher = binaryOperator(hasRHS()))
2599 /// \code
2600 ///   a || b
2601 /// \endcode
2602 AST_MATCHER_P(BinaryOperator, hasRHS,
2603               internal::Matcher<Expr>, InnerMatcher) {
2604   Expr *RightHandSide = Node.getRHS();
2605   return (RightHandSide != nullptr &&
2606           InnerMatcher.matches(*RightHandSide, Finder, Builder));
2607 }
2608
2609 /// \brief Matches if either the left hand side or the right hand side of a
2610 /// binary operator matches.
2611 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2612     const internal::Matcher<Expr> &InnerMatcher) {
2613   return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2614 }
2615
2616 /// \brief Matches if the operand of a unary operator matches.
2617 ///
2618 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2619 /// \code
2620 ///   !true
2621 /// \endcode
2622 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2623               internal::Matcher<Expr>, InnerMatcher) {
2624   const Expr * const Operand = Node.getSubExpr();
2625   return (Operand != nullptr &&
2626           InnerMatcher.matches(*Operand, Finder, Builder));
2627 }
2628
2629 /// \brief Matches if the cast's source expression matches the given matcher.
2630 ///
2631 /// Example: matches "a string" (matcher =
2632 ///                                  hasSourceExpression(constructExpr()))
2633 /// \code
2634 /// class URL { URL(string); };
2635 /// URL url = "a string";
2636 AST_MATCHER_P(CastExpr, hasSourceExpression,
2637               internal::Matcher<Expr>, InnerMatcher) {
2638   const Expr* const SubExpression = Node.getSubExpr();
2639   return (SubExpression != nullptr &&
2640           InnerMatcher.matches(*SubExpression, Finder, Builder));
2641 }
2642
2643 /// \brief Matches casts whose destination type matches a given matcher.
2644 ///
2645 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2646 /// actual casts "explicit" casts.)
2647 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2648               internal::Matcher<QualType>, InnerMatcher) {
2649   const QualType NodeType = Node.getTypeAsWritten();
2650   return InnerMatcher.matches(NodeType, Finder, Builder);
2651 }
2652
2653 /// \brief Matches implicit casts whose destination type matches a given
2654 /// matcher.
2655 ///
2656 /// FIXME: Unit test this matcher
2657 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2658               internal::Matcher<QualType>, InnerMatcher) {
2659   return InnerMatcher.matches(Node.getType(), Finder, Builder);
2660 }
2661
2662 /// \brief Matches the true branch expression of a conditional operator.
2663 ///
2664 /// Example matches a
2665 /// \code
2666 ///   condition ? a : b
2667 /// \endcode
2668 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2669               internal::Matcher<Expr>, InnerMatcher) {
2670   Expr *Expression = Node.getTrueExpr();
2671   return (Expression != nullptr &&
2672           InnerMatcher.matches(*Expression, Finder, Builder));
2673 }
2674
2675 /// \brief Matches the false branch expression of a conditional operator.
2676 ///
2677 /// Example matches b
2678 /// \code
2679 ///   condition ? a : b
2680 /// \endcode
2681 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2682               internal::Matcher<Expr>, InnerMatcher) {
2683   Expr *Expression = Node.getFalseExpr();
2684   return (Expression != nullptr &&
2685           InnerMatcher.matches(*Expression, Finder, Builder));
2686 }
2687
2688 /// \brief Matches if a declaration has a body attached.
2689 ///
2690 /// Example matches A, va, fa
2691 /// \code
2692 ///   class A {};
2693 ///   class B;  // Doesn't match, as it has no body.
2694 ///   int va;
2695 ///   extern int vb;  // Doesn't match, as it doesn't define the variable.
2696 ///   void fa() {}
2697 ///   void fb();  // Doesn't match, as it has no body.
2698 /// \endcode
2699 ///
2700 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2701 AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3(
2702                                           TagDecl, VarDecl, FunctionDecl)) {
2703   return Node.isThisDeclarationADefinition();
2704 }
2705
2706 /// \brief Matches the class declaration that the given method declaration
2707 /// belongs to.
2708 ///
2709 /// FIXME: Generalize this for other kinds of declarations.
2710 /// FIXME: What other kind of declarations would we need to generalize
2711 /// this to?
2712 ///
2713 /// Example matches A() in the last line
2714 ///     (matcher = constructExpr(hasDeclaration(methodDecl(
2715 ///         ofClass(hasName("A"))))))
2716 /// \code
2717 ///   class A {
2718 ///    public:
2719 ///     A();
2720 ///   };
2721 ///   A a = A();
2722 /// \endcode
2723 AST_MATCHER_P(CXXMethodDecl, ofClass,
2724               internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2725   const CXXRecordDecl *Parent = Node.getParent();
2726   return (Parent != nullptr &&
2727           InnerMatcher.matches(*Parent, Finder, Builder));
2728 }
2729
2730 /// \brief Matches if the given method declaration is virtual.
2731 ///
2732 /// Given
2733 /// \code
2734 ///   class A {
2735 ///    public:
2736 ///     virtual void x();
2737 ///   };
2738 /// \endcode
2739 ///   matches A::x
2740 AST_MATCHER(CXXMethodDecl, isVirtual) {
2741   return Node.isVirtual();
2742 }
2743
2744 /// \brief Matches if the given method declaration is pure.
2745 ///
2746 /// Given
2747 /// \code
2748 ///   class A {
2749 ///    public:
2750 ///     virtual void x() = 0;
2751 ///   };
2752 /// \endcode
2753 ///   matches A::x
2754 AST_MATCHER(CXXMethodDecl, isPure) {
2755   return Node.isPure();
2756 }
2757
2758 /// \brief Matches if the given method declaration is const.
2759 ///
2760 /// Given
2761 /// \code
2762 /// struct A {
2763 ///   void foo() const;
2764 ///   void bar();
2765 /// };
2766 /// \endcode
2767 ///
2768 /// methodDecl(isConst()) matches A::foo() but not A::bar()
2769 AST_MATCHER(CXXMethodDecl, isConst) {
2770   return Node.isConst();
2771 }
2772
2773 /// \brief Matches if the given method declaration overrides another method.
2774 ///
2775 /// Given
2776 /// \code
2777 ///   class A {
2778 ///    public:
2779 ///     virtual void x();
2780 ///   };
2781 ///   class B : public A {
2782 ///    public:
2783 ///     virtual void x();
2784 ///   };
2785 /// \endcode
2786 ///   matches B::x
2787 AST_MATCHER(CXXMethodDecl, isOverride) {
2788   return Node.size_overridden_methods() > 0;
2789 }
2790
2791 /// \brief Matches member expressions that are called with '->' as opposed
2792 /// to '.'.
2793 ///
2794 /// Member calls on the implicit this pointer match as called with '->'.
2795 ///
2796 /// Given
2797 /// \code
2798 ///   class Y {
2799 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2800 ///     int a;
2801 ///     static int b;
2802 ///   };
2803 /// \endcode
2804 /// memberExpr(isArrow())
2805 ///   matches this->x, x, y.x, a, this->b
2806 AST_MATCHER(MemberExpr, isArrow) {
2807   return Node.isArrow();
2808 }
2809
2810 /// \brief Matches QualType nodes that are of integer type.
2811 ///
2812 /// Given
2813 /// \code
2814 ///   void a(int);
2815 ///   void b(long);
2816 ///   void c(double);
2817 /// \endcode
2818 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2819 /// matches "a(int)", "b(long)", but not "c(double)".
2820 AST_MATCHER(QualType, isInteger) {
2821     return Node->isIntegerType();
2822 }
2823
2824 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2825 /// include "top-level" const.
2826 ///
2827 /// Given
2828 /// \code
2829 ///   void a(int);
2830 ///   void b(int const);
2831 ///   void c(const int);
2832 ///   void d(const int*);
2833 ///   void e(int const) {};
2834 /// \endcode
2835 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2836 ///   matches "void b(int const)", "void c(const int)" and
2837 ///   "void e(int const) {}". It does not match d as there
2838 ///   is no top-level const on the parameter type "const int *".
2839 AST_MATCHER(QualType, isConstQualified) {
2840   return Node.isConstQualified();
2841 }
2842
2843 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2844 /// the node, not hidden within a typedef.
2845 ///
2846 /// Given
2847 /// \code
2848 ///   typedef const int const_int;
2849 ///   const_int i;
2850 ///   int *const j;
2851 ///   int *volatile k;
2852 ///   int m;
2853 /// \endcode
2854 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2855 /// \c i is const-qualified but the qualifier is not local.
2856 AST_MATCHER(QualType, hasLocalQualifiers) {
2857   return Node.hasLocalQualifiers();
2858 }
2859
2860 /// \brief Matches a member expression where the member is matched by a
2861 /// given matcher.
2862 ///
2863 /// Given
2864 /// \code
2865 ///   struct { int first, second; } first, second;
2866 ///   int i(second.first);
2867 ///   int j(first.second);
2868 /// \endcode
2869 /// memberExpr(member(hasName("first")))
2870 ///   matches second.first
2871 ///   but not first.second (because the member name there is "second").
2872 AST_MATCHER_P(MemberExpr, member,
2873               internal::Matcher<ValueDecl>, InnerMatcher) {
2874   return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2875 }
2876
2877 /// \brief Matches a member expression where the object expression is
2878 /// matched by a given matcher.
2879 ///
2880 /// Given
2881 /// \code
2882 ///   struct X { int m; };
2883 ///   void f(X x) { x.m; m; }
2884 /// \endcode
2885 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2886 ///   matches "x.m" and "m"
2887 /// with hasObjectExpression(...)
2888 ///   matching "x" and the implicit object expression of "m" which has type X*.
2889 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2890               internal::Matcher<Expr>, InnerMatcher) {
2891   return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2892 }
2893
2894 /// \brief Matches any using shadow declaration.
2895 ///
2896 /// Given
2897 /// \code
2898 ///   namespace X { void b(); }
2899 ///   using X::b;
2900 /// \endcode
2901 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2902 ///   matches \code using X::b \endcode
2903 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2904               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2905   return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
2906                                     Node.shadow_end(), Finder, Builder);
2907 }
2908
2909 /// \brief Matches a using shadow declaration where the target declaration is
2910 /// matched by the given matcher.
2911 ///
2912 /// Given
2913 /// \code
2914 ///   namespace X { int a; void b(); }
2915 ///   using X::a;
2916 ///   using X::b;
2917 /// \endcode
2918 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2919 ///   matches \code using X::b \endcode
2920 ///   but not \code using X::a \endcode
2921 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2922               internal::Matcher<NamedDecl>, InnerMatcher) {
2923   return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2924 }
2925
2926 /// \brief Matches template instantiations of function, class, or static
2927 /// member variable template instantiations.
2928 ///
2929 /// Given
2930 /// \code
2931 ///   template <typename T> class X {}; class A {}; X<A> x;
2932 /// \endcode
2933 /// or
2934 /// \code
2935 ///   template <typename T> class X {}; class A {}; template class X<A>;
2936 /// \endcode
2937 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2938 ///   matches the template instantiation of X<A>.
2939 ///
2940 /// But given
2941 /// \code
2942 ///   template <typename T>  class X {}; class A {};
2943 ///   template <> class X<A> {}; X<A> x;
2944 /// \endcode
2945 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2946 ///   does not match, as X<A> is an explicit template specialization.
2947 ///
2948 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2949 AST_POLYMORPHIC_MATCHER(
2950     isTemplateInstantiation,
2951     AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2952   return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2953           Node.getTemplateSpecializationKind() ==
2954           TSK_ExplicitInstantiationDefinition);
2955 }
2956
2957 /// \brief Matches explicit template specializations of function, class, or
2958 /// static member variable template instantiations.
2959 ///
2960 /// Given
2961 /// \code
2962 ///   template<typename T> void A(T t) { }
2963 ///   template<> void A(int N) { }
2964 /// \endcode
2965 /// functionDecl(isExplicitTemplateSpecialization())
2966 ///   matches the specialization A<int>().
2967 ///
2968 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2969 AST_POLYMORPHIC_MATCHER(
2970     isExplicitTemplateSpecialization,
2971     AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2972   return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2973 }
2974
2975 /// \brief Matches \c TypeLocs for which the given inner
2976 /// QualType-matcher matches.
2977 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
2978                                 internal::Matcher<QualType>, InnerMatcher, 0) {
2979   return internal::BindableMatcher<TypeLoc>(
2980       new internal::TypeLocTypeMatcher(InnerMatcher));
2981 }
2982
2983 /// \brief Matches builtin Types.
2984 ///
2985 /// Given
2986 /// \code
2987 ///   struct A {};
2988 ///   A a;
2989 ///   int b;
2990 ///   float c;
2991 ///   bool d;
2992 /// \endcode
2993 /// builtinType()
2994 ///   matches "int b", "float c" and "bool d"
2995 AST_TYPE_MATCHER(BuiltinType, builtinType);
2996
2997 /// \brief Matches all kinds of arrays.
2998 ///
2999 /// Given
3000 /// \code
3001 ///   int a[] = { 2, 3 };
3002 ///   int b[4];
3003 ///   void f() { int c[a[0]]; }
3004 /// \endcode
3005 /// arrayType()
3006 ///   matches "int a[]", "int b[4]" and "int c[a[0]]";
3007 AST_TYPE_MATCHER(ArrayType, arrayType);
3008
3009 /// \brief Matches C99 complex types.
3010 ///
3011 /// Given
3012 /// \code
3013 ///   _Complex float f;
3014 /// \endcode
3015 /// complexType()
3016 ///   matches "_Complex float f"
3017 AST_TYPE_MATCHER(ComplexType, complexType);
3018
3019 /// \brief Matches arrays and C99 complex types that have a specific element
3020 /// type.
3021 ///
3022 /// Given
3023 /// \code
3024 ///   struct A {};
3025 ///   A a[7];
3026 ///   int b[7];
3027 /// \endcode
3028 /// arrayType(hasElementType(builtinType()))
3029 ///   matches "int b[7]"
3030 ///
3031 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
3032 AST_TYPELOC_TRAVERSE_MATCHER(
3033     hasElementType, getElement,
3034     AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType));
3035
3036 /// \brief Matches C arrays with a specified constant size.
3037 ///
3038 /// Given
3039 /// \code
3040 ///   void() {
3041 ///     int a[2];
3042 ///     int b[] = { 2, 3 };
3043 ///     int c[b[0]];
3044 ///   }
3045 /// \endcode
3046 /// constantArrayType()
3047 ///   matches "int a[2]"
3048 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
3049
3050 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
3051 ///
3052 /// Given
3053 /// \code
3054 ///   int a[42];
3055 ///   int b[2 * 21];
3056 ///   int c[41], d[43];
3057 /// \endcode
3058 /// constantArrayType(hasSize(42))
3059 ///   matches "int a[42]" and "int b[2 * 21]"
3060 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
3061   return Node.getSize() == N;
3062 }
3063
3064 /// \brief Matches C++ arrays whose size is a value-dependent expression.
3065 ///
3066 /// Given
3067 /// \code
3068 ///   template<typename T, int Size>
3069 ///   class array {
3070 ///     T data[Size];
3071 ///   };
3072 /// \endcode
3073 /// dependentSizedArrayType
3074 ///   matches "T data[Size]"
3075 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
3076
3077 /// \brief Matches C arrays with unspecified size.
3078 ///
3079 /// Given
3080 /// \code
3081 ///   int a[] = { 2, 3 };
3082 ///   int b[42];
3083 ///   void f(int c[]) { int d[a[0]]; };
3084 /// \endcode
3085 /// incompleteArrayType()
3086 ///   matches "int a[]" and "int c[]"
3087 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
3088
3089 /// \brief Matches C arrays with a specified size that is not an
3090 /// integer-constant-expression.
3091 ///
3092 /// Given
3093 /// \code
3094 ///   void f() {
3095 ///     int a[] = { 2, 3 }
3096 ///     int b[42];
3097 ///     int c[a[0]];
3098 ///   }
3099 /// \endcode
3100 /// variableArrayType()
3101 ///   matches "int c[a[0]]"
3102 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
3103
3104 /// \brief Matches \c VariableArrayType nodes that have a specific size
3105 /// expression.
3106 ///
3107 /// Given
3108 /// \code
3109 ///   void f(int b) {
3110 ///     int a[b];
3111 ///   }
3112 /// \endcode
3113 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3114 ///   varDecl(hasName("b")))))))
3115 ///   matches "int a[b]"
3116 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
3117               internal::Matcher<Expr>, InnerMatcher) {
3118   return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
3119 }
3120
3121 /// \brief Matches atomic types.
3122 ///
3123 /// Given
3124 /// \code
3125 ///   _Atomic(int) i;
3126 /// \endcode
3127 /// atomicType()
3128 ///   matches "_Atomic(int) i"
3129 AST_TYPE_MATCHER(AtomicType, atomicType);
3130
3131 /// \brief Matches atomic types with a specific value type.
3132 ///
3133 /// Given
3134 /// \code
3135 ///   _Atomic(int) i;
3136 ///   _Atomic(float) f;
3137 /// \endcode
3138 /// atomicType(hasValueType(isInteger()))
3139 ///  matches "_Atomic(int) i"
3140 ///
3141 /// Usable as: Matcher<AtomicType>
3142 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
3143                              AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType));
3144
3145 /// \brief Matches types nodes representing C++11 auto types.
3146 ///
3147 /// Given:
3148 /// \code
3149 ///   auto n = 4;
3150 ///   int v[] = { 2, 3 }
3151 ///   for (auto i : v) { }
3152 /// \endcode
3153 /// autoType()
3154 ///   matches "auto n" and "auto i"
3155 AST_TYPE_MATCHER(AutoType, autoType);
3156
3157 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3158 ///
3159 /// Note: There is no \c TypeLoc for the deduced type and thus no
3160 /// \c getDeducedLoc() matcher.
3161 ///
3162 /// Given
3163 /// \code
3164 ///   auto a = 1;
3165 ///   auto b = 2.0;
3166 /// \endcode
3167 /// autoType(hasDeducedType(isInteger()))
3168 ///   matches "auto a"
3169 ///
3170 /// Usable as: Matcher<AutoType>
3171 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3172                           AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType));
3173
3174 /// \brief Matches \c FunctionType nodes.
3175 ///
3176 /// Given
3177 /// \code
3178 ///   int (*f)(int);
3179 ///   void g();
3180 /// \endcode
3181 /// functionType()
3182 ///   matches "int (*f)(int)" and the type of "g".
3183 AST_TYPE_MATCHER(FunctionType, functionType);
3184
3185 /// \brief Matches \c ParenType nodes.
3186 ///
3187 /// Given
3188 /// \code
3189 ///   int (*ptr_to_array)[4];
3190 ///   int *array_of_ptrs[4];
3191 /// \endcode
3192 ///
3193 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3194 /// \c array_of_ptrs.
3195 AST_TYPE_MATCHER(ParenType, parenType);
3196
3197 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
3198 ///
3199 /// Given
3200 /// \code
3201 ///   int (*ptr_to_array)[4];
3202 ///   int (*ptr_to_func)(int);
3203 /// \endcode
3204 ///
3205 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
3206 /// \c ptr_to_func but not \c ptr_to_array.
3207 ///
3208 /// Usable as: Matcher<ParenType>
3209 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
3210                           AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType));
3211
3212 /// \brief Matches block pointer types, i.e. types syntactically represented as
3213 /// "void (^)(int)".
3214 ///
3215 /// The \c pointee is always required to be a \c FunctionType.
3216 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
3217
3218 /// \brief Matches member pointer types.
3219 /// Given
3220 /// \code
3221 ///   struct A { int i; }
3222 ///   A::* ptr = A::i;
3223 /// \endcode
3224 /// memberPointerType()
3225 ///   matches "A::* ptr"
3226 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3227
3228 /// \brief Matches pointer types.
3229 ///
3230 /// Given
3231 /// \code
3232 ///   int *a;
3233 ///   int &b = *a;
3234 ///   int c = 5;
3235 /// \endcode
3236 /// pointerType()
3237 ///   matches "int *a"
3238 AST_TYPE_MATCHER(PointerType, pointerType);
3239
3240 /// \brief Matches both lvalue and rvalue reference types.
3241 ///
3242 /// Given
3243 /// \code
3244 ///   int *a;
3245 ///   int &b = *a;
3246 ///   int &&c = 1;
3247 ///   auto &d = b;
3248 ///   auto &&e = c;
3249 ///   auto &&f = 2;
3250 ///   int g = 5;
3251 /// \endcode
3252 ///
3253 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3254 AST_TYPE_MATCHER(ReferenceType, referenceType);
3255
3256 /// \brief Matches lvalue reference types.
3257 ///
3258 /// Given:
3259 /// \code
3260 ///   int *a;
3261 ///   int &b = *a;
3262 ///   int &&c = 1;
3263 ///   auto &d = b;
3264 ///   auto &&e = c;
3265 ///   auto &&f = 2;
3266 ///   int g = 5;
3267 /// \endcode
3268 ///
3269 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3270 /// matched since the type is deduced as int& by reference collapsing rules.
3271 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3272
3273 /// \brief Matches rvalue reference types.
3274 ///
3275 /// Given:
3276 /// \code
3277 ///   int *a;
3278 ///   int &b = *a;
3279 ///   int &&c = 1;
3280 ///   auto &d = b;
3281 ///   auto &&e = c;
3282 ///   auto &&f = 2;
3283 ///   int g = 5;
3284 /// \endcode
3285 ///
3286 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3287 /// matched as it is deduced to int& by reference collapsing rules.
3288 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3289
3290 /// \brief Narrows PointerType (and similar) matchers to those where the
3291 /// \c pointee matches a given matcher.
3292 ///
3293 /// Given
3294 /// \code
3295 ///   int *a;
3296 ///   int const *b;
3297 ///   float const *f;
3298 /// \endcode
3299 /// pointerType(pointee(isConstQualified(), isInteger()))
3300 ///   matches "int const *b"
3301 ///
3302 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3303 ///   Matcher<PointerType>, Matcher<ReferenceType>
3304 AST_TYPELOC_TRAVERSE_MATCHER(
3305     pointee, getPointee,
3306     AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType,
3307                                       PointerType, ReferenceType));
3308
3309 /// \brief Matches typedef types.
3310 ///
3311 /// Given
3312 /// \code
3313 ///   typedef int X;
3314 /// \endcode
3315 /// typedefType()
3316 ///   matches "typedef int X"
3317 AST_TYPE_MATCHER(TypedefType, typedefType);
3318
3319 /// \brief Matches template specialization types.
3320 ///
3321 /// Given
3322 /// \code
3323 ///   template <typename T>
3324 ///   class C { };
3325 ///
3326 ///   template class C<int>;  // A
3327 ///   C<char> var;            // B
3328 /// \code
3329 ///
3330 /// \c templateSpecializationType() matches the type of the explicit
3331 /// instantiation in \c A and the type of the variable declaration in \c B.
3332 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3333
3334 /// \brief Matches types nodes representing unary type transformations.
3335 ///
3336 /// Given:
3337 /// \code
3338 ///   typedef __underlying_type(T) type;
3339 /// \endcode
3340 /// unaryTransformType()
3341 ///   matches "__underlying_type(T)"
3342 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
3343
3344 /// \brief Matches record types (e.g. structs, classes).
3345 ///
3346 /// Given
3347 /// \code
3348 ///   class C {};
3349 ///   struct S {};
3350 ///
3351 ///   C c;
3352 ///   S s;
3353 /// \code
3354 ///
3355 /// \c recordType() matches the type of the variable declarations of both \c c
3356 /// and \c s.
3357 AST_TYPE_MATCHER(RecordType, recordType);
3358
3359 /// \brief Matches types specified with an elaborated type keyword or with a
3360 /// qualified name.
3361 ///
3362 /// Given
3363 /// \code
3364 ///   namespace N {
3365 ///     namespace M {
3366 ///       class D {};
3367 ///     }
3368 ///   }
3369 ///   class C {};
3370 ///
3371 ///   class C c;
3372 ///   N::M::D d;
3373 /// \code
3374 ///
3375 /// \c elaboratedType() matches the type of the variable declarations of both
3376 /// \c c and \c d.
3377 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3378
3379 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3380 /// matches \c InnerMatcher if the qualifier exists.
3381 ///
3382 /// Given
3383 /// \code
3384 ///   namespace N {
3385 ///     namespace M {
3386 ///       class D {};
3387 ///     }
3388 ///   }
3389 ///   N::M::D d;
3390 /// \code
3391 ///
3392 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3393 /// matches the type of the variable declaration of \c d.
3394 AST_MATCHER_P(ElaboratedType, hasQualifier,
3395               internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3396   if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3397     return InnerMatcher.matches(*Qualifier, Finder, Builder);
3398
3399   return false;
3400 }
3401
3402 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3403 ///
3404 /// Given
3405 /// \code
3406 ///   namespace N {
3407 ///     namespace M {
3408 ///       class D {};
3409 ///     }
3410 ///   }
3411 ///   N::M::D d;
3412 /// \code
3413 ///
3414 /// \c elaboratedType(namesType(recordType(
3415 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3416 /// declaration of \c d.
3417 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3418               InnerMatcher) {
3419   return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3420 }
3421
3422 /// \brief Matches declarations whose declaration context, interpreted as a
3423 /// Decl, matches \c InnerMatcher.
3424 ///
3425 /// Given
3426 /// \code
3427 ///   namespace N {
3428 ///     namespace M {
3429 ///       class D {};
3430 ///     }
3431 ///   }
3432 /// \code
3433 ///
3434 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3435 /// declaration of \c class \c D.
3436 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3437   return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3438                               Finder, Builder);
3439 }
3440
3441 /// \brief Matches nested name specifiers.
3442 ///
3443 /// Given
3444 /// \code
3445 ///   namespace ns {
3446 ///     struct A { static void f(); };
3447 ///     void A::f() {}
3448 ///     void g() { A::f(); }
3449 ///   }
3450 ///   ns::A a;
3451 /// \endcode
3452 /// nestedNameSpecifier()
3453 ///   matches "ns::" and both "A::"
3454 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3455
3456 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3457 const internal::VariadicAllOfMatcher<
3458   NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3459
3460 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3461 /// NestedNameSpecifier-matcher matches.
3462 AST_MATCHER_FUNCTION_P_OVERLOAD(
3463     internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
3464     internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
3465   return internal::BindableMatcher<NestedNameSpecifierLoc>(
3466       new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3467           InnerMatcher));
3468 }
3469
3470 /// \brief Matches nested name specifiers that specify a type matching the
3471 /// given \c QualType matcher without qualifiers.
3472 ///
3473 /// Given
3474 /// \code
3475 ///   struct A { struct B { struct C {}; }; };
3476 ///   A::B::C c;
3477 /// \endcode
3478 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3479 ///   matches "A::"
3480 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3481               internal::Matcher<QualType>, InnerMatcher) {
3482   if (!Node.getAsType())
3483     return false;
3484   return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3485 }
3486
3487 /// \brief Matches nested name specifier locs that specify a type matching the
3488 /// given \c TypeLoc.
3489 ///
3490 /// Given
3491 /// \code
3492 ///   struct A { struct B { struct C {}; }; };
3493 ///   A::B::C c;
3494 /// \endcode
3495 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3496 ///   hasDeclaration(recordDecl(hasName("A")))))))
3497 ///   matches "A::"
3498 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3499               internal::Matcher<TypeLoc>, InnerMatcher) {
3500   return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3501 }
3502
3503 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3504 ///
3505 /// Given
3506 /// \code
3507 ///   struct A { struct B { struct C {}; }; };
3508 ///   A::B::C c;
3509 /// \endcode
3510 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3511 ///   matches "A::"
3512 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3513                        internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3514                        0) {
3515   NestedNameSpecifier *NextNode = Node.getPrefix();
3516   if (!NextNode)
3517     return false;
3518   return InnerMatcher.matches(*NextNode, Finder, Builder);
3519 }
3520
3521 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3522 ///
3523 /// Given
3524 /// \code
3525 ///   struct A { struct B { struct C {}; }; };
3526 ///   A::B::C c;
3527 /// \endcode
3528 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3529 ///   matches "A::"
3530 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3531                        internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3532                        1) {
3533   NestedNameSpecifierLoc NextNode = Node.getPrefix();
3534   if (!NextNode)
3535     return false;
3536   return InnerMatcher.matches(NextNode, Finder, Builder);
3537 }
3538
3539 /// \brief Matches nested name specifiers that specify a namespace matching the
3540 /// given namespace matcher.
3541 ///
3542 /// Given
3543 /// \code
3544 ///   namespace ns { struct A {}; }
3545 ///   ns::A a;
3546 /// \endcode
3547 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3548 ///   matches "ns::"
3549 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3550               internal::Matcher<NamespaceDecl>, InnerMatcher) {
3551   if (!Node.getAsNamespace())
3552     return false;
3553   return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3554 }
3555
3556 /// \brief Overloads for the \c equalsNode matcher.
3557 /// FIXME: Implement for other node types.
3558 /// @{
3559
3560 /// \brief Matches if a node equals another node.
3561 ///
3562 /// \c Decl has pointer identity in the AST.
3563 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
3564   return &Node == Other;
3565 }
3566 /// \brief Matches if a node equals another node.
3567 ///
3568 /// \c Stmt has pointer identity in the AST.
3569 ///
3570 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
3571   return &Node == Other;
3572 }
3573
3574 /// @}
3575
3576 /// \brief Matches each case or default statement belonging to the given switch
3577 /// statement. This matcher may produce multiple matches.
3578 ///
3579 /// Given
3580 /// \code
3581 ///   switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
3582 /// \endcode
3583 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
3584 ///   matches four times, with "c" binding each of "case 1:", "case 2:",
3585 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
3586 /// "switch (1)", "switch (2)" and "switch (2)".
3587 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
3588               InnerMatcher) {
3589   BoundNodesTreeBuilder Result;
3590   // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
3591   // iteration order. We should use the more general iterating matchers once
3592   // they are capable of expressing this matcher (for example, it should ignore
3593   // case statements belonging to nested switch statements).
3594   bool Matched = false;
3595   for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
3596        SC = SC->getNextSwitchCase()) {
3597     BoundNodesTreeBuilder CaseBuilder(*Builder);
3598     bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
3599     if (CaseMatched) {
3600       Matched = true;
3601       Result.addMatch(CaseBuilder);
3602     }
3603   }
3604   *Builder = Result;
3605   return Matched;
3606 }
3607
3608 /// \brief Matches each constructor initializer in a constructor definition.
3609 ///
3610 /// Given
3611 /// \code
3612 ///   class A { A() : i(42), j(42) {} int i; int j; };
3613 /// \endcode
3614 /// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x"))))
3615 ///   will trigger two matches, binding for 'i' and 'j' respectively.
3616 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
3617               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3618   BoundNodesTreeBuilder Result;
3619   bool Matched = false;
3620   for (const auto *I : Node.inits()) {
3621     BoundNodesTreeBuilder InitBuilder(*Builder);
3622     if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
3623       Matched = true;
3624       Result.addMatch(InitBuilder);
3625     }
3626   }
3627   *Builder = Result;
3628   return Matched;
3629 }
3630
3631 /// \brief If the given case statement does not use the GNU case range
3632 /// extension, matches the constant given in the statement.
3633 ///
3634 /// Given
3635 /// \code
3636 ///   switch (1) { case 1: case 1+1: case 3 ... 4: ; }
3637 /// \endcode
3638 /// caseStmt(hasCaseConstant(integerLiteral()))
3639 ///   matches "case 1:"
3640 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
3641               InnerMatcher) {
3642   if (Node.getRHS())
3643     return false;
3644
3645   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
3646 }
3647
3648 /// \brief Matches CUDA kernel call expression.
3649 ///
3650 /// Example matches,
3651 /// \code
3652 ///   kernel<<<i,j>>>();
3653 /// \endcode
3654 const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
3655     CUDAKernelCallExpr;
3656
3657 /// \brief Matches declaration that has CUDA device attribute.
3658 ///
3659 /// Given
3660 /// \code
3661 ///   __attribute__((device)) void f() { ... }
3662 /// \endcode
3663 /// matches the function declaration of f.
3664 AST_MATCHER(Decl, hasCudaDeviceAttr) {
3665   return Node.hasAttr<clang::CUDADeviceAttr>();
3666 }
3667
3668 /// \brief Matches declaration that has CUDA host attribute.
3669 ///
3670 /// Given
3671 /// \code
3672 ///   __attribute__((host)) void f() { ... }
3673 /// \endcode
3674 /// matches the function declaration of f.
3675 AST_MATCHER(Decl, hasCudaHostAttr) {
3676   return Node.hasAttr<clang::CUDAHostAttr>();
3677 }
3678
3679 /// \brief  Matches declaration that has CUDA global attribute.
3680 ///
3681 /// Given
3682 /// \code
3683 ///   __attribute__((global)) void f() { ... }
3684 /// \endcode
3685 /// matches the function declaration of f.
3686 AST_MATCHER(Decl, hasCudaGlobalAttr) {
3687   return Node.hasAttr<clang::CUDAGlobalAttr>();
3688 }
3689
3690 } // end namespace ast_matchers
3691 } // end namespace clang
3692
3693 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H