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