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