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