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