]> granicus.if.org Git - clang/blob - include/clang/ASTMatchers/ASTMatchers.h
[ASTMatchers] Existing matcher hasAnyArgument fixed
[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 //    cxxRecordDecl(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 //    cxxRecordDecl(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 RecordDecl 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_ASTMATCHERS_ASTMATCHERS_H
46 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
47
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/DeclFriend.h"
50 #include "clang/AST/DeclObjC.h"
51 #include "clang/AST/DeclTemplate.h"
52 #include "clang/ASTMatchers/ASTMatchersInternal.h"
53 #include "clang/ASTMatchers/ASTMatchersMacros.h"
54 #include "llvm/ADT/Twine.h"
55 #include "llvm/Support/Regex.h"
56 #include <iterator>
57
58 namespace clang {
59 namespace ast_matchers {
60
61 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
62 ///
63 /// The bound nodes are generated by calling \c bind("id") on the node matchers
64 /// of the nodes we want to access later.
65 ///
66 /// The instances of BoundNodes are created by \c MatchFinder when the user's
67 /// callbacks are executed every time a match is found.
68 class BoundNodes {
69 public:
70   /// \brief Returns the AST node bound to \c ID.
71   ///
72   /// Returns NULL if there was no node bound to \c ID or if there is a node but
73   /// it cannot be converted to the specified type.
74   template <typename T>
75   const T *getNodeAs(StringRef ID) const {
76     return MyBoundNodes.getNodeAs<T>(ID);
77   }
78
79   /// \brief Deprecated. Please use \c getNodeAs instead.
80   /// @{
81   template <typename T>
82   const T *getDeclAs(StringRef ID) const {
83     return getNodeAs<T>(ID);
84   }
85   template <typename T>
86   const T *getStmtAs(StringRef ID) const {
87     return getNodeAs<T>(ID);
88   }
89   /// @}
90
91   /// \brief Type of mapping from binding identifiers to bound nodes. This type
92   /// is an associative container with a key type of \c std::string and a value
93   /// type of \c clang::ast_type_traits::DynTypedNode
94   typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
95
96   /// \brief Retrieve mapping from binding identifiers to bound nodes.
97   const IDToNodeMap &getMap() const {
98     return MyBoundNodes.getMap();
99   }
100
101 private:
102   /// \brief Create BoundNodes from a pre-filled map of bindings.
103   BoundNodes(internal::BoundNodesMap &MyBoundNodes)
104       : MyBoundNodes(MyBoundNodes) {}
105
106   internal::BoundNodesMap MyBoundNodes;
107
108   friend class internal::BoundNodesTreeBuilder;
109 };
110
111 /// \brief If the provided matcher matches a node, binds the node to \c ID.
112 ///
113 /// FIXME: Do we want to support this now that we have bind()?
114 template <typename T>
115 internal::Matcher<T> id(StringRef ID,
116                         const internal::BindableMatcher<T> &InnerMatcher) {
117   return InnerMatcher.bind(ID);
118 }
119
120 /// \brief Types of matchers for the top-level classes in the AST class
121 /// hierarchy.
122 /// @{
123 typedef internal::Matcher<Decl> DeclarationMatcher;
124 typedef internal::Matcher<Stmt> StatementMatcher;
125 typedef internal::Matcher<QualType> TypeMatcher;
126 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
127 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
128 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
129 /// @}
130
131 /// \brief Matches any node.
132 ///
133 /// Useful when another matcher requires a child matcher, but there's no
134 /// additional constraint. This will often be used with an explicit conversion
135 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
136 ///
137 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
138 /// \code
139 /// "int* p" and "void f()" in
140 ///   int* p;
141 ///   void f();
142 /// \endcode
143 ///
144 /// Usable as: Any Matcher
145 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
146
147 /// \brief Matches the top declaration context.
148 ///
149 /// Given
150 /// \code
151 ///   int X;
152 ///   namespace NS {
153 ///   int Y;
154 ///   }  // namespace NS
155 /// \endcode
156 /// decl(hasDeclContext(translationUnitDecl()))
157 ///   matches "int X", but not "int Y".
158 const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
159     translationUnitDecl;
160
161 /// \brief Matches typedef declarations.
162 ///
163 /// Given
164 /// \code
165 ///   typedef int X;
166 /// \endcode
167 /// typedefDecl()
168 ///   matches "typedef int X"
169 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
170
171 /// \brief Matches AST nodes that were expanded within the main-file.
172 ///
173 /// Example matches X but not Y
174 ///   (matcher = cxxRecordDecl(isExpansionInMainFile())
175 /// \code
176 ///   #include <Y.h>
177 ///   class X {};
178 /// \endcode
179 /// Y.h:
180 /// \code
181 ///   class Y {};
182 /// \endcode
183 ///
184 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
185 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
186                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
187   auto &SourceManager = Finder->getASTContext().getSourceManager();
188   return SourceManager.isInMainFile(
189       SourceManager.getExpansionLoc(Node.getLocStart()));
190 }
191
192 /// \brief Matches AST nodes that were expanded within system-header-files.
193 ///
194 /// Example matches Y but not X
195 ///     (matcher = cxxRecordDecl(isExpansionInSystemHeader())
196 /// \code
197 ///   #include <SystemHeader.h>
198 ///   class X {};
199 /// \endcode
200 /// SystemHeader.h:
201 /// \code
202 ///   class Y {};
203 /// \endcode
204 ///
205 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
206 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
207                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
208   auto &SourceManager = Finder->getASTContext().getSourceManager();
209   auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
210   if (ExpansionLoc.isInvalid()) {
211     return false;
212   }
213   return SourceManager.isInSystemHeader(ExpansionLoc);
214 }
215
216 /// \brief Matches AST nodes that were expanded within files whose name is
217 /// partially matching a given regex.
218 ///
219 /// Example matches Y but not X
220 ///     (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
221 /// \code
222 ///   #include "ASTMatcher.h"
223 ///   class X {};
224 /// \endcode
225 /// ASTMatcher.h:
226 /// \code
227 ///   class Y {};
228 /// \endcode
229 ///
230 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
231 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
232                           AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
233                           std::string, RegExp) {
234   auto &SourceManager = Finder->getASTContext().getSourceManager();
235   auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
236   if (ExpansionLoc.isInvalid()) {
237     return false;
238   }
239   auto FileEntry =
240       SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
241   if (!FileEntry) {
242     return false;
243   }
244
245   auto Filename = FileEntry->getName();
246   llvm::Regex RE(RegExp);
247   return RE.match(Filename);
248 }
249
250 /// \brief Matches declarations.
251 ///
252 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
253 /// \code
254 ///   void X();
255 ///   class C {
256 ///     friend X;
257 ///   };
258 /// \endcode
259 const internal::VariadicAllOfMatcher<Decl> decl;
260
261 /// \brief Matches a declaration of a linkage specification.
262 ///
263 /// Given
264 /// \code
265 ///   extern "C" {}
266 /// \endcode
267 /// linkageSpecDecl()
268 ///   matches "extern "C" {}"
269 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
270     linkageSpecDecl;
271
272 /// \brief Matches a declaration of anything that could have a name.
273 ///
274 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
275 /// \code
276 ///   typedef int X;
277 ///   struct S {
278 ///     union {
279 ///       int i;
280 ///     } U;
281 ///   };
282 /// \endcode
283 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
284
285 /// \brief Matches a declaration of label.
286 ///
287 /// Given
288 /// \code
289 ///   goto FOO;
290 ///   FOO: bar();
291 /// \endcode
292 /// labelDecl()
293 ///   matches 'FOO:'
294 const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
295
296 /// \brief Matches a declaration of a namespace.
297 ///
298 /// Given
299 /// \code
300 ///   namespace {}
301 ///   namespace test {}
302 /// \endcode
303 /// namespaceDecl()
304 ///   matches "namespace {}" and "namespace test {}"
305 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
306
307 /// \brief Matches a declaration of a namespace alias.
308 ///
309 /// Given
310 /// \code
311 ///   namespace test {}
312 ///   namespace alias = ::test;
313 /// \endcode
314 /// namespaceAliasDecl()
315 ///   matches "namespace alias" but not "namespace test"
316 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
317     namespaceAliasDecl;
318
319 /// \brief Matches class, struct, and union declarations.
320 ///
321 /// Example matches \c X, \c Z, \c U, and \c S
322 /// \code
323 ///   class X;
324 ///   template<class T> class Z {};
325 ///   struct S {};
326 ///   union U {};
327 /// \endcode
328 const internal::VariadicDynCastAllOfMatcher<
329   Decl,
330   RecordDecl> recordDecl;
331
332 /// \brief Matches C++ class declarations.
333 ///
334 /// Example matches \c X, \c Z
335 /// \code
336 ///   class X;
337 ///   template<class T> class Z {};
338 /// \endcode
339 const internal::VariadicDynCastAllOfMatcher<
340   Decl,
341   CXXRecordDecl> cxxRecordDecl;
342
343 /// \brief Matches C++ class template declarations.
344 ///
345 /// Example matches \c Z
346 /// \code
347 ///   template<class T> class Z {};
348 /// \endcode
349 const internal::VariadicDynCastAllOfMatcher<
350   Decl,
351   ClassTemplateDecl> classTemplateDecl;
352
353 /// \brief Matches C++ class template specializations.
354 ///
355 /// Given
356 /// \code
357 ///   template<typename T> class A {};
358 ///   template<> class A<double> {};
359 ///   A<int> a;
360 /// \endcode
361 /// classTemplateSpecializationDecl()
362 ///   matches the specializations \c A<int> and \c A<double>
363 const internal::VariadicDynCastAllOfMatcher<
364   Decl,
365   ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
366
367 /// \brief Matches declarator declarations (field, variable, function
368 /// and non-type template parameter declarations).
369 ///
370 /// Given
371 /// \code
372 ///   class X { int y; };
373 /// \endcode
374 /// declaratorDecl()
375 ///   matches \c int y.
376 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
377     declaratorDecl;
378
379 /// \brief Matches parameter variable declarations.
380 ///
381 /// Given
382 /// \code
383 ///   void f(int x);
384 /// \endcode
385 /// parmVarDecl()
386 ///   matches \c int x.
387 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
388
389 /// \brief Matches C++ access specifier declarations.
390 ///
391 /// Given
392 /// \code
393 ///   class C {
394 ///   public:
395 ///     int a;
396 ///   };
397 /// \endcode
398 /// accessSpecDecl()
399 ///   matches 'public:'
400 const internal::VariadicDynCastAllOfMatcher<
401   Decl,
402   AccessSpecDecl> accessSpecDecl;
403
404 /// \brief Matches constructor initializers.
405 ///
406 /// Examples matches \c i(42).
407 /// \code
408 ///   class C {
409 ///     C() : i(42) {}
410 ///     int i;
411 ///   };
412 /// \endcode
413 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
414
415 /// \brief Matches template arguments.
416 ///
417 /// Given
418 /// \code
419 ///   template <typename T> struct C {};
420 ///   C<int> c;
421 /// \endcode
422 /// templateArgument()
423 ///   matches 'int' in C<int>.
424 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
425
426 /// \brief Matches non-type template parameter declarations.
427 ///
428 /// Given
429 /// \code
430 ///   template <typename T, int N> struct C {};
431 /// \endcode
432 /// nonTypeTemplateParmDecl()
433 ///   matches 'N', but not 'T'.
434 const internal::VariadicDynCastAllOfMatcher<
435   Decl,
436   NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
437
438 /// \brief Matches template type parameter declarations.
439 ///
440 /// Given
441 /// \code
442 ///   template <typename T, int N> struct C {};
443 /// \endcode
444 /// templateTypeParmDecl()
445 ///   matches 'T', but not 'N'.
446 const internal::VariadicDynCastAllOfMatcher<
447   Decl,
448   TemplateTypeParmDecl> templateTypeParmDecl;
449
450 /// \brief Matches public C++ declarations.
451 ///
452 /// Given
453 /// \code
454 ///   class C {
455 ///   public:    int a;
456 ///   protected: int b;
457 ///   private:   int c;
458 ///   };
459 /// \endcode
460 /// fieldDecl(isPublic())
461 ///   matches 'int a;' 
462 AST_MATCHER(Decl, isPublic) {
463   return Node.getAccess() == AS_public;
464 }
465
466 /// \brief Matches protected C++ declarations.
467 ///
468 /// Given
469 /// \code
470 ///   class C {
471 ///   public:    int a;
472 ///   protected: int b;
473 ///   private:   int c;
474 ///   };
475 /// \endcode
476 /// fieldDecl(isProtected())
477 ///   matches 'int b;' 
478 AST_MATCHER(Decl, isProtected) {
479   return Node.getAccess() == AS_protected;
480 }
481
482 /// \brief Matches private C++ declarations.
483 ///
484 /// Given
485 /// \code
486 ///   class C {
487 ///   public:    int a;
488 ///   protected: int b;
489 ///   private:   int c;
490 ///   };
491 /// \endcode
492 /// fieldDecl(isPrivate())
493 ///   matches 'int c;' 
494 AST_MATCHER(Decl, isPrivate) {
495   return Node.getAccess() == AS_private;
496 }
497
498 /// \brief Matches a declaration that has been implicitly added
499 /// by the compiler (eg. implicit default/copy constructors).
500 AST_MATCHER(Decl, isImplicit) {
501   return Node.isImplicit();
502 }
503
504 /// \brief Matches classTemplateSpecializations that have at least one
505 /// TemplateArgument matching the given InnerMatcher.
506 ///
507 /// Given
508 /// \code
509 ///   template<typename T> class A {};
510 ///   template<> class A<double> {};
511 ///   A<int> a;
512 /// \endcode
513 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
514 ///     refersToType(asString("int"))))
515 ///   matches the specialization \c A<int>
516 AST_POLYMORPHIC_MATCHER_P(
517     hasAnyTemplateArgument,
518     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
519                                     TemplateSpecializationType),
520     internal::Matcher<TemplateArgument>, InnerMatcher) {
521   ArrayRef<TemplateArgument> List =
522       internal::getTemplateSpecializationArgs(Node);
523   return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
524                              Builder);
525 }
526
527 /// \brief Matches expressions that match InnerMatcher after any implicit casts
528 /// are stripped off.
529 ///
530 /// Parentheses and explicit casts are not discarded.
531 /// Given
532 /// \code
533 ///   int arr[5];
534 ///   int a = 0;
535 ///   char b = 0;
536 ///   const int c = a;
537 ///   int *d = arr;
538 ///   long e = (long) 0l;
539 /// \endcode
540 /// The matchers
541 /// \code
542 ///    varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
543 ///    varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
544 /// \endcode
545 /// would match the declarations for a, b, c, and d, but not e.
546 /// While
547 /// \code
548 ///    varDecl(hasInitializer(integerLiteral()))
549 ///    varDecl(hasInitializer(declRefExpr()))
550 /// \endcode
551 /// only match the declarations for b, c, and d.
552 AST_MATCHER_P(Expr, ignoringImpCasts,
553               internal::Matcher<Expr>, InnerMatcher) {
554   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
555 }
556
557 /// \brief Matches expressions that match InnerMatcher after parentheses and
558 /// casts are stripped off.
559 ///
560 /// Implicit and non-C Style casts are also discarded.
561 /// Given
562 /// \code
563 ///   int a = 0;
564 ///   char b = (0);
565 ///   void* c = reinterpret_cast<char*>(0);
566 ///   char d = char(0);
567 /// \endcode
568 /// The matcher
569 ///    varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
570 /// would match the declarations for a, b, c, and d.
571 /// while
572 ///    varDecl(hasInitializer(integerLiteral()))
573 /// only match the declaration for a.
574 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
575   return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
576 }
577
578 /// \brief Matches expressions that match InnerMatcher after implicit casts and
579 /// parentheses are stripped off.
580 ///
581 /// Explicit casts are not discarded.
582 /// Given
583 /// \code
584 ///   int arr[5];
585 ///   int a = 0;
586 ///   char b = (0);
587 ///   const int c = a;
588 ///   int *d = (arr);
589 ///   long e = ((long) 0l);
590 /// \endcode
591 /// The matchers
592 ///    varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
593 ///    varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
594 /// would match the declarations for a, b, c, and d, but not e.
595 /// while
596 ///    varDecl(hasInitializer(integerLiteral()))
597 ///    varDecl(hasInitializer(declRefExpr()))
598 /// would only match the declaration for a.
599 AST_MATCHER_P(Expr, ignoringParenImpCasts,
600               internal::Matcher<Expr>, InnerMatcher) {
601   return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
602 }
603
604 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
605 /// matches the given InnerMatcher.
606 ///
607 /// Given
608 /// \code
609 ///   template<typename T, typename U> class A {};
610 ///   A<bool, int> b;
611 ///   A<int, bool> c;
612 /// \endcode
613 /// classTemplateSpecializationDecl(hasTemplateArgument(
614 ///     1, refersToType(asString("int"))))
615 ///   matches the specialization \c A<bool, int>
616 AST_POLYMORPHIC_MATCHER_P2(
617     hasTemplateArgument,
618     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
619                                     TemplateSpecializationType),
620     unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
621   ArrayRef<TemplateArgument> List =
622       internal::getTemplateSpecializationArgs(Node);
623   if (List.size() <= N)
624     return false;
625   return InnerMatcher.matches(List[N], Finder, Builder);
626 }
627
628 /// \brief Matches if the number of template arguments equals \p N.
629 ///
630 /// Given
631 /// \code
632 ///   template<typename T> struct C {};
633 ///   C<int> c;
634 /// \endcode
635 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
636 ///   matches C<int>.
637 AST_POLYMORPHIC_MATCHER_P(
638     templateArgumentCountIs,
639     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
640                                     TemplateSpecializationType),
641     unsigned, N) {
642   return internal::getTemplateSpecializationArgs(Node).size() == N;
643 }
644
645 /// \brief Matches a TemplateArgument that refers to a certain type.
646 ///
647 /// Given
648 /// \code
649 ///   struct X {};
650 ///   template<typename T> struct A {};
651 ///   A<X> a;
652 /// \endcode
653 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
654 ///     refersToType(class(hasName("X")))))
655 ///   matches the specialization \c A<X>
656 AST_MATCHER_P(TemplateArgument, refersToType,
657               internal::Matcher<QualType>, InnerMatcher) {
658   if (Node.getKind() != TemplateArgument::Type)
659     return false;
660   return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
661 }
662
663 /// \brief Matches a canonical TemplateArgument that refers to a certain
664 /// declaration.
665 ///
666 /// Given
667 /// \code
668 ///   template<typename T> struct A {};
669 ///   struct B { B* next; };
670 ///   A<&B::next> a;
671 /// \endcode
672 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
673 ///     refersToDeclaration(fieldDecl(hasName("next"))))
674 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
675 ///     \c B::next
676 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
677               internal::Matcher<Decl>, InnerMatcher) {
678   if (Node.getKind() == TemplateArgument::Declaration)
679     return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
680   return false;
681 }
682
683 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
684 ///
685 /// Given
686 /// \code
687 ///   template<typename T> struct A {};
688 ///   struct B { B* next; };
689 ///   A<&B::next> a;
690 /// \endcode
691 /// templateSpecializationType(hasAnyTemplateArgument(
692 ///   isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
693 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
694 ///     \c B::next
695 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
696   if (Node.getKind() == TemplateArgument::Expression)
697     return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
698   return false;
699 }
700
701 /// \brief Matches a TemplateArgument that is an integral value.
702 ///
703 /// Given
704 /// \code
705 ///   template<int T> struct A {};
706 ///   C<42> c;
707 /// \endcode
708 /// classTemplateSpecializationDecl(
709 ///   hasAnyTemplateArgument(isIntegral()))
710 ///   matches the implicit instantiation of C in C<42>
711 ///   with isIntegral() matching 42.
712 AST_MATCHER(TemplateArgument, isIntegral) {
713   return Node.getKind() == TemplateArgument::Integral;
714 }
715
716 /// \brief Matches a TemplateArgument that referes to an integral type.
717 ///
718 /// Given
719 /// \code
720 ///   template<int T> struct A {};
721 ///   C<42> c;
722 /// \endcode
723 /// classTemplateSpecializationDecl(
724 ///   hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
725 ///   matches the implicit instantiation of C in C<42>.
726 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
727               internal::Matcher<QualType>, InnerMatcher) {
728   if (Node.getKind() != TemplateArgument::Integral)
729     return false;
730   return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
731 }
732
733 /// \brief Matches a TemplateArgument of integral type with a given value.
734 ///
735 /// Note that 'Value' is a string as the template argument's value is
736 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
737 /// representation of that integral value in base 10.
738 ///
739 /// Given
740 /// \code
741 ///   template<int T> struct A {};
742 ///   C<42> c;
743 /// \endcode
744 /// classTemplateSpecializationDecl(
745 ///   hasAnyTemplateArgument(equalsIntegralValue("42")))
746 ///   matches the implicit instantiation of C in C<42>.
747 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
748               std::string, Value) {
749   if (Node.getKind() != TemplateArgument::Integral)
750     return false;
751   return Node.getAsIntegral().toString(10) == Value;
752 }
753
754 /// \brief Matches any value declaration.
755 ///
756 /// Example matches A, B, C and F
757 /// \code
758 ///   enum X { A, B, C };
759 ///   void F();
760 /// \endcode
761 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
762
763 /// \brief Matches C++ constructor declarations.
764 ///
765 /// Example matches Foo::Foo() and Foo::Foo(int)
766 /// \code
767 ///   class Foo {
768 ///    public:
769 ///     Foo();
770 ///     Foo(int);
771 ///     int DoSomething();
772 ///   };
773 /// \endcode
774 const internal::VariadicDynCastAllOfMatcher<
775   Decl,
776   CXXConstructorDecl> cxxConstructorDecl;
777
778 /// \brief Matches explicit C++ destructor declarations.
779 ///
780 /// Example matches Foo::~Foo()
781 /// \code
782 ///   class Foo {
783 ///    public:
784 ///     virtual ~Foo();
785 ///   };
786 /// \endcode
787 const internal::VariadicDynCastAllOfMatcher<
788   Decl,
789   CXXDestructorDecl> cxxDestructorDecl;
790
791 /// \brief Matches enum declarations.
792 ///
793 /// Example matches X
794 /// \code
795 ///   enum X {
796 ///     A, B, C
797 ///   };
798 /// \endcode
799 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
800
801 /// \brief Matches enum constants.
802 ///
803 /// Example matches A, B, C
804 /// \code
805 ///   enum X {
806 ///     A, B, C
807 ///   };
808 /// \endcode
809 const internal::VariadicDynCastAllOfMatcher<
810   Decl,
811   EnumConstantDecl> enumConstantDecl;
812
813 /// \brief Matches method declarations.
814 ///
815 /// Example matches y
816 /// \code
817 ///   class X { void y(); };
818 /// \endcode
819 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
820
821 /// \brief Matches conversion operator declarations.
822 ///
823 /// Example matches the operator.
824 /// \code
825 ///   class X { operator int() const; };
826 /// \endcode
827 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
828     cxxConversionDecl;
829
830 /// \brief Matches variable declarations.
831 ///
832 /// Note: this does not match declarations of member variables, which are
833 /// "field" declarations in Clang parlance.
834 ///
835 /// Example matches a
836 /// \code
837 ///   int a;
838 /// \endcode
839 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
840
841 /// \brief Matches field declarations.
842 ///
843 /// Given
844 /// \code
845 ///   class X { int m; };
846 /// \endcode
847 /// fieldDecl()
848 ///   matches 'm'.
849 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
850
851 /// \brief Matches function declarations.
852 ///
853 /// Example matches f
854 /// \code
855 ///   void f();
856 /// \endcode
857 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
858
859 /// \brief Matches C++ function template declarations.
860 ///
861 /// Example matches f
862 /// \code
863 ///   template<class T> void f(T t) {}
864 /// \endcode
865 const internal::VariadicDynCastAllOfMatcher<
866   Decl,
867   FunctionTemplateDecl> functionTemplateDecl;
868
869 /// \brief Matches friend declarations.
870 ///
871 /// Given
872 /// \code
873 ///   class X { friend void foo(); };
874 /// \endcode
875 /// friendDecl()
876 ///   matches 'friend void foo()'.
877 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
878
879 /// \brief Matches statements.
880 ///
881 /// Given
882 /// \code
883 ///   { ++a; }
884 /// \endcode
885 /// stmt()
886 ///   matches both the compound statement '{ ++a; }' and '++a'.
887 const internal::VariadicAllOfMatcher<Stmt> stmt;
888
889 /// \brief Matches declaration statements.
890 ///
891 /// Given
892 /// \code
893 ///   int a;
894 /// \endcode
895 /// declStmt()
896 ///   matches 'int a'.
897 const internal::VariadicDynCastAllOfMatcher<
898   Stmt,
899   DeclStmt> declStmt;
900
901 /// \brief Matches member expressions.
902 ///
903 /// Given
904 /// \code
905 ///   class Y {
906 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
907 ///     int a; static int b;
908 ///   };
909 /// \endcode
910 /// memberExpr()
911 ///   matches this->x, x, y.x, a, this->b
912 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
913
914 /// \brief Matches call expressions.
915 ///
916 /// Example matches x.y() and y()
917 /// \code
918 ///   X x;
919 ///   x.y();
920 ///   y();
921 /// \endcode
922 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
923
924 /// \brief Matches lambda expressions.
925 ///
926 /// Example matches [&](){return 5;}
927 /// \code
928 ///   [&](){return 5;}
929 /// \endcode
930 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
931
932 /// \brief Matches member call expressions.
933 ///
934 /// Example matches x.y()
935 /// \code
936 ///   X x;
937 ///   x.y();
938 /// \endcode
939 const internal::VariadicDynCastAllOfMatcher<
940   Stmt,
941   CXXMemberCallExpr> cxxMemberCallExpr;
942
943 /// \brief Matches ObjectiveC Message invocation expressions.
944 ///
945 /// The innermost message send invokes the "alloc" class method on the
946 /// NSString class, while the outermost message send invokes the
947 /// "initWithString" instance method on the object returned from
948 /// NSString's "alloc". This matcher should match both message sends.
949 /// \code
950 ///   [[NSString alloc] initWithString:@"Hello"]
951 /// \endcode
952 const internal::VariadicDynCastAllOfMatcher<
953   Stmt,
954   ObjCMessageExpr> objcMessageExpr;
955
956 /// \brief Matches Objective-C interface declarations.
957 ///
958 /// Example matches Foo
959 /// \code
960 ///   @interface Foo
961 ///   @end
962 /// \endcode
963 const internal::VariadicDynCastAllOfMatcher<
964   Decl,
965   ObjCInterfaceDecl> objcInterfaceDecl;
966
967 /// \brief Matches expressions that introduce cleanups to be run at the end
968 /// of the sub-expression's evaluation.
969 ///
970 /// Example matches std::string()
971 /// \code
972 ///   const std::string str = std::string();
973 /// \endcode
974 const internal::VariadicDynCastAllOfMatcher<
975   Stmt,
976   ExprWithCleanups> exprWithCleanups;
977
978 /// \brief Matches init list expressions.
979 ///
980 /// Given
981 /// \code
982 ///   int a[] = { 1, 2 };
983 ///   struct B { int x, y; };
984 ///   B b = { 5, 6 };
985 /// \endcode
986 /// initListExpr()
987 ///   matches "{ 1, 2 }" and "{ 5, 6 }"
988 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
989
990 /// \brief Matches the syntactic form of init list expressions
991 /// (if expression have it).
992 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
993               internal::Matcher<Expr>, InnerMatcher) {
994   const Expr *SyntForm = Node.getSyntacticForm();
995   return (SyntForm != nullptr &&
996           InnerMatcher.matches(*SyntForm, Finder, Builder));
997 }
998
999 /// \brief Matches implicit initializers of init list expressions.
1000 ///
1001 /// Given
1002 /// \code
1003 ///   point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1004 /// \endcode
1005 /// implicitValueInitExpr()
1006 ///   matches "[0].y" (implicitly)
1007 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1008 implicitValueInitExpr;
1009
1010 /// \brief Matches paren list expressions.
1011 /// ParenListExprs don't have a predefined type and are used for late parsing.
1012 /// In the final AST, they can be met in template declarations.
1013 ///
1014 /// Given
1015 /// \code
1016 ///   template<typename T> class X {
1017 ///     void f() {
1018 ///       X x(*this);
1019 ///       int a = 0, b = 1; int i = (a, b);
1020 ///     }
1021 ///   };
1022 /// \endcode
1023 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1024 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1025 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr;
1026
1027 /// \brief Matches substitutions of non-type template parameters.
1028 ///
1029 /// Given
1030 /// \code
1031 ///   template <int N>
1032 ///   struct A { static const int n = N; };
1033 ///   struct B : public A<42> {};
1034 /// \endcode
1035 /// substNonTypeTemplateParmExpr()
1036 ///   matches "N" in the right-hand side of "static const int n = N;"
1037 const internal::VariadicDynCastAllOfMatcher<
1038   Stmt,
1039   SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
1040
1041 /// \brief Matches using declarations.
1042 ///
1043 /// Given
1044 /// \code
1045 ///   namespace X { int x; }
1046 ///   using X::x;
1047 /// \endcode
1048 /// usingDecl()
1049 ///   matches \code using X::x \endcode
1050 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1051
1052 /// \brief Matches using namespace declarations.
1053 ///
1054 /// Given
1055 /// \code
1056 ///   namespace X { int x; }
1057 ///   using namespace X;
1058 /// \endcode
1059 /// usingDirectiveDecl()
1060 ///   matches \code using namespace X \endcode
1061 const internal::VariadicDynCastAllOfMatcher<
1062   Decl,
1063   UsingDirectiveDecl> usingDirectiveDecl;
1064
1065 /// \brief Matches unresolved using value declarations.
1066 ///
1067 /// Given
1068 /// \code
1069 ///   template<typename X>
1070 ///   class C : private X {
1071 ///     using X::x;
1072 ///   };
1073 /// \endcode
1074 /// unresolvedUsingValueDecl()
1075 ///   matches \code using X::x \endcode
1076 const internal::VariadicDynCastAllOfMatcher<
1077   Decl,
1078   UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1079
1080 /// \brief Matches unresolved using value declarations that involve the
1081 /// typename.
1082 ///
1083 /// Given
1084 /// \code
1085 ///   template <typename T>
1086 ///   struct Base { typedef T Foo; };
1087 ///
1088 ///   template<typename T>
1089 ///   struct S : private Base<T> {
1090 ///     using typename Base<T>::Foo;
1091 ///   };
1092 /// \endcode
1093 /// unresolvedUsingTypenameDecl()
1094 ///   matches \code using Base<T>::Foo \endcode
1095 const internal::VariadicDynCastAllOfMatcher<
1096   Decl,
1097   UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1098
1099 /// \brief Matches parentheses used in expressions.
1100 ///
1101 /// Example matches (foo() + 1)
1102 /// \code
1103 ///   int foo() { return 1; }
1104 ///   int a = (foo() + 1);
1105 /// \endcode
1106 const internal::VariadicDynCastAllOfMatcher<
1107   Stmt,
1108   ParenExpr> parenExpr;
1109
1110 /// \brief Matches constructor call expressions (including implicit ones).
1111 ///
1112 /// Example matches string(ptr, n) and ptr within arguments of f
1113 ///     (matcher = cxxConstructExpr())
1114 /// \code
1115 ///   void f(const string &a, const string &b);
1116 ///   char *ptr;
1117 ///   int n;
1118 ///   f(string(ptr, n), ptr);
1119 /// \endcode
1120 const internal::VariadicDynCastAllOfMatcher<
1121   Stmt,
1122   CXXConstructExpr> cxxConstructExpr;
1123
1124 /// \brief Matches unresolved constructor call expressions.
1125 ///
1126 /// Example matches T(t) in return statement of f
1127 ///     (matcher = cxxUnresolvedConstructExpr())
1128 /// \code
1129 ///   template <typename T>
1130 ///   void f(const T& t) { return T(t); }
1131 /// \endcode
1132 const internal::VariadicDynCastAllOfMatcher<
1133   Stmt,
1134   CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1135
1136 /// \brief Matches implicit and explicit this expressions.
1137 ///
1138 /// Example matches the implicit this expression in "return i".
1139 ///     (matcher = cxxThisExpr())
1140 /// \code
1141 /// struct foo {
1142 ///   int i;
1143 ///   int f() { return i; }
1144 /// };
1145 /// \endcode
1146 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1147
1148 /// \brief Matches nodes where temporaries are created.
1149 ///
1150 /// Example matches FunctionTakesString(GetStringByValue())
1151 ///     (matcher = cxxBindTemporaryExpr())
1152 /// \code
1153 ///   FunctionTakesString(GetStringByValue());
1154 ///   FunctionTakesStringByPointer(GetStringPointer());
1155 /// \endcode
1156 const internal::VariadicDynCastAllOfMatcher<
1157   Stmt,
1158   CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1159
1160 /// \brief Matches nodes where temporaries are materialized.
1161 ///
1162 /// Example: Given
1163 /// \code
1164 ///   struct T {void func()};
1165 ///   T f();
1166 ///   void g(T);
1167 /// \endcode
1168 /// materializeTemporaryExpr() matches 'f()' in these statements
1169 /// \code
1170 ///   T u(f());
1171 ///   g(f());
1172 /// \endcode
1173 /// but does not match
1174 /// \code
1175 ///   f();
1176 ///   f().func();
1177 /// \endcode
1178 const internal::VariadicDynCastAllOfMatcher<
1179   Stmt,
1180   MaterializeTemporaryExpr> materializeTemporaryExpr;
1181
1182 /// \brief Matches new expressions.
1183 ///
1184 /// Given
1185 /// \code
1186 ///   new X;
1187 /// \endcode
1188 /// cxxNewExpr()
1189 ///   matches 'new X'.
1190 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1191
1192 /// \brief Matches delete expressions.
1193 ///
1194 /// Given
1195 /// \code
1196 ///   delete X;
1197 /// \endcode
1198 /// cxxDeleteExpr()
1199 ///   matches 'delete X'.
1200 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1201
1202 /// \brief Matches array subscript expressions.
1203 ///
1204 /// Given
1205 /// \code
1206 ///   int i = a[1];
1207 /// \endcode
1208 /// arraySubscriptExpr()
1209 ///   matches "a[1]"
1210 const internal::VariadicDynCastAllOfMatcher<
1211   Stmt,
1212   ArraySubscriptExpr> arraySubscriptExpr;
1213
1214 /// \brief Matches the value of a default argument at the call site.
1215 ///
1216 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1217 ///     default value of the second parameter in the call expression f(42)
1218 ///     (matcher = cxxDefaultArgExpr())
1219 /// \code
1220 ///   void f(int x, int y = 0);
1221 ///   f(42);
1222 /// \endcode
1223 const internal::VariadicDynCastAllOfMatcher<
1224   Stmt,
1225   CXXDefaultArgExpr> cxxDefaultArgExpr;
1226
1227 /// \brief Matches overloaded operator calls.
1228 ///
1229 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1230 /// binaryOperator matcher.
1231 /// Currently it does not match operators such as new delete.
1232 /// FIXME: figure out why these do not match?
1233 ///
1234 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1235 ///     (matcher = cxxOperatorCallExpr())
1236 /// \code
1237 ///   ostream &operator<< (ostream &out, int i) { };
1238 ///   ostream &o; int b = 1, c = 1;
1239 ///   o << b << c;
1240 /// \endcode
1241 const internal::VariadicDynCastAllOfMatcher<
1242   Stmt,
1243   CXXOperatorCallExpr> cxxOperatorCallExpr;
1244
1245 /// \brief Matches expressions.
1246 ///
1247 /// Example matches x()
1248 /// \code
1249 ///   void f() { x(); }
1250 /// \endcode
1251 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1252
1253 /// \brief Matches expressions that refer to declarations.
1254 ///
1255 /// Example matches x in if (x)
1256 /// \code
1257 ///   bool x;
1258 ///   if (x) {}
1259 /// \endcode
1260 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1261
1262 /// \brief Matches if statements.
1263 ///
1264 /// Example matches 'if (x) {}'
1265 /// \code
1266 ///   if (x) {}
1267 /// \endcode
1268 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1269
1270 /// \brief Matches for statements.
1271 ///
1272 /// Example matches 'for (;;) {}'
1273 /// \code
1274 ///   for (;;) {}
1275 ///   int i[] =  {1, 2, 3}; for (auto a : i);
1276 /// \endcode
1277 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1278
1279 /// \brief Matches the increment statement of a for loop.
1280 ///
1281 /// Example:
1282 ///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1283 /// matches '++x' in
1284 /// \code
1285 ///     for (x; x < N; ++x) { }
1286 /// \endcode
1287 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1288               InnerMatcher) {
1289   const Stmt *const Increment = Node.getInc();
1290   return (Increment != nullptr &&
1291           InnerMatcher.matches(*Increment, Finder, Builder));
1292 }
1293
1294 /// \brief Matches the initialization statement of a for loop.
1295 ///
1296 /// Example:
1297 ///     forStmt(hasLoopInit(declStmt()))
1298 /// matches 'int x = 0' in
1299 /// \code
1300 ///     for (int x = 0; x < N; ++x) { }
1301 /// \endcode
1302 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1303               InnerMatcher) {
1304   const Stmt *const Init = Node.getInit();
1305   return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1306 }
1307
1308 /// \brief Matches range-based for statements.
1309 ///
1310 /// cxxForRangeStmt() matches 'for (auto a : i)'
1311 /// \code
1312 ///   int i[] =  {1, 2, 3}; for (auto a : i);
1313 ///   for(int j = 0; j < 5; ++j);
1314 /// \endcode
1315 const internal::VariadicDynCastAllOfMatcher<
1316   Stmt,
1317   CXXForRangeStmt> cxxForRangeStmt;
1318
1319 /// \brief Matches the initialization statement of a for loop.
1320 ///
1321 /// Example:
1322 ///     forStmt(hasLoopVariable(anything()))
1323 /// matches 'int x' in
1324 /// \code
1325 ///     for (int x : a) { }
1326 /// \endcode
1327 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1328               InnerMatcher) {
1329   const VarDecl *const Var = Node.getLoopVariable();
1330   return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1331 }
1332
1333 /// \brief Matches the range initialization statement of a for loop.
1334 ///
1335 /// Example:
1336 ///     forStmt(hasRangeInit(anything()))
1337 /// matches 'a' in
1338 /// \code
1339 ///     for (int x : a) { }
1340 /// \endcode
1341 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1342               InnerMatcher) {
1343   const Expr *const Init = Node.getRangeInit();
1344   return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1345 }
1346
1347 /// \brief Matches while statements.
1348 ///
1349 /// Given
1350 /// \code
1351 ///   while (true) {}
1352 /// \endcode
1353 /// whileStmt()
1354 ///   matches 'while (true) {}'.
1355 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1356
1357 /// \brief Matches do statements.
1358 ///
1359 /// Given
1360 /// \code
1361 ///   do {} while (true);
1362 /// \endcode
1363 /// doStmt()
1364 ///   matches 'do {} while(true)'
1365 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1366
1367 /// \brief Matches break statements.
1368 ///
1369 /// Given
1370 /// \code
1371 ///   while (true) { break; }
1372 /// \endcode
1373 /// breakStmt()
1374 ///   matches 'break'
1375 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1376
1377 /// \brief Matches continue statements.
1378 ///
1379 /// Given
1380 /// \code
1381 ///   while (true) { continue; }
1382 /// \endcode
1383 /// continueStmt()
1384 ///   matches 'continue'
1385 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1386
1387 /// \brief Matches return statements.
1388 ///
1389 /// Given
1390 /// \code
1391 ///   return 1;
1392 /// \endcode
1393 /// returnStmt()
1394 ///   matches 'return 1'
1395 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1396
1397 /// \brief Matches goto statements.
1398 ///
1399 /// Given
1400 /// \code
1401 ///   goto FOO;
1402 ///   FOO: bar();
1403 /// \endcode
1404 /// gotoStmt()
1405 ///   matches 'goto FOO'
1406 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1407
1408 /// \brief Matches label statements.
1409 ///
1410 /// Given
1411 /// \code
1412 ///   goto FOO;
1413 ///   FOO: bar();
1414 /// \endcode
1415 /// labelStmt()
1416 ///   matches 'FOO:'
1417 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1418
1419 /// \brief Matches address of label statements (GNU extension).
1420 ///
1421 /// Given
1422 /// \code
1423 ///   FOO: bar();
1424 ///   void *ptr = &&FOO;
1425 ///   goto *bar;
1426 /// \endcode
1427 /// addrLabelExpr()
1428 ///   matches '&&FOO'
1429 const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr;
1430
1431 /// \brief Matches switch statements.
1432 ///
1433 /// Given
1434 /// \code
1435 ///   switch(a) { case 42: break; default: break; }
1436 /// \endcode
1437 /// switchStmt()
1438 ///   matches 'switch(a)'.
1439 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1440
1441 /// \brief Matches case and default statements inside switch statements.
1442 ///
1443 /// Given
1444 /// \code
1445 ///   switch(a) { case 42: break; default: break; }
1446 /// \endcode
1447 /// switchCase()
1448 ///   matches 'case 42: break;' and 'default: break;'.
1449 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1450
1451 /// \brief Matches case statements inside switch statements.
1452 ///
1453 /// Given
1454 /// \code
1455 ///   switch(a) { case 42: break; default: break; }
1456 /// \endcode
1457 /// caseStmt()
1458 ///   matches 'case 42: break;'.
1459 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1460
1461 /// \brief Matches default statements inside switch statements.
1462 ///
1463 /// Given
1464 /// \code
1465 ///   switch(a) { case 42: break; default: break; }
1466 /// \endcode
1467 /// defaultStmt()
1468 ///   matches 'default: break;'.
1469 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1470
1471 /// \brief Matches compound statements.
1472 ///
1473 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1474 /// \code
1475 ///   for (;;) {{}}
1476 /// \endcode
1477 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1478
1479 /// \brief Matches catch statements.
1480 ///
1481 /// \code
1482 ///   try {} catch(int i) {}
1483 /// \endcode
1484 /// cxxCatchStmt()
1485 ///   matches 'catch(int i)'
1486 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1487
1488 /// \brief Matches try statements.
1489 ///
1490 /// \code
1491 ///   try {} catch(int i) {}
1492 /// \endcode
1493 /// cxxTryStmt()
1494 ///   matches 'try {}'
1495 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1496
1497 /// \brief Matches throw expressions.
1498 ///
1499 /// \code
1500 ///   try { throw 5; } catch(int i) {}
1501 /// \endcode
1502 /// cxxThrowExpr()
1503 ///   matches 'throw 5'
1504 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1505
1506 /// \brief Matches null statements.
1507 ///
1508 /// \code
1509 ///   foo();;
1510 /// \endcode
1511 /// nullStmt()
1512 ///   matches the second ';'
1513 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1514
1515 /// \brief Matches asm statements.
1516 ///
1517 /// \code
1518 ///  int i = 100;
1519 ///   __asm("mov al, 2");
1520 /// \endcode
1521 /// asmStmt()
1522 ///   matches '__asm("mov al, 2")'
1523 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1524
1525 /// \brief Matches bool literals.
1526 ///
1527 /// Example matches true
1528 /// \code
1529 ///   true
1530 /// \endcode
1531 const internal::VariadicDynCastAllOfMatcher<
1532   Stmt,
1533   CXXBoolLiteralExpr> cxxBoolLiteral;
1534
1535 /// \brief Matches string literals (also matches wide string literals).
1536 ///
1537 /// Example matches "abcd", L"abcd"
1538 /// \code
1539 ///   char *s = "abcd"; wchar_t *ws = L"abcd"
1540 /// \endcode
1541 const internal::VariadicDynCastAllOfMatcher<
1542   Stmt,
1543   StringLiteral> stringLiteral;
1544
1545 /// \brief Matches character literals (also matches wchar_t).
1546 ///
1547 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1548 /// though.
1549 ///
1550 /// Example matches 'a', L'a'
1551 /// \code
1552 ///   char ch = 'a'; wchar_t chw = L'a';
1553 /// \endcode
1554 const internal::VariadicDynCastAllOfMatcher<
1555   Stmt,
1556   CharacterLiteral> characterLiteral;
1557
1558 /// \brief Matches integer literals of all sizes / encodings, e.g.
1559 /// 1, 1L, 0x1 and 1U.
1560 ///
1561 /// Does not match character-encoded integers such as L'a'.
1562 const internal::VariadicDynCastAllOfMatcher<
1563   Stmt,
1564   IntegerLiteral> integerLiteral;
1565
1566 /// \brief Matches float literals of all sizes / encodings, e.g.
1567 /// 1.0, 1.0f, 1.0L and 1e10.
1568 ///
1569 /// Does not match implicit conversions such as
1570 /// \code
1571 ///   float a = 10;
1572 /// \endcode
1573 const internal::VariadicDynCastAllOfMatcher<
1574   Stmt,
1575   FloatingLiteral> floatLiteral;
1576
1577 /// \brief Matches user defined literal operator call.
1578 ///
1579 /// Example match: "foo"_suffix
1580 const internal::VariadicDynCastAllOfMatcher<
1581   Stmt,
1582   UserDefinedLiteral> userDefinedLiteral;
1583
1584 /// \brief Matches compound (i.e. non-scalar) literals
1585 ///
1586 /// Example match: {1}, (1, 2)
1587 /// \code
1588 ///   int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1589 /// \endcode
1590 const internal::VariadicDynCastAllOfMatcher<
1591   Stmt,
1592   CompoundLiteralExpr> compoundLiteralExpr;
1593
1594 /// \brief Matches nullptr literal.
1595 const internal::VariadicDynCastAllOfMatcher<
1596   Stmt,
1597   CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1598
1599 /// \brief Matches GNU __null expression.
1600 const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr;
1601
1602 /// \brief Matches atomic builtins.
1603 /// Example matches __atomic_load_n(ptr, 1)
1604 /// \code
1605 ///   void foo() { int *ptr; __atomic_load_n(ptr, 1); }
1606 /// \endcode
1607 const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
1608
1609 /// \brief Matches statement expression (GNU extension).
1610 ///
1611 /// Example match: ({ int X = 4; X; })
1612 /// \code
1613 ///   int C = ({ int X = 4; X; });
1614 /// \endcode
1615 const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
1616
1617 /// \brief Matches binary operator expressions.
1618 ///
1619 /// Example matches a || b
1620 /// \code
1621 ///   !(a || b)
1622 /// \endcode
1623 const internal::VariadicDynCastAllOfMatcher<
1624   Stmt,
1625   BinaryOperator> binaryOperator;
1626
1627 /// \brief Matches unary operator expressions.
1628 ///
1629 /// Example matches !a
1630 /// \code
1631 ///   !a || b
1632 /// \endcode
1633 const internal::VariadicDynCastAllOfMatcher<
1634   Stmt,
1635   UnaryOperator> unaryOperator;
1636
1637 /// \brief Matches conditional operator expressions.
1638 ///
1639 /// Example matches a ? b : c
1640 /// \code
1641 ///   (a ? b : c) + 42
1642 /// \endcode
1643 const internal::VariadicDynCastAllOfMatcher<
1644   Stmt,
1645   ConditionalOperator> conditionalOperator;
1646
1647 /// \brief Matches binary conditional operator expressions (GNU extension).
1648 ///
1649 /// Example matches a ?: b
1650 /// \code
1651 ///   (a ?: b) + 42;
1652 /// \endcode
1653 const internal::VariadicDynCastAllOfMatcher<
1654   Stmt,
1655   BinaryConditionalOperator> binaryConditionalOperator;
1656
1657 /// \brief Matches opaque value expressions. They are used as helpers
1658 /// to reference another expressions and can be met
1659 /// in BinaryConditionalOperators, for example.
1660 ///
1661 /// Example matches 'a'
1662 /// \code
1663 ///   (a ?: c) + 42;
1664 /// \endcode
1665 const internal::VariadicDynCastAllOfMatcher<
1666   Stmt,
1667   OpaqueValueExpr> opaqueValueExpr;
1668
1669 /// \brief Matches a C++ static_assert declaration.
1670 ///
1671 /// Example:
1672 ///   staticAssertExpr()
1673 /// matches
1674 ///   static_assert(sizeof(S) == sizeof(int))
1675 /// in
1676 /// \code
1677 ///   struct S {
1678 ///     int x;
1679 ///   };
1680 ///   static_assert(sizeof(S) == sizeof(int));
1681 /// \endcode
1682 const internal::VariadicDynCastAllOfMatcher<
1683   Decl,
1684   StaticAssertDecl> staticAssertDecl;
1685
1686 /// \brief Matches a reinterpret_cast expression.
1687 ///
1688 /// Either the source expression or the destination type can be matched
1689 /// using has(), but hasDestinationType() is more specific and can be
1690 /// more readable.
1691 ///
1692 /// Example matches reinterpret_cast<char*>(&p) in
1693 /// \code
1694 ///   void* p = reinterpret_cast<char*>(&p);
1695 /// \endcode
1696 const internal::VariadicDynCastAllOfMatcher<
1697   Stmt,
1698   CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1699
1700 /// \brief Matches a C++ static_cast expression.
1701 ///
1702 /// \see hasDestinationType
1703 /// \see reinterpretCast
1704 ///
1705 /// Example:
1706 ///   cxxStaticCastExpr()
1707 /// matches
1708 ///   static_cast<long>(8)
1709 /// in
1710 /// \code
1711 ///   long eight(static_cast<long>(8));
1712 /// \endcode
1713 const internal::VariadicDynCastAllOfMatcher<
1714   Stmt,
1715   CXXStaticCastExpr> cxxStaticCastExpr;
1716
1717 /// \brief Matches a dynamic_cast expression.
1718 ///
1719 /// Example:
1720 ///   cxxDynamicCastExpr()
1721 /// matches
1722 ///   dynamic_cast<D*>(&b);
1723 /// in
1724 /// \code
1725 ///   struct B { virtual ~B() {} }; struct D : B {};
1726 ///   B b;
1727 ///   D* p = dynamic_cast<D*>(&b);
1728 /// \endcode
1729 const internal::VariadicDynCastAllOfMatcher<
1730   Stmt,
1731   CXXDynamicCastExpr> cxxDynamicCastExpr;
1732
1733 /// \brief Matches a const_cast expression.
1734 ///
1735 /// Example: Matches const_cast<int*>(&r) in
1736 /// \code
1737 ///   int n = 42;
1738 ///   const int &r(n);
1739 ///   int* p = const_cast<int*>(&r);
1740 /// \endcode
1741 const internal::VariadicDynCastAllOfMatcher<
1742   Stmt,
1743   CXXConstCastExpr> cxxConstCastExpr;
1744
1745 /// \brief Matches a C-style cast expression.
1746 ///
1747 /// Example: Matches (int*) 2.2f in
1748 /// \code
1749 ///   int i = (int) 2.2f;
1750 /// \endcode
1751 const internal::VariadicDynCastAllOfMatcher<
1752   Stmt,
1753   CStyleCastExpr> cStyleCastExpr;
1754
1755 /// \brief Matches explicit cast expressions.
1756 ///
1757 /// Matches any cast expression written in user code, whether it be a
1758 /// C-style cast, a functional-style cast, or a keyword cast.
1759 ///
1760 /// Does not match implicit conversions.
1761 ///
1762 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1763 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1764 /// actual cast expressions.
1765 ///
1766 /// \see hasDestinationType.
1767 ///
1768 /// Example: matches all five of the casts in
1769 /// \code
1770 ///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1771 /// \endcode
1772 /// but does not match the implicit conversion in
1773 /// \code
1774 ///   long ell = 42;
1775 /// \endcode
1776 const internal::VariadicDynCastAllOfMatcher<
1777   Stmt,
1778   ExplicitCastExpr> explicitCastExpr;
1779
1780 /// \brief Matches the implicit cast nodes of Clang's AST.
1781 ///
1782 /// This matches many different places, including function call return value
1783 /// eliding, as well as any type conversions.
1784 const internal::VariadicDynCastAllOfMatcher<
1785   Stmt,
1786   ImplicitCastExpr> implicitCastExpr;
1787
1788 /// \brief Matches any cast nodes of Clang's AST.
1789 ///
1790 /// Example: castExpr() matches each of the following:
1791 /// \code
1792 ///   (int) 3;
1793 ///   const_cast<Expr *>(SubExpr);
1794 ///   char c = 0;
1795 /// \endcode
1796 /// but does not match
1797 /// \code
1798 ///   int i = (0);
1799 ///   int k = 0;
1800 /// \endcode
1801 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1802
1803 /// \brief Matches functional cast expressions
1804 ///
1805 /// Example: Matches Foo(bar);
1806 /// \code
1807 ///   Foo f = bar;
1808 ///   Foo g = (Foo) bar;
1809 ///   Foo h = Foo(bar);
1810 /// \endcode
1811 const internal::VariadicDynCastAllOfMatcher<
1812   Stmt,
1813   CXXFunctionalCastExpr> cxxFunctionalCastExpr;
1814
1815 /// \brief Matches functional cast expressions having N != 1 arguments
1816 ///
1817 /// Example: Matches Foo(bar, bar)
1818 /// \code
1819 ///   Foo h = Foo(bar, bar);
1820 /// \endcode
1821 const internal::VariadicDynCastAllOfMatcher<
1822   Stmt,
1823   CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
1824
1825 /// \brief Matches predefined identifier expressions [C99 6.4.2.2].
1826 ///
1827 /// Example: Matches __func__
1828 /// \code
1829 ///   printf("%s", __func__);
1830 /// \endcode
1831 const internal::VariadicDynCastAllOfMatcher<
1832   Stmt,
1833   PredefinedExpr> predefinedExpr;
1834
1835 /// \brief Matches C99 designated initializer expressions [C99 6.7.8].
1836 ///
1837 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
1838 /// \code
1839 ///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
1840 /// \endcode
1841 const internal::VariadicDynCastAllOfMatcher<
1842   Stmt,
1843   DesignatedInitExpr> designatedInitExpr;
1844
1845 /// \brief Matches designated initializer expressions that contain
1846 /// a specific number of designators.
1847 ///
1848 /// Example: Given
1849 /// \code
1850 ///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
1851 ///   point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
1852 /// \endcode
1853 /// designatorCountIs(2)
1854 ///   matches '{ [2].y = 1.0, [0].x = 1.0 }',
1855 ///   but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
1856 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
1857   return Node.size() == N;
1858 }
1859
1860 /// \brief Matches \c QualTypes in the clang AST.
1861 const internal::VariadicAllOfMatcher<QualType> qualType;
1862
1863 /// \brief Matches \c Types in the clang AST.
1864 const internal::VariadicAllOfMatcher<Type> type;
1865
1866 /// \brief Matches \c TypeLocs in the clang AST.
1867 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1868
1869 /// \brief Matches if any of the given matchers matches.
1870 ///
1871 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1872 /// matching submatcher.
1873 ///
1874 /// For example, in:
1875 /// \code
1876 ///   class A { int a; int b; };
1877 /// \endcode
1878 /// The matcher:
1879 /// \code
1880 ///   cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1881 ///                        has(fieldDecl(hasName("b")).bind("v"))))
1882 /// \endcode
1883 /// will generate two results binding "v", the first of which binds
1884 /// the field declaration of \c a, the second the field declaration of
1885 /// \c b.
1886 ///
1887 /// Usable as: Any Matcher
1888 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
1889   internal::DynTypedMatcher::VO_EachOf
1890 };
1891
1892 /// \brief Matches if any of the given matchers matches.
1893 ///
1894 /// Usable as: Any Matcher
1895 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
1896   internal::DynTypedMatcher::VO_AnyOf
1897 };
1898
1899 /// \brief Matches if all given matchers match.
1900 ///
1901 /// Usable as: Any Matcher
1902 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
1903   internal::DynTypedMatcher::VO_AllOf
1904 };
1905
1906 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1907 ///
1908 /// Given
1909 /// \code
1910 ///   Foo x = bar;
1911 ///   int y = sizeof(x) + alignof(x);
1912 /// \endcode
1913 /// unaryExprOrTypeTraitExpr()
1914 ///   matches \c sizeof(x) and \c alignof(x)
1915 const internal::VariadicDynCastAllOfMatcher<
1916   Stmt,
1917   UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1918
1919 /// \brief Matches unary expressions that have a specific type of argument.
1920 ///
1921 /// Given
1922 /// \code
1923 ///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1924 /// \endcode
1925 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1926 ///   matches \c sizeof(a) and \c alignof(c)
1927 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1928               internal::Matcher<QualType>, InnerMatcher) {
1929   const QualType ArgumentType = Node.getTypeOfArgument();
1930   return InnerMatcher.matches(ArgumentType, Finder, Builder);
1931 }
1932
1933 /// \brief Matches unary expressions of a certain kind.
1934 ///
1935 /// Given
1936 /// \code
1937 ///   int x;
1938 ///   int s = sizeof(x) + alignof(x)
1939 /// \endcode
1940 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1941 ///   matches \c sizeof(x)
1942 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1943   return Node.getKind() == Kind;
1944 }
1945
1946 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1947 /// alignof.
1948 inline internal::Matcher<Stmt> alignOfExpr(
1949     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1950   return stmt(unaryExprOrTypeTraitExpr(allOf(
1951       ofKind(UETT_AlignOf), InnerMatcher)));
1952 }
1953
1954 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1955 /// sizeof.
1956 inline internal::Matcher<Stmt> sizeOfExpr(
1957     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1958   return stmt(unaryExprOrTypeTraitExpr(
1959       allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1960 }
1961
1962 /// \brief Matches NamedDecl nodes that have the specified name.
1963 ///
1964 /// Supports specifying enclosing namespaces or classes by prefixing the name
1965 /// with '<enclosing>::'.
1966 /// Does not match typedefs of an underlying type with the given name.
1967 ///
1968 /// Example matches X (Name == "X")
1969 /// \code
1970 ///   class X;
1971 /// \endcode
1972 ///
1973 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1974 /// \code
1975 ///   namespace a { namespace b { class X; } }
1976 /// \endcode
1977 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
1978   std::vector<std::string> Names;
1979   Names.push_back(Name);
1980   return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
1981 }
1982
1983 /// \brief Matches NamedDecl nodes that have any of the specified names.
1984 ///
1985 /// This matcher is only provided as a performance optimization of hasName.
1986 /// \code
1987 ///     hasAnyName(a, b, c)
1988 /// \endcode
1989 ///  is equivalent to, but faster than
1990 /// \code
1991 ///     anyOf(hasName(a), hasName(b), hasName(c))
1992 /// \endcode
1993 const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
1994                                  internal::hasAnyNameFunc>
1995     hasAnyName = {};
1996
1997 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1998 /// a substring matched by the given RegExp.
1999 ///
2000 /// Supports specifying enclosing namespaces or classes by
2001 /// prefixing the name with '<enclosing>::'.  Does not match typedefs
2002 /// of an underlying type with the given name.
2003 ///
2004 /// Example matches X (regexp == "::X")
2005 /// \code
2006 ///   class X;
2007 /// \endcode
2008 ///
2009 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2010 /// \code
2011 ///   namespace foo { namespace bar { class X; } }
2012 /// \endcode
2013 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2014   assert(!RegExp.empty());
2015   std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2016   llvm::Regex RE(RegExp);
2017   return RE.match(FullNameString);
2018 }
2019
2020 /// \brief Matches overloaded operator names.
2021 ///
2022 /// Matches overloaded operator names specified in strings without the
2023 /// "operator" prefix: e.g. "<<".
2024 ///
2025 /// Given:
2026 /// \code
2027 ///   class A { int operator*(); };
2028 ///   const A &operator<<(const A &a, const A &b);
2029 ///   A a;
2030 ///   a << a;   // <-- This matches
2031 /// \endcode
2032 ///
2033 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2034 /// specified line and
2035 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2036 /// matches the declaration of \c A.
2037 ///
2038 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2039 inline internal::PolymorphicMatcherWithParam1<
2040     internal::HasOverloadedOperatorNameMatcher, StringRef,
2041     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2042 hasOverloadedOperatorName(StringRef Name) {
2043   return internal::PolymorphicMatcherWithParam1<
2044       internal::HasOverloadedOperatorNameMatcher, StringRef,
2045       AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2046 }
2047
2048 /// \brief Matches C++ classes that are directly or indirectly derived from
2049 /// a class matching \c Base.
2050 ///
2051 /// Note that a class is not considered to be derived from itself.
2052 ///
2053 /// Example matches Y, Z, C (Base == hasName("X"))
2054 /// \code
2055 ///   class X;
2056 ///   class Y : public X {};  // directly derived
2057 ///   class Z : public Y {};  // indirectly derived
2058 ///   typedef X A;
2059 ///   typedef A B;
2060 ///   class C : public B {};  // derived from a typedef of X
2061 /// \endcode
2062 ///
2063 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2064 /// \code
2065 ///   class Foo;
2066 ///   typedef Foo X;
2067 ///   class Bar : public Foo {};  // derived from a type that X is a typedef of
2068 /// \endcode
2069 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2070               internal::Matcher<NamedDecl>, Base) {
2071   return Finder->classIsDerivedFrom(&Node, Base, Builder);
2072 }
2073
2074 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2075 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2076   assert(!BaseName.empty());
2077   return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2078 }
2079
2080 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
2081 /// match \c Base.
2082 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2083                        internal::Matcher<NamedDecl>, Base, 0) {
2084   return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2085       .matches(Node, Finder, Builder);
2086 }
2087
2088 /// \brief Overloaded method as shortcut for
2089 /// \c isSameOrDerivedFrom(hasName(...)).
2090 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2091                        BaseName, 1) {
2092   assert(!BaseName.empty());
2093   return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2094 }
2095
2096 /// \brief Matches the first method of a class or struct that satisfies \c
2097 /// InnerMatcher.
2098 ///
2099 /// Given:
2100 /// \code
2101 ///   class A { void func(); };
2102 ///   class B { void member(); };
2103 /// \endcode
2104 ///
2105 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2106 /// \c A but not \c B.
2107 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2108               InnerMatcher) {
2109   return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2110                                     Node.method_end(), Finder, Builder);
2111 }
2112
2113 /// \brief Matches AST nodes that have child AST nodes that match the
2114 /// provided matcher.
2115 ///
2116 /// Example matches X, Y
2117 ///   (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2118 /// \code
2119 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
2120 ///   class Y { class X {}; };
2121 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
2122 /// \endcode
2123 ///
2124 /// ChildT must be an AST base type.
2125 ///
2126 /// Usable as: Any Matcher
2127 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
2128 LLVM_ATTRIBUTE_UNUSED has = {};
2129
2130 /// \brief Matches AST nodes that have descendant AST nodes that match the
2131 /// provided matcher.
2132 ///
2133 /// Example matches X, Y, Z
2134 ///     (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2135 /// \code
2136 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
2137 ///   class Y { class X {}; };
2138 ///   class Z { class Y { class X {}; }; };
2139 /// \endcode
2140 ///
2141 /// DescendantT must be an AST base type.
2142 ///
2143 /// Usable as: Any Matcher
2144 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
2145 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
2146
2147 /// \brief Matches AST nodes that have child AST nodes that match the
2148 /// provided matcher.
2149 ///
2150 /// Example matches X, Y
2151 ///   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2152 /// \code
2153 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
2154 ///   class Y { class X {}; };
2155 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
2156 /// \endcode
2157 ///
2158 /// ChildT must be an AST base type.
2159 ///
2160 /// As opposed to 'has', 'forEach' will cause a match for each result that
2161 /// matches instead of only on the first one.
2162 ///
2163 /// Usable as: Any Matcher
2164 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2165 LLVM_ATTRIBUTE_UNUSED forEach = {};
2166
2167 /// \brief Matches AST nodes that have descendant AST nodes that match the
2168 /// provided matcher.
2169 ///
2170 /// Example matches X, A, B, C
2171 ///   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2172 /// \code
2173 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
2174 ///   class A { class X {}; };
2175 ///   class B { class C { class X {}; }; };
2176 /// \endcode
2177 ///
2178 /// DescendantT must be an AST base type.
2179 ///
2180 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2181 /// each result that matches instead of only on the first one.
2182 ///
2183 /// Note: Recursively combined ForEachDescendant can cause many matches:
2184 ///   cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2185 ///     forEachDescendant(cxxRecordDecl())
2186 ///   )))
2187 /// will match 10 times (plus injected class name matches) on:
2188 /// \code
2189 ///   class A { class B { class C { class D { class E {}; }; }; }; };
2190 /// \endcode
2191 ///
2192 /// Usable as: Any Matcher
2193 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2194 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2195
2196 /// \brief Matches if the node or any descendant matches.
2197 ///
2198 /// Generates results for each match.
2199 ///
2200 /// For example, in:
2201 /// \code
2202 ///   class A { class B {}; class C {}; };
2203 /// \endcode
2204 /// The matcher:
2205 /// \code
2206 ///   cxxRecordDecl(hasName("::A"),
2207 ///                 findAll(cxxRecordDecl(isDefinition()).bind("m")))
2208 /// \endcode
2209 /// will generate results for \c A, \c B and \c C.
2210 ///
2211 /// Usable as: Any Matcher
2212 template <typename T>
2213 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2214   return eachOf(Matcher, forEachDescendant(Matcher));
2215 }
2216
2217 /// \brief Matches AST nodes that have a parent that matches the provided
2218 /// matcher.
2219 ///
2220 /// Given
2221 /// \code
2222 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2223 /// \endcode
2224 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2225 ///
2226 /// Usable as: Any Matcher
2227 const internal::ArgumentAdaptingMatcherFunc<
2228     internal::HasParentMatcher,
2229     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2230     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2231     LLVM_ATTRIBUTE_UNUSED hasParent = {};
2232
2233 /// \brief Matches AST nodes that have an ancestor that matches the provided
2234 /// matcher.
2235 ///
2236 /// Given
2237 /// \code
2238 /// void f() { if (true) { int x = 42; } }
2239 /// void g() { for (;;) { int x = 43; } }
2240 /// \endcode
2241 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2242 ///
2243 /// Usable as: Any Matcher
2244 const internal::ArgumentAdaptingMatcherFunc<
2245     internal::HasAncestorMatcher,
2246     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2247     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2248     LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2249
2250 /// \brief Matches if the provided matcher does not match.
2251 ///
2252 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2253 /// \code
2254 ///   class X {};
2255 ///   class Y {};
2256 /// \endcode
2257 ///
2258 /// Usable as: Any Matcher
2259 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2260   internal::DynTypedMatcher::VO_UnaryNot
2261 };
2262
2263 /// \brief Matches a node if the declaration associated with that node
2264 /// matches the given matcher.
2265 ///
2266 /// The associated declaration is:
2267 /// - for type nodes, the declaration of the underlying type
2268 /// - for CallExpr, the declaration of the callee
2269 /// - for MemberExpr, the declaration of the referenced member
2270 /// - for CXXConstructExpr, the declaration of the constructor
2271 ///
2272 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2273 /// function. e.g. various subtypes of clang::Type and various expressions.
2274 ///
2275 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
2276 ///   Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
2277 ///   Matcher<LabelStmt>, Matcher<AddrLabelExpr>, Matcher<MemberExpr>,
2278 ///   Matcher<QualType>, Matcher<RecordType>, Matcher<TagType>,
2279 ///   Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
2280 ///   Matcher<TypedefType>, Matcher<UnresolvedUsingType>
2281 inline internal::PolymorphicMatcherWithParam1<
2282     internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2283     void(internal::HasDeclarationSupportedTypes)>
2284 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2285   return internal::PolymorphicMatcherWithParam1<
2286       internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2287       void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2288 }
2289
2290 /// \brief Matches on the implicit object argument of a member call expression.
2291 ///
2292 /// Example matches y.x()
2293 ///   (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2294 /// \code
2295 ///   class Y { public: void x(); };
2296 ///   void z() { Y y; y.x(); }",
2297 /// \endcode
2298 ///
2299 /// FIXME: Overload to allow directly matching types?
2300 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2301               InnerMatcher) {
2302   const Expr *ExprNode = Node.getImplicitObjectArgument()
2303                             ->IgnoreParenImpCasts();
2304   return (ExprNode != nullptr &&
2305           InnerMatcher.matches(*ExprNode, Finder, Builder));
2306 }
2307
2308
2309 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2310 ///
2311 /// Example
2312 /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *")));
2313 /// matches the [webView ...] message invocation.
2314 /// \code
2315 ///   NSString *webViewJavaScript = ...
2316 ///   UIWebView *webView = ...
2317 ///   [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2318 /// \endcode
2319 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2320               InnerMatcher) {
2321   const QualType TypeDecl = Node.getReceiverType();
2322   return InnerMatcher.matches(TypeDecl, Finder, Builder);
2323 }
2324   
2325 /// \brief Matches when BaseName == Selector.getAsString()
2326 ///
2327 ///  matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2328 ///  matches the outer message expr in the code below, but NOT the message
2329 ///  invocation for self.bodyView.
2330 /// \code
2331 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
2332 /// \endcode
2333 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2334   Selector Sel = Node.getSelector();
2335   return BaseName.compare(Sel.getAsString()) == 0;
2336 }
2337
2338   
2339 /// \brief Matches ObjC selectors whose name contains
2340 /// a substring matched by the given RegExp.
2341 ///  matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2342 ///  matches the outer message expr in the code below, but NOT the message
2343 ///  invocation for self.bodyView.
2344 /// \code
2345 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
2346 /// \endcode
2347 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2348   assert(!RegExp.empty());
2349   std::string SelectorString = Node.getSelector().getAsString();
2350   llvm::Regex RE(RegExp);
2351   return RE.match(SelectorString);
2352 }
2353
2354 /// \brief Matches when the selector is the empty selector
2355 ///
2356 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2357 /// represent an error condition in the tree!
2358 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2359   return Node.getSelector().isNull();
2360 }
2361
2362 /// \brief Matches when the selector is a Unary Selector
2363 ///
2364 ///  matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2365 ///  matches self.bodyView in the code below, but NOT the outer message
2366 ///  invocation of "loadHTMLString:baseURL:".
2367 /// \code
2368 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
2369 /// \endcode
2370 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2371   return Node.getSelector().isUnarySelector();
2372 }
2373
2374 /// \brief Matches when the selector is a keyword selector
2375 ///
2376 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2377 /// message expression in
2378 ///
2379 /// \code
2380 ///   UIWebView *webView = ...;
2381 ///   CGRect bodyFrame = webView.frame;
2382 ///   bodyFrame.size.height = self.bodyContentHeight;
2383 ///   webView.frame = bodyFrame;
2384 ///   //     ^---- matches here
2385 /// \endcode
2386 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2387   return Node.getSelector().isKeywordSelector();
2388 }
2389
2390 /// \brief Matches when the selector has the specified number of arguments
2391 ///
2392 ///  matcher = objCMessageExpr(numSelectorArgs(0));
2393 ///  matches self.bodyView in the code below
2394 ///
2395 ///  matcher = objCMessageExpr(numSelectorArgs(2));
2396 ///  matches the invocation of "loadHTMLString:baseURL:" but not that
2397 ///  of self.bodyView
2398 /// \code
2399 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
2400 /// \endcode
2401 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2402   return Node.getSelector().getNumArgs() == N;
2403 }
2404    
2405 /// \brief Matches if the call expression's callee expression matches.
2406 ///
2407 /// Given
2408 /// \code
2409 ///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
2410 ///   void f() { f(); }
2411 /// \endcode
2412 /// callExpr(callee(expr()))
2413 ///   matches this->x(), x(), y.x(), f()
2414 /// with callee(...)
2415 ///   matching this->x, x, y.x, f respectively
2416 ///
2417 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2418 /// because this introduces ambiguous overloads with calls to Callee taking a
2419 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2420 /// implemented in terms of implicit casts.
2421 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2422               InnerMatcher) {
2423   const Expr *ExprNode = Node.getCallee();
2424   return (ExprNode != nullptr &&
2425           InnerMatcher.matches(*ExprNode, Finder, Builder));
2426 }
2427
2428 /// \brief Matches if the call expression's callee's declaration matches the
2429 /// given matcher.
2430 ///
2431 /// Example matches y.x() (matcher = callExpr(callee(
2432 ///                                    cxxMethodDecl(hasName("x")))))
2433 /// \code
2434 ///   class Y { public: void x(); };
2435 ///   void z() { Y y; y.x(); }
2436 /// \endcode
2437 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2438                        1) {
2439   return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2440 }
2441
2442 /// \brief Matches if the expression's or declaration's type matches a type
2443 /// matcher.
2444 ///
2445 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2446 ///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2447 ///             and U (matcher = typedefDecl(hasType(asString("int")))
2448 /// \code
2449 ///  class X {};
2450 ///  void y(X &x) { x; X z; }
2451 ///  typedef int U;
2452 /// \endcode
2453 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2454     hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefDecl, ValueDecl),
2455     internal::Matcher<QualType>, InnerMatcher, 0) {
2456   return InnerMatcher.matches(internal::getUnderlyingType<NodeType>(Node),
2457                               Finder, Builder);
2458 }
2459
2460 /// \brief Overloaded to match the declaration of the expression's or value
2461 /// declaration's type.
2462 ///
2463 /// In case of a value declaration (for example a variable declaration),
2464 /// this resolves one layer of indirection. For example, in the value
2465 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2466 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2467 /// declaration of x.
2468 ///
2469 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2470 ///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2471 /// \code
2472 ///  class X {};
2473 ///  void y(X &x) { x; X z; }
2474 /// \endcode
2475 ///
2476 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2477 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2478                                    AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2479                                                                    ValueDecl),
2480                                    internal::Matcher<Decl>, InnerMatcher, 1) {
2481   return qualType(hasDeclaration(InnerMatcher))
2482       .matches(Node.getType(), Finder, Builder);
2483 }
2484
2485 /// \brief Matches if the type location of the declarator decl's type matches
2486 /// the inner matcher.
2487 ///
2488 /// Given
2489 /// \code
2490 ///   int x;
2491 /// \endcode
2492 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2493 ///   matches int x
2494 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2495   if (!Node.getTypeSourceInfo())
2496     // This happens for example for implicit destructors.
2497     return false;
2498   return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2499 }
2500
2501 /// \brief Matches if the matched type is represented by the given string.
2502 ///
2503 /// Given
2504 /// \code
2505 ///   class Y { public: void x(); };
2506 ///   void z() { Y* y; y->x(); }
2507 /// \endcode
2508 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2509 ///   matches y->x()
2510 AST_MATCHER_P(QualType, asString, std::string, Name) {
2511   return Name == Node.getAsString();
2512 }
2513
2514 /// \brief Matches if the matched type is a pointer type and the pointee type
2515 /// matches the specified matcher.
2516 ///
2517 /// Example matches y->x()
2518 ///   (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2519 ///      cxxRecordDecl(hasName("Y")))))))
2520 /// \code
2521 ///   class Y { public: void x(); };
2522 ///   void z() { Y *y; y->x(); }
2523 /// \endcode
2524 AST_MATCHER_P(
2525     QualType, pointsTo, internal::Matcher<QualType>,
2526     InnerMatcher) {
2527   return (!Node.isNull() && Node->isAnyPointerType() &&
2528           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2529 }
2530
2531 /// \brief Overloaded to match the pointee type's declaration.
2532 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2533                        InnerMatcher, 1) {
2534   return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2535       .matches(Node, Finder, Builder);
2536 }
2537
2538 /// \brief Matches if the matched type is a reference type and the referenced
2539 /// type matches the specified matcher.
2540 ///
2541 /// Example matches X &x and const X &y
2542 ///     (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2543 /// \code
2544 ///   class X {
2545 ///     void a(X b) {
2546 ///       X &x = b;
2547 ///       const X &y = b;
2548 ///     }
2549 ///   };
2550 /// \endcode
2551 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2552               InnerMatcher) {
2553   return (!Node.isNull() && Node->isReferenceType() &&
2554           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2555 }
2556
2557 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2558 ///
2559 /// Given:
2560 /// \code
2561 ///   typedef int &int_ref;
2562 ///   int a;
2563 ///   int_ref b = a;
2564 /// \endcode
2565 ///
2566 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2567 /// declaration of b but \c
2568 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2569 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2570               InnerMatcher) {
2571   if (Node.isNull())
2572     return false;
2573   return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2574 }
2575
2576 /// \brief Overloaded to match the referenced type's declaration.
2577 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2578                        InnerMatcher, 1) {
2579   return references(qualType(hasDeclaration(InnerMatcher)))
2580       .matches(Node, Finder, Builder);
2581 }
2582
2583 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2584               internal::Matcher<Expr>, InnerMatcher) {
2585   const Expr *ExprNode = Node.getImplicitObjectArgument();
2586   return (ExprNode != nullptr &&
2587           InnerMatcher.matches(*ExprNode, Finder, Builder));
2588 }
2589
2590 /// \brief Matches if the expression's type either matches the specified
2591 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2592 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2593                        internal::Matcher<QualType>, InnerMatcher, 0) {
2594   return onImplicitObjectArgument(
2595       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2596       .matches(Node, Finder, Builder);
2597 }
2598
2599 /// \brief Overloaded to match the type's declaration.
2600 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2601                        internal::Matcher<Decl>, InnerMatcher, 1) {
2602   return onImplicitObjectArgument(
2603       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2604       .matches(Node, Finder, Builder);
2605 }
2606
2607 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2608 /// specified matcher.
2609 ///
2610 /// Example matches x in if(x)
2611 ///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
2612 /// \code
2613 ///   bool x;
2614 ///   if (x) {}
2615 /// \endcode
2616 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2617               InnerMatcher) {
2618   const Decl *DeclNode = Node.getDecl();
2619   return (DeclNode != nullptr &&
2620           InnerMatcher.matches(*DeclNode, Finder, Builder));
2621 }
2622
2623 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2624 /// specific using shadow declaration.
2625 ///
2626 /// Given
2627 /// \code
2628 ///   namespace a { void f() {} }
2629 ///   using a::f;
2630 ///   void g() {
2631 ///     f();     // Matches this ..
2632 ///     a::f();  // .. but not this.
2633 ///   }
2634 /// \endcode
2635 /// declRefExpr(throughUsingDecl(anything()))
2636 ///   matches \c f()
2637 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2638               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2639   const NamedDecl *FoundDecl = Node.getFoundDecl();
2640   if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2641     return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2642   return false;
2643 }
2644
2645 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2646 ///
2647 /// Given
2648 /// \code
2649 ///   int a, b;
2650 ///   int c;
2651 /// \endcode
2652 /// declStmt(hasSingleDecl(anything()))
2653 ///   matches 'int c;' but not 'int a, b;'.
2654 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2655   if (Node.isSingleDecl()) {
2656     const Decl *FoundDecl = Node.getSingleDecl();
2657     return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2658   }
2659   return false;
2660 }
2661
2662 /// \brief Matches a variable declaration that has an initializer expression
2663 /// that matches the given matcher.
2664 ///
2665 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2666 /// \code
2667 ///   bool y() { return true; }
2668 ///   bool x = y();
2669 /// \endcode
2670 AST_MATCHER_P(
2671     VarDecl, hasInitializer, internal::Matcher<Expr>,
2672     InnerMatcher) {
2673   const Expr *Initializer = Node.getAnyInitializer();
2674   return (Initializer != nullptr &&
2675           InnerMatcher.matches(*Initializer, Finder, Builder));
2676 }
2677
2678 /// \brief Matches a variable declaration that has function scope and is a
2679 /// non-static local variable.
2680 ///
2681 /// Example matches x (matcher = varDecl(hasLocalStorage())
2682 /// \code
2683 /// void f() {
2684 ///   int x;
2685 ///   static int y;
2686 /// }
2687 /// int z;
2688 /// \endcode
2689 AST_MATCHER(VarDecl, hasLocalStorage) {
2690   return Node.hasLocalStorage();
2691 }
2692
2693 /// \brief Matches a variable declaration that does not have local storage.
2694 ///
2695 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2696 /// \code
2697 /// void f() {
2698 ///   int x;
2699 ///   static int y;
2700 /// }
2701 /// int z;
2702 /// \endcode
2703 AST_MATCHER(VarDecl, hasGlobalStorage) {
2704   return Node.hasGlobalStorage();
2705 }
2706
2707 /// \brief Matches a variable declaration that has automatic storage duration.
2708 ///
2709 /// Example matches x, but not y, z, or a.
2710 /// (matcher = varDecl(hasAutomaticStorageDuration())
2711 /// \code
2712 /// void f() {
2713 ///   int x;
2714 ///   static int y;
2715 ///   thread_local int z;
2716 /// }
2717 /// int a;
2718 /// \endcode
2719 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
2720   return Node.getStorageDuration() == SD_Automatic;
2721 }
2722
2723 /// \brief Matches a variable declaration that has static storage duration.
2724 ///
2725 /// Example matches y and a, but not x or z.
2726 /// (matcher = varDecl(hasStaticStorageDuration())
2727 /// \code
2728 /// void f() {
2729 ///   int x;
2730 ///   static int y;
2731 ///   thread_local int z;
2732 /// }
2733 /// int a;
2734 /// \endcode
2735 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
2736   return Node.getStorageDuration() == SD_Static;
2737 }
2738
2739 /// \brief Matches a variable declaration that has thread storage duration.
2740 ///
2741 /// Example matches z, but not x, z, or a.
2742 /// (matcher = varDecl(hasThreadStorageDuration())
2743 /// \code
2744 /// void f() {
2745 ///   int x;
2746 ///   static int y;
2747 ///   thread_local int z;
2748 /// }
2749 /// int a;
2750 /// \endcode
2751 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
2752   return Node.getStorageDuration() == SD_Thread;
2753 }
2754
2755 /// \brief Matches a variable declaration that is an exception variable from
2756 /// a C++ catch block, or an Objective-C \@catch statement.
2757 ///
2758 /// Example matches x (matcher = varDecl(isExceptionVariable())
2759 /// \code
2760 /// void f(int y) {
2761 ///   try {
2762 ///   } catch (int x) {
2763 ///   }
2764 /// }
2765 /// \endcode
2766 AST_MATCHER(VarDecl, isExceptionVariable) {
2767   return Node.isExceptionVariable();
2768 }
2769
2770 /// \brief Checks that a call expression or a constructor call expression has
2771 /// a specific number of arguments (including absent default arguments).
2772 ///
2773 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2774 /// \code
2775 ///   void f(int x, int y);
2776 ///   f(0, 0);
2777 /// \endcode
2778 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
2779                           AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2780                                                           CXXConstructExpr,
2781                                                           ObjCMessageExpr),
2782                           unsigned, N) {
2783   return Node.getNumArgs() == N;
2784 }
2785
2786 /// \brief Matches the n'th argument of a call expression or a constructor
2787 /// call expression.
2788 ///
2789 /// Example matches y in x(y)
2790 ///     (matcher = callExpr(hasArgument(0, declRefExpr())))
2791 /// \code
2792 ///   void x(int) { int y; x(y); }
2793 /// \endcode
2794 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
2795                            AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2796                                                            CXXConstructExpr,
2797                                                            ObjCMessageExpr),
2798                            unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2799   return (N < Node.getNumArgs() &&
2800           InnerMatcher.matches(
2801               *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2802 }
2803
2804 /// \brief Matches declaration statements that contain a specific number of
2805 /// declarations.
2806 ///
2807 /// Example: Given
2808 /// \code
2809 ///   int a, b;
2810 ///   int c;
2811 ///   int d = 2, e;
2812 /// \endcode
2813 /// declCountIs(2)
2814 ///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2815 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2816   return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2817 }
2818
2819 /// \brief Matches the n'th declaration of a declaration statement.
2820 ///
2821 /// Note that this does not work for global declarations because the AST
2822 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2823 /// DeclStmt's.
2824 /// Example: Given non-global declarations
2825 /// \code
2826 ///   int a, b = 0;
2827 ///   int c;
2828 ///   int d = 2, e;
2829 /// \endcode
2830 /// declStmt(containsDeclaration(
2831 ///       0, varDecl(hasInitializer(anything()))))
2832 ///   matches only 'int d = 2, e;', and
2833 /// declStmt(containsDeclaration(1, varDecl()))
2834 /// \code
2835 ///   matches 'int a, b = 0' as well as 'int d = 2, e;'
2836 ///   but 'int c;' is not matched.
2837 /// \endcode
2838 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2839                internal::Matcher<Decl>, InnerMatcher) {
2840   const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2841   if (N >= NumDecls)
2842     return false;
2843   DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2844   std::advance(Iterator, N);
2845   return InnerMatcher.matches(**Iterator, Finder, Builder);
2846 }
2847
2848 /// \brief Matches a C++ catch statement that has a catch-all handler.
2849 ///
2850 /// Given
2851 /// \code
2852 ///   try {
2853 ///     // ...
2854 ///   } catch (int) {
2855 ///     // ...
2856 ///   } catch (...) {
2857 ///     // ...
2858 ///   }
2859 /// /endcode
2860 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
2861 AST_MATCHER(CXXCatchStmt, isCatchAll) {
2862   return Node.getExceptionDecl() == nullptr;
2863 }
2864
2865 /// \brief Matches a constructor initializer.
2866 ///
2867 /// Given
2868 /// \code
2869 ///   struct Foo {
2870 ///     Foo() : foo_(1) { }
2871 ///     int foo_;
2872 ///   };
2873 /// \endcode
2874 /// cxxRecordDecl(has(cxxConstructorDecl(
2875 ///   hasAnyConstructorInitializer(anything())
2876 /// )))
2877 ///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2878 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2879               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2880   return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2881                                     Node.init_end(), Finder, Builder);
2882 }
2883
2884 /// \brief Matches the field declaration of a constructor initializer.
2885 ///
2886 /// Given
2887 /// \code
2888 ///   struct Foo {
2889 ///     Foo() : foo_(1) { }
2890 ///     int foo_;
2891 ///   };
2892 /// \endcode
2893 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2894 ///     forField(hasName("foo_"))))))
2895 ///   matches Foo
2896 /// with forField matching foo_
2897 AST_MATCHER_P(CXXCtorInitializer, forField,
2898               internal::Matcher<FieldDecl>, InnerMatcher) {
2899   const FieldDecl *NodeAsDecl = Node.getMember();
2900   return (NodeAsDecl != nullptr &&
2901       InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2902 }
2903
2904 /// \brief Matches the initializer expression of a constructor initializer.
2905 ///
2906 /// Given
2907 /// \code
2908 ///   struct Foo {
2909 ///     Foo() : foo_(1) { }
2910 ///     int foo_;
2911 ///   };
2912 /// \endcode
2913 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2914 ///     withInitializer(integerLiteral(equals(1)))))))
2915 ///   matches Foo
2916 /// with withInitializer matching (1)
2917 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2918               internal::Matcher<Expr>, InnerMatcher) {
2919   const Expr* NodeAsExpr = Node.getInit();
2920   return (NodeAsExpr != nullptr &&
2921       InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2922 }
2923
2924 /// \brief Matches a constructor initializer if it is explicitly written in
2925 /// code (as opposed to implicitly added by the compiler).
2926 ///
2927 /// Given
2928 /// \code
2929 ///   struct Foo {
2930 ///     Foo() { }
2931 ///     Foo(int) : foo_("A") { }
2932 ///     string foo_;
2933 ///   };
2934 /// \endcode
2935 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
2936 ///   will match Foo(int), but not Foo()
2937 AST_MATCHER(CXXCtorInitializer, isWritten) {
2938   return Node.isWritten();
2939 }
2940
2941 /// \brief Matches a constructor initializer if it is initializing a base, as
2942 /// opposed to a member.
2943 ///
2944 /// Given
2945 /// \code
2946 ///   struct B {};
2947 ///   struct D : B {
2948 ///     int I;
2949 ///     D(int i) : I(i) {}
2950 ///   };
2951 ///   struct E : B {
2952 ///     E() : B() {}
2953 ///   };
2954 /// \endcode
2955 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
2956 ///   will match E(), but not match D(int).
2957 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
2958   return Node.isBaseInitializer();
2959 }
2960
2961 /// \brief Matches a constructor initializer if it is initializing a member, as
2962 /// opposed to a base.
2963 ///
2964 /// Given
2965 /// \code
2966 ///   struct B {};
2967 ///   struct D : B {
2968 ///     int I;
2969 ///     D(int i) : I(i) {}
2970 ///   };
2971 ///   struct E : B {
2972 ///     E() : B() {}
2973 ///   };
2974 /// \endcode
2975 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
2976 ///   will match D(int), but not match E().
2977 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
2978   return Node.isMemberInitializer();
2979 }
2980
2981 /// \brief Matches any argument of a call expression or a constructor call
2982 /// expression.
2983 ///
2984 /// Given
2985 /// \code
2986 ///   void x(int, int, int) { int y; x(1, y, 42); }
2987 /// \endcode
2988 /// callExpr(hasAnyArgument(declRefExpr()))
2989 ///   matches x(1, y, 42)
2990 /// with hasAnyArgument(...)
2991 ///   matching y
2992 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
2993                           AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2994                                                           CXXConstructExpr),
2995                           internal::Matcher<Expr>, InnerMatcher) {
2996   for (const Expr *Arg : Node.arguments()) {
2997     BoundNodesTreeBuilder Result(*Builder);
2998     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
2999       *Builder = std::move(Result);
3000       return true;
3001     }
3002   }
3003   return false;
3004 }
3005
3006 /// \brief Matches a constructor call expression which uses list initialization.
3007 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3008   return Node.isListInitialization();
3009 }
3010
3011 /// \brief Matches a constructor call expression which requires
3012 /// zero initialization.
3013 ///
3014 /// Given
3015 /// \code
3016 /// void foo() {
3017 ///   struct point { double x; double y; };
3018 ///   point pt[2] = { { 1.0, 2.0 } };
3019 /// }
3020 /// \endcode
3021 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3022 /// will match the implicit array filler for pt[1].
3023 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3024   return Node.requiresZeroInitialization();
3025 }
3026
3027 /// \brief Matches the n'th parameter of a function declaration.
3028 ///
3029 /// Given
3030 /// \code
3031 ///   class X { void f(int x) {} };
3032 /// \endcode
3033 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3034 ///   matches f(int x) {}
3035 /// with hasParameter(...)
3036 ///   matching int x
3037 AST_MATCHER_P2(FunctionDecl, hasParameter,
3038                unsigned, N, internal::Matcher<ParmVarDecl>,
3039                InnerMatcher) {
3040   return (N < Node.getNumParams() &&
3041           InnerMatcher.matches(
3042               *Node.getParamDecl(N), Finder, Builder));
3043 }
3044
3045 /// \brief Matches all arguments and their respective ParmVarDecl.
3046 ///
3047 /// Given
3048 /// \code
3049 ///   void f(int i);
3050 ///   int y;
3051 ///   f(y);
3052 /// \endcode
3053 /// callExpr(declRefExpr(to(varDecl(hasName("y")))),
3054 /// parmVarDecl(hasType(isInteger())))
3055 ///   matches f(y);
3056 /// with declRefExpr(...)
3057 ///   matching int y
3058 /// and parmVarDecl(...)
3059 ///   matching int i
3060 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3061                            AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3062                                                            CXXConstructExpr),
3063                            internal::Matcher<Expr>, ArgMatcher,
3064                            internal::Matcher<ParmVarDecl>, ParamMatcher) {
3065   BoundNodesTreeBuilder Result;
3066   // The first argument of an overloaded member operator is the implicit object
3067   // argument of the method which should not be matched against a parameter, so
3068   // we skip over it here.
3069   BoundNodesTreeBuilder Matches;
3070   unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3071                               .matches(Node, Finder, &Matches)
3072                           ? 1
3073                           : 0;
3074   int ParamIndex = 0;
3075   bool Matched = false;
3076   for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3077     BoundNodesTreeBuilder ArgMatches(*Builder);
3078     if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3079                            Finder, &ArgMatches)) {
3080       BoundNodesTreeBuilder ParamMatches(ArgMatches);
3081       if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3082                          hasParameter(ParamIndex, ParamMatcher)))),
3083                      callExpr(callee(functionDecl(
3084                          hasParameter(ParamIndex, ParamMatcher))))))
3085               .matches(Node, Finder, &ParamMatches)) {
3086         Result.addMatch(ParamMatches);
3087         Matched = true;
3088       }
3089     }
3090     ++ParamIndex;
3091   }
3092   *Builder = std::move(Result);
3093   return Matched;
3094 }
3095
3096 /// \brief Matches any parameter of a function declaration.
3097 ///
3098 /// Does not match the 'this' parameter of a method.
3099 ///
3100 /// Given
3101 /// \code
3102 ///   class X { void f(int x, int y, int z) {} };
3103 /// \endcode
3104 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3105 ///   matches f(int x, int y, int z) {}
3106 /// with hasAnyParameter(...)
3107 ///   matching int y
3108 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
3109               internal::Matcher<ParmVarDecl>, InnerMatcher) {
3110   return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3111                                     Node.param_end(), Finder, Builder);
3112 }
3113
3114 /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3115 /// specific parameter count.
3116 ///
3117 /// Given
3118 /// \code
3119 ///   void f(int i) {}
3120 ///   void g(int i, int j) {}
3121 ///   void h(int i, int j);
3122 ///   void j(int i);
3123 ///   void k(int x, int y, int z, ...);
3124 /// \endcode
3125 /// functionDecl(parameterCountIs(2))
3126 ///   matches void g(int i, int j) {}
3127 /// functionProtoType(parameterCountIs(2))
3128 ///   matches void h(int i, int j)
3129 /// functionProtoType(parameterCountIs(3))
3130 ///   matches void k(int x, int y, int z, ...);
3131 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3132                           AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3133                                                           FunctionProtoType),
3134                           unsigned, N) {
3135   return Node.getNumParams() == N;
3136 }
3137
3138 /// \brief Matches the return type of a function declaration.
3139 ///
3140 /// Given:
3141 /// \code
3142 ///   class X { int f() { return 1; } };
3143 /// \endcode
3144 /// cxxMethodDecl(returns(asString("int")))
3145 ///   matches int f() { return 1; }
3146 AST_MATCHER_P(FunctionDecl, returns,
3147               internal::Matcher<QualType>, InnerMatcher) {
3148   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3149 }
3150
3151 /// \brief Matches extern "C" function declarations.
3152 ///
3153 /// Given:
3154 /// \code
3155 ///   extern "C" void f() {}
3156 ///   extern "C" { void g() {} }
3157 ///   void h() {}
3158 /// \endcode
3159 /// functionDecl(isExternC())
3160 ///   matches the declaration of f and g, but not the declaration h
3161 AST_MATCHER(FunctionDecl, isExternC) {
3162   return Node.isExternC();
3163 }
3164
3165 /// \brief Matches deleted function declarations.
3166 ///
3167 /// Given:
3168 /// \code
3169 ///   void Func();
3170 ///   void DeletedFunc() = delete;
3171 /// \endcode
3172 /// functionDecl(isDeleted())
3173 ///   matches the declaration of DeletedFunc, but not Func.
3174 AST_MATCHER(FunctionDecl, isDeleted) {
3175   return Node.isDeleted();
3176 }
3177
3178 /// \brief Matches defaulted function declarations.
3179 ///
3180 /// Given:
3181 /// \code
3182 ///   class A { ~A(); };
3183 ///   class B { ~B() = default; };
3184 /// \endcode
3185 /// functionDecl(isDefaulted())
3186 ///   matches the declaration of ~B, but not ~A.
3187 AST_MATCHER(FunctionDecl, isDefaulted) {
3188   return Node.isDefaulted();
3189 }
3190
3191 /// \brief Matches functions that have a non-throwing exception specification.
3192 ///
3193 /// Given:
3194 /// \code
3195 ///   void f();
3196 ///   void g() noexcept;
3197 ///   void h() throw();
3198 ///   void i() throw(int);
3199 ///   void j() noexcept(false);
3200 /// \endcode
3201 /// functionDecl(isNoThrow())
3202 ///   matches the declarations of g, and h, but not f, i or j.
3203 AST_MATCHER(FunctionDecl, isNoThrow) {
3204   const auto *FnTy = Node.getType()->getAs<FunctionProtoType>();
3205
3206   // If the function does not have a prototype, then it is assumed to be a
3207   // throwing function (as it would if the function did not have any exception
3208   // specification).
3209   if (!FnTy)
3210     return false;
3211
3212   // Assume the best for any unresolved exception specification.
3213   if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3214     return true;
3215
3216   return FnTy->isNothrow(Node.getASTContext());
3217 }
3218
3219 /// \brief Matches constexpr variable and function declarations.
3220 ///
3221 /// Given:
3222 /// \code
3223 ///   constexpr int foo = 42;
3224 ///   constexpr int bar();
3225 /// \endcode
3226 /// varDecl(isConstexpr())
3227 ///   matches the declaration of foo.
3228 /// functionDecl(isConstexpr())
3229 ///   matches the declaration of bar.
3230 AST_POLYMORPHIC_MATCHER(isConstexpr,
3231                         AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3232                                                         FunctionDecl)) {
3233   return Node.isConstexpr();
3234 }
3235
3236 /// \brief Matches the condition expression of an if statement, for loop,
3237 /// or conditional operator.
3238 ///
3239 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3240 /// \code
3241 ///   if (true) {}
3242 /// \endcode
3243 AST_POLYMORPHIC_MATCHER_P(
3244     hasCondition,
3245     AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3246                                     AbstractConditionalOperator),
3247     internal::Matcher<Expr>, InnerMatcher) {
3248   const Expr *const Condition = Node.getCond();
3249   return (Condition != nullptr &&
3250           InnerMatcher.matches(*Condition, Finder, Builder));
3251 }
3252
3253 /// \brief Matches the then-statement of an if statement.
3254 ///
3255 /// Examples matches the if statement
3256 ///   (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3257 /// \code
3258 ///   if (false) true; else false;
3259 /// \endcode
3260 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3261   const Stmt *const Then = Node.getThen();
3262   return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3263 }
3264
3265 /// \brief Matches the else-statement of an if statement.
3266 ///
3267 /// Examples matches the if statement
3268 ///   (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3269 /// \code
3270 ///   if (false) false; else true;
3271 /// \endcode
3272 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3273   const Stmt *const Else = Node.getElse();
3274   return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3275 }
3276
3277 /// \brief Matches if a node equals a previously bound node.
3278 ///
3279 /// Matches a node if it equals the node previously bound to \p ID.
3280 ///
3281 /// Given
3282 /// \code
3283 ///   class X { int a; int b; };
3284 /// \endcode
3285 /// cxxRecordDecl(
3286 ///     has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3287 ///     has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3288 ///   matches the class \c X, as \c a and \c b have the same type.
3289 ///
3290 /// Note that when multiple matches are involved via \c forEach* matchers,
3291 /// \c equalsBoundNodes acts as a filter.
3292 /// For example:
3293 /// compoundStmt(
3294 ///     forEachDescendant(varDecl().bind("d")),
3295 ///     forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3296 /// will trigger a match for each combination of variable declaration
3297 /// and reference to that variable declaration within a compound statement.
3298 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3299                           AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3300                                                           QualType),
3301                           std::string, ID) {
3302   // FIXME: Figure out whether it makes sense to allow this
3303   // on any other node types.
3304   // For *Loc it probably does not make sense, as those seem
3305   // unique. For NestedNameSepcifier it might make sense, as
3306   // those also have pointer identity, but I'm not sure whether
3307   // they're ever reused.
3308   internal::NotEqualsBoundNodePredicate Predicate;
3309   Predicate.ID = ID;
3310   Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3311   return Builder->removeBindings(Predicate);
3312 }
3313
3314 /// \brief Matches the condition variable statement in an if statement.
3315 ///
3316 /// Given
3317 /// \code
3318 ///   if (A* a = GetAPointer()) {}
3319 /// \endcode
3320 /// hasConditionVariableStatement(...)
3321 ///   matches 'A* a = GetAPointer()'.
3322 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3323               internal::Matcher<DeclStmt>, InnerMatcher) {
3324   const DeclStmt* const DeclarationStatement =
3325     Node.getConditionVariableDeclStmt();
3326   return DeclarationStatement != nullptr &&
3327          InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3328 }
3329
3330 /// \brief Matches the index expression of an array subscript expression.
3331 ///
3332 /// Given
3333 /// \code
3334 ///   int i[5];
3335 ///   void f() { i[1] = 42; }
3336 /// \endcode
3337 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3338 ///   matches \c i[1] with the \c integerLiteral() matching \c 1
3339 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3340               internal::Matcher<Expr>, InnerMatcher) {
3341   if (const Expr* Expression = Node.getIdx())
3342     return InnerMatcher.matches(*Expression, Finder, Builder);
3343   return false;
3344 }
3345
3346 /// \brief Matches the base expression of an array subscript expression.
3347 ///
3348 /// Given
3349 /// \code
3350 ///   int i[5];
3351 ///   void f() { i[1] = 42; }
3352 /// \endcode
3353 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3354 ///     hasSourceExpression(declRefExpr()))))
3355 ///   matches \c i[1] with the \c declRefExpr() matching \c i
3356 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3357               internal::Matcher<Expr>, InnerMatcher) {
3358   if (const Expr* Expression = Node.getBase())
3359     return InnerMatcher.matches(*Expression, Finder, Builder);
3360   return false;
3361 }
3362
3363 /// \brief Matches a 'for', 'while', 'do while' statement or a function
3364 /// definition that has a given body.
3365 ///
3366 /// Given
3367 /// \code
3368 ///   for (;;) {}
3369 /// \endcode
3370 /// hasBody(compoundStmt())
3371 ///   matches 'for (;;) {}'
3372 /// with compoundStmt()
3373 ///   matching '{}'
3374 AST_POLYMORPHIC_MATCHER_P(hasBody,
3375                           AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3376                                                           WhileStmt,
3377                                                           CXXForRangeStmt,
3378                                                           FunctionDecl),
3379                           internal::Matcher<Stmt>, InnerMatcher) {
3380   const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
3381   return (Statement != nullptr &&
3382           InnerMatcher.matches(*Statement, Finder, Builder));
3383 }
3384
3385 /// \brief Matches compound statements where at least one substatement matches
3386 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
3387 ///
3388 /// Given
3389 /// \code
3390 ///   { {}; 1+2; }
3391 /// \endcode
3392 /// hasAnySubstatement(compoundStmt())
3393 ///   matches '{ {}; 1+2; }'
3394 /// with compoundStmt()
3395 ///   matching '{}'
3396 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
3397                           AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
3398                                                           StmtExpr),
3399                           internal::Matcher<Stmt>, InnerMatcher) {
3400   const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
3401   return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
3402                                           CS->body_end(), Finder, Builder);
3403 }
3404
3405 /// \brief Checks that a compound statement contains a specific number of
3406 /// child statements.
3407 ///
3408 /// Example: Given
3409 /// \code
3410 ///   { for (;;) {} }
3411 /// \endcode
3412 /// compoundStmt(statementCountIs(0)))
3413 ///   matches '{}'
3414 ///   but does not match the outer compound statement.
3415 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3416   return Node.size() == N;
3417 }
3418
3419 /// \brief Matches literals that are equal to the given value.
3420 ///
3421 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3422 /// \code
3423 ///   true
3424 /// \endcode
3425 ///
3426 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3427 ///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3428 template <typename ValueT>
3429 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3430 equals(const ValueT &Value) {
3431   return internal::PolymorphicMatcherWithParam1<
3432     internal::ValueEqualsMatcher,
3433     ValueT>(Value);
3434 }
3435
3436 /// \brief Matches the operator Name of operator expressions (binary or
3437 /// unary).
3438 ///
3439 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3440 /// \code
3441 ///   !(a || b)
3442 /// \endcode
3443 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3444                           AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3445                                                           UnaryOperator),
3446                           std::string, Name) {
3447   return Name == Node.getOpcodeStr(Node.getOpcode());
3448 }
3449
3450 /// \brief Matches the left hand side of binary operator expressions.
3451 ///
3452 /// Example matches a (matcher = binaryOperator(hasLHS()))
3453 /// \code
3454 ///   a || b
3455 /// \endcode
3456 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3457                           AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3458                                                           ArraySubscriptExpr),
3459                           internal::Matcher<Expr>, InnerMatcher) {
3460   const Expr *LeftHandSide = Node.getLHS();
3461   return (LeftHandSide != nullptr &&
3462           InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3463 }
3464
3465 /// \brief Matches the right hand side of binary operator expressions.
3466 ///
3467 /// Example matches b (matcher = binaryOperator(hasRHS()))
3468 /// \code
3469 ///   a || b
3470 /// \endcode
3471 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3472                           AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3473                                                           ArraySubscriptExpr),
3474                           internal::Matcher<Expr>, InnerMatcher) {
3475   const Expr *RightHandSide = Node.getRHS();
3476   return (RightHandSide != nullptr &&
3477           InnerMatcher.matches(*RightHandSide, Finder, Builder));
3478 }
3479
3480 /// \brief Matches if either the left hand side or the right hand side of a
3481 /// binary operator matches.
3482 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3483     const internal::Matcher<Expr> &InnerMatcher) {
3484   return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3485 }
3486
3487 /// \brief Matches if the operand of a unary operator matches.
3488 ///
3489 /// Example matches true (matcher = hasUnaryOperand(
3490 ///                                   cxxBoolLiteral(equals(true))))
3491 /// \code
3492 ///   !true
3493 /// \endcode
3494 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3495               internal::Matcher<Expr>, InnerMatcher) {
3496   const Expr * const Operand = Node.getSubExpr();
3497   return (Operand != nullptr &&
3498           InnerMatcher.matches(*Operand, Finder, Builder));
3499 }
3500
3501 /// \brief Matches if the cast's source expression
3502 /// or opaque value's source expression matches the given matcher.
3503 ///
3504 /// Example 1: matches "a string"
3505 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
3506 /// \code
3507 /// class URL { URL(string); };
3508 /// URL url = "a string";
3509 /// \endcode
3510 ///
3511 /// Example 2: matches 'b' (matcher =
3512 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
3513 /// \code
3514 /// int a = b ?: 1;
3515 /// \endcode
3516
3517 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
3518                           AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
3519                                                           OpaqueValueExpr),
3520                           internal::Matcher<Expr>, InnerMatcher) {
3521   const Expr *const SubExpression =
3522       internal::GetSourceExpressionMatcher<NodeType>::get(Node);
3523   return (SubExpression != nullptr &&
3524           InnerMatcher.matches(*SubExpression, Finder, Builder));
3525 }
3526
3527 /// \brief Matches casts whose destination type matches a given matcher.
3528 ///
3529 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3530 /// actual casts "explicit" casts.)
3531 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3532               internal::Matcher<QualType>, InnerMatcher) {
3533   const QualType NodeType = Node.getTypeAsWritten();
3534   return InnerMatcher.matches(NodeType, Finder, Builder);
3535 }
3536
3537 /// \brief Matches implicit casts whose destination type matches a given
3538 /// matcher.
3539 ///
3540 /// FIXME: Unit test this matcher
3541 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3542               internal::Matcher<QualType>, InnerMatcher) {
3543   return InnerMatcher.matches(Node.getType(), Finder, Builder);
3544 }
3545
3546 /// \brief Matches RecordDecl object that are spelled with "struct."
3547 ///
3548 /// Example matches S, but not C or U.
3549 /// \code
3550 ///   struct S {};
3551 ///   class C {};
3552 ///   union U {};
3553 /// \endcode
3554 AST_MATCHER(RecordDecl, isStruct) {
3555   return Node.isStruct();
3556 }
3557
3558 /// \brief Matches RecordDecl object that are spelled with "union."
3559 ///
3560 /// Example matches U, but not C or S.
3561 /// \code
3562 ///   struct S {};
3563 ///   class C {};
3564 ///   union U {};
3565 /// \endcode
3566 AST_MATCHER(RecordDecl, isUnion) {
3567   return Node.isUnion();
3568 }
3569
3570 /// \brief Matches RecordDecl object that are spelled with "class."
3571 ///
3572 /// Example matches C, but not S or U.
3573 /// \code
3574 ///   struct S {};
3575 ///   class C {};
3576 ///   union U {};
3577 /// \endcode
3578 AST_MATCHER(RecordDecl, isClass) {
3579   return Node.isClass();
3580 }
3581
3582 /// \brief Matches the true branch expression of a conditional operator.
3583 ///
3584 /// Example 1 (conditional ternary operator): matches a
3585 /// \code
3586 ///   condition ? a : b
3587 /// \endcode
3588 ///
3589 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
3590 /// \code
3591 ///   condition ?: b
3592 /// \endcode
3593 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
3594               internal::Matcher<Expr>, InnerMatcher) {
3595   const Expr *Expression = Node.getTrueExpr();
3596   return (Expression != nullptr &&
3597           InnerMatcher.matches(*Expression, Finder, Builder));
3598 }
3599
3600 /// \brief Matches the false branch expression of a conditional operator
3601 /// (binary or ternary).
3602 ///
3603 /// Example matches b
3604 /// \code
3605 ///   condition ? a : b
3606 ///   condition ?: b
3607 /// \endcode
3608 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
3609               internal::Matcher<Expr>, InnerMatcher) {
3610   const Expr *Expression = Node.getFalseExpr();
3611   return (Expression != nullptr &&
3612           InnerMatcher.matches(*Expression, Finder, Builder));
3613 }
3614
3615 /// \brief Matches if a declaration has a body attached.
3616 ///
3617 /// Example matches A, va, fa
3618 /// \code
3619 ///   class A {};
3620 ///   class B;  // Doesn't match, as it has no body.
3621 ///   int va;
3622 ///   extern int vb;  // Doesn't match, as it doesn't define the variable.
3623 ///   void fa() {}
3624 ///   void fb();  // Doesn't match, as it has no body.
3625 /// \endcode
3626 ///
3627 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
3628 AST_POLYMORPHIC_MATCHER(isDefinition,
3629                         AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
3630                                                         FunctionDecl)) {
3631   return Node.isThisDeclarationADefinition();
3632 }
3633
3634 /// \brief Matches if a function declaration is variadic.
3635 ///
3636 /// Example matches f, but not g or h. The function i will not match, even when
3637 /// compiled in C mode.
3638 /// \code
3639 ///   void f(...);
3640 ///   void g(int);
3641 ///   template <typename... Ts> void h(Ts...);
3642 ///   void i();
3643 /// \endcode
3644 AST_MATCHER(FunctionDecl, isVariadic) {
3645   return Node.isVariadic();
3646 }
3647
3648 /// \brief Matches the class declaration that the given method declaration
3649 /// belongs to.
3650 ///
3651 /// FIXME: Generalize this for other kinds of declarations.
3652 /// FIXME: What other kind of declarations would we need to generalize
3653 /// this to?
3654 ///
3655 /// Example matches A() in the last line
3656 ///     (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
3657 ///         ofClass(hasName("A"))))))
3658 /// \code
3659 ///   class A {
3660 ///    public:
3661 ///     A();
3662 ///   };
3663 ///   A a = A();
3664 /// \endcode
3665 AST_MATCHER_P(CXXMethodDecl, ofClass,
3666               internal::Matcher<CXXRecordDecl>, InnerMatcher) {
3667   const CXXRecordDecl *Parent = Node.getParent();
3668   return (Parent != nullptr &&
3669           InnerMatcher.matches(*Parent, Finder, Builder));
3670 }
3671
3672 /// \brief Matches if the given method declaration is virtual.
3673 ///
3674 /// Given
3675 /// \code
3676 ///   class A {
3677 ///    public:
3678 ///     virtual void x();
3679 ///   };
3680 /// \endcode
3681 ///   matches A::x
3682 AST_MATCHER(CXXMethodDecl, isVirtual) {
3683   return Node.isVirtual();
3684 }
3685
3686 /// \brief Matches if the given method declaration has an explicit "virtual".
3687 ///
3688 /// Given
3689 /// \code
3690 ///   class A {
3691 ///    public:
3692 ///     virtual void x();
3693 ///   };
3694 ///   class B : public A {
3695 ///    public:
3696 ///     void x();
3697 ///   };
3698 /// \endcode
3699 ///   matches A::x but not B::x
3700 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
3701   return Node.isVirtualAsWritten();
3702 }
3703
3704 /// \brief Matches if the given method or class declaration is final.
3705 ///
3706 /// Given:
3707 /// \code
3708 ///   class A final {};
3709 ///
3710 ///   struct B {
3711 ///     virtual void f();
3712 ///   };
3713 ///
3714 ///   struct C : B {
3715 ///     void f() final;
3716 ///   };
3717 /// \endcode
3718 /// matches A and C::f, but not B, C, or B::f
3719 AST_POLYMORPHIC_MATCHER(isFinal,
3720                         AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
3721                                                         CXXMethodDecl)) {
3722   return Node.template hasAttr<FinalAttr>();
3723 }
3724
3725 /// \brief Matches if the given method declaration is pure.
3726 ///
3727 /// Given
3728 /// \code
3729 ///   class A {
3730 ///    public:
3731 ///     virtual void x() = 0;
3732 ///   };
3733 /// \endcode
3734 ///   matches A::x
3735 AST_MATCHER(CXXMethodDecl, isPure) {
3736   return Node.isPure();
3737 }
3738
3739 /// \brief Matches if the given method declaration is const.
3740 ///
3741 /// Given
3742 /// \code
3743 /// struct A {
3744 ///   void foo() const;
3745 ///   void bar();
3746 /// };
3747 /// \endcode
3748 ///
3749 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
3750 AST_MATCHER(CXXMethodDecl, isConst) {
3751   return Node.isConst();
3752 }
3753
3754 /// \brief Matches if the given method declaration declares a copy assignment
3755 /// operator.
3756 ///
3757 /// Given
3758 /// \code
3759 /// struct A {
3760 ///   A &operator=(const A &);
3761 ///   A &operator=(A &&);
3762 /// };
3763 /// \endcode
3764 ///
3765 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
3766 /// the second one.
3767 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
3768   return Node.isCopyAssignmentOperator();
3769 }
3770
3771 /// \brief Matches if the given method declaration declares a move assignment
3772 /// operator.
3773 ///
3774 /// Given
3775 /// \code
3776 /// struct A {
3777 ///   A &operator=(const A &);
3778 ///   A &operator=(A &&);
3779 /// };
3780 /// \endcode
3781 ///
3782 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
3783 /// the first one.
3784 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
3785   return Node.isMoveAssignmentOperator();
3786 }
3787
3788 /// \brief Matches if the given method declaration overrides another method.
3789 ///
3790 /// Given
3791 /// \code
3792 ///   class A {
3793 ///    public:
3794 ///     virtual void x();
3795 ///   };
3796 ///   class B : public A {
3797 ///    public:
3798 ///     virtual void x();
3799 ///   };
3800 /// \endcode
3801 ///   matches B::x
3802 AST_MATCHER(CXXMethodDecl, isOverride) {
3803   return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
3804 }
3805
3806 /// \brief Matches member expressions that are called with '->' as opposed
3807 /// to '.'.
3808 ///
3809 /// Member calls on the implicit this pointer match as called with '->'.
3810 ///
3811 /// Given
3812 /// \code
3813 ///   class Y {
3814 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
3815 ///     int a;
3816 ///     static int b;
3817 ///   };
3818 /// \endcode
3819 /// memberExpr(isArrow())
3820 ///   matches this->x, x, y.x, a, this->b
3821 AST_MATCHER(MemberExpr, isArrow) {
3822   return Node.isArrow();
3823 }
3824
3825 /// \brief Matches QualType nodes that are of integer type.
3826 ///
3827 /// Given
3828 /// \code
3829 ///   void a(int);
3830 ///   void b(long);
3831 ///   void c(double);
3832 /// \endcode
3833 /// functionDecl(hasAnyParameter(hasType(isInteger())))
3834 /// matches "a(int)", "b(long)", but not "c(double)".
3835 AST_MATCHER(QualType, isInteger) {
3836     return Node->isIntegerType();
3837 }
3838
3839 /// \brief Matches QualType nodes that are of character type.
3840 ///
3841 /// Given
3842 /// \code
3843 ///   void a(char);
3844 ///   void b(wchar_t);
3845 ///   void c(double);
3846 /// \endcode
3847 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
3848 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
3849 AST_MATCHER(QualType, isAnyCharacter) {
3850     return Node->isAnyCharacterType();
3851 }
3852
3853 /// \brief Matches QualType nodes that are of any pointer type; this includes
3854 /// the Objective-C object pointer type, which is different despite being
3855 /// syntactically similar.
3856 ///
3857 /// Given
3858 /// \code
3859 ///   int *i = nullptr;
3860 ///
3861 ///   @interface Foo
3862 ///   @end
3863 ///   Foo *f;
3864 ///
3865 ///   int j;
3866 /// \endcode
3867 /// varDecl(hasType(isAnyPointer()))
3868 ///   matches "int *i" and "Foo *f", but not "int j".
3869 AST_MATCHER(QualType, isAnyPointer) {
3870   return Node->isAnyPointerType();
3871 }
3872
3873 /// \brief Matches QualType nodes that are const-qualified, i.e., that
3874 /// include "top-level" const.
3875 ///
3876 /// Given
3877 /// \code
3878 ///   void a(int);
3879 ///   void b(int const);
3880 ///   void c(const int);
3881 ///   void d(const int*);
3882 ///   void e(int const) {};
3883 /// \endcode
3884 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
3885 ///   matches "void b(int const)", "void c(const int)" and
3886 ///   "void e(int const) {}". It does not match d as there
3887 ///   is no top-level const on the parameter type "const int *".
3888 AST_MATCHER(QualType, isConstQualified) {
3889   return Node.isConstQualified();
3890 }
3891
3892 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
3893 /// include "top-level" volatile.
3894 ///
3895 /// Given
3896 /// \code
3897 ///   void a(int);
3898 ///   void b(int volatile);
3899 ///   void c(volatile int);
3900 ///   void d(volatile int*);
3901 ///   void e(int volatile) {};
3902 /// \endcode
3903 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
3904 ///   matches "void b(int volatile)", "void c(volatile int)" and
3905 ///   "void e(int volatile) {}". It does not match d as there
3906 ///   is no top-level volatile on the parameter type "volatile int *".
3907 AST_MATCHER(QualType, isVolatileQualified) {
3908   return Node.isVolatileQualified();
3909 }
3910
3911 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
3912 /// the node, not hidden within a typedef.
3913 ///
3914 /// Given
3915 /// \code
3916 ///   typedef const int const_int;
3917 ///   const_int i;
3918 ///   int *const j;
3919 ///   int *volatile k;
3920 ///   int m;
3921 /// \endcode
3922 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
3923 /// \c i is const-qualified but the qualifier is not local.
3924 AST_MATCHER(QualType, hasLocalQualifiers) {
3925   return Node.hasLocalQualifiers();
3926 }
3927
3928 /// \brief Matches a member expression where the member is matched by a
3929 /// given matcher.
3930 ///
3931 /// Given
3932 /// \code
3933 ///   struct { int first, second; } first, second;
3934 ///   int i(second.first);
3935 ///   int j(first.second);
3936 /// \endcode
3937 /// memberExpr(member(hasName("first")))
3938 ///   matches second.first
3939 ///   but not first.second (because the member name there is "second").
3940 AST_MATCHER_P(MemberExpr, member,
3941               internal::Matcher<ValueDecl>, InnerMatcher) {
3942   return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
3943 }
3944
3945 /// \brief Matches a member expression where the object expression is
3946 /// matched by a given matcher.
3947 ///
3948 /// Given
3949 /// \code
3950 ///   struct X { int m; };
3951 ///   void f(X x) { x.m; m; }
3952 /// \endcode
3953 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
3954 ///   matches "x.m" and "m"
3955 /// with hasObjectExpression(...)
3956 ///   matching "x" and the implicit object expression of "m" which has type X*.
3957 AST_MATCHER_P(MemberExpr, hasObjectExpression,
3958               internal::Matcher<Expr>, InnerMatcher) {
3959   return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
3960 }
3961
3962 /// \brief Matches any using shadow declaration.
3963 ///
3964 /// Given
3965 /// \code
3966 ///   namespace X { void b(); }
3967 ///   using X::b;
3968 /// \endcode
3969 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
3970 ///   matches \code using X::b \endcode
3971 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
3972               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3973   return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
3974                                     Node.shadow_end(), Finder, Builder);
3975 }
3976
3977 /// \brief Matches a using shadow declaration where the target declaration is
3978 /// matched by the given matcher.
3979 ///
3980 /// Given
3981 /// \code
3982 ///   namespace X { int a; void b(); }
3983 ///   using X::a;
3984 ///   using X::b;
3985 /// \endcode
3986 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
3987 ///   matches \code using X::b \endcode
3988 ///   but not \code using X::a \endcode
3989 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
3990               internal::Matcher<NamedDecl>, InnerMatcher) {
3991   return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
3992 }
3993
3994 /// \brief Matches template instantiations of function, class, or static
3995 /// member variable template instantiations.
3996 ///
3997 /// Given
3998 /// \code
3999 ///   template <typename T> class X {}; class A {}; X<A> x;
4000 /// \endcode
4001 /// or
4002 /// \code
4003 ///   template <typename T> class X {}; class A {}; template class X<A>;
4004 /// \endcode
4005 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4006 ///   matches the template instantiation of X<A>.
4007 ///
4008 /// But given
4009 /// \code
4010 ///   template <typename T>  class X {}; class A {};
4011 ///   template <> class X<A> {}; X<A> x;
4012 /// \endcode
4013 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4014 ///   does not match, as X<A> is an explicit template specialization.
4015 ///
4016 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4017 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4018                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4019                                                         CXXRecordDecl)) {
4020   return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4021           Node.getTemplateSpecializationKind() ==
4022           TSK_ExplicitInstantiationDefinition);
4023 }
4024
4025 /// \brief Matches declarations that are template instantiations or are inside
4026 /// template instantiations.
4027 ///
4028 /// Given
4029 /// \code
4030 ///   template<typename T> void A(T t) { T i; }
4031 ///   A(0);
4032 ///   A(0U);
4033 /// \endcode
4034 /// functionDecl(isInstantiated())
4035 ///   matches 'A(int) {...};' and 'A(unsigned) {...}'.
4036 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4037   auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4038                                     functionDecl(isTemplateInstantiation())));
4039   return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4040 }
4041
4042 /// \brief Matches statements inside of a template instantiation.
4043 ///
4044 /// Given
4045 /// \code
4046 ///   int j;
4047 ///   template<typename T> void A(T t) { T i; j += 42;}
4048 ///   A(0);
4049 ///   A(0U);
4050 /// \endcode
4051 /// declStmt(isInTemplateInstantiation())
4052 ///   matches 'int i;' and 'unsigned i'.
4053 /// unless(stmt(isInTemplateInstantiation()))
4054 ///   will NOT match j += 42; as it's shared between the template definition and
4055 ///   instantiation.
4056 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4057   return stmt(
4058       hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4059                              functionDecl(isTemplateInstantiation())))));
4060 }
4061
4062 /// \brief Matches explicit template specializations of function, class, or
4063 /// static member variable template instantiations.
4064 ///
4065 /// Given
4066 /// \code
4067 ///   template<typename T> void A(T t) { }
4068 ///   template<> void A(int N) { }
4069 /// \endcode
4070 /// functionDecl(isExplicitTemplateSpecialization())
4071 ///   matches the specialization A<int>().
4072 ///
4073 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4074 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4075                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4076                                                         CXXRecordDecl)) {
4077   return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4078 }
4079
4080 /// \brief Matches \c TypeLocs for which the given inner
4081 /// QualType-matcher matches.
4082 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4083                                 internal::Matcher<QualType>, InnerMatcher, 0) {
4084   return internal::BindableMatcher<TypeLoc>(
4085       new internal::TypeLocTypeMatcher(InnerMatcher));
4086 }
4087
4088 /// \brief Matches type \c bool.
4089 ///
4090 /// Given
4091 /// \code
4092 ///  struct S { bool func(); };
4093 /// \endcode
4094 /// functionDecl(returns(booleanType()))
4095 ///   matches "bool func();"
4096 AST_MATCHER(Type, booleanType) {
4097   return Node.isBooleanType();
4098 }
4099
4100 /// \brief Matches type \c void.
4101 ///
4102 /// Given
4103 /// \code
4104 ///  struct S { void func(); };
4105 /// \endcode
4106 /// functionDecl(returns(voidType()))
4107 ///   matches "void func();"
4108 AST_MATCHER(Type, voidType) {
4109   return Node.isVoidType();
4110 }
4111
4112 /// \brief Matches builtin Types.
4113 ///
4114 /// Given
4115 /// \code
4116 ///   struct A {};
4117 ///   A a;
4118 ///   int b;
4119 ///   float c;
4120 ///   bool d;
4121 /// \endcode
4122 /// builtinType()
4123 ///   matches "int b", "float c" and "bool d"
4124 AST_TYPE_MATCHER(BuiltinType, builtinType);
4125
4126 /// \brief Matches all kinds of arrays.
4127 ///
4128 /// Given
4129 /// \code
4130 ///   int a[] = { 2, 3 };
4131 ///   int b[4];
4132 ///   void f() { int c[a[0]]; }
4133 /// \endcode
4134 /// arrayType()
4135 ///   matches "int a[]", "int b[4]" and "int c[a[0]]";
4136 AST_TYPE_MATCHER(ArrayType, arrayType);
4137
4138 /// \brief Matches C99 complex types.
4139 ///
4140 /// Given
4141 /// \code
4142 ///   _Complex float f;
4143 /// \endcode
4144 /// complexType()
4145 ///   matches "_Complex float f"
4146 AST_TYPE_MATCHER(ComplexType, complexType);
4147
4148 /// \brief Matches any real floating-point type (float, double, long double).
4149 ///
4150 /// Given
4151 /// \code
4152 ///   int i;
4153 ///   float f;
4154 /// \endcode
4155 /// realFloatingPointType()
4156 ///   matches "float f" but not "int i"
4157 AST_MATCHER(Type, realFloatingPointType) {
4158   return Node.isRealFloatingType();
4159 }
4160
4161 /// \brief Matches arrays and C99 complex types that have a specific element
4162 /// type.
4163 ///
4164 /// Given
4165 /// \code
4166 ///   struct A {};
4167 ///   A a[7];
4168 ///   int b[7];
4169 /// \endcode
4170 /// arrayType(hasElementType(builtinType()))
4171 ///   matches "int b[7]"
4172 ///
4173 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
4174 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
4175                              AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
4176                                                              ComplexType));
4177
4178 /// \brief Matches C arrays with a specified constant size.
4179 ///
4180 /// Given
4181 /// \code
4182 ///   void() {
4183 ///     int a[2];
4184 ///     int b[] = { 2, 3 };
4185 ///     int c[b[0]];
4186 ///   }
4187 /// \endcode
4188 /// constantArrayType()
4189 ///   matches "int a[2]"
4190 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
4191
4192 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
4193 ///
4194 /// Given
4195 /// \code
4196 ///   int a[42];
4197 ///   int b[2 * 21];
4198 ///   int c[41], d[43];
4199 /// \endcode
4200 /// constantArrayType(hasSize(42))
4201 ///   matches "int a[42]" and "int b[2 * 21]"
4202 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
4203   return Node.getSize() == N;
4204 }
4205
4206 /// \brief Matches C++ arrays whose size is a value-dependent expression.
4207 ///
4208 /// Given
4209 /// \code
4210 ///   template<typename T, int Size>
4211 ///   class array {
4212 ///     T data[Size];
4213 ///   };
4214 /// \endcode
4215 /// dependentSizedArrayType
4216 ///   matches "T data[Size]"
4217 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
4218
4219 /// \brief Matches C arrays with unspecified size.
4220 ///
4221 /// Given
4222 /// \code
4223 ///   int a[] = { 2, 3 };
4224 ///   int b[42];
4225 ///   void f(int c[]) { int d[a[0]]; };
4226 /// \endcode
4227 /// incompleteArrayType()
4228 ///   matches "int a[]" and "int c[]"
4229 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
4230
4231 /// \brief Matches C arrays with a specified size that is not an
4232 /// integer-constant-expression.
4233 ///
4234 /// Given
4235 /// \code
4236 ///   void f() {
4237 ///     int a[] = { 2, 3 }
4238 ///     int b[42];
4239 ///     int c[a[0]];
4240 ///   }
4241 /// \endcode
4242 /// variableArrayType()
4243 ///   matches "int c[a[0]]"
4244 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
4245
4246 /// \brief Matches \c VariableArrayType nodes that have a specific size
4247 /// expression.
4248 ///
4249 /// Given
4250 /// \code
4251 ///   void f(int b) {
4252 ///     int a[b];
4253 ///   }
4254 /// \endcode
4255 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4256 ///   varDecl(hasName("b")))))))
4257 ///   matches "int a[b]"
4258 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
4259               internal::Matcher<Expr>, InnerMatcher) {
4260   return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
4261 }
4262
4263 /// \brief Matches atomic types.
4264 ///
4265 /// Given
4266 /// \code
4267 ///   _Atomic(int) i;
4268 /// \endcode
4269 /// atomicType()
4270 ///   matches "_Atomic(int) i"
4271 AST_TYPE_MATCHER(AtomicType, atomicType);
4272
4273 /// \brief Matches atomic types with a specific value type.
4274 ///
4275 /// Given
4276 /// \code
4277 ///   _Atomic(int) i;
4278 ///   _Atomic(float) f;
4279 /// \endcode
4280 /// atomicType(hasValueType(isInteger()))
4281 ///  matches "_Atomic(int) i"
4282 ///
4283 /// Usable as: Matcher<AtomicType>
4284 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
4285                              AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
4286
4287 /// \brief Matches types nodes representing C++11 auto types.
4288 ///
4289 /// Given:
4290 /// \code
4291 ///   auto n = 4;
4292 ///   int v[] = { 2, 3 }
4293 ///   for (auto i : v) { }
4294 /// \endcode
4295 /// autoType()
4296 ///   matches "auto n" and "auto i"
4297 AST_TYPE_MATCHER(AutoType, autoType);
4298
4299 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
4300 ///
4301 /// Note: There is no \c TypeLoc for the deduced type and thus no
4302 /// \c getDeducedLoc() matcher.
4303 ///
4304 /// Given
4305 /// \code
4306 ///   auto a = 1;
4307 ///   auto b = 2.0;
4308 /// \endcode
4309 /// autoType(hasDeducedType(isInteger()))
4310 ///   matches "auto a"
4311 ///
4312 /// Usable as: Matcher<AutoType>
4313 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
4314                           AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
4315
4316 /// \brief Matches \c FunctionType nodes.
4317 ///
4318 /// Given
4319 /// \code
4320 ///   int (*f)(int);
4321 ///   void g();
4322 /// \endcode
4323 /// functionType()
4324 ///   matches "int (*f)(int)" and the type of "g".
4325 AST_TYPE_MATCHER(FunctionType, functionType);
4326
4327 /// \brief Matches \c FunctionProtoType nodes.
4328 ///
4329 /// Given
4330 /// \code
4331 ///   int (*f)(int);
4332 ///   void g();
4333 /// \endcode
4334 /// functionProtoType()
4335 ///   matches "int (*f)(int)" and the type of "g" in C++ mode.
4336 ///   In C mode, "g" is not matched because it does not contain a prototype.
4337 AST_TYPE_MATCHER(FunctionProtoType, functionProtoType);
4338
4339 /// \brief Matches \c ParenType nodes.
4340 ///
4341 /// Given
4342 /// \code
4343 ///   int (*ptr_to_array)[4];
4344 ///   int *array_of_ptrs[4];
4345 /// \endcode
4346 ///
4347 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4348 /// \c array_of_ptrs.
4349 AST_TYPE_MATCHER(ParenType, parenType);
4350
4351 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4352 ///
4353 /// Given
4354 /// \code
4355 ///   int (*ptr_to_array)[4];
4356 ///   int (*ptr_to_func)(int);
4357 /// \endcode
4358 ///
4359 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4360 /// \c ptr_to_func but not \c ptr_to_array.
4361 ///
4362 /// Usable as: Matcher<ParenType>
4363 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4364                           AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4365
4366 /// \brief Matches block pointer types, i.e. types syntactically represented as
4367 /// "void (^)(int)".
4368 ///
4369 /// The \c pointee is always required to be a \c FunctionType.
4370 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4371
4372 /// \brief Matches member pointer types.
4373 /// Given
4374 /// \code
4375 ///   struct A { int i; }
4376 ///   A::* ptr = A::i;
4377 /// \endcode
4378 /// memberPointerType()
4379 ///   matches "A::* ptr"
4380 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4381
4382 /// \brief Matches pointer types, but does not match Objective-C object pointer
4383 /// types.
4384 ///
4385 /// Given
4386 /// \code
4387 ///   int *a;
4388 ///   int &b = *a;
4389 ///   int c = 5;
4390 ///
4391 ///   @interface Foo
4392 ///   @end
4393 ///   Foo *f;
4394 /// \endcode
4395 /// pointerType()
4396 ///   matches "int *a", but does not match "Foo *f".
4397 AST_TYPE_MATCHER(PointerType, pointerType);
4398
4399 /// \brief Matches an Objective-C object pointer type, which is different from
4400 /// a pointer type, despite being syntactically similar.
4401 ///
4402 /// Given
4403 /// \code
4404 ///   int *a;
4405 ///
4406 ///   @interface Foo
4407 ///   @end
4408 ///   Foo *f;
4409 /// \endcode
4410 /// pointerType()
4411 ///   matches "Foo *f", but does not match "int *a".
4412 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4413
4414 /// \brief Matches both lvalue and rvalue reference types.
4415 ///
4416 /// Given
4417 /// \code
4418 ///   int *a;
4419 ///   int &b = *a;
4420 ///   int &&c = 1;
4421 ///   auto &d = b;
4422 ///   auto &&e = c;
4423 ///   auto &&f = 2;
4424 ///   int g = 5;
4425 /// \endcode
4426 ///
4427 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4428 AST_TYPE_MATCHER(ReferenceType, referenceType);
4429
4430 /// \brief Matches lvalue reference types.
4431 ///
4432 /// Given:
4433 /// \code
4434 ///   int *a;
4435 ///   int &b = *a;
4436 ///   int &&c = 1;
4437 ///   auto &d = b;
4438 ///   auto &&e = c;
4439 ///   auto &&f = 2;
4440 ///   int g = 5;
4441 /// \endcode
4442 ///
4443 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4444 /// matched since the type is deduced as int& by reference collapsing rules.
4445 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4446
4447 /// \brief Matches rvalue reference types.
4448 ///
4449 /// Given:
4450 /// \code
4451 ///   int *a;
4452 ///   int &b = *a;
4453 ///   int &&c = 1;
4454 ///   auto &d = b;
4455 ///   auto &&e = c;
4456 ///   auto &&f = 2;
4457 ///   int g = 5;
4458 /// \endcode
4459 ///
4460 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4461 /// matched as it is deduced to int& by reference collapsing rules.
4462 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4463
4464 /// \brief Narrows PointerType (and similar) matchers to those where the
4465 /// \c pointee matches a given matcher.
4466 ///
4467 /// Given
4468 /// \code
4469 ///   int *a;
4470 ///   int const *b;
4471 ///   float const *f;
4472 /// \endcode
4473 /// pointerType(pointee(isConstQualified(), isInteger()))
4474 ///   matches "int const *b"
4475 ///
4476 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4477 ///   Matcher<PointerType>, Matcher<ReferenceType>
4478 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4479                              AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4480                                                              MemberPointerType,
4481                                                              PointerType,
4482                                                              ReferenceType));
4483
4484 /// \brief Matches typedef types.
4485 ///
4486 /// Given
4487 /// \code
4488 ///   typedef int X;
4489 /// \endcode
4490 /// typedefType()
4491 ///   matches "typedef int X"
4492 AST_TYPE_MATCHER(TypedefType, typedefType);
4493
4494 /// \brief Matches template specialization types.
4495 ///
4496 /// Given
4497 /// \code
4498 ///   template <typename T>
4499 ///   class C { };
4500 ///
4501 ///   template class C<int>;  // A
4502 ///   C<char> var;            // B
4503 /// \endcode
4504 ///
4505 /// \c templateSpecializationType() matches the type of the explicit
4506 /// instantiation in \c A and the type of the variable declaration in \c B.
4507 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
4508
4509 /// \brief Matches types nodes representing unary type transformations.
4510 ///
4511 /// Given:
4512 /// \code
4513 ///   typedef __underlying_type(T) type;
4514 /// \endcode
4515 /// unaryTransformType()
4516 ///   matches "__underlying_type(T)"
4517 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
4518
4519 /// \brief Matches record types (e.g. structs, classes).
4520 ///
4521 /// Given
4522 /// \code
4523 ///   class C {};
4524 ///   struct S {};
4525 ///
4526 ///   C c;
4527 ///   S s;
4528 /// \endcode
4529 ///
4530 /// \c recordType() matches the type of the variable declarations of both \c c
4531 /// and \c s.
4532 AST_TYPE_MATCHER(RecordType, recordType);
4533
4534 /// \brief Matches types specified with an elaborated type keyword or with a
4535 /// qualified name.
4536 ///
4537 /// Given
4538 /// \code
4539 ///   namespace N {
4540 ///     namespace M {
4541 ///       class D {};
4542 ///     }
4543 ///   }
4544 ///   class C {};
4545 ///
4546 ///   class C c;
4547 ///   N::M::D d;
4548 /// \endcode
4549 ///
4550 /// \c elaboratedType() matches the type of the variable declarations of both
4551 /// \c c and \c d.
4552 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
4553
4554 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
4555 /// matches \c InnerMatcher if the qualifier exists.
4556 ///
4557 /// Given
4558 /// \code
4559 ///   namespace N {
4560 ///     namespace M {
4561 ///       class D {};
4562 ///     }
4563 ///   }
4564 ///   N::M::D d;
4565 /// \endcode
4566 ///
4567 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
4568 /// matches the type of the variable declaration of \c d.
4569 AST_MATCHER_P(ElaboratedType, hasQualifier,
4570               internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
4571   if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
4572     return InnerMatcher.matches(*Qualifier, Finder, Builder);
4573
4574   return false;
4575 }
4576
4577 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
4578 ///
4579 /// Given
4580 /// \code
4581 ///   namespace N {
4582 ///     namespace M {
4583 ///       class D {};
4584 ///     }
4585 ///   }
4586 ///   N::M::D d;
4587 /// \endcode
4588 ///
4589 /// \c elaboratedType(namesType(recordType(
4590 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
4591 /// declaration of \c d.
4592 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
4593               InnerMatcher) {
4594   return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
4595 }
4596
4597 /// \brief Matches types that represent the result of substituting a type for a
4598 /// template type parameter.
4599 ///
4600 /// Given
4601 /// \code
4602 ///   template <typename T>
4603 ///   void F(T t) {
4604 ///     int i = 1 + t;
4605 ///   }
4606 /// \endcode
4607 ///
4608 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
4609 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
4610
4611 /// \brief Matches template type parameter types.
4612 ///
4613 /// Example matches T, but not int.
4614 ///     (matcher = templateTypeParmType())
4615 /// \code
4616 ///   template <typename T> void f(int i);
4617 /// \endcode
4618 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
4619
4620 /// \brief Matches injected class name types.
4621 ///
4622 /// Example matches S s, but not S<T> s.
4623 ///     (matcher = parmVarDecl(hasType(injectedClassNameType())))
4624 /// \code
4625 ///   template <typename T> struct S {
4626 ///     void f(S s);
4627 ///     void g(S<T> s);
4628 ///   };
4629 /// \endcode
4630 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
4631
4632 /// \brief Matches decayed type
4633 /// Example matches i[] in declaration of f.
4634 ///     (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
4635 /// Example matches i[1].
4636 ///     (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
4637 /// \code
4638 ///   void f(int i[]) {
4639 ///     i[1] = 0;
4640 ///   }
4641 /// \endcode
4642 AST_TYPE_MATCHER(DecayedType, decayedType);
4643
4644 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
4645 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
4646               InnerType) {
4647   return InnerType.matches(Node.getDecayedType(), Finder, Builder);
4648 }
4649
4650 /// \brief Matches declarations whose declaration context, interpreted as a
4651 /// Decl, matches \c InnerMatcher.
4652 ///
4653 /// Given
4654 /// \code
4655 ///   namespace N {
4656 ///     namespace M {
4657 ///       class D {};
4658 ///     }
4659 ///   }
4660 /// \endcode
4661 ///
4662 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
4663 /// declaration of \c class \c D.
4664 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
4665   const DeclContext *DC = Node.getDeclContext();
4666   if (!DC) return false;
4667   return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
4668 }
4669
4670 /// \brief Matches nested name specifiers.
4671 ///
4672 /// Given
4673 /// \code
4674 ///   namespace ns {
4675 ///     struct A { static void f(); };
4676 ///     void A::f() {}
4677 ///     void g() { A::f(); }
4678 ///   }
4679 ///   ns::A a;
4680 /// \endcode
4681 /// nestedNameSpecifier()
4682 ///   matches "ns::" and both "A::"
4683 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
4684
4685 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
4686 const internal::VariadicAllOfMatcher<
4687   NestedNameSpecifierLoc> nestedNameSpecifierLoc;
4688
4689 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
4690 /// NestedNameSpecifier-matcher matches.
4691 AST_MATCHER_FUNCTION_P_OVERLOAD(
4692     internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
4693     internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
4694   return internal::BindableMatcher<NestedNameSpecifierLoc>(
4695       new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
4696           InnerMatcher));
4697 }
4698
4699 /// \brief Matches nested name specifiers that specify a type matching the
4700 /// given \c QualType matcher without qualifiers.
4701 ///
4702 /// Given
4703 /// \code
4704 ///   struct A { struct B { struct C {}; }; };
4705 ///   A::B::C c;
4706 /// \endcode
4707 /// nestedNameSpecifier(specifiesType(
4708 ///   hasDeclaration(cxxRecordDecl(hasName("A")))
4709 /// ))
4710 ///   matches "A::"
4711 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
4712               internal::Matcher<QualType>, InnerMatcher) {
4713   if (!Node.getAsType())
4714     return false;
4715   return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
4716 }
4717
4718 /// \brief Matches nested name specifier locs that specify a type matching the
4719 /// given \c TypeLoc.
4720 ///
4721 /// Given
4722 /// \code
4723 ///   struct A { struct B { struct C {}; }; };
4724 ///   A::B::C c;
4725 /// \endcode
4726 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
4727 ///   hasDeclaration(cxxRecordDecl(hasName("A")))))))
4728 ///   matches "A::"
4729 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
4730               internal::Matcher<TypeLoc>, InnerMatcher) {
4731   return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
4732 }
4733
4734 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
4735 ///
4736 /// Given
4737 /// \code
4738 ///   struct A { struct B { struct C {}; }; };
4739 ///   A::B::C c;
4740 /// \endcode
4741 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
4742 ///   matches "A::"
4743 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
4744                        internal::Matcher<NestedNameSpecifier>, InnerMatcher,
4745                        0) {
4746   const NestedNameSpecifier *NextNode = Node.getPrefix();
4747   if (!NextNode)
4748     return false;
4749   return InnerMatcher.matches(*NextNode, Finder, Builder);
4750 }
4751
4752 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
4753 ///
4754 /// Given
4755 /// \code
4756 ///   struct A { struct B { struct C {}; }; };
4757 ///   A::B::C c;
4758 /// \endcode
4759 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
4760 ///   matches "A::"
4761 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
4762                        internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
4763                        1) {
4764   NestedNameSpecifierLoc NextNode = Node.getPrefix();
4765   if (!NextNode)
4766     return false;
4767   return InnerMatcher.matches(NextNode, Finder, Builder);
4768 }
4769
4770 /// \brief Matches nested name specifiers that specify a namespace matching the
4771 /// given namespace matcher.
4772 ///
4773 /// Given
4774 /// \code
4775 ///   namespace ns { struct A {}; }
4776 ///   ns::A a;
4777 /// \endcode
4778 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
4779 ///   matches "ns::"
4780 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
4781               internal::Matcher<NamespaceDecl>, InnerMatcher) {
4782   if (!Node.getAsNamespace())
4783     return false;
4784   return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
4785 }
4786
4787 /// \brief Overloads for the \c equalsNode matcher.
4788 /// FIXME: Implement for other node types.
4789 /// @{
4790
4791 /// \brief Matches if a node equals another node.
4792 ///
4793 /// \c Decl has pointer identity in the AST.
4794 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
4795   return &Node == Other;
4796 }
4797 /// \brief Matches if a node equals another node.
4798 ///
4799 /// \c Stmt has pointer identity in the AST.
4800 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
4801   return &Node == Other;
4802 }
4803 /// \brief Matches if a node equals another node.
4804 ///
4805 /// \c Type has pointer identity in the AST.
4806 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
4807     return &Node == Other;
4808 }
4809
4810 /// @}
4811
4812 /// \brief Matches each case or default statement belonging to the given switch
4813 /// statement. This matcher may produce multiple matches.
4814 ///
4815 /// Given
4816 /// \code
4817 ///   switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
4818 /// \endcode
4819 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
4820 ///   matches four times, with "c" binding each of "case 1:", "case 2:",
4821 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
4822 /// "switch (1)", "switch (2)" and "switch (2)".
4823 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
4824               InnerMatcher) {
4825   BoundNodesTreeBuilder Result;
4826   // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
4827   // iteration order. We should use the more general iterating matchers once
4828   // they are capable of expressing this matcher (for example, it should ignore
4829   // case statements belonging to nested switch statements).
4830   bool Matched = false;
4831   for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
4832        SC = SC->getNextSwitchCase()) {
4833     BoundNodesTreeBuilder CaseBuilder(*Builder);
4834     bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
4835     if (CaseMatched) {
4836       Matched = true;
4837       Result.addMatch(CaseBuilder);
4838     }
4839   }
4840   *Builder = std::move(Result);
4841   return Matched;
4842 }
4843
4844 /// \brief Matches each constructor initializer in a constructor definition.
4845 ///
4846 /// Given
4847 /// \code
4848 ///   class A { A() : i(42), j(42) {} int i; int j; };
4849 /// \endcode
4850 /// cxxConstructorDecl(forEachConstructorInitializer(
4851 ///   forField(decl().bind("x"))
4852 /// ))
4853 ///   will trigger two matches, binding for 'i' and 'j' respectively.
4854 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
4855               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4856   BoundNodesTreeBuilder Result;
4857   bool Matched = false;
4858   for (const auto *I : Node.inits()) {
4859     BoundNodesTreeBuilder InitBuilder(*Builder);
4860     if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
4861       Matched = true;
4862       Result.addMatch(InitBuilder);
4863     }
4864   }
4865   *Builder = std::move(Result);
4866   return Matched;
4867 }
4868
4869 /// \brief Matches constructor declarations that are copy constructors.
4870 ///
4871 /// Given
4872 /// \code
4873 ///   struct S {
4874 ///     S(); // #1
4875 ///     S(const S &); // #2
4876 ///     S(S &&); // #3
4877 ///   };
4878 /// \endcode
4879 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
4880 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
4881   return Node.isCopyConstructor();
4882 }
4883
4884 /// \brief Matches constructor declarations that are move constructors.
4885 ///
4886 /// Given
4887 /// \code
4888 ///   struct S {
4889 ///     S(); // #1
4890 ///     S(const S &); // #2
4891 ///     S(S &&); // #3
4892 ///   };
4893 /// \endcode
4894 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
4895 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
4896   return Node.isMoveConstructor();
4897 }
4898
4899 /// \brief Matches constructor declarations that are default constructors.
4900 ///
4901 /// Given
4902 /// \code
4903 ///   struct S {
4904 ///     S(); // #1
4905 ///     S(const S &); // #2
4906 ///     S(S &&); // #3
4907 ///   };
4908 /// \endcode
4909 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
4910 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
4911   return Node.isDefaultConstructor();
4912 }
4913
4914 /// \brief Matches constructor and conversion declarations that are marked with
4915 /// the explicit keyword.
4916 ///
4917 /// Given
4918 /// \code
4919 ///   struct S {
4920 ///     S(int); // #1
4921 ///     explicit S(double); // #2
4922 ///     operator int(); // #3
4923 ///     explicit operator bool(); // #4
4924 ///   };
4925 /// \endcode
4926 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
4927 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
4928 AST_POLYMORPHIC_MATCHER(isExplicit,
4929                         AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
4930                                                         CXXConversionDecl)) {
4931   return Node.isExplicit();
4932 }
4933
4934 /// \brief Matches function and namespace declarations that are marked with
4935 /// the inline keyword.
4936 ///
4937 /// Given
4938 /// \code
4939 ///   inline void f();
4940 ///   void g();
4941 ///   namespace n {
4942 ///   inline namespace m {}
4943 ///   }
4944 /// \endcode
4945 /// functionDecl(isInline()) will match ::f().
4946 /// namespaceDecl(isInline()) will match n::m.
4947 AST_POLYMORPHIC_MATCHER(isInline,
4948                         AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
4949                                                         FunctionDecl)) {
4950   // This is required because the spelling of the function used to determine
4951   // whether inline is specified or not differs between the polymorphic types.
4952   if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
4953     return FD->isInlineSpecified();
4954   else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
4955     return NSD->isInline();
4956   llvm_unreachable("Not a valid polymorphic type");
4957 }
4958
4959 /// \brief Matches anonymous namespace declarations.
4960 ///
4961 /// Given
4962 /// \code
4963 ///   namespace n {
4964 ///   namespace {} // #1
4965 ///   }
4966 /// \endcode
4967 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
4968 AST_MATCHER(NamespaceDecl, isAnonymous) {
4969   return Node.isAnonymousNamespace();
4970 }
4971
4972 /// \brief If the given case statement does not use the GNU case range
4973 /// extension, matches the constant given in the statement.
4974 ///
4975 /// Given
4976 /// \code
4977 ///   switch (1) { case 1: case 1+1: case 3 ... 4: ; }
4978 /// \endcode
4979 /// caseStmt(hasCaseConstant(integerLiteral()))
4980 ///   matches "case 1:"
4981 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
4982               InnerMatcher) {
4983   if (Node.getRHS())
4984     return false;
4985
4986   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
4987 }
4988
4989 /// \brief Matches declaration that has a given attribute.
4990 ///
4991 /// Given
4992 /// \code
4993 ///   __attribute__((device)) void f() { ... }
4994 /// \endcode
4995 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
4996 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
4997 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
4998 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
4999   for (const auto *Attr : Node.attrs()) {
5000     if (Attr->getKind() == AttrKind)
5001       return true;
5002   }
5003   return false;
5004 }
5005
5006 /// \brief Matches the return value expression of a return statement
5007 ///
5008 /// Given
5009 /// \code
5010 ///   return a + b;
5011 /// \endcode
5012 /// hasReturnValue(binaryOperator())
5013 ///   matches 'return a + b'
5014 /// with binaryOperator()
5015 ///   matching 'a + b'
5016 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>, 
5017               InnerMatcher) {
5018   return InnerMatcher.matches(*Node.getRetValue(), Finder, Builder);
5019 }
5020
5021
5022 /// \brief Matches CUDA kernel call expression.
5023 ///
5024 /// Example matches,
5025 /// \code
5026 ///   kernel<<<i,j>>>();
5027 /// \endcode
5028 const internal::VariadicDynCastAllOfMatcher<
5029   Stmt,
5030   CUDAKernelCallExpr> cudaKernelCallExpr;
5031
5032
5033 /// \brief Matches expressions that resolve to a null pointer constant, such as
5034 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5035 ///
5036 /// Given:
5037 /// \code
5038 ///   void *v1 = NULL;
5039 ///   void *v2 = nullptr;
5040 ///   void *v3 = __null; // GNU extension
5041 ///   char *cp = (char *)0;
5042 ///   int *ip = 0;
5043 ///   int i = 0;
5044 /// \endcode
5045 /// expr(nullPointerConstant())
5046 ///   matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5047 ///   initializer for i.
5048 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5049   return anyOf(
5050       gnuNullExpr(), cxxNullPtrLiteralExpr(),
5051       integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5052 }
5053 } // end namespace ast_matchers
5054 } // end namespace clang
5055
5056 #endif