1 //===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements matchers to be used together with the MatchFinder to
10 //  match AST nodes.
11 //
12 //  Matchers are created by generator functions, which can be combined in
13 //  a functional in-language DSL to express queries over the C++ AST.
14 //
15 //  For example, to match a class with a certain name, one would call:
16 //    cxxRecordDecl(hasName("MyClass"))
17 //  which returns a matcher that can be used to find all AST nodes that declare
18 //  a class named 'MyClass'.
19 //
20 //  For more complicated match expressions we're often interested in accessing
21 //  multiple parts of the matched AST nodes once a match is found. In that case,
22 //  call `.bind("name")` on match expressions that match the nodes you want to
23 //  access.
24 //
25 //  For example, when we're interested in child classes of a certain class, we
26 //  would write:
27 //    cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child")))
28 //  When the match is found via the MatchFinder, a user provided callback will
29 //  be called with a BoundNodes instance that contains a mapping from the
30 //  strings that we provided for the `.bind()` calls to the nodes that were
31 //  matched.
32 //  In the given example, each time our matcher finds a match we get a callback
33 //  where "child" is bound to the RecordDecl node of the matching child
34 //  class declaration.
35 //
36 //  See ASTMatchersInternal.h for a more in-depth explanation of the
37 //  implementation details of the matcher framework.
38 //
39 //  See ASTMatchFinder.h for how to use the generated matchers to run over
40 //  an AST.
41 //
42 //===----------------------------------------------------------------------===//
43 
44 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
45 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
46 
47 #include "clang/AST/ASTContext.h"
48 #include "clang/AST/ASTTypeTraits.h"
49 #include "clang/AST/Attr.h"
50 #include "clang/AST/CXXInheritance.h"
51 #include "clang/AST/Decl.h"
52 #include "clang/AST/DeclCXX.h"
53 #include "clang/AST/DeclFriend.h"
54 #include "clang/AST/DeclObjC.h"
55 #include "clang/AST/DeclTemplate.h"
56 #include "clang/AST/Expr.h"
57 #include "clang/AST/ExprCXX.h"
58 #include "clang/AST/ExprObjC.h"
59 #include "clang/AST/LambdaCapture.h"
60 #include "clang/AST/NestedNameSpecifier.h"
61 #include "clang/AST/OpenMPClause.h"
62 #include "clang/AST/OperationKinds.h"
63 #include "clang/AST/ParentMapContext.h"
64 #include "clang/AST/Stmt.h"
65 #include "clang/AST/StmtCXX.h"
66 #include "clang/AST/StmtObjC.h"
67 #include "clang/AST/StmtOpenMP.h"
68 #include "clang/AST/TemplateBase.h"
69 #include "clang/AST/TemplateName.h"
70 #include "clang/AST/Type.h"
71 #include "clang/AST/TypeLoc.h"
72 #include "clang/ASTMatchers/ASTMatchersInternal.h"
73 #include "clang/ASTMatchers/ASTMatchersMacros.h"
74 #include "clang/Basic/AttrKinds.h"
75 #include "clang/Basic/ExceptionSpecificationType.h"
76 #include "clang/Basic/FileManager.h"
77 #include "clang/Basic/IdentifierTable.h"
78 #include "clang/Basic/LLVM.h"
79 #include "clang/Basic/SourceManager.h"
80 #include "clang/Basic/Specifiers.h"
81 #include "clang/Basic/TypeTraits.h"
82 #include "llvm/ADT/ArrayRef.h"
83 #include "llvm/ADT/SmallVector.h"
84 #include "llvm/ADT/StringRef.h"
85 #include "llvm/Support/Casting.h"
86 #include "llvm/Support/Compiler.h"
87 #include "llvm/Support/ErrorHandling.h"
88 #include "llvm/Support/Regex.h"
89 #include <cassert>
90 #include <cstddef>
91 #include <iterator>
92 #include <limits>
93 #include <string>
94 #include <utility>
95 #include <vector>
96 
97 namespace clang {
98 namespace ast_matchers {
99 
100 /// Maps string IDs to AST nodes matched by parts of a matcher.
101 ///
102 /// The bound nodes are generated by calling \c bind("id") on the node matchers
103 /// of the nodes we want to access later.
104 ///
105 /// The instances of BoundNodes are created by \c MatchFinder when the user's
106 /// callbacks are executed every time a match is found.
107 class BoundNodes {
108 public:
109   /// Returns the AST node bound to \c ID.
110   ///
111   /// Returns NULL if there was no node bound to \c ID or if there is a node but
112   /// it cannot be converted to the specified type.
113   template <typename T>
getNodeAs(StringRef ID)114   const T *getNodeAs(StringRef ID) const {
115     return MyBoundNodes.getNodeAs<T>(ID);
116   }
117 
118   /// Type of mapping from binding identifiers to bound nodes. This type
119   /// is an associative container with a key type of \c std::string and a value
120   /// type of \c clang::DynTypedNode
121   using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
122 
123   /// Retrieve mapping from binding identifiers to bound nodes.
getMap()124   const IDToNodeMap &getMap() const {
125     return MyBoundNodes.getMap();
126   }
127 
128 private:
129   friend class internal::BoundNodesTreeBuilder;
130 
131   /// Create BoundNodes from a pre-filled map of bindings.
BoundNodes(internal::BoundNodesMap & MyBoundNodes)132   BoundNodes(internal::BoundNodesMap &MyBoundNodes)
133       : MyBoundNodes(MyBoundNodes) {}
134 
135   internal::BoundNodesMap MyBoundNodes;
136 };
137 
138 /// Types of matchers for the top-level classes in the AST class
139 /// hierarchy.
140 /// @{
141 using DeclarationMatcher = internal::Matcher<Decl>;
142 using StatementMatcher = internal::Matcher<Stmt>;
143 using TypeMatcher = internal::Matcher<QualType>;
144 using TypeLocMatcher = internal::Matcher<TypeLoc>;
145 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
146 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
147 using CXXBaseSpecifierMatcher = internal::Matcher<CXXBaseSpecifier>;
148 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
149 using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
150 using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
151 /// @}
152 
153 /// Matches any node.
154 ///
155 /// Useful when another matcher requires a child matcher, but there's no
156 /// additional constraint. This will often be used with an explicit conversion
157 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
158 ///
159 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
160 /// \code
161 /// "int* p" and "void f()" in
162 ///   int* p;
163 ///   void f();
164 /// \endcode
165 ///
166 /// Usable as: Any Matcher
anything()167 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
168 
169 /// Matches the top declaration context.
170 ///
171 /// Given
172 /// \code
173 ///   int X;
174 ///   namespace NS {
175 ///   int Y;
176 ///   }  // namespace NS
177 /// \endcode
178 /// decl(hasDeclContext(translationUnitDecl()))
179 ///   matches "int X", but not "int Y".
180 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
181     translationUnitDecl;
182 
183 /// Matches typedef declarations.
184 ///
185 /// Given
186 /// \code
187 ///   typedef int X;
188 ///   using Y = int;
189 /// \endcode
190 /// typedefDecl()
191 ///   matches "typedef int X", but not "using Y = int"
192 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
193     typedefDecl;
194 
195 /// Matches typedef name declarations.
196 ///
197 /// Given
198 /// \code
199 ///   typedef int X;
200 ///   using Y = int;
201 /// \endcode
202 /// typedefNameDecl()
203 ///   matches "typedef int X" and "using Y = int"
204 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
205     typedefNameDecl;
206 
207 /// Matches type alias declarations.
208 ///
209 /// Given
210 /// \code
211 ///   typedef int X;
212 ///   using Y = int;
213 /// \endcode
214 /// typeAliasDecl()
215 ///   matches "using Y = int", but not "typedef int X"
216 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
217     typeAliasDecl;
218 
219 /// Matches type alias template declarations.
220 ///
221 /// typeAliasTemplateDecl() matches
222 /// \code
223 ///   template <typename T>
224 ///   using Y = X<T>;
225 /// \endcode
226 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
227     typeAliasTemplateDecl;
228 
229 /// Matches AST nodes that were expanded within the main-file.
230 ///
231 /// Example matches X but not Y
232 ///   (matcher = cxxRecordDecl(isExpansionInMainFile())
233 /// \code
234 ///   #include <Y.h>
235 ///   class X {};
236 /// \endcode
237 /// Y.h:
238 /// \code
239 ///   class Y {};
240 /// \endcode
241 ///
242 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc))243 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
244                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
245   auto &SourceManager = Finder->getASTContext().getSourceManager();
246   return SourceManager.isInMainFile(
247       SourceManager.getExpansionLoc(Node.getBeginLoc()));
248 }
249 
250 /// Matches AST nodes that were expanded within system-header-files.
251 ///
252 /// Example matches Y but not X
253 ///     (matcher = cxxRecordDecl(isExpansionInSystemHeader())
254 /// \code
255 ///   #include <SystemHeader.h>
256 ///   class X {};
257 /// \endcode
258 /// SystemHeader.h:
259 /// \code
260 ///   class Y {};
261 /// \endcode
262 ///
263 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc))264 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
265                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
266   auto &SourceManager = Finder->getASTContext().getSourceManager();
267   auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
268   if (ExpansionLoc.isInvalid()) {
269     return false;
270   }
271   return SourceManager.isInSystemHeader(ExpansionLoc);
272 }
273 
274 /// Matches AST nodes that were expanded within files whose name is
275 /// partially matching a given regex.
276 ///
277 /// Example matches Y but not X
278 ///     (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
279 /// \code
280 ///   #include "ASTMatcher.h"
281 ///   class X {};
282 /// \endcode
283 /// ASTMatcher.h:
284 /// \code
285 ///   class Y {};
286 /// \endcode
287 ///
288 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc),RegExp)289 AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
290                               AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt,
291                                                               TypeLoc),
292                               RegExp) {
293   auto &SourceManager = Finder->getASTContext().getSourceManager();
294   auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
295   if (ExpansionLoc.isInvalid()) {
296     return false;
297   }
298   auto FileEntry =
299       SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
300   if (!FileEntry) {
301     return false;
302   }
303 
304   auto Filename = FileEntry->getName();
305   return RegExp->match(Filename);
306 }
307 
308 /// Matches statements that are (transitively) expanded from the named macro.
309 /// Does not match if only part of the statement is expanded from that macro or
310 /// if different parts of the the statement are expanded from different
311 /// appearances of the macro.
AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc),std::string,MacroName)312 AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
313                           AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
314                           std::string, MacroName) {
315   // Verifies that the statement' beginning and ending are both expanded from
316   // the same instance of the given macro.
317   auto& Context = Finder->getASTContext();
318   llvm::Optional<SourceLocation> B =
319       internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
320   if (!B) return false;
321   llvm::Optional<SourceLocation> E =
322       internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
323   if (!E) return false;
324   return *B == *E;
325 }
326 
327 /// Matches declarations.
328 ///
329 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
330 /// \code
331 ///   void X();
332 ///   class C {
333 ///     friend X;
334 ///   };
335 /// \endcode
336 extern const internal::VariadicAllOfMatcher<Decl> decl;
337 
338 /// Matches decomposition-declarations.
339 ///
340 /// Examples matches the declaration node with \c foo and \c bar, but not
341 /// \c number.
342 /// (matcher = declStmt(has(decompositionDecl())))
343 ///
344 /// \code
345 ///   int number = 42;
346 ///   auto [foo, bar] = std::make_pair{42, 42};
347 /// \endcode
348 extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl>
349     decompositionDecl;
350 
351 /// Matches binding declarations
352 /// Example matches \c foo and \c bar
353 /// (matcher = bindingDecl()
354 ///
355 /// \code
356 ///   auto [foo, bar] = std::make_pair{42, 42};
357 /// \endcode
358 extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl>
359     bindingDecl;
360 
361 /// Matches a declaration of a linkage specification.
362 ///
363 /// Given
364 /// \code
365 ///   extern "C" {}
366 /// \endcode
367 /// linkageSpecDecl()
368 ///   matches "extern "C" {}"
369 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
370     linkageSpecDecl;
371 
372 /// Matches a declaration of anything that could have a name.
373 ///
374 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
375 /// \code
376 ///   typedef int X;
377 ///   struct S {
378 ///     union {
379 ///       int i;
380 ///     } U;
381 ///   };
382 /// \endcode
383 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
384 
385 /// Matches a declaration of label.
386 ///
387 /// Given
388 /// \code
389 ///   goto FOO;
390 ///   FOO: bar();
391 /// \endcode
392 /// labelDecl()
393 ///   matches 'FOO:'
394 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
395 
396 /// Matches a declaration of a namespace.
397 ///
398 /// Given
399 /// \code
400 ///   namespace {}
401 ///   namespace test {}
402 /// \endcode
403 /// namespaceDecl()
404 ///   matches "namespace {}" and "namespace test {}"
405 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
406     namespaceDecl;
407 
408 /// Matches a declaration of a namespace alias.
409 ///
410 /// Given
411 /// \code
412 ///   namespace test {}
413 ///   namespace alias = ::test;
414 /// \endcode
415 /// namespaceAliasDecl()
416 ///   matches "namespace alias" but not "namespace test"
417 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
418     namespaceAliasDecl;
419 
420 /// Matches class, struct, and union declarations.
421 ///
422 /// Example matches \c X, \c Z, \c U, and \c S
423 /// \code
424 ///   class X;
425 ///   template<class T> class Z {};
426 ///   struct S {};
427 ///   union U {};
428 /// \endcode
429 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
430 
431 /// Matches C++ class declarations.
432 ///
433 /// Example matches \c X, \c Z
434 /// \code
435 ///   class X;
436 ///   template<class T> class Z {};
437 /// \endcode
438 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
439     cxxRecordDecl;
440 
441 /// Matches C++ class template declarations.
442 ///
443 /// Example matches \c Z
444 /// \code
445 ///   template<class T> class Z {};
446 /// \endcode
447 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
448     classTemplateDecl;
449 
450 /// Matches C++ class template specializations.
451 ///
452 /// Given
453 /// \code
454 ///   template<typename T> class A {};
455 ///   template<> class A<double> {};
456 ///   A<int> a;
457 /// \endcode
458 /// classTemplateSpecializationDecl()
459 ///   matches the specializations \c A<int> and \c A<double>
460 extern const internal::VariadicDynCastAllOfMatcher<
461     Decl, ClassTemplateSpecializationDecl>
462     classTemplateSpecializationDecl;
463 
464 /// Matches C++ class template partial specializations.
465 ///
466 /// Given
467 /// \code
468 ///   template<class T1, class T2, int I>
469 ///   class A {};
470 ///
471 ///   template<class T, int I>
472 ///   class A<T, T*, I> {};
473 ///
474 ///   template<>
475 ///   class A<int, int, 1> {};
476 /// \endcode
477 /// classTemplatePartialSpecializationDecl()
478 ///   matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
479 extern const internal::VariadicDynCastAllOfMatcher<
480     Decl, ClassTemplatePartialSpecializationDecl>
481     classTemplatePartialSpecializationDecl;
482 
483 /// Matches declarator declarations (field, variable, function
484 /// and non-type template parameter declarations).
485 ///
486 /// Given
487 /// \code
488 ///   class X { int y; };
489 /// \endcode
490 /// declaratorDecl()
491 ///   matches \c int y.
492 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
493     declaratorDecl;
494 
495 /// Matches parameter variable declarations.
496 ///
497 /// Given
498 /// \code
499 ///   void f(int x);
500 /// \endcode
501 /// parmVarDecl()
502 ///   matches \c int x.
503 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
504     parmVarDecl;
505 
506 /// Matches C++ access specifier declarations.
507 ///
508 /// Given
509 /// \code
510 ///   class C {
511 ///   public:
512 ///     int a;
513 ///   };
514 /// \endcode
515 /// accessSpecDecl()
516 ///   matches 'public:'
517 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
518     accessSpecDecl;
519 
520 /// Matches class bases.
521 ///
522 /// Examples matches \c public virtual B.
523 /// \code
524 ///   class B {};
525 ///   class C : public virtual B {};
526 /// \endcode
527 extern const internal::VariadicAllOfMatcher<CXXBaseSpecifier> cxxBaseSpecifier;
528 
529 /// Matches constructor initializers.
530 ///
531 /// Examples matches \c i(42).
532 /// \code
533 ///   class C {
534 ///     C() : i(42) {}
535 ///     int i;
536 ///   };
537 /// \endcode
538 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
539     cxxCtorInitializer;
540 
541 /// Matches template arguments.
542 ///
543 /// Given
544 /// \code
545 ///   template <typename T> struct C {};
546 ///   C<int> c;
547 /// \endcode
548 /// templateArgument()
549 ///   matches 'int' in C<int>.
550 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
551 
552 /// Matches template arguments (with location info).
553 ///
554 /// Given
555 /// \code
556 ///   template <typename T> struct C {};
557 ///   C<int> c;
558 /// \endcode
559 /// templateArgumentLoc()
560 ///   matches 'int' in C<int>.
561 extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
562     templateArgumentLoc;
563 
564 /// Matches template name.
565 ///
566 /// Given
567 /// \code
568 ///   template <typename T> class X { };
569 ///   X<int> xi;
570 /// \endcode
571 /// templateName()
572 ///   matches 'X' in X<int>.
573 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
574 
575 /// Matches non-type template parameter declarations.
576 ///
577 /// Given
578 /// \code
579 ///   template <typename T, int N> struct C {};
580 /// \endcode
581 /// nonTypeTemplateParmDecl()
582 ///   matches 'N', but not 'T'.
583 extern const internal::VariadicDynCastAllOfMatcher<Decl,
584                                                    NonTypeTemplateParmDecl>
585     nonTypeTemplateParmDecl;
586 
587 /// Matches template type parameter declarations.
588 ///
589 /// Given
590 /// \code
591 ///   template <typename T, int N> struct C {};
592 /// \endcode
593 /// templateTypeParmDecl()
594 ///   matches 'T', but not 'N'.
595 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
596     templateTypeParmDecl;
597 
598 /// Matches template template parameter declarations.
599 ///
600 /// Given
601 /// \code
602 ///   template <template <typename> class Z, int N> struct C {};
603 /// \endcode
604 /// templateTypeParmDecl()
605 ///   matches 'Z', but not 'N'.
606 extern const internal::VariadicDynCastAllOfMatcher<Decl,
607                                                    TemplateTemplateParmDecl>
608     templateTemplateParmDecl;
609 
610 /// Matches public C++ declarations and C++ base specifers that specify public
611 /// inheritance.
612 ///
613 /// Examples:
614 /// \code
615 ///   class C {
616 ///   public:    int a; // fieldDecl(isPublic()) matches 'a'
617 ///   protected: int b;
618 ///   private:   int c;
619 ///   };
620 /// \endcode
621 ///
622 /// \code
623 ///   class Base {};
624 ///   class Derived1 : public Base {}; // matches 'Base'
625 ///   struct Derived2 : Base {}; // matches 'Base'
626 /// \endcode
AST_POLYMORPHIC_MATCHER(isPublic,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,CXXBaseSpecifier))627 AST_POLYMORPHIC_MATCHER(isPublic,
628                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
629                                                         CXXBaseSpecifier)) {
630   return getAccessSpecifier(Node) == AS_public;
631 }
632 
633 /// Matches protected C++ declarations and C++ base specifers that specify
634 /// protected inheritance.
635 ///
636 /// Examples:
637 /// \code
638 ///   class C {
639 ///   public:    int a;
640 ///   protected: int b; // fieldDecl(isProtected()) matches 'b'
641 ///   private:   int c;
642 ///   };
643 /// \endcode
644 ///
645 /// \code
646 ///   class Base {};
647 ///   class Derived : protected Base {}; // matches 'Base'
648 /// \endcode
AST_POLYMORPHIC_MATCHER(isProtected,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,CXXBaseSpecifier))649 AST_POLYMORPHIC_MATCHER(isProtected,
650                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
651                                                         CXXBaseSpecifier)) {
652   return getAccessSpecifier(Node) == AS_protected;
653 }
654 
655 /// Matches private C++ declarations and C++ base specifers that specify private
656 /// inheritance.
657 ///
658 /// Examples:
659 /// \code
660 ///   class C {
661 ///   public:    int a;
662 ///   protected: int b;
663 ///   private:   int c; // fieldDecl(isPrivate()) matches 'c'
664 ///   };
665 /// \endcode
666 ///
667 /// \code
668 ///   struct Base {};
669 ///   struct Derived1 : private Base {}; // matches 'Base'
670 ///   class Derived2 : Base {}; // matches 'Base'
671 /// \endcode
AST_POLYMORPHIC_MATCHER(isPrivate,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,CXXBaseSpecifier))672 AST_POLYMORPHIC_MATCHER(isPrivate,
673                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
674                                                         CXXBaseSpecifier)) {
675   return getAccessSpecifier(Node) == AS_private;
676 }
677 
678 /// Matches non-static data members that are bit-fields.
679 ///
680 /// Given
681 /// \code
682 ///   class C {
683 ///     int a : 2;
684 ///     int b;
685 ///   };
686 /// \endcode
687 /// fieldDecl(isBitField())
688 ///   matches 'int a;' but not 'int b;'.
AST_MATCHER(FieldDecl,isBitField)689 AST_MATCHER(FieldDecl, isBitField) {
690   return Node.isBitField();
691 }
692 
693 /// Matches non-static data members that are bit-fields of the specified
694 /// bit width.
695 ///
696 /// Given
697 /// \code
698 ///   class C {
699 ///     int a : 2;
700 ///     int b : 4;
701 ///     int c : 2;
702 ///   };
703 /// \endcode
704 /// fieldDecl(hasBitWidth(2))
705 ///   matches 'int a;' and 'int c;' but not 'int b;'.
AST_MATCHER_P(FieldDecl,hasBitWidth,unsigned,Width)706 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
707   return Node.isBitField() &&
708          Node.getBitWidthValue(Finder->getASTContext()) == Width;
709 }
710 
711 /// Matches non-static data members that have an in-class initializer.
712 ///
713 /// Given
714 /// \code
715 ///   class C {
716 ///     int a = 2;
717 ///     int b = 3;
718 ///     int c;
719 ///   };
720 /// \endcode
721 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
722 ///   matches 'int a;' but not 'int b;'.
723 /// fieldDecl(hasInClassInitializer(anything()))
724 ///   matches 'int a;' and 'int b;' but not 'int c;'.
AST_MATCHER_P(FieldDecl,hasInClassInitializer,internal::Matcher<Expr>,InnerMatcher)725 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
726               InnerMatcher) {
727   const Expr *Initializer = Node.getInClassInitializer();
728   return (Initializer != nullptr &&
729           InnerMatcher.matches(*Initializer, Finder, Builder));
730 }
731 
732 /// Determines whether the function is "main", which is the entry point
733 /// into an executable program.
AST_MATCHER(FunctionDecl,isMain)734 AST_MATCHER(FunctionDecl, isMain) {
735   return Node.isMain();
736 }
737 
738 /// Matches the specialized template of a specialization declaration.
739 ///
740 /// Given
741 /// \code
742 ///   template<typename T> class A {}; #1
743 ///   template<> class A<int> {}; #2
744 /// \endcode
745 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
746 ///   matches '#2' with classTemplateDecl() matching the class template
747 ///   declaration of 'A' at #1.
AST_MATCHER_P(ClassTemplateSpecializationDecl,hasSpecializedTemplate,internal::Matcher<ClassTemplateDecl>,InnerMatcher)748 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
749               internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
750   const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
751   return (Decl != nullptr &&
752           InnerMatcher.matches(*Decl, Finder, Builder));
753 }
754 
755 /// Matches a declaration that has been implicitly added
756 /// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl,isImplicit)757 AST_MATCHER(Decl, isImplicit) {
758   return Node.isImplicit();
759 }
760 
761 /// Matches classTemplateSpecializations, templateSpecializationType and
762 /// functionDecl that have at least one TemplateArgument matching the given
763 /// InnerMatcher.
764 ///
765 /// Given
766 /// \code
767 ///   template<typename T> class A {};
768 ///   template<> class A<double> {};
769 ///   A<int> a;
770 ///
771 ///   template<typename T> f() {};
772 ///   void func() { f<int>(); };
773 /// \endcode
774 ///
775 /// \endcode
776 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
777 ///     refersToType(asString("int"))))
778 ///   matches the specialization \c A<int>
779 ///
780 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
781 ///   matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P(hasAnyTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType,FunctionDecl),internal::Matcher<TemplateArgument>,InnerMatcher)782 AST_POLYMORPHIC_MATCHER_P(
783     hasAnyTemplateArgument,
784     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
785                                     TemplateSpecializationType,
786                                     FunctionDecl),
787     internal::Matcher<TemplateArgument>, InnerMatcher) {
788   ArrayRef<TemplateArgument> List =
789       internal::getTemplateSpecializationArgs(Node);
790   return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
791                              Builder) != List.end();
792 }
793 
794 /// Causes all nested matchers to be matched with the specified traversal kind.
795 ///
796 /// Given
797 /// \code
798 ///   void foo()
799 ///   {
800 ///       int i = 3.0;
801 ///   }
802 /// \endcode
803 /// The matcher
804 /// \code
805 ///   traverse(TK_IgnoreUnlessSpelledInSource,
806 ///     varDecl(hasInitializer(floatLiteral().bind("init")))
807 ///   )
808 /// \endcode
809 /// matches the variable declaration with "init" bound to the "3.0".
810 template <typename T>
traverse(TraversalKind TK,const internal::Matcher<T> & InnerMatcher)811 internal::Matcher<T> traverse(TraversalKind TK,
812                               const internal::Matcher<T> &InnerMatcher) {
813   return internal::DynTypedMatcher::constructRestrictedWrapper(
814              new internal::TraversalMatcher<T>(TK, InnerMatcher),
815              InnerMatcher.getID().first)
816       .template unconditionalConvertTo<T>();
817 }
818 
819 template <typename T>
820 internal::BindableMatcher<T>
traverse(TraversalKind TK,const internal::BindableMatcher<T> & InnerMatcher)821 traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
822   return internal::BindableMatcher<T>(
823       internal::DynTypedMatcher::constructRestrictedWrapper(
824           new internal::TraversalMatcher<T>(TK, InnerMatcher),
825           InnerMatcher.getID().first)
826           .template unconditionalConvertTo<T>());
827 }
828 
829 template <typename... T>
830 internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
traverse(TraversalKind TK,const internal::VariadicOperatorMatcher<T...> & InnerMatcher)831 traverse(TraversalKind TK,
832          const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
833   return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
834       TK, InnerMatcher);
835 }
836 
837 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
838           typename T, typename ToTypes>
839 internal::TraversalWrapper<
840     internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
traverse(TraversalKind TK,const internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT,T,ToTypes> & InnerMatcher)841 traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
842                                ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
843   return internal::TraversalWrapper<
844       internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
845                                                    ToTypes>>(TK, InnerMatcher);
846 }
847 
848 template <template <typename T, typename... P> class MatcherT, typename... P,
849           typename ReturnTypesF>
850 internal::TraversalWrapper<
851     internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>
traverse(TraversalKind TK,const internal::PolymorphicMatcher<MatcherT,ReturnTypesF,P...> & InnerMatcher)852 traverse(TraversalKind TK,
853          const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>
854              &InnerMatcher) {
855   return internal::TraversalWrapper<
856       internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK,
857                                                                   InnerMatcher);
858 }
859 
860 template <typename... T>
861 internal::Matcher<typename internal::GetClade<T...>::Type>
traverse(TraversalKind TK,const internal::MapAnyOfHelper<T...> & InnerMatcher)862 traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
863   return traverse(TK, InnerMatcher.with());
864 }
865 
866 /// Matches expressions that match InnerMatcher after any implicit AST
867 /// nodes are stripped off.
868 ///
869 /// Parentheses and explicit casts are not discarded.
870 /// Given
871 /// \code
872 ///   class C {};
873 ///   C a = C();
874 ///   C b;
875 ///   C c = b;
876 /// \endcode
877 /// The matchers
878 /// \code
879 ///    varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
880 /// \endcode
881 /// would match the declarations for a, b, and c.
882 /// While
883 /// \code
884 ///    varDecl(hasInitializer(cxxConstructExpr()))
885 /// \endcode
886 /// only match the declarations for b and c.
AST_MATCHER_P(Expr,ignoringImplicit,internal::Matcher<Expr>,InnerMatcher)887 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
888               InnerMatcher) {
889   return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
890 }
891 
892 /// Matches expressions that match InnerMatcher after any implicit casts
893 /// are stripped off.
894 ///
895 /// Parentheses and explicit casts are not discarded.
896 /// Given
897 /// \code
898 ///   int arr[5];
899 ///   int a = 0;
900 ///   char b = 0;
901 ///   const int c = a;
902 ///   int *d = arr;
903 ///   long e = (long) 0l;
904 /// \endcode
905 /// The matchers
906 /// \code
907 ///    varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
908 ///    varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
909 /// \endcode
910 /// would match the declarations for a, b, c, and d, but not e.
911 /// While
912 /// \code
913 ///    varDecl(hasInitializer(integerLiteral()))
914 ///    varDecl(hasInitializer(declRefExpr()))
915 /// \endcode
916 /// only match the declarations for b, c, and d.
AST_MATCHER_P(Expr,ignoringImpCasts,internal::Matcher<Expr>,InnerMatcher)917 AST_MATCHER_P(Expr, ignoringImpCasts,
918               internal::Matcher<Expr>, InnerMatcher) {
919   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
920 }
921 
922 /// Matches expressions that match InnerMatcher after parentheses and
923 /// casts are stripped off.
924 ///
925 /// Implicit and non-C Style casts are also discarded.
926 /// Given
927 /// \code
928 ///   int a = 0;
929 ///   char b = (0);
930 ///   void* c = reinterpret_cast<char*>(0);
931 ///   char d = char(0);
932 /// \endcode
933 /// The matcher
934 ///    varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
935 /// would match the declarations for a, b, c, and d.
936 /// while
937 ///    varDecl(hasInitializer(integerLiteral()))
938 /// only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenCasts,internal::Matcher<Expr>,InnerMatcher)939 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
940   return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
941 }
942 
943 /// Matches expressions that match InnerMatcher after implicit casts and
944 /// parentheses are stripped off.
945 ///
946 /// Explicit casts are not discarded.
947 /// Given
948 /// \code
949 ///   int arr[5];
950 ///   int a = 0;
951 ///   char b = (0);
952 ///   const int c = a;
953 ///   int *d = (arr);
954 ///   long e = ((long) 0l);
955 /// \endcode
956 /// The matchers
957 ///    varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
958 ///    varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
959 /// would match the declarations for a, b, c, and d, but not e.
960 /// while
961 ///    varDecl(hasInitializer(integerLiteral()))
962 ///    varDecl(hasInitializer(declRefExpr()))
963 /// would only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenImpCasts,internal::Matcher<Expr>,InnerMatcher)964 AST_MATCHER_P(Expr, ignoringParenImpCasts,
965               internal::Matcher<Expr>, InnerMatcher) {
966   return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
967 }
968 
969 /// Matches types that match InnerMatcher after any parens are stripped.
970 ///
971 /// Given
972 /// \code
973 ///   void (*fp)(void);
974 /// \endcode
975 /// The matcher
976 /// \code
977 ///   varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
978 /// \endcode
979 /// would match the declaration for fp.
980 AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
981                        InnerMatcher, 0) {
982   return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
983 }
984 
985 /// Overload \c ignoringParens for \c Expr.
986 ///
987 /// Given
988 /// \code
989 ///   const char* str = ("my-string");
990 /// \endcode
991 /// The matcher
992 /// \code
993 ///   implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
994 /// \endcode
995 /// would match the implicit cast resulting from the assignment.
996 AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
997                        InnerMatcher, 1) {
998   const Expr *E = Node.IgnoreParens();
999   return InnerMatcher.matches(*E, Finder, Builder);
1000 }
1001 
1002 /// Matches expressions that are instantiation-dependent even if it is
1003 /// neither type- nor value-dependent.
1004 ///
1005 /// In the following example, the expression sizeof(sizeof(T() + T()))
1006 /// is instantiation-dependent (since it involves a template parameter T),
1007 /// but is neither type- nor value-dependent, since the type of the inner
1008 /// sizeof is known (std::size_t) and therefore the size of the outer
1009 /// sizeof is known.
1010 /// \code
1011 ///   template<typename T>
1012 ///   void f(T x, T y) { sizeof(sizeof(T() + T()); }
1013 /// \endcode
1014 /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
AST_MATCHER(Expr,isInstantiationDependent)1015 AST_MATCHER(Expr, isInstantiationDependent) {
1016   return Node.isInstantiationDependent();
1017 }
1018 
1019 /// Matches expressions that are type-dependent because the template type
1020 /// is not yet instantiated.
1021 ///
1022 /// For example, the expressions "x" and "x + y" are type-dependent in
1023 /// the following code, but "y" is not type-dependent:
1024 /// \code
1025 ///   template<typename T>
1026 ///   void add(T x, int y) {
1027 ///     x + y;
1028 ///   }
1029 /// \endcode
1030 /// expr(isTypeDependent()) matches x + y
AST_MATCHER(Expr,isTypeDependent)1031 AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
1032 
1033 /// Matches expression that are value-dependent because they contain a
1034 /// non-type template parameter.
1035 ///
1036 /// For example, the array bound of "Chars" in the following example is
1037 /// value-dependent.
1038 /// \code
1039 ///   template<int Size> int f() { return Size; }
1040 /// \endcode
1041 /// expr(isValueDependent()) matches return Size
AST_MATCHER(Expr,isValueDependent)1042 AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
1043 
1044 /// Matches classTemplateSpecializations, templateSpecializationType and
1045 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
1046 ///
1047 /// Given
1048 /// \code
1049 ///   template<typename T, typename U> class A {};
1050 ///   A<bool, int> b;
1051 ///   A<int, bool> c;
1052 ///
1053 ///   template<typename T> void f() {}
1054 ///   void func() { f<int>(); };
1055 /// \endcode
1056 /// classTemplateSpecializationDecl(hasTemplateArgument(
1057 ///     1, refersToType(asString("int"))))
1058 ///   matches the specialization \c A<bool, int>
1059 ///
1060 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1061 ///   matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P2(hasTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType,FunctionDecl),unsigned,N,internal::Matcher<TemplateArgument>,InnerMatcher)1062 AST_POLYMORPHIC_MATCHER_P2(
1063     hasTemplateArgument,
1064     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
1065                                     TemplateSpecializationType,
1066                                     FunctionDecl),
1067     unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1068   ArrayRef<TemplateArgument> List =
1069       internal::getTemplateSpecializationArgs(Node);
1070   if (List.size() <= N)
1071     return false;
1072   return InnerMatcher.matches(List[N], Finder, Builder);
1073 }
1074 
1075 /// Matches if the number of template arguments equals \p N.
1076 ///
1077 /// Given
1078 /// \code
1079 ///   template<typename T> struct C {};
1080 ///   C<int> c;
1081 /// \endcode
1082 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1083 ///   matches C<int>.
AST_POLYMORPHIC_MATCHER_P(templateArgumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType),unsigned,N)1084 AST_POLYMORPHIC_MATCHER_P(
1085     templateArgumentCountIs,
1086     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
1087                                     TemplateSpecializationType),
1088     unsigned, N) {
1089   return internal::getTemplateSpecializationArgs(Node).size() == N;
1090 }
1091 
1092 /// Matches a TemplateArgument that refers to a certain type.
1093 ///
1094 /// Given
1095 /// \code
1096 ///   struct X {};
1097 ///   template<typename T> struct A {};
1098 ///   A<X> a;
1099 /// \endcode
1100 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1101 ///     refersToType(class(hasName("X")))))
1102 ///   matches the specialization \c A<X>
AST_MATCHER_P(TemplateArgument,refersToType,internal::Matcher<QualType>,InnerMatcher)1103 AST_MATCHER_P(TemplateArgument, refersToType,
1104               internal::Matcher<QualType>, InnerMatcher) {
1105   if (Node.getKind() != TemplateArgument::Type)
1106     return false;
1107   return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1108 }
1109 
1110 /// Matches a TemplateArgument that refers to a certain template.
1111 ///
1112 /// Given
1113 /// \code
1114 ///   template<template <typename> class S> class X {};
1115 ///   template<typename T> class Y {};
1116 ///   X<Y> xi;
1117 /// \endcode
1118 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1119 ///     refersToTemplate(templateName())))
1120 ///   matches the specialization \c X<Y>
AST_MATCHER_P(TemplateArgument,refersToTemplate,internal::Matcher<TemplateName>,InnerMatcher)1121 AST_MATCHER_P(TemplateArgument, refersToTemplate,
1122               internal::Matcher<TemplateName>, InnerMatcher) {
1123   if (Node.getKind() != TemplateArgument::Template)
1124     return false;
1125   return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1126 }
1127 
1128 /// Matches a canonical TemplateArgument that refers to a certain
1129 /// declaration.
1130 ///
1131 /// Given
1132 /// \code
1133 ///   struct B { int next; };
1134 ///   template<int(B::*next_ptr)> struct A {};
1135 ///   A<&B::next> a;
1136 /// \endcode
1137 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1138 ///     refersToDeclaration(fieldDecl(hasName("next")))))
1139 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1140 ///     \c B::next
AST_MATCHER_P(TemplateArgument,refersToDeclaration,internal::Matcher<Decl>,InnerMatcher)1141 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1142               internal::Matcher<Decl>, InnerMatcher) {
1143   if (Node.getKind() == TemplateArgument::Declaration)
1144     return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1145   return false;
1146 }
1147 
1148 /// Matches a sugar TemplateArgument that refers to a certain expression.
1149 ///
1150 /// Given
1151 /// \code
1152 ///   struct B { int next; };
1153 ///   template<int(B::*next_ptr)> struct A {};
1154 ///   A<&B::next> a;
1155 /// \endcode
1156 /// templateSpecializationType(hasAnyTemplateArgument(
1157 ///   isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1158 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1159 ///     \c B::next
AST_MATCHER_P(TemplateArgument,isExpr,internal::Matcher<Expr>,InnerMatcher)1160 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1161   if (Node.getKind() == TemplateArgument::Expression)
1162     return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1163   return false;
1164 }
1165 
1166 /// Matches a TemplateArgument that is an integral value.
1167 ///
1168 /// Given
1169 /// \code
1170 ///   template<int T> struct C {};
1171 ///   C<42> c;
1172 /// \endcode
1173 /// classTemplateSpecializationDecl(
1174 ///   hasAnyTemplateArgument(isIntegral()))
1175 ///   matches the implicit instantiation of C in C<42>
1176 ///   with isIntegral() matching 42.
AST_MATCHER(TemplateArgument,isIntegral)1177 AST_MATCHER(TemplateArgument, isIntegral) {
1178   return Node.getKind() == TemplateArgument::Integral;
1179 }
1180 
1181 /// Matches a TemplateArgument that refers to an integral type.
1182 ///
1183 /// Given
1184 /// \code
1185 ///   template<int T> struct C {};
1186 ///   C<42> c;
1187 /// \endcode
1188 /// classTemplateSpecializationDecl(
1189 ///   hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1190 ///   matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument,refersToIntegralType,internal::Matcher<QualType>,InnerMatcher)1191 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1192               internal::Matcher<QualType>, InnerMatcher) {
1193   if (Node.getKind() != TemplateArgument::Integral)
1194     return false;
1195   return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1196 }
1197 
1198 /// Matches a TemplateArgument of integral type with a given value.
1199 ///
1200 /// Note that 'Value' is a string as the template argument's value is
1201 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
1202 /// representation of that integral value in base 10.
1203 ///
1204 /// Given
1205 /// \code
1206 ///   template<int T> struct C {};
1207 ///   C<42> c;
1208 /// \endcode
1209 /// classTemplateSpecializationDecl(
1210 ///   hasAnyTemplateArgument(equalsIntegralValue("42")))
1211 ///   matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument,equalsIntegralValue,std::string,Value)1212 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1213               std::string, Value) {
1214   if (Node.getKind() != TemplateArgument::Integral)
1215     return false;
1216   return Node.getAsIntegral().toString(10) == Value;
1217 }
1218 
1219 /// Matches an Objective-C autorelease pool statement.
1220 ///
1221 /// Given
1222 /// \code
1223 ///   @autoreleasepool {
1224 ///     int x = 0;
1225 ///   }
1226 /// \endcode
1227 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1228 /// inside the autorelease pool.
1229 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1230        ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1231 
1232 /// Matches any value declaration.
1233 ///
1234 /// Example matches A, B, C and F
1235 /// \code
1236 ///   enum X { A, B, C };
1237 ///   void F();
1238 /// \endcode
1239 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1240 
1241 /// Matches C++ constructor declarations.
1242 ///
1243 /// Example matches Foo::Foo() and Foo::Foo(int)
1244 /// \code
1245 ///   class Foo {
1246 ///    public:
1247 ///     Foo();
1248 ///     Foo(int);
1249 ///     int DoSomething();
1250 ///   };
1251 /// \endcode
1252 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1253     cxxConstructorDecl;
1254 
1255 /// Matches explicit C++ destructor declarations.
1256 ///
1257 /// Example matches Foo::~Foo()
1258 /// \code
1259 ///   class Foo {
1260 ///    public:
1261 ///     virtual ~Foo();
1262 ///   };
1263 /// \endcode
1264 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1265     cxxDestructorDecl;
1266 
1267 /// Matches enum declarations.
1268 ///
1269 /// Example matches X
1270 /// \code
1271 ///   enum X {
1272 ///     A, B, C
1273 ///   };
1274 /// \endcode
1275 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1276 
1277 /// Matches enum constants.
1278 ///
1279 /// Example matches A, B, C
1280 /// \code
1281 ///   enum X {
1282 ///     A, B, C
1283 ///   };
1284 /// \endcode
1285 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1286     enumConstantDecl;
1287 
1288 /// Matches tag declarations.
1289 ///
1290 /// Example matches X, Z, U, S, E
1291 /// \code
1292 ///   class X;
1293 ///   template<class T> class Z {};
1294 ///   struct S {};
1295 ///   union U {};
1296 ///   enum E {
1297 ///     A, B, C
1298 ///   };
1299 /// \endcode
1300 extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1301 
1302 /// Matches method declarations.
1303 ///
1304 /// Example matches y
1305 /// \code
1306 ///   class X { void y(); };
1307 /// \endcode
1308 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1309     cxxMethodDecl;
1310 
1311 /// Matches conversion operator declarations.
1312 ///
1313 /// Example matches the operator.
1314 /// \code
1315 ///   class X { operator int() const; };
1316 /// \endcode
1317 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1318     cxxConversionDecl;
1319 
1320 /// Matches user-defined and implicitly generated deduction guide.
1321 ///
1322 /// Example matches the deduction guide.
1323 /// \code
1324 ///   template<typename T>
1325 ///   class X { X(int) };
1326 ///   X(int) -> X<int>;
1327 /// \endcode
1328 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1329     cxxDeductionGuideDecl;
1330 
1331 /// Matches variable declarations.
1332 ///
1333 /// Note: this does not match declarations of member variables, which are
1334 /// "field" declarations in Clang parlance.
1335 ///
1336 /// Example matches a
1337 /// \code
1338 ///   int a;
1339 /// \endcode
1340 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1341 
1342 /// Matches field declarations.
1343 ///
1344 /// Given
1345 /// \code
1346 ///   class X { int m; };
1347 /// \endcode
1348 /// fieldDecl()
1349 ///   matches 'm'.
1350 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1351 
1352 /// Matches indirect field declarations.
1353 ///
1354 /// Given
1355 /// \code
1356 ///   struct X { struct { int a; }; };
1357 /// \endcode
1358 /// indirectFieldDecl()
1359 ///   matches 'a'.
1360 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1361     indirectFieldDecl;
1362 
1363 /// Matches function declarations.
1364 ///
1365 /// Example matches f
1366 /// \code
1367 ///   void f();
1368 /// \endcode
1369 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1370     functionDecl;
1371 
1372 /// Matches C++ function template declarations.
1373 ///
1374 /// Example matches f
1375 /// \code
1376 ///   template<class T> void f(T t) {}
1377 /// \endcode
1378 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1379     functionTemplateDecl;
1380 
1381 /// Matches friend declarations.
1382 ///
1383 /// Given
1384 /// \code
1385 ///   class X { friend void foo(); };
1386 /// \endcode
1387 /// friendDecl()
1388 ///   matches 'friend void foo()'.
1389 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1390 
1391 /// Matches statements.
1392 ///
1393 /// Given
1394 /// \code
1395 ///   { ++a; }
1396 /// \endcode
1397 /// stmt()
1398 ///   matches both the compound statement '{ ++a; }' and '++a'.
1399 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1400 
1401 /// Matches declaration statements.
1402 ///
1403 /// Given
1404 /// \code
1405 ///   int a;
1406 /// \endcode
1407 /// declStmt()
1408 ///   matches 'int a'.
1409 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1410 
1411 /// Matches member expressions.
1412 ///
1413 /// Given
1414 /// \code
1415 ///   class Y {
1416 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1417 ///     int a; static int b;
1418 ///   };
1419 /// \endcode
1420 /// memberExpr()
1421 ///   matches this->x, x, y.x, a, this->b
1422 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1423 
1424 /// Matches unresolved member expressions.
1425 ///
1426 /// Given
1427 /// \code
1428 ///   struct X {
1429 ///     template <class T> void f();
1430 ///     void g();
1431 ///   };
1432 ///   template <class T> void h() { X x; x.f<T>(); x.g(); }
1433 /// \endcode
1434 /// unresolvedMemberExpr()
1435 ///   matches x.f<T>
1436 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1437     unresolvedMemberExpr;
1438 
1439 /// Matches member expressions where the actual member referenced could not be
1440 /// resolved because the base expression or the member name was dependent.
1441 ///
1442 /// Given
1443 /// \code
1444 ///   template <class T> void f() { T t; t.g(); }
1445 /// \endcode
1446 /// cxxDependentScopeMemberExpr()
1447 ///   matches t.g
1448 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1449                                                    CXXDependentScopeMemberExpr>
1450     cxxDependentScopeMemberExpr;
1451 
1452 /// Matches call expressions.
1453 ///
1454 /// Example matches x.y() and y()
1455 /// \code
1456 ///   X x;
1457 ///   x.y();
1458 ///   y();
1459 /// \endcode
1460 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1461 
1462 /// Matches call expressions which were resolved using ADL.
1463 ///
1464 /// Example matches y(x) but not y(42) or NS::y(x).
1465 /// \code
1466 ///   namespace NS {
1467 ///     struct X {};
1468 ///     void y(X);
1469 ///   }
1470 ///
1471 ///   void y(...);
1472 ///
1473 ///   void test() {
1474 ///     NS::X x;
1475 ///     y(x); // Matches
1476 ///     NS::y(x); // Doesn't match
1477 ///     y(42); // Doesn't match
1478 ///     using NS::y;
1479 ///     y(x); // Found by both unqualified lookup and ADL, doesn't match
1480 //    }
1481 /// \endcode
AST_MATCHER(CallExpr,usesADL)1482 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1483 
1484 /// Matches lambda expressions.
1485 ///
1486 /// Example matches [&](){return 5;}
1487 /// \code
1488 ///   [&](){return 5;}
1489 /// \endcode
1490 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1491 
1492 /// Matches member call expressions.
1493 ///
1494 /// Example matches x.y()
1495 /// \code
1496 ///   X x;
1497 ///   x.y();
1498 /// \endcode
1499 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1500     cxxMemberCallExpr;
1501 
1502 /// Matches ObjectiveC Message invocation expressions.
1503 ///
1504 /// The innermost message send invokes the "alloc" class method on the
1505 /// NSString class, while the outermost message send invokes the
1506 /// "initWithString" instance method on the object returned from
1507 /// NSString's "alloc". This matcher should match both message sends.
1508 /// \code
1509 ///   [[NSString alloc] initWithString:@"Hello"]
1510 /// \endcode
1511 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1512     objcMessageExpr;
1513 
1514 /// Matches Objective-C interface declarations.
1515 ///
1516 /// Example matches Foo
1517 /// \code
1518 ///   @interface Foo
1519 ///   @end
1520 /// \endcode
1521 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1522     objcInterfaceDecl;
1523 
1524 /// Matches Objective-C implementation declarations.
1525 ///
1526 /// Example matches Foo
1527 /// \code
1528 ///   @implementation Foo
1529 ///   @end
1530 /// \endcode
1531 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1532     objcImplementationDecl;
1533 
1534 /// Matches Objective-C protocol declarations.
1535 ///
1536 /// Example matches FooDelegate
1537 /// \code
1538 ///   @protocol FooDelegate
1539 ///   @end
1540 /// \endcode
1541 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1542     objcProtocolDecl;
1543 
1544 /// Matches Objective-C category declarations.
1545 ///
1546 /// Example matches Foo (Additions)
1547 /// \code
1548 ///   @interface Foo (Additions)
1549 ///   @end
1550 /// \endcode
1551 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1552     objcCategoryDecl;
1553 
1554 /// Matches Objective-C category definitions.
1555 ///
1556 /// Example matches Foo (Additions)
1557 /// \code
1558 ///   @implementation Foo (Additions)
1559 ///   @end
1560 /// \endcode
1561 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1562     objcCategoryImplDecl;
1563 
1564 /// Matches Objective-C method declarations.
1565 ///
1566 /// Example matches both declaration and definition of -[Foo method]
1567 /// \code
1568 ///   @interface Foo
1569 ///   - (void)method;
1570 ///   @end
1571 ///
1572 ///   @implementation Foo
1573 ///   - (void)method {}
1574 ///   @end
1575 /// \endcode
1576 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1577     objcMethodDecl;
1578 
1579 /// Matches block declarations.
1580 ///
1581 /// Example matches the declaration of the nameless block printing an input
1582 /// integer.
1583 ///
1584 /// \code
1585 ///   myFunc(^(int p) {
1586 ///     printf("%d", p);
1587 ///   })
1588 /// \endcode
1589 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1590     blockDecl;
1591 
1592 /// Matches Objective-C instance variable declarations.
1593 ///
1594 /// Example matches _enabled
1595 /// \code
1596 ///   @implementation Foo {
1597 ///     BOOL _enabled;
1598 ///   }
1599 ///   @end
1600 /// \endcode
1601 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1602     objcIvarDecl;
1603 
1604 /// Matches Objective-C property declarations.
1605 ///
1606 /// Example matches enabled
1607 /// \code
1608 ///   @interface Foo
1609 ///   @property BOOL enabled;
1610 ///   @end
1611 /// \endcode
1612 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1613     objcPropertyDecl;
1614 
1615 /// Matches Objective-C \@throw statements.
1616 ///
1617 /// Example matches \@throw
1618 /// \code
1619 ///   @throw obj;
1620 /// \endcode
1621 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1622     objcThrowStmt;
1623 
1624 /// Matches Objective-C @try statements.
1625 ///
1626 /// Example matches @try
1627 /// \code
1628 ///   @try {}
1629 ///   @catch (...) {}
1630 /// \endcode
1631 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1632     objcTryStmt;
1633 
1634 /// Matches Objective-C @catch statements.
1635 ///
1636 /// Example matches @catch
1637 /// \code
1638 ///   @try {}
1639 ///   @catch (...) {}
1640 /// \endcode
1641 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1642     objcCatchStmt;
1643 
1644 /// Matches Objective-C @finally statements.
1645 ///
1646 /// Example matches @finally
1647 /// \code
1648 ///   @try {}
1649 ///   @finally {}
1650 /// \endcode
1651 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1652     objcFinallyStmt;
1653 
1654 /// Matches expressions that introduce cleanups to be run at the end
1655 /// of the sub-expression's evaluation.
1656 ///
1657 /// Example matches std::string()
1658 /// \code
1659 ///   const std::string str = std::string();
1660 /// \endcode
1661 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1662     exprWithCleanups;
1663 
1664 /// Matches init list expressions.
1665 ///
1666 /// Given
1667 /// \code
1668 ///   int a[] = { 1, 2 };
1669 ///   struct B { int x, y; };
1670 ///   B b = { 5, 6 };
1671 /// \endcode
1672 /// initListExpr()
1673 ///   matches "{ 1, 2 }" and "{ 5, 6 }"
1674 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1675     initListExpr;
1676 
1677 /// Matches the syntactic form of init list expressions
1678 /// (if expression have it).
AST_MATCHER_P(InitListExpr,hasSyntacticForm,internal::Matcher<Expr>,InnerMatcher)1679 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1680               internal::Matcher<Expr>, InnerMatcher) {
1681   const Expr *SyntForm = Node.getSyntacticForm();
1682   return (SyntForm != nullptr &&
1683           InnerMatcher.matches(*SyntForm, Finder, Builder));
1684 }
1685 
1686 /// Matches C++ initializer list expressions.
1687 ///
1688 /// Given
1689 /// \code
1690 ///   std::vector<int> a({ 1, 2, 3 });
1691 ///   std::vector<int> b = { 4, 5 };
1692 ///   int c[] = { 6, 7 };
1693 ///   std::pair<int, int> d = { 8, 9 };
1694 /// \endcode
1695 /// cxxStdInitializerListExpr()
1696 ///   matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1697 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1698                                                    CXXStdInitializerListExpr>
1699     cxxStdInitializerListExpr;
1700 
1701 /// Matches implicit initializers of init list expressions.
1702 ///
1703 /// Given
1704 /// \code
1705 ///   point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1706 /// \endcode
1707 /// implicitValueInitExpr()
1708 ///   matches "[0].y" (implicitly)
1709 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1710     implicitValueInitExpr;
1711 
1712 /// Matches paren list expressions.
1713 /// ParenListExprs don't have a predefined type and are used for late parsing.
1714 /// In the final AST, they can be met in template declarations.
1715 ///
1716 /// Given
1717 /// \code
1718 ///   template<typename T> class X {
1719 ///     void f() {
1720 ///       X x(*this);
1721 ///       int a = 0, b = 1; int i = (a, b);
1722 ///     }
1723 ///   };
1724 /// \endcode
1725 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1726 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1727 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1728     parenListExpr;
1729 
1730 /// Matches substitutions of non-type template parameters.
1731 ///
1732 /// Given
1733 /// \code
1734 ///   template <int N>
1735 ///   struct A { static const int n = N; };
1736 ///   struct B : public A<42> {};
1737 /// \endcode
1738 /// substNonTypeTemplateParmExpr()
1739 ///   matches "N" in the right-hand side of "static const int n = N;"
1740 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1741                                                    SubstNonTypeTemplateParmExpr>
1742     substNonTypeTemplateParmExpr;
1743 
1744 /// Matches using declarations.
1745 ///
1746 /// Given
1747 /// \code
1748 ///   namespace X { int x; }
1749 ///   using X::x;
1750 /// \endcode
1751 /// usingDecl()
1752 ///   matches \code using X::x \endcode
1753 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1754 
1755 /// Matches using namespace declarations.
1756 ///
1757 /// Given
1758 /// \code
1759 ///   namespace X { int x; }
1760 ///   using namespace X;
1761 /// \endcode
1762 /// usingDirectiveDecl()
1763 ///   matches \code using namespace X \endcode
1764 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1765     usingDirectiveDecl;
1766 
1767 /// Matches reference to a name that can be looked up during parsing
1768 /// but could not be resolved to a specific declaration.
1769 ///
1770 /// Given
1771 /// \code
1772 ///   template<typename T>
1773 ///   T foo() { T a; return a; }
1774 ///   template<typename T>
1775 ///   void bar() {
1776 ///     foo<T>();
1777 ///   }
1778 /// \endcode
1779 /// unresolvedLookupExpr()
1780 ///   matches \code foo<T>() \endcode
1781 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1782     unresolvedLookupExpr;
1783 
1784 /// Matches unresolved using value declarations.
1785 ///
1786 /// Given
1787 /// \code
1788 ///   template<typename X>
1789 ///   class C : private X {
1790 ///     using X::x;
1791 ///   };
1792 /// \endcode
1793 /// unresolvedUsingValueDecl()
1794 ///   matches \code using X::x \endcode
1795 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1796                                                    UnresolvedUsingValueDecl>
1797     unresolvedUsingValueDecl;
1798 
1799 /// Matches unresolved using value declarations that involve the
1800 /// typename.
1801 ///
1802 /// Given
1803 /// \code
1804 ///   template <typename T>
1805 ///   struct Base { typedef T Foo; };
1806 ///
1807 ///   template<typename T>
1808 ///   struct S : private Base<T> {
1809 ///     using typename Base<T>::Foo;
1810 ///   };
1811 /// \endcode
1812 /// unresolvedUsingTypenameDecl()
1813 ///   matches \code using Base<T>::Foo \endcode
1814 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1815                                                    UnresolvedUsingTypenameDecl>
1816     unresolvedUsingTypenameDecl;
1817 
1818 /// Matches a constant expression wrapper.
1819 ///
1820 /// Example matches the constant in the case statement:
1821 ///     (matcher = constantExpr())
1822 /// \code
1823 ///   switch (a) {
1824 ///   case 37: break;
1825 ///   }
1826 /// \endcode
1827 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1828     constantExpr;
1829 
1830 /// Matches parentheses used in expressions.
1831 ///
1832 /// Example matches (foo() + 1)
1833 /// \code
1834 ///   int foo() { return 1; }
1835 ///   int a = (foo() + 1);
1836 /// \endcode
1837 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1838 
1839 /// Matches constructor call expressions (including implicit ones).
1840 ///
1841 /// Example matches string(ptr, n) and ptr within arguments of f
1842 ///     (matcher = cxxConstructExpr())
1843 /// \code
1844 ///   void f(const string &a, const string &b);
1845 ///   char *ptr;
1846 ///   int n;
1847 ///   f(string(ptr, n), ptr);
1848 /// \endcode
1849 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1850     cxxConstructExpr;
1851 
1852 /// Matches unresolved constructor call expressions.
1853 ///
1854 /// Example matches T(t) in return statement of f
1855 ///     (matcher = cxxUnresolvedConstructExpr())
1856 /// \code
1857 ///   template <typename T>
1858 ///   void f(const T& t) { return T(t); }
1859 /// \endcode
1860 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1861                                                    CXXUnresolvedConstructExpr>
1862     cxxUnresolvedConstructExpr;
1863 
1864 /// Matches implicit and explicit this expressions.
1865 ///
1866 /// Example matches the implicit this expression in "return i".
1867 ///     (matcher = cxxThisExpr())
1868 /// \code
1869 /// struct foo {
1870 ///   int i;
1871 ///   int f() { return i; }
1872 /// };
1873 /// \endcode
1874 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1875     cxxThisExpr;
1876 
1877 /// Matches nodes where temporaries are created.
1878 ///
1879 /// Example matches FunctionTakesString(GetStringByValue())
1880 ///     (matcher = cxxBindTemporaryExpr())
1881 /// \code
1882 ///   FunctionTakesString(GetStringByValue());
1883 ///   FunctionTakesStringByPointer(GetStringPointer());
1884 /// \endcode
1885 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1886     cxxBindTemporaryExpr;
1887 
1888 /// Matches nodes where temporaries are materialized.
1889 ///
1890 /// Example: Given
1891 /// \code
1892 ///   struct T {void func();};
1893 ///   T f();
1894 ///   void g(T);
1895 /// \endcode
1896 /// materializeTemporaryExpr() matches 'f()' in these statements
1897 /// \code
1898 ///   T u(f());
1899 ///   g(f());
1900 ///   f().func();
1901 /// \endcode
1902 /// but does not match
1903 /// \code
1904 ///   f();
1905 /// \endcode
1906 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1907                                                    MaterializeTemporaryExpr>
1908     materializeTemporaryExpr;
1909 
1910 /// Matches new expressions.
1911 ///
1912 /// Given
1913 /// \code
1914 ///   new X;
1915 /// \endcode
1916 /// cxxNewExpr()
1917 ///   matches 'new X'.
1918 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1919 
1920 /// Matches delete expressions.
1921 ///
1922 /// Given
1923 /// \code
1924 ///   delete X;
1925 /// \endcode
1926 /// cxxDeleteExpr()
1927 ///   matches 'delete X'.
1928 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1929     cxxDeleteExpr;
1930 
1931 /// Matches noexcept expressions.
1932 ///
1933 /// Given
1934 /// \code
1935 ///   bool a() noexcept;
1936 ///   bool b() noexcept(true);
1937 ///   bool c() noexcept(false);
1938 ///   bool d() noexcept(noexcept(a()));
1939 ///   bool e = noexcept(b()) || noexcept(c());
1940 /// \endcode
1941 /// cxxNoexceptExpr()
1942 ///   matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1943 ///   doesn't match the noexcept specifier in the declarations a, b, c or d.
1944 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1945     cxxNoexceptExpr;
1946 
1947 /// Matches array subscript expressions.
1948 ///
1949 /// Given
1950 /// \code
1951 ///   int i = a[1];
1952 /// \endcode
1953 /// arraySubscriptExpr()
1954 ///   matches "a[1]"
1955 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1956     arraySubscriptExpr;
1957 
1958 /// Matches the value of a default argument at the call site.
1959 ///
1960 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1961 ///     default value of the second parameter in the call expression f(42)
1962 ///     (matcher = cxxDefaultArgExpr())
1963 /// \code
1964 ///   void f(int x, int y = 0);
1965 ///   f(42);
1966 /// \endcode
1967 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1968     cxxDefaultArgExpr;
1969 
1970 /// Matches overloaded operator calls.
1971 ///
1972 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1973 /// binaryOperator matcher.
1974 /// Currently it does not match operators such as new delete.
1975 /// FIXME: figure out why these do not match?
1976 ///
1977 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1978 ///     (matcher = cxxOperatorCallExpr())
1979 /// \code
1980 ///   ostream &operator<< (ostream &out, int i) { };
1981 ///   ostream &o; int b = 1, c = 1;
1982 ///   o << b << c;
1983 /// \endcode
1984 /// See also the binaryOperation() matcher for more-general matching of binary
1985 /// uses of this AST node.
1986 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1987     cxxOperatorCallExpr;
1988 
1989 /// Matches rewritten binary operators
1990 ///
1991 /// Example matches use of "<":
1992 /// \code
1993 ///   #include <compare>
1994 ///   struct HasSpaceshipMem {
1995 ///     int a;
1996 ///     constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
1997 ///   };
1998 ///   void compare() {
1999 ///     HasSpaceshipMem hs1, hs2;
2000 ///     if (hs1 < hs2)
2001 ///         return;
2002 ///   }
2003 /// \endcode
2004 /// See also the binaryOperation() matcher for more-general matching
2005 /// of this AST node.
2006 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2007                                                    CXXRewrittenBinaryOperator>
2008     cxxRewrittenBinaryOperator;
2009 
2010 /// Matches expressions.
2011 ///
2012 /// Example matches x()
2013 /// \code
2014 ///   void f() { x(); }
2015 /// \endcode
2016 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2017 
2018 /// Matches expressions that refer to declarations.
2019 ///
2020 /// Example matches x in if (x)
2021 /// \code
2022 ///   bool x;
2023 ///   if (x) {}
2024 /// \endcode
2025 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2026     declRefExpr;
2027 
2028 /// Matches a reference to an ObjCIvar.
2029 ///
2030 /// Example: matches "a" in "init" method:
2031 /// \code
2032 /// @implementation A {
2033 ///   NSString *a;
2034 /// }
2035 /// - (void) init {
2036 ///   a = @"hello";
2037 /// }
2038 /// \endcode
2039 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2040     objcIvarRefExpr;
2041 
2042 /// Matches a reference to a block.
2043 ///
2044 /// Example: matches "^{}":
2045 /// \code
2046 ///   void f() { ^{}(); }
2047 /// \endcode
2048 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2049 
2050 /// Matches if statements.
2051 ///
2052 /// Example matches 'if (x) {}'
2053 /// \code
2054 ///   if (x) {}
2055 /// \endcode
2056 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2057 
2058 /// Matches for statements.
2059 ///
2060 /// Example matches 'for (;;) {}'
2061 /// \code
2062 ///   for (;;) {}
2063 ///   int i[] =  {1, 2, 3}; for (auto a : i);
2064 /// \endcode
2065 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2066 
2067 /// Matches the increment statement of a for loop.
2068 ///
2069 /// Example:
2070 ///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2071 /// matches '++x' in
2072 /// \code
2073 ///     for (x; x < N; ++x) { }
2074 /// \endcode
AST_MATCHER_P(ForStmt,hasIncrement,internal::Matcher<Stmt>,InnerMatcher)2075 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2076               InnerMatcher) {
2077   const Stmt *const Increment = Node.getInc();
2078   return (Increment != nullptr &&
2079           InnerMatcher.matches(*Increment, Finder, Builder));
2080 }
2081 
2082 /// Matches the initialization statement of a for loop.
2083 ///
2084 /// Example:
2085 ///     forStmt(hasLoopInit(declStmt()))
2086 /// matches 'int x = 0' in
2087 /// \code
2088 ///     for (int x = 0; x < N; ++x) { }
2089 /// \endcode
AST_MATCHER_P(ForStmt,hasLoopInit,internal::Matcher<Stmt>,InnerMatcher)2090 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2091               InnerMatcher) {
2092   const Stmt *const Init = Node.getInit();
2093   return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2094 }
2095 
2096 /// Matches range-based for statements.
2097 ///
2098 /// cxxForRangeStmt() matches 'for (auto a : i)'
2099 /// \code
2100 ///   int i[] =  {1, 2, 3}; for (auto a : i);
2101 ///   for(int j = 0; j < 5; ++j);
2102 /// \endcode
2103 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2104     cxxForRangeStmt;
2105 
2106 /// Matches the initialization statement of a for loop.
2107 ///
2108 /// Example:
2109 ///     forStmt(hasLoopVariable(anything()))
2110 /// matches 'int x' in
2111 /// \code
2112 ///     for (int x : a) { }
2113 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasLoopVariable,internal::Matcher<VarDecl>,InnerMatcher)2114 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2115               InnerMatcher) {
2116   const VarDecl *const Var = Node.getLoopVariable();
2117   return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2118 }
2119 
2120 /// Matches the range initialization statement of a for loop.
2121 ///
2122 /// Example:
2123 ///     forStmt(hasRangeInit(anything()))
2124 /// matches 'a' in
2125 /// \code
2126 ///     for (int x : a) { }
2127 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasRangeInit,internal::Matcher<Expr>,InnerMatcher)2128 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2129               InnerMatcher) {
2130   const Expr *const Init = Node.getRangeInit();
2131   return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2132 }
2133 
2134 /// Matches while statements.
2135 ///
2136 /// Given
2137 /// \code
2138 ///   while (true) {}
2139 /// \endcode
2140 /// whileStmt()
2141 ///   matches 'while (true) {}'.
2142 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2143 
2144 /// Matches do statements.
2145 ///
2146 /// Given
2147 /// \code
2148 ///   do {} while (true);
2149 /// \endcode
2150 /// doStmt()
2151 ///   matches 'do {} while(true)'
2152 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2153 
2154 /// Matches break statements.
2155 ///
2156 /// Given
2157 /// \code
2158 ///   while (true) { break; }
2159 /// \endcode
2160 /// breakStmt()
2161 ///   matches 'break'
2162 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2163 
2164 /// Matches continue statements.
2165 ///
2166 /// Given
2167 /// \code
2168 ///   while (true) { continue; }
2169 /// \endcode
2170 /// continueStmt()
2171 ///   matches 'continue'
2172 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2173     continueStmt;
2174 
2175 /// Matches co_return statements.
2176 ///
2177 /// Given
2178 /// \code
2179 ///   while (true) { co_return; }
2180 /// \endcode
2181 /// coreturnStmt()
2182 ///   matches 'co_return'
2183 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2184     coreturnStmt;
2185 
2186 /// Matches return statements.
2187 ///
2188 /// Given
2189 /// \code
2190 ///   return 1;
2191 /// \endcode
2192 /// returnStmt()
2193 ///   matches 'return 1'
2194 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2195 
2196 /// Matches goto statements.
2197 ///
2198 /// Given
2199 /// \code
2200 ///   goto FOO;
2201 ///   FOO: bar();
2202 /// \endcode
2203 /// gotoStmt()
2204 ///   matches 'goto FOO'
2205 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2206 
2207 /// Matches label statements.
2208 ///
2209 /// Given
2210 /// \code
2211 ///   goto FOO;
2212 ///   FOO: bar();
2213 /// \endcode
2214 /// labelStmt()
2215 ///   matches 'FOO:'
2216 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2217 
2218 /// Matches address of label statements (GNU extension).
2219 ///
2220 /// Given
2221 /// \code
2222 ///   FOO: bar();
2223 ///   void *ptr = &&FOO;
2224 ///   goto *bar;
2225 /// \endcode
2226 /// addrLabelExpr()
2227 ///   matches '&&FOO'
2228 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2229     addrLabelExpr;
2230 
2231 /// Matches switch statements.
2232 ///
2233 /// Given
2234 /// \code
2235 ///   switch(a) { case 42: break; default: break; }
2236 /// \endcode
2237 /// switchStmt()
2238 ///   matches 'switch(a)'.
2239 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2240 
2241 /// Matches case and default statements inside switch statements.
2242 ///
2243 /// Given
2244 /// \code
2245 ///   switch(a) { case 42: break; default: break; }
2246 /// \endcode
2247 /// switchCase()
2248 ///   matches 'case 42:' and 'default:'.
2249 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2250 
2251 /// Matches case statements inside switch statements.
2252 ///
2253 /// Given
2254 /// \code
2255 ///   switch(a) { case 42: break; default: break; }
2256 /// \endcode
2257 /// caseStmt()
2258 ///   matches 'case 42:'.
2259 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2260 
2261 /// Matches default statements inside switch statements.
2262 ///
2263 /// Given
2264 /// \code
2265 ///   switch(a) { case 42: break; default: break; }
2266 /// \endcode
2267 /// defaultStmt()
2268 ///   matches 'default:'.
2269 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2270     defaultStmt;
2271 
2272 /// Matches compound statements.
2273 ///
2274 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2275 /// \code
2276 ///   for (;;) {{}}
2277 /// \endcode
2278 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2279     compoundStmt;
2280 
2281 /// Matches catch statements.
2282 ///
2283 /// \code
2284 ///   try {} catch(int i) {}
2285 /// \endcode
2286 /// cxxCatchStmt()
2287 ///   matches 'catch(int i)'
2288 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2289     cxxCatchStmt;
2290 
2291 /// Matches try statements.
2292 ///
2293 /// \code
2294 ///   try {} catch(int i) {}
2295 /// \endcode
2296 /// cxxTryStmt()
2297 ///   matches 'try {}'
2298 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2299 
2300 /// Matches throw expressions.
2301 ///
2302 /// \code
2303 ///   try { throw 5; } catch(int i) {}
2304 /// \endcode
2305 /// cxxThrowExpr()
2306 ///   matches 'throw 5'
2307 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2308     cxxThrowExpr;
2309 
2310 /// Matches null statements.
2311 ///
2312 /// \code
2313 ///   foo();;
2314 /// \endcode
2315 /// nullStmt()
2316 ///   matches the second ';'
2317 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2318 
2319 /// Matches asm statements.
2320 ///
2321 /// \code
2322 ///  int i = 100;
2323 ///   __asm("mov al, 2");
2324 /// \endcode
2325 /// asmStmt()
2326 ///   matches '__asm("mov al, 2")'
2327 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2328 
2329 /// Matches bool literals.
2330 ///
2331 /// Example matches true
2332 /// \code
2333 ///   true
2334 /// \endcode
2335 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2336     cxxBoolLiteral;
2337 
2338 /// Matches string literals (also matches wide string literals).
2339 ///
2340 /// Example matches "abcd", L"abcd"
2341 /// \code
2342 ///   char *s = "abcd";
2343 ///   wchar_t *ws = L"abcd";
2344 /// \endcode
2345 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2346     stringLiteral;
2347 
2348 /// Matches character literals (also matches wchar_t).
2349 ///
2350 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2351 /// though.
2352 ///
2353 /// Example matches 'a', L'a'
2354 /// \code
2355 ///   char ch = 'a';
2356 ///   wchar_t chw = L'a';
2357 /// \endcode
2358 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2359     characterLiteral;
2360 
2361 /// Matches integer literals of all sizes / encodings, e.g.
2362 /// 1, 1L, 0x1 and 1U.
2363 ///
2364 /// Does not match character-encoded integers such as L'a'.
2365 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2366     integerLiteral;
2367 
2368 /// Matches float literals of all sizes / encodings, e.g.
2369 /// 1.0, 1.0f, 1.0L and 1e10.
2370 ///
2371 /// Does not match implicit conversions such as
2372 /// \code
2373 ///   float a = 10;
2374 /// \endcode
2375 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2376     floatLiteral;
2377 
2378 /// Matches imaginary literals, which are based on integer and floating
2379 /// point literals e.g.: 1i, 1.0i
2380 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2381     imaginaryLiteral;
2382 
2383 /// Matches fixed point literals
2384 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2385     fixedPointLiteral;
2386 
2387 /// Matches user defined literal operator call.
2388 ///
2389 /// Example match: "foo"_suffix
2390 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2391     userDefinedLiteral;
2392 
2393 /// Matches compound (i.e. non-scalar) literals
2394 ///
2395 /// Example match: {1}, (1, 2)
2396 /// \code
2397 ///   int array[4] = {1};
2398 ///   vector int myvec = (vector int)(1, 2);
2399 /// \endcode
2400 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2401     compoundLiteralExpr;
2402 
2403 /// Matches co_await expressions.
2404 ///
2405 /// Given
2406 /// \code
2407 ///   co_await 1;
2408 /// \endcode
2409 /// coawaitExpr()
2410 ///   matches 'co_await 1'
2411 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2412     coawaitExpr;
2413 /// Matches co_await expressions where the type of the promise is dependent
2414 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2415     dependentCoawaitExpr;
2416 /// Matches co_yield expressions.
2417 ///
2418 /// Given
2419 /// \code
2420 ///   co_yield 1;
2421 /// \endcode
2422 /// coyieldExpr()
2423 ///   matches 'co_yield 1'
2424 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2425     coyieldExpr;
2426 
2427 /// Matches nullptr literal.
2428 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2429     cxxNullPtrLiteralExpr;
2430 
2431 /// Matches GNU __builtin_choose_expr.
2432 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2433     chooseExpr;
2434 
2435 /// Matches GNU __null expression.
2436 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2437     gnuNullExpr;
2438 
2439 /// Matches C11 _Generic expression.
2440 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2441     genericSelectionExpr;
2442 
2443 /// Matches atomic builtins.
2444 /// Example matches __atomic_load_n(ptr, 1)
2445 /// \code
2446 ///   void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2447 /// \endcode
2448 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2449 
2450 /// Matches statement expression (GNU extension).
2451 ///
2452 /// Example match: ({ int X = 4; X; })
2453 /// \code
2454 ///   int C = ({ int X = 4; X; });
2455 /// \endcode
2456 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2457 
2458 /// Matches binary operator expressions.
2459 ///
2460 /// Example matches a || b
2461 /// \code
2462 ///   !(a || b)
2463 /// \endcode
2464 /// See also the binaryOperation() matcher for more-general matching.
2465 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2466     binaryOperator;
2467 
2468 /// Matches unary operator expressions.
2469 ///
2470 /// Example matches !a
2471 /// \code
2472 ///   !a || b
2473 /// \endcode
2474 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2475     unaryOperator;
2476 
2477 /// Matches conditional operator expressions.
2478 ///
2479 /// Example matches a ? b : c
2480 /// \code
2481 ///   (a ? b : c) + 42
2482 /// \endcode
2483 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2484     conditionalOperator;
2485 
2486 /// Matches binary conditional operator expressions (GNU extension).
2487 ///
2488 /// Example matches a ?: b
2489 /// \code
2490 ///   (a ?: b) + 42;
2491 /// \endcode
2492 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2493                                                    BinaryConditionalOperator>
2494     binaryConditionalOperator;
2495 
2496 /// Matches opaque value expressions. They are used as helpers
2497 /// to reference another expressions and can be met
2498 /// in BinaryConditionalOperators, for example.
2499 ///
2500 /// Example matches 'a'
2501 /// \code
2502 ///   (a ?: c) + 42;
2503 /// \endcode
2504 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2505     opaqueValueExpr;
2506 
2507 /// Matches a C++ static_assert declaration.
2508 ///
2509 /// Example:
2510 ///   staticAssertExpr()
2511 /// matches
2512 ///   static_assert(sizeof(S) == sizeof(int))
2513 /// in
2514 /// \code
2515 ///   struct S {
2516 ///     int x;
2517 ///   };
2518 ///   static_assert(sizeof(S) == sizeof(int));
2519 /// \endcode
2520 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2521     staticAssertDecl;
2522 
2523 /// Matches a reinterpret_cast expression.
2524 ///
2525 /// Either the source expression or the destination type can be matched
2526 /// using has(), but hasDestinationType() is more specific and can be
2527 /// more readable.
2528 ///
2529 /// Example matches reinterpret_cast<char*>(&p) in
2530 /// \code
2531 ///   void* p = reinterpret_cast<char*>(&p);
2532 /// \endcode
2533 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2534     cxxReinterpretCastExpr;
2535 
2536 /// Matches a C++ static_cast expression.
2537 ///
2538 /// \see hasDestinationType
2539 /// \see reinterpretCast
2540 ///
2541 /// Example:
2542 ///   cxxStaticCastExpr()
2543 /// matches
2544 ///   static_cast<long>(8)
2545 /// in
2546 /// \code
2547 ///   long eight(static_cast<long>(8));
2548 /// \endcode
2549 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2550     cxxStaticCastExpr;
2551 
2552 /// Matches a dynamic_cast expression.
2553 ///
2554 /// Example:
2555 ///   cxxDynamicCastExpr()
2556 /// matches
2557 ///   dynamic_cast<D*>(&b);
2558 /// in
2559 /// \code
2560 ///   struct B { virtual ~B() {} }; struct D : B {};
2561 ///   B b;
2562 ///   D* p = dynamic_cast<D*>(&b);
2563 /// \endcode
2564 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2565     cxxDynamicCastExpr;
2566 
2567 /// Matches a const_cast expression.
2568 ///
2569 /// Example: Matches const_cast<int*>(&r) in
2570 /// \code
2571 ///   int n = 42;
2572 ///   const int &r(n);
2573 ///   int* p = const_cast<int*>(&r);
2574 /// \endcode
2575 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2576     cxxConstCastExpr;
2577 
2578 /// Matches a C-style cast expression.
2579 ///
2580 /// Example: Matches (int) 2.2f in
2581 /// \code
2582 ///   int i = (int) 2.2f;
2583 /// \endcode
2584 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2585     cStyleCastExpr;
2586 
2587 /// Matches explicit cast expressions.
2588 ///
2589 /// Matches any cast expression written in user code, whether it be a
2590 /// C-style cast, a functional-style cast, or a keyword cast.
2591 ///
2592 /// Does not match implicit conversions.
2593 ///
2594 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2595 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2596 /// actual cast expressions.
2597 ///
2598 /// \see hasDestinationType.
2599 ///
2600 /// Example: matches all five of the casts in
2601 /// \code
2602 ///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2603 /// \endcode
2604 /// but does not match the implicit conversion in
2605 /// \code
2606 ///   long ell = 42;
2607 /// \endcode
2608 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2609     explicitCastExpr;
2610 
2611 /// Matches the implicit cast nodes of Clang's AST.
2612 ///
2613 /// This matches many different places, including function call return value
2614 /// eliding, as well as any type conversions.
2615 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2616     implicitCastExpr;
2617 
2618 /// Matches any cast nodes of Clang's AST.
2619 ///
2620 /// Example: castExpr() matches each of the following:
2621 /// \code
2622 ///   (int) 3;
2623 ///   const_cast<Expr *>(SubExpr);
2624 ///   char c = 0;
2625 /// \endcode
2626 /// but does not match
2627 /// \code
2628 ///   int i = (0);
2629 ///   int k = 0;
2630 /// \endcode
2631 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2632 
2633 /// Matches functional cast expressions
2634 ///
2635 /// Example: Matches Foo(bar);
2636 /// \code
2637 ///   Foo f = bar;
2638 ///   Foo g = (Foo) bar;
2639 ///   Foo h = Foo(bar);
2640 /// \endcode
2641 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2642     cxxFunctionalCastExpr;
2643 
2644 /// Matches functional cast expressions having N != 1 arguments
2645 ///
2646 /// Example: Matches Foo(bar, bar)
2647 /// \code
2648 ///   Foo h = Foo(bar, bar);
2649 /// \endcode
2650 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2651     cxxTemporaryObjectExpr;
2652 
2653 /// Matches predefined identifier expressions [C99 6.4.2.2].
2654 ///
2655 /// Example: Matches __func__
2656 /// \code
2657 ///   printf("%s", __func__);
2658 /// \endcode
2659 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2660     predefinedExpr;
2661 
2662 /// Matches C99 designated initializer expressions [C99 6.7.8].
2663 ///
2664 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2665 /// \code
2666 ///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2667 /// \endcode
2668 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2669     designatedInitExpr;
2670 
2671 /// Matches designated initializer expressions that contain
2672 /// a specific number of designators.
2673 ///
2674 /// Example: Given
2675 /// \code
2676 ///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2677 ///   point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2678 /// \endcode
2679 /// designatorCountIs(2)
2680 ///   matches '{ [2].y = 1.0, [0].x = 1.0 }',
2681 ///   but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
AST_MATCHER_P(DesignatedInitExpr,designatorCountIs,unsigned,N)2682 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2683   return Node.size() == N;
2684 }
2685 
2686 /// Matches \c QualTypes in the clang AST.
2687 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2688 
2689 /// Matches \c Types in the clang AST.
2690 extern const internal::VariadicAllOfMatcher<Type> type;
2691 
2692 /// Matches \c TypeLocs in the clang AST.
2693 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2694 
2695 /// Matches if any of the given matchers matches.
2696 ///
2697 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2698 /// matching submatcher.
2699 ///
2700 /// For example, in:
2701 /// \code
2702 ///   class A { int a; int b; };
2703 /// \endcode
2704 /// The matcher:
2705 /// \code
2706 ///   cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2707 ///                        has(fieldDecl(hasName("b")).bind("v"))))
2708 /// \endcode
2709 /// will generate two results binding "v", the first of which binds
2710 /// the field declaration of \c a, the second the field declaration of
2711 /// \c b.
2712 ///
2713 /// Usable as: Any Matcher
2714 extern const internal::VariadicOperatorMatcherFunc<
2715     2, std::numeric_limits<unsigned>::max()>
2716     eachOf;
2717 
2718 /// Matches if any of the given matchers matches.
2719 ///
2720 /// Usable as: Any Matcher
2721 extern const internal::VariadicOperatorMatcherFunc<
2722     2, std::numeric_limits<unsigned>::max()>
2723     anyOf;
2724 
2725 /// Matches if all given matchers match.
2726 ///
2727 /// Usable as: Any Matcher
2728 extern const internal::VariadicOperatorMatcherFunc<
2729     2, std::numeric_limits<unsigned>::max()>
2730     allOf;
2731 
2732 /// Matches any node regardless of the submatcher.
2733 ///
2734 /// However, \c optionally will retain any bindings generated by the submatcher.
2735 /// Useful when additional information which may or may not present about a main
2736 /// matching node is desired.
2737 ///
2738 /// For example, in:
2739 /// \code
2740 ///   class Foo {
2741 ///     int bar;
2742 ///   }
2743 /// \endcode
2744 /// The matcher:
2745 /// \code
2746 ///   cxxRecordDecl(
2747 ///     optionally(has(
2748 ///       fieldDecl(hasName("bar")).bind("var")
2749 ///   ))).bind("record")
2750 /// \endcode
2751 /// will produce a result binding for both "record" and "var".
2752 /// The matcher will produce a "record" binding for even if there is no data
2753 /// member named "bar" in that class.
2754 ///
2755 /// Usable as: Any Matcher
2756 extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2757 
2758 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2759 ///
2760 /// Given
2761 /// \code
2762 ///   Foo x = bar;
2763 ///   int y = sizeof(x) + alignof(x);
2764 /// \endcode
2765 /// unaryExprOrTypeTraitExpr()
2766 ///   matches \c sizeof(x) and \c alignof(x)
2767 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2768                                                    UnaryExprOrTypeTraitExpr>
2769     unaryExprOrTypeTraitExpr;
2770 
2771 /// Matches any of the \p NodeMatchers with InnerMatchers nested within
2772 ///
2773 /// Given
2774 /// \code
2775 ///   if (true);
2776 ///   for (; true; );
2777 /// \endcode
2778 /// with the matcher
2779 /// \code
2780 ///   mapAnyOf(ifStmt, forStmt).with(
2781 ///     hasCondition(cxxBoolLiteralExpr(equals(true)))
2782 ///     ).bind("trueCond")
2783 /// \endcode
2784 /// matches the \c if and the \c for. It is equivalent to:
2785 /// \code
2786 ///   auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2787 ///   anyOf(
2788 ///     ifStmt(trueCond).bind("trueCond"),
2789 ///     forStmt(trueCond).bind("trueCond")
2790 ///     );
2791 /// \endcode
2792 ///
2793 /// The with() chain-call accepts zero or more matchers which are combined
2794 /// as-if with allOf() in each of the node matchers.
2795 /// Usable as: Any Matcher
2796 template <typename T, typename... U>
mapAnyOf(internal::VariadicDynCastAllOfMatcher<T,U> const &...)2797 auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2798   return internal::MapAnyOfHelper<U...>();
2799 }
2800 
2801 /// Matches nodes which can be used with binary operators.
2802 ///
2803 /// The code
2804 /// \code
2805 ///   var1 != var2;
2806 /// \endcode
2807 /// might be represented in the clang AST as a binaryOperator, a
2808 /// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2809 ///
2810 /// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2811 ///   least one is a class type (cxxOperatorCallExpr)
2812 /// * whether the code appears in a template declaration, if at least one of the
2813 ///   vars is a dependent-type (binaryOperator)
2814 /// * whether the code relies on a rewritten binary operator, such as a
2815 /// spaceship operator or an inverted equality operator
2816 /// (cxxRewrittenBinaryOperator)
2817 ///
2818 /// This matcher elides details in places where the matchers for the nodes are
2819 /// compatible.
2820 ///
2821 /// Given
2822 /// \code
2823 ///   binaryOperation(
2824 ///     hasOperatorName("!="),
2825 ///     hasLHS(expr().bind("lhs")),
2826 ///     hasRHS(expr().bind("rhs"))
2827 ///   )
2828 /// \endcode
2829 /// matches each use of "!=" in:
2830 /// \code
2831 ///   struct S{
2832 ///       bool operator!=(const S&) const;
2833 ///   };
2834 ///
2835 ///   void foo()
2836 ///   {
2837 ///      1 != 2;
2838 ///      S() != S();
2839 ///   }
2840 ///
2841 ///   template<typename T>
2842 ///   void templ()
2843 ///   {
2844 ///      1 != 2;
2845 ///      T() != S();
2846 ///   }
2847 ///   struct HasOpEq
2848 ///   {
2849 ///       bool operator==(const HasOpEq &) const;
2850 ///   };
2851 ///
2852 ///   void inverse()
2853 ///   {
2854 ///       HasOpEq s1;
2855 ///       HasOpEq s2;
2856 ///       if (s1 != s2)
2857 ///           return;
2858 ///   }
2859 ///
2860 ///   struct HasSpaceship
2861 ///   {
2862 ///       bool operator<=>(const HasOpEq &) const;
2863 ///   };
2864 ///
2865 ///   void use_spaceship()
2866 ///   {
2867 ///       HasSpaceship s1;
2868 ///       HasSpaceship s2;
2869 ///       if (s1 != s2)
2870 ///           return;
2871 ///   }
2872 /// \endcode
2873 extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2874                                        CXXRewrittenBinaryOperator>
2875     binaryOperation;
2876 
2877 /// Matches function calls and constructor calls
2878 ///
2879 /// Because CallExpr and CXXConstructExpr do not share a common
2880 /// base class with API accessing arguments etc, AST Matchers for code
2881 /// which should match both are typically duplicated. This matcher
2882 /// removes the need for duplication.
2883 ///
2884 /// Given code
2885 /// \code
2886 /// struct ConstructorTakesInt
2887 /// {
2888 ///   ConstructorTakesInt(int i) {}
2889 /// };
2890 ///
2891 /// void callTakesInt(int i)
2892 /// {
2893 /// }
2894 ///
2895 /// void doCall()
2896 /// {
2897 ///   callTakesInt(42);
2898 /// }
2899 ///
2900 /// void doConstruct()
2901 /// {
2902 ///   ConstructorTakesInt cti(42);
2903 /// }
2904 /// \endcode
2905 ///
2906 /// The matcher
2907 /// \code
2908 /// invocation(hasArgument(0, integerLiteral(equals(42))))
2909 /// \endcode
2910 /// matches the expression in both doCall and doConstruct
2911 extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
2912 
2913 /// Matches unary expressions that have a specific type of argument.
2914 ///
2915 /// Given
2916 /// \code
2917 ///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2918 /// \endcode
2919 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2920 ///   matches \c sizeof(a) and \c alignof(c)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,hasArgumentOfType,internal::Matcher<QualType>,InnerMatcher)2921 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2922               internal::Matcher<QualType>, InnerMatcher) {
2923   const QualType ArgumentType = Node.getTypeOfArgument();
2924   return InnerMatcher.matches(ArgumentType, Finder, Builder);
2925 }
2926 
2927 /// Matches unary expressions of a certain kind.
2928 ///
2929 /// Given
2930 /// \code
2931 ///   int x;
2932 ///   int s = sizeof(x) + alignof(x)
2933 /// \endcode
2934 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2935 ///   matches \c sizeof(x)
2936 ///
2937 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2938 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,ofKind,UnaryExprOrTypeTrait,Kind)2939 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2940   return Node.getKind() == Kind;
2941 }
2942 
2943 /// Same as unaryExprOrTypeTraitExpr, but only matching
2944 /// alignof.
alignOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)2945 inline internal::BindableMatcher<Stmt> alignOfExpr(
2946     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2947   return stmt(unaryExprOrTypeTraitExpr(
2948       allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2949             InnerMatcher)));
2950 }
2951 
2952 /// Same as unaryExprOrTypeTraitExpr, but only matching
2953 /// sizeof.
sizeOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)2954 inline internal::BindableMatcher<Stmt> sizeOfExpr(
2955     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2956   return stmt(unaryExprOrTypeTraitExpr(
2957       allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2958 }
2959 
2960 /// Matches NamedDecl nodes that have the specified name.
2961 ///
2962 /// Supports specifying enclosing namespaces or classes by prefixing the name
2963 /// with '<enclosing>::'.
2964 /// Does not match typedefs of an underlying type with the given name.
2965 ///
2966 /// Example matches X (Name == "X")
2967 /// \code
2968 ///   class X;
2969 /// \endcode
2970 ///
2971 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2972 /// \code
2973 ///   namespace a { namespace b { class X; } }
2974 /// \endcode
hasName(StringRef Name)2975 inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
2976   return internal::Matcher<NamedDecl>(
2977       new internal::HasNameMatcher({std::string(Name)}));
2978 }
2979 
2980 /// Matches NamedDecl nodes that have any of the specified names.
2981 ///
2982 /// This matcher is only provided as a performance optimization of hasName.
2983 /// \code
2984 ///     hasAnyName(a, b, c)
2985 /// \endcode
2986 ///  is equivalent to, but faster than
2987 /// \code
2988 ///     anyOf(hasName(a), hasName(b), hasName(c))
2989 /// \endcode
2990 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2991                                         internal::hasAnyNameFunc>
2992     hasAnyName;
2993 
2994 /// Matches NamedDecl nodes whose fully qualified names contain
2995 /// a substring matched by the given RegExp.
2996 ///
2997 /// Supports specifying enclosing namespaces or classes by
2998 /// prefixing the name with '<enclosing>::'.  Does not match typedefs
2999 /// of an underlying type with the given name.
3000 ///
3001 /// Example matches X (regexp == "::X")
3002 /// \code
3003 ///   class X;
3004 /// \endcode
3005 ///
3006 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3007 /// \code
3008 ///   namespace foo { namespace bar { class X; } }
3009 /// \endcode
AST_MATCHER_REGEX(NamedDecl,matchesName,RegExp)3010 AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3011   std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3012   return RegExp->match(FullNameString);
3013 }
3014 
3015 /// Matches overloaded operator names.
3016 ///
3017 /// Matches overloaded operator names specified in strings without the
3018 /// "operator" prefix: e.g. "<<".
3019 ///
3020 /// Given:
3021 /// \code
3022 ///   class A { int operator*(); };
3023 ///   const A &operator<<(const A &a, const A &b);
3024 ///   A a;
3025 ///   a << a;   // <-- This matches
3026 /// \endcode
3027 ///
3028 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3029 /// specified line and
3030 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3031 /// matches the declaration of \c A.
3032 ///
3033 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3034 inline internal::PolymorphicMatcher<
3035     internal::HasOverloadedOperatorNameMatcher,
3036     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl),
3037     std::vector<std::string>>
hasOverloadedOperatorName(StringRef Name)3038 hasOverloadedOperatorName(StringRef Name) {
3039   return internal::PolymorphicMatcher<
3040       internal::HasOverloadedOperatorNameMatcher,
3041       AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl),
3042       std::vector<std::string>>({std::string(Name)});
3043 }
3044 
3045 /// Matches overloaded operator names.
3046 ///
3047 /// Matches overloaded operator names specified in strings without the
3048 /// "operator" prefix: e.g. "<<".
3049 ///
3050 ///   hasAnyOverloadedOperatorName("+", "-")
3051 /// Is equivalent to
3052 ///   anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3053 extern const internal::VariadicFunction<
3054     internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3055                                  AST_POLYMORPHIC_SUPPORTED_TYPES(
3056                                      CXXOperatorCallExpr, FunctionDecl),
3057                                  std::vector<std::string>>,
3058     StringRef, internal::hasAnyOverloadedOperatorNameFunc>
3059     hasAnyOverloadedOperatorName;
3060 
3061 /// Matches template-dependent, but known, member names.
3062 ///
3063 /// In template declarations, dependent members are not resolved and so can
3064 /// not be matched to particular named declarations.
3065 ///
3066 /// This matcher allows to match on the known name of members.
3067 ///
3068 /// Given
3069 /// \code
3070 ///   template <typename T>
3071 ///   struct S {
3072 ///       void mem();
3073 ///   };
3074 ///   template <typename T>
3075 ///   void x() {
3076 ///       S<T> s;
3077 ///       s.mem();
3078 ///   }
3079 /// \endcode
3080 /// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
AST_MATCHER_P(CXXDependentScopeMemberExpr,hasMemberName,std::string,N)3081 AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3082   return Node.getMember().getAsString() == N;
3083 }
3084 
3085 /// Matches template-dependent, but known, member names against an already-bound
3086 /// node
3087 ///
3088 /// In template declarations, dependent members are not resolved and so can
3089 /// not be matched to particular named declarations.
3090 ///
3091 /// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3092 /// and CXXMethodDecl nodes.
3093 ///
3094 /// Given
3095 /// \code
3096 ///   template <typename T>
3097 ///   struct S {
3098 ///       void mem();
3099 ///   };
3100 ///   template <typename T>
3101 ///   void x() {
3102 ///       S<T> s;
3103 ///       s.mem();
3104 ///   }
3105 /// \endcode
3106 /// The matcher
3107 /// @code
3108 /// \c cxxDependentScopeMemberExpr(
3109 ///   hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3110 ///       hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3111 ///           cxxMethodDecl(hasName("mem")).bind("templMem")
3112 ///           )))))
3113 ///       )))),
3114 ///   memberHasSameNameAsBoundNode("templMem")
3115 ///   )
3116 /// @endcode
3117 /// first matches and binds the @c mem member of the @c S template, then
3118 /// compares its name to the usage in @c s.mem() in the @c x function template
AST_MATCHER_P(CXXDependentScopeMemberExpr,memberHasSameNameAsBoundNode,std::string,BindingID)3119 AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3120               std::string, BindingID) {
3121   auto MemberName = Node.getMember().getAsString();
3122 
3123   return Builder->removeBindings(
3124       [this, MemberName](const BoundNodesMap &Nodes) {
3125         const auto &BN = Nodes.getNode(this->BindingID);
3126         if (const auto *ND = BN.get<NamedDecl>()) {
3127           if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3128             return true;
3129           return ND->getName() != MemberName;
3130         }
3131         return true;
3132       });
3133 }
3134 
3135 /// Matches C++ classes that are directly or indirectly derived from a class
3136 /// matching \c Base, or Objective-C classes that directly or indirectly
3137 /// subclass a class matching \c Base.
3138 ///
3139 /// Note that a class is not considered to be derived from itself.
3140 ///
3141 /// Example matches Y, Z, C (Base == hasName("X"))
3142 /// \code
3143 ///   class X;
3144 ///   class Y : public X {};  // directly derived
3145 ///   class Z : public Y {};  // indirectly derived
3146 ///   typedef X A;
3147 ///   typedef A B;
3148 ///   class C : public B {};  // derived from a typedef of X
3149 /// \endcode
3150 ///
3151 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
3152 /// \code
3153 ///   class Foo;
3154 ///   typedef Foo X;
3155 ///   class Bar : public Foo {};  // derived from a type that X is a typedef of
3156 /// \endcode
3157 ///
3158 /// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3159 /// \code
3160 ///   @interface NSObject @end
3161 ///   @interface Bar : NSObject @end
3162 /// \endcode
3163 ///
3164 /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
AST_POLYMORPHIC_MATCHER_P(isDerivedFrom,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXRecordDecl,ObjCInterfaceDecl),internal::Matcher<NamedDecl>,Base)3165 AST_POLYMORPHIC_MATCHER_P(
3166     isDerivedFrom,
3167     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3168     internal::Matcher<NamedDecl>, Base) {
3169   // Check if the node is a C++ struct/union/class.
3170   if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3171     return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3172 
3173   // The node must be an Objective-C class.
3174   const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3175   return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3176                                         /*Directly=*/false);
3177 }
3178 
3179 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3180 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3181     isDerivedFrom,
3182     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3183     std::string, BaseName, 1) {
3184   if (BaseName.empty())
3185     return false;
3186 
3187   const auto M = isDerivedFrom(hasName(BaseName));
3188 
3189   if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3190     return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3191 
3192   const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3193   return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3194 }
3195 
3196 /// Matches C++ classes that have a direct or indirect base matching \p
3197 /// BaseSpecMatcher.
3198 ///
3199 /// Example:
3200 /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3201 /// \code
3202 ///   class Foo;
3203 ///   class Bar : Foo {};
3204 ///   class Baz : Bar {};
3205 ///   class SpecialBase;
3206 ///   class Proxy : SpecialBase {};  // matches Proxy
3207 ///   class IndirectlyDerived : Proxy {};  //matches IndirectlyDerived
3208 /// \endcode
3209 ///
3210 // FIXME: Refactor this and isDerivedFrom to reuse implementation.
AST_MATCHER_P(CXXRecordDecl,hasAnyBase,internal::Matcher<CXXBaseSpecifier>,BaseSpecMatcher)3211 AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3212               BaseSpecMatcher) {
3213   return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3214 }
3215 
3216 /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3217 ///
3218 /// Example:
3219 /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3220 /// \code
3221 ///   class Foo;
3222 ///   class Bar : Foo {};
3223 ///   class Baz : Bar {};
3224 ///   class SpecialBase;
3225 ///   class Proxy : SpecialBase {};  // matches Proxy
3226 ///   class IndirectlyDerived : Proxy {};  // doesn't match
3227 /// \endcode
AST_MATCHER_P(CXXRecordDecl,hasDirectBase,internal::Matcher<CXXBaseSpecifier>,BaseSpecMatcher)3228 AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3229               BaseSpecMatcher) {
3230   return Node.hasDefinition() &&
3231          llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3232            return BaseSpecMatcher.matches(Base, Finder, Builder);
3233          });
3234 }
3235 
3236 /// Similar to \c isDerivedFrom(), but also matches classes that directly
3237 /// match \c Base.
3238 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3239     isSameOrDerivedFrom,
3240     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3241     internal::Matcher<NamedDecl>, Base, 0) {
3242   const auto M = anyOf(Base, isDerivedFrom(Base));
3243 
3244   if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3245     return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3246 
3247   const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3248   return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3249 }
3250 
3251 /// Overloaded method as shortcut for
3252 /// \c isSameOrDerivedFrom(hasName(...)).
3253 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3254     isSameOrDerivedFrom,
3255     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3256     std::string, BaseName, 1) {
3257   if (BaseName.empty())
3258     return false;
3259 
3260   const auto M = isSameOrDerivedFrom(hasName(BaseName));
3261 
3262   if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3263     return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3264 
3265   const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3266   return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3267 }
3268 
3269 /// Matches C++ or Objective-C classes that are directly derived from a class
3270 /// matching \c Base.
3271 ///
3272 /// Note that a class is not considered to be derived from itself.
3273 ///
3274 /// Example matches Y, C (Base == hasName("X"))
3275 /// \code
3276 ///   class X;
3277 ///   class Y : public X {};  // directly derived
3278 ///   class Z : public Y {};  // indirectly derived
3279 ///   typedef X A;
3280 ///   typedef A B;
3281 ///   class C : public B {};  // derived from a typedef of X
3282 /// \endcode
3283 ///
3284 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
3285 /// \code
3286 ///   class Foo;
3287 ///   typedef Foo X;
3288 ///   class Bar : public Foo {};  // derived from a type that X is a typedef of
3289 /// \endcode
3290 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3291     isDirectlyDerivedFrom,
3292     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3293     internal::Matcher<NamedDecl>, Base, 0) {
3294   // Check if the node is a C++ struct/union/class.
3295   if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3296     return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3297 
3298   // The node must be an Objective-C class.
3299   const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3300   return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3301                                         /*Directly=*/true);
3302 }
3303 
3304 /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3305 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3306     isDirectlyDerivedFrom,
3307     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3308     std::string, BaseName, 1) {
3309   if (BaseName.empty())
3310     return false;
3311   const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3312 
3313   if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3314     return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3315 
3316   const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3317   return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3318 }
3319 /// Matches the first method of a class or struct that satisfies \c
3320 /// InnerMatcher.
3321 ///
3322 /// Given:
3323 /// \code
3324 ///   class A { void func(); };
3325 ///   class B { void member(); };
3326 /// \endcode
3327 ///
3328 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3329 /// \c A but not \c B.
AST_MATCHER_P(CXXRecordDecl,hasMethod,internal::Matcher<CXXMethodDecl>,InnerMatcher)3330 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3331               InnerMatcher) {
3332   BoundNodesTreeBuilder Result(*Builder);
3333   auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3334                                             Node.method_end(), Finder, &Result);
3335   if (MatchIt == Node.method_end())
3336     return false;
3337 
3338   if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3339     return false;
3340   *Builder = std::move(Result);
3341   return true;
3342 }
3343 
3344 /// Matches the generated class of lambda expressions.
3345 ///
3346 /// Given:
3347 /// \code
3348 ///   auto x = []{};
3349 /// \endcode
3350 ///
3351 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3352 /// \c decltype(x)
AST_MATCHER(CXXRecordDecl,isLambda)3353 AST_MATCHER(CXXRecordDecl, isLambda) {
3354   return Node.isLambda();
3355 }
3356 
3357 /// Matches AST nodes that have child AST nodes that match the
3358 /// provided matcher.
3359 ///
3360 /// Example matches X, Y
3361 ///   (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3362 /// \code
3363 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
3364 ///   class Y { class X {}; };
3365 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
3366 /// \endcode
3367 ///
3368 /// ChildT must be an AST base type.
3369 ///
3370 /// Usable as: Any Matcher
3371 /// Note that has is direct matcher, so it also matches things like implicit
3372 /// casts and paren casts. If you are matching with expr then you should
3373 /// probably consider using ignoringParenImpCasts like:
3374 /// has(ignoringParenImpCasts(expr())).
3375 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3376 
3377 /// Matches AST nodes that have descendant AST nodes that match the
3378 /// provided matcher.
3379 ///
3380 /// Example matches X, Y, Z
3381 ///     (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3382 /// \code
3383 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
3384 ///   class Y { class X {}; };
3385 ///   class Z { class Y { class X {}; }; };
3386 /// \endcode
3387 ///
3388 /// DescendantT must be an AST base type.
3389 ///
3390 /// Usable as: Any Matcher
3391 extern const internal::ArgumentAdaptingMatcherFunc<
3392     internal::HasDescendantMatcher>
3393     hasDescendant;
3394 
3395 /// Matches AST nodes that have child AST nodes that match the
3396 /// provided matcher.
3397 ///
3398 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3399 ///   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3400 /// \code
3401 ///   class X {};
3402 ///   class Y { class X {}; };  // Matches Y, because Y::X is a class of name X
3403 ///                             // inside Y.
3404 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
3405 /// \endcode
3406 ///
3407 /// ChildT must be an AST base type.
3408 ///
3409 /// As opposed to 'has', 'forEach' will cause a match for each result that
3410 /// matches instead of only on the first one.
3411 ///
3412 /// Usable as: Any Matcher
3413 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3414     forEach;
3415 
3416 /// Matches AST nodes that have descendant AST nodes that match the
3417 /// provided matcher.
3418 ///
3419 /// Example matches X, A, A::X, B, B::C, B::C::X
3420 ///   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3421 /// \code
3422 ///   class X {};
3423 ///   class A { class X {}; };  // Matches A, because A::X is a class of name
3424 ///                             // X inside A.
3425 ///   class B { class C { class X {}; }; };
3426 /// \endcode
3427 ///
3428 /// DescendantT must be an AST base type.
3429 ///
3430 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3431 /// each result that matches instead of only on the first one.
3432 ///
3433 /// Note: Recursively combined ForEachDescendant can cause many matches:
3434 ///   cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3435 ///     forEachDescendant(cxxRecordDecl())
3436 ///   )))
3437 /// will match 10 times (plus injected class name matches) on:
3438 /// \code
3439 ///   class A { class B { class C { class D { class E {}; }; }; }; };
3440 /// \endcode
3441 ///
3442 /// Usable as: Any Matcher
3443 extern const internal::ArgumentAdaptingMatcherFunc<
3444     internal::ForEachDescendantMatcher>
3445     forEachDescendant;
3446 
3447 /// Matches if the node or any descendant matches.
3448 ///
3449 /// Generates results for each match.
3450 ///
3451 /// For example, in:
3452 /// \code
3453 ///   class A { class B {}; class C {}; };
3454 /// \endcode
3455 /// The matcher:
3456 /// \code
3457 ///   cxxRecordDecl(hasName("::A"),
3458 ///                 findAll(cxxRecordDecl(isDefinition()).bind("m")))
3459 /// \endcode
3460 /// will generate results for \c A, \c B and \c C.
3461 ///
3462 /// Usable as: Any Matcher
3463 template <typename T>
findAll(const internal::Matcher<T> & Matcher)3464 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3465   return eachOf(Matcher, forEachDescendant(Matcher));
3466 }
3467 
3468 /// Matches AST nodes that have a parent that matches the provided
3469 /// matcher.
3470 ///
3471 /// Given
3472 /// \code
3473 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3474 /// \endcode
3475 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3476 ///
3477 /// Usable as: Any Matcher
3478 extern const internal::ArgumentAdaptingMatcherFunc<
3479     internal::HasParentMatcher,
3480     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
3481     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
3482     hasParent;
3483 
3484 /// Matches AST nodes that have an ancestor that matches the provided
3485 /// matcher.
3486 ///
3487 /// Given
3488 /// \code
3489 /// void f() { if (true) { int x = 42; } }
3490 /// void g() { for (;;) { int x = 43; } }
3491 /// \endcode
3492 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3493 ///
3494 /// Usable as: Any Matcher
3495 extern const internal::ArgumentAdaptingMatcherFunc<
3496     internal::HasAncestorMatcher,
3497     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
3498     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
3499     hasAncestor;
3500 
3501 /// Matches if the provided matcher does not match.
3502 ///
3503 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3504 /// \code
3505 ///   class X {};
3506 ///   class Y {};
3507 /// \endcode
3508 ///
3509 /// Usable as: Any Matcher
3510 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3511 
3512 /// Matches a node if the declaration associated with that node
3513 /// matches the given matcher.
3514 ///
3515 /// The associated declaration is:
3516 /// - for type nodes, the declaration of the underlying type
3517 /// - for CallExpr, the declaration of the callee
3518 /// - for MemberExpr, the declaration of the referenced member
3519 /// - for CXXConstructExpr, the declaration of the constructor
3520 /// - for CXXNewExpr, the declaration of the operator new
3521 /// - for ObjCIvarExpr, the declaration of the ivar
3522 ///
3523 /// For type nodes, hasDeclaration will generally match the declaration of the
3524 /// sugared type. Given
3525 /// \code
3526 ///   class X {};
3527 ///   typedef X Y;
3528 ///   Y y;
3529 /// \endcode
3530 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3531 /// typedefDecl. A common use case is to match the underlying, desugared type.
3532 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3533 /// \code
3534 ///   varDecl(hasType(hasUnqualifiedDesugaredType(
3535 ///       recordType(hasDeclaration(decl())))))
3536 /// \endcode
3537 /// In this matcher, the decl will match the CXXRecordDecl of class X.
3538 ///
3539 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3540 ///   Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3541 ///   Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3542 ///   Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3543 ///   Matcher<TagType>, Matcher<TemplateSpecializationType>,
3544 ///   Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3545 ///   Matcher<UnresolvedUsingType>
3546 inline internal::PolymorphicMatcher<
3547     internal::HasDeclarationMatcher,
3548     void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
hasDeclaration(const internal::Matcher<Decl> & InnerMatcher)3549 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3550   return internal::PolymorphicMatcher<
3551       internal::HasDeclarationMatcher,
3552       void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3553       InnerMatcher);
3554 }
3555 
3556 /// Matches a \c NamedDecl whose underlying declaration matches the given
3557 /// matcher.
3558 ///
3559 /// Given
3560 /// \code
3561 ///   namespace N { template<class T> void f(T t); }
3562 ///   template <class T> void g() { using N::f; f(T()); }
3563 /// \endcode
3564 /// \c unresolvedLookupExpr(hasAnyDeclaration(
3565 ///     namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3566 ///   matches the use of \c f in \c g() .
AST_MATCHER_P(NamedDecl,hasUnderlyingDecl,internal::Matcher<NamedDecl>,InnerMatcher)3567 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3568               InnerMatcher) {
3569   const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3570 
3571   return UnderlyingDecl != nullptr &&
3572          InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3573 }
3574 
3575 /// Matches on the implicit object argument of a member call expression, after
3576 /// stripping off any parentheses or implicit casts.
3577 ///
3578 /// Given
3579 /// \code
3580 ///   class Y { public: void m(); };
3581 ///   Y g();
3582 ///   class X : public Y {};
3583 ///   void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3584 /// \endcode
3585 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3586 ///   matches `y.m()` and `(g()).m()`.
3587 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3588 ///   matches `x.m()`.
3589 /// cxxMemberCallExpr(on(callExpr()))
3590 ///   matches `(g()).m()`.
3591 ///
3592 /// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr,on,internal::Matcher<Expr>,InnerMatcher)3593 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3594               InnerMatcher) {
3595   const Expr *ExprNode = Node.getImplicitObjectArgument()
3596                             ->IgnoreParenImpCasts();
3597   return (ExprNode != nullptr &&
3598           InnerMatcher.matches(*ExprNode, Finder, Builder));
3599 }
3600 
3601 
3602 /// Matches on the receiver of an ObjectiveC Message expression.
3603 ///
3604 /// Example
3605 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3606 /// matches the [webView ...] message invocation.
3607 /// \code
3608 ///   NSString *webViewJavaScript = ...
3609 ///   UIWebView *webView = ...
3610 ///   [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3611 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,hasReceiverType,internal::Matcher<QualType>,InnerMatcher)3612 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3613               InnerMatcher) {
3614   const QualType TypeDecl = Node.getReceiverType();
3615   return InnerMatcher.matches(TypeDecl, Finder, Builder);
3616 }
3617 
3618 /// Returns true when the Objective-C method declaration is a class method.
3619 ///
3620 /// Example
3621 /// matcher = objcMethodDecl(isClassMethod())
3622 /// matches
3623 /// \code
3624 /// @interface I + (void)foo; @end
3625 /// \endcode
3626 /// but not
3627 /// \code
3628 /// @interface I - (void)bar; @end
3629 /// \endcode
AST_MATCHER(ObjCMethodDecl,isClassMethod)3630 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
3631   return Node.isClassMethod();
3632 }
3633 
3634 /// Returns true when the Objective-C method declaration is an instance method.
3635 ///
3636 /// Example
3637 /// matcher = objcMethodDecl(isInstanceMethod())
3638 /// matches
3639 /// \code
3640 /// @interface I - (void)bar; @end
3641 /// \endcode
3642 /// but not
3643 /// \code
3644 /// @interface I + (void)foo; @end
3645 /// \endcode
AST_MATCHER(ObjCMethodDecl,isInstanceMethod)3646 AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
3647   return Node.isInstanceMethod();
3648 }
3649 
3650 /// Returns true when the Objective-C message is sent to a class.
3651 ///
3652 /// Example
3653 /// matcher = objcMessageExpr(isClassMessage())
3654 /// matches
3655 /// \code
3656 ///   [NSString stringWithFormat:@"format"];
3657 /// \endcode
3658 /// but not
3659 /// \code
3660 ///   NSString *x = @"hello";
3661 ///   [x containsString:@"h"];
3662 /// \endcode
AST_MATCHER(ObjCMessageExpr,isClassMessage)3663 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
3664   return Node.isClassMessage();
3665 }
3666 
3667 /// Returns true when the Objective-C message is sent to an instance.
3668 ///
3669 /// Example
3670 /// matcher = objcMessageExpr(isInstanceMessage())
3671 /// matches
3672 /// \code
3673 ///   NSString *x = @"hello";
3674 ///   [x containsString:@"h"];
3675 /// \endcode
3676 /// but not
3677 /// \code
3678 ///   [NSString stringWithFormat:@"format"];
3679 /// \endcode
AST_MATCHER(ObjCMessageExpr,isInstanceMessage)3680 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3681   return Node.isInstanceMessage();
3682 }
3683 
3684 /// Matches if the Objective-C message is sent to an instance,
3685 /// and the inner matcher matches on that instance.
3686 ///
3687 /// For example the method call in
3688 /// \code
3689 ///   NSString *x = @"hello";
3690 ///   [x containsString:@"h"];
3691 /// \endcode
3692 /// is matched by
3693 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
AST_MATCHER_P(ObjCMessageExpr,hasReceiver,internal::Matcher<Expr>,InnerMatcher)3694 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3695               InnerMatcher) {
3696   const Expr *ReceiverNode = Node.getInstanceReceiver();
3697   return (ReceiverNode != nullptr &&
3698           InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3699                                Builder));
3700 }
3701 
3702 /// Matches when BaseName == Selector.getAsString()
3703 ///
3704 ///  matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3705 ///  matches the outer message expr in the code below, but NOT the message
3706 ///  invocation for self.bodyView.
3707 /// \code
3708 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3709 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,hasSelector,std::string,BaseName)3710 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3711   Selector Sel = Node.getSelector();
3712   return BaseName.compare(Sel.getAsString()) == 0;
3713 }
3714 
3715 
3716 /// Matches when at least one of the supplied string equals to the
3717 /// Selector.getAsString()
3718 ///
3719 ///  matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3720 ///  matches both of the expressions below:
3721 /// \code
3722 ///     [myObj methodA:argA];
3723 ///     [myObj methodB:argB];
3724 /// \endcode
3725 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3726                                         StringRef,
3727                                         internal::hasAnySelectorFunc>
3728                                         hasAnySelector;
3729 
3730 /// Matches ObjC selectors whose name contains
3731 /// a substring matched by the given RegExp.
3732 ///  matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3733 ///  matches the outer message expr in the code below, but NOT the message
3734 ///  invocation for self.bodyView.
3735 /// \code
3736 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3737 /// \endcode
AST_MATCHER_REGEX(ObjCMessageExpr,matchesSelector,RegExp)3738 AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3739   std::string SelectorString = Node.getSelector().getAsString();
3740   return RegExp->match(SelectorString);
3741 }
3742 
3743 /// Matches when the selector is the empty selector
3744 ///
3745 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3746 /// represent an error condition in the tree!
AST_MATCHER(ObjCMessageExpr,hasNullSelector)3747 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3748   return Node.getSelector().isNull();
3749 }
3750 
3751 /// Matches when the selector is a Unary Selector
3752 ///
3753 ///  matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3754 ///  matches self.bodyView in the code below, but NOT the outer message
3755 ///  invocation of "loadHTMLString:baseURL:".
3756 /// \code
3757 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3758 /// \endcode
AST_MATCHER(ObjCMessageExpr,hasUnarySelector)3759 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3760   return Node.getSelector().isUnarySelector();
3761 }
3762 
3763 /// Matches when the selector is a keyword selector
3764 ///
3765 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3766 /// message expression in
3767 ///
3768 /// \code
3769 ///   UIWebView *webView = ...;
3770 ///   CGRect bodyFrame = webView.frame;
3771 ///   bodyFrame.size.height = self.bodyContentHeight;
3772 ///   webView.frame = bodyFrame;
3773 ///   //     ^---- matches here
3774 /// \endcode
AST_MATCHER(ObjCMessageExpr,hasKeywordSelector)3775 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3776   return Node.getSelector().isKeywordSelector();
3777 }
3778 
3779 /// Matches when the selector has the specified number of arguments
3780 ///
3781 ///  matcher = objCMessageExpr(numSelectorArgs(0));
3782 ///  matches self.bodyView in the code below
3783 ///
3784 ///  matcher = objCMessageExpr(numSelectorArgs(2));
3785 ///  matches the invocation of "loadHTMLString:baseURL:" but not that
3786 ///  of self.bodyView
3787 /// \code
3788 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3789 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,numSelectorArgs,unsigned,N)3790 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3791   return Node.getSelector().getNumArgs() == N;
3792 }
3793 
3794 /// Matches if the call expression's callee expression matches.
3795 ///
3796 /// Given
3797 /// \code
3798 ///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
3799 ///   void f() { f(); }
3800 /// \endcode
3801 /// callExpr(callee(expr()))
3802 ///   matches this->x(), x(), y.x(), f()
3803 /// with callee(...)
3804 ///   matching this->x, x, y.x, f respectively
3805 ///
3806 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3807 /// because this introduces ambiguous overloads with calls to Callee taking a
3808 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3809 /// implemented in terms of implicit casts.
AST_MATCHER_P(CallExpr,callee,internal::Matcher<Stmt>,InnerMatcher)3810 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3811               InnerMatcher) {
3812   const Expr *ExprNode = Node.getCallee();
3813   return (ExprNode != nullptr &&
3814           InnerMatcher.matches(*ExprNode, Finder, Builder));
3815 }
3816 
3817 /// Matches if the call expression's callee's declaration matches the
3818 /// given matcher.
3819 ///
3820 /// Example matches y.x() (matcher = callExpr(callee(
3821 ///                                    cxxMethodDecl(hasName("x")))))
3822 /// \code
3823 ///   class Y { public: void x(); };
3824 ///   void z() { Y y; y.x(); }
3825 /// \endcode
3826 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3827                        1) {
3828   return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3829 }
3830 
3831 /// Matches if the expression's or declaration's type matches a type
3832 /// matcher.
3833 ///
3834 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3835 ///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3836 ///             and U (matcher = typedefDecl(hasType(asString("int")))
3837 ///             and friend class X (matcher = friendDecl(hasType("X"))
3838 ///             and public virtual X (matcher = cxxBaseSpecifier(hasType(
3839 ///                                               asString("class X")))
3840 /// \code
3841 ///  class X {};
3842 ///  void y(X &x) { x; X z; }
3843 ///  typedef int U;
3844 ///  class Y { friend class X; };
3845 ///  class Z : public virtual X {};
3846 /// \endcode
3847 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3848     hasType,
3849     AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3850                                     ValueDecl, CXXBaseSpecifier),
3851     internal::Matcher<QualType>, InnerMatcher, 0) {
3852   QualType QT = internal::getUnderlyingType(Node);
3853   if (!QT.isNull())
3854     return InnerMatcher.matches(QT, Finder, Builder);
3855   return false;
3856 }
3857 
3858 /// Overloaded to match the declaration of the expression's or value
3859 /// declaration's type.
3860 ///
3861 /// In case of a value declaration (for example a variable declaration),
3862 /// this resolves one layer of indirection. For example, in the value
3863 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3864 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3865 /// declaration of x.
3866 ///
3867 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3868 ///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3869 ///             and friend class X (matcher = friendDecl(hasType("X"))
3870 ///             and public virtual X (matcher = cxxBaseSpecifier(hasType(
3871 ///                                               cxxRecordDecl(hasName("X"))))
3872 /// \code
3873 ///  class X {};
3874 ///  void y(X &x) { x; X z; }
3875 ///  class Y { friend class X; };
3876 ///  class Z : public virtual X {};
3877 /// \endcode
3878 ///
3879 /// Example matches class Derived
3880 /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
3881 /// \code
3882 /// class Base {};
3883 /// class Derived : Base {};
3884 /// \endcode
3885 ///
3886 /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
3887 /// Matcher<CXXBaseSpecifier>
3888 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3889     hasType,
3890     AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
3891                                     CXXBaseSpecifier),
3892     internal::Matcher<Decl>, InnerMatcher, 1) {
3893   QualType QT = internal::getUnderlyingType(Node);
3894   if (!QT.isNull())
3895     return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3896   return false;
3897 }
3898 
3899 /// Matches if the type location of a node matches the inner matcher.
3900 ///
3901 /// Examples:
3902 /// \code
3903 ///   int x;
3904 /// \endcode
3905 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3906 ///   matches int x
3907 ///
3908 /// \code
3909 /// auto x = int(3);
3910 /// \code
3911 /// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
3912 ///   matches int(3)
3913 ///
3914 /// \code
3915 /// struct Foo { Foo(int, int); };
3916 /// auto x = Foo(1, 2);
3917 /// \code
3918 /// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
3919 ///   matches Foo(1, 2)
3920 ///
3921 /// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
3922 ///   Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
3923 ///   Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
3924 ///   Matcher<CXXUnresolvedConstructExpr>,
3925 ///   Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>,
3926 ///   Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
3927 ///   Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
3928 ///   Matcher<TypedefNameDecl>
AST_POLYMORPHIC_MATCHER_P(hasTypeLoc,AST_POLYMORPHIC_SUPPORTED_TYPES (BlockDecl,CXXBaseSpecifier,CXXCtorInitializer,CXXFunctionalCastExpr,CXXNewExpr,CXXTemporaryObjectExpr,CXXUnresolvedConstructExpr,ClassTemplateSpecializationDecl,CompoundLiteralExpr,DeclaratorDecl,ExplicitCastExpr,ObjCPropertyDecl,TemplateArgumentLoc,TypedefNameDecl),internal::Matcher<TypeLoc>,Inner)3929 AST_POLYMORPHIC_MATCHER_P(
3930     hasTypeLoc,
3931     AST_POLYMORPHIC_SUPPORTED_TYPES(
3932         BlockDecl, CXXBaseSpecifier, CXXCtorInitializer, CXXFunctionalCastExpr,
3933         CXXNewExpr, CXXTemporaryObjectExpr, CXXUnresolvedConstructExpr,
3934         ClassTemplateSpecializationDecl, CompoundLiteralExpr, DeclaratorDecl,
3935         ExplicitCastExpr, ObjCPropertyDecl, TemplateArgumentLoc,
3936         TypedefNameDecl),
3937     internal::Matcher<TypeLoc>, Inner) {
3938   TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
3939   if (source == nullptr) {
3940     // This happens for example for implicit destructors.
3941     return false;
3942   }
3943   return Inner.matches(source->getTypeLoc(), Finder, Builder);
3944 }
3945 
3946 /// Matches if the matched type is represented by the given string.
3947 ///
3948 /// Given
3949 /// \code
3950 ///   class Y { public: void x(); };
3951 ///   void z() { Y* y; y->x(); }
3952 /// \endcode
3953 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3954 ///   matches y->x()
AST_MATCHER_P(QualType,asString,std::string,Name)3955 AST_MATCHER_P(QualType, asString, std::string, Name) {
3956   return Name == Node.getAsString();
3957 }
3958 
3959 /// Matches if the matched type is a pointer type and the pointee type
3960 /// matches the specified matcher.
3961 ///
3962 /// Example matches y->x()
3963 ///   (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3964 ///      cxxRecordDecl(hasName("Y")))))))
3965 /// \code
3966 ///   class Y { public: void x(); };
3967 ///   void z() { Y *y; y->x(); }
3968 /// \endcode
AST_MATCHER_P(QualType,pointsTo,internal::Matcher<QualType>,InnerMatcher)3969 AST_MATCHER_P(
3970     QualType, pointsTo, internal::Matcher<QualType>,
3971     InnerMatcher) {
3972   return (!Node.isNull() && Node->isAnyPointerType() &&
3973           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3974 }
3975 
3976 /// Overloaded to match the pointee type's declaration.
3977 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3978                        InnerMatcher, 1) {
3979   return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3980       .matches(Node, Finder, Builder);
3981 }
3982 
3983 /// Matches if the matched type matches the unqualified desugared
3984 /// type of the matched node.
3985 ///
3986 /// For example, in:
3987 /// \code
3988 ///   class A {};
3989 ///   using B = A;
3990 /// \endcode
3991 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3992 /// both B and A.
AST_MATCHER_P(Type,hasUnqualifiedDesugaredType,internal::Matcher<Type>,InnerMatcher)3993 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3994               InnerMatcher) {
3995   return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3996                               Builder);
3997 }
3998 
3999 /// Matches if the matched type is a reference type and the referenced
4000 /// type matches the specified matcher.
4001 ///
4002 /// Example matches X &x and const X &y
4003 ///     (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4004 /// \code
4005 ///   class X {
4006 ///     void a(X b) {
4007 ///       X &x = b;
4008 ///       const X &y = b;
4009 ///     }
4010 ///   };
4011 /// \endcode
AST_MATCHER_P(QualType,references,internal::Matcher<QualType>,InnerMatcher)4012 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4013               InnerMatcher) {
4014   return (!Node.isNull() && Node->isReferenceType() &&
4015           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4016 }
4017 
4018 /// Matches QualTypes whose canonical type matches InnerMatcher.
4019 ///
4020 /// Given:
4021 /// \code
4022 ///   typedef int &int_ref;
4023 ///   int a;
4024 ///   int_ref b = a;
4025 /// \endcode
4026 ///
4027 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4028 /// declaration of b but \c
4029 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
AST_MATCHER_P(QualType,hasCanonicalType,internal::Matcher<QualType>,InnerMatcher)4030 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4031               InnerMatcher) {
4032   if (Node.isNull())
4033     return false;
4034   return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4035 }
4036 
4037 /// Overloaded to match the referenced type's declaration.
4038 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4039                        InnerMatcher, 1) {
4040   return references(qualType(hasDeclaration(InnerMatcher)))
4041       .matches(Node, Finder, Builder);
4042 }
4043 
4044 /// Matches on the implicit object argument of a member call expression. Unlike
4045 /// `on`, matches the argument directly without stripping away anything.
4046 ///
4047 /// Given
4048 /// \code
4049 ///   class Y { public: void m(); };
4050 ///   Y g();
4051 ///   class X : public Y { void g(); };
4052 ///   void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4053 /// \endcode
4054 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4055 ///     cxxRecordDecl(hasName("Y")))))
4056 ///   matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
4057 /// cxxMemberCallExpr(on(callExpr()))
4058 ///   does not match `(g()).m()`, because the parens are not ignored.
4059 ///
4060 /// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr,onImplicitObjectArgument,internal::Matcher<Expr>,InnerMatcher)4061 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4062               internal::Matcher<Expr>, InnerMatcher) {
4063   const Expr *ExprNode = Node.getImplicitObjectArgument();
4064   return (ExprNode != nullptr &&
4065           InnerMatcher.matches(*ExprNode, Finder, Builder));
4066 }
4067 
4068 /// Matches if the type of the expression's implicit object argument either
4069 /// matches the InnerMatcher, or is a pointer to a type that matches the
4070 /// InnerMatcher.
4071 ///
4072 /// Given
4073 /// \code
4074 ///   class Y { public: void m(); };
4075 ///   class X : public Y { void g(); };
4076 ///   void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4077 /// \endcode
4078 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4079 ///     cxxRecordDecl(hasName("Y")))))
4080 ///   matches `y.m()`, `p->m()` and `x.m()`.
4081 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4082 ///     cxxRecordDecl(hasName("X")))))
4083 ///   matches `x.g()`.
4084 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
4085                        internal::Matcher<QualType>, InnerMatcher, 0) {
4086   return onImplicitObjectArgument(
4087       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4088       .matches(Node, Finder, Builder);
4089 }
4090 
4091 /// Overloaded to match the type's declaration.
4092 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
4093                        internal::Matcher<Decl>, InnerMatcher, 1) {
4094   return onImplicitObjectArgument(
4095       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4096       .matches(Node, Finder, Builder);
4097 }
4098 
4099 /// Matches a DeclRefExpr that refers to a declaration that matches the
4100 /// specified matcher.
4101 ///
4102 /// Example matches x in if(x)
4103 ///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
4104 /// \code
4105 ///   bool x;
4106 ///   if (x) {}
4107 /// \endcode
AST_MATCHER_P(DeclRefExpr,to,internal::Matcher<Decl>,InnerMatcher)4108 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4109               InnerMatcher) {
4110   const Decl *DeclNode = Node.getDecl();
4111   return (DeclNode != nullptr &&
4112           InnerMatcher.matches(*DeclNode, Finder, Builder));
4113 }
4114 
4115 /// Matches a \c DeclRefExpr that refers to a declaration through a
4116 /// specific using shadow declaration.
4117 ///
4118 /// Given
4119 /// \code
4120 ///   namespace a { void f() {} }
4121 ///   using a::f;
4122 ///   void g() {
4123 ///     f();     // Matches this ..
4124 ///     a::f();  // .. but not this.
4125 ///   }
4126 /// \endcode
4127 /// declRefExpr(throughUsingDecl(anything()))
4128 ///   matches \c f()
AST_MATCHER_P(DeclRefExpr,throughUsingDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)4129 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
4130               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4131   const NamedDecl *FoundDecl = Node.getFoundDecl();
4132   if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4133     return InnerMatcher.matches(*UsingDecl, Finder, Builder);
4134   return false;
4135 }
4136 
4137 /// Matches an \c OverloadExpr if any of the declarations in the set of
4138 /// overloads matches the given matcher.
4139 ///
4140 /// Given
4141 /// \code
4142 ///   template <typename T> void foo(T);
4143 ///   template <typename T> void bar(T);
4144 ///   template <typename T> void baz(T t) {
4145 ///     foo(t);
4146 ///     bar(t);
4147 ///   }
4148 /// \endcode
4149 /// unresolvedLookupExpr(hasAnyDeclaration(
4150 ///     functionTemplateDecl(hasName("foo"))))
4151 ///   matches \c foo in \c foo(t); but not \c bar in \c bar(t);
AST_MATCHER_P(OverloadExpr,hasAnyDeclaration,internal::Matcher<Decl>,InnerMatcher)4152 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4153               InnerMatcher) {
4154   return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4155                                     Node.decls_end(), Finder,
4156                                     Builder) != Node.decls_end();
4157 }
4158 
4159 /// Matches the Decl of a DeclStmt which has a single declaration.
4160 ///
4161 /// Given
4162 /// \code
4163 ///   int a, b;
4164 ///   int c;
4165 /// \endcode
4166 /// declStmt(hasSingleDecl(anything()))
4167 ///   matches 'int c;' but not 'int a, b;'.
AST_MATCHER_P(DeclStmt,hasSingleDecl,internal::Matcher<Decl>,InnerMatcher)4168 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4169   if (Node.isSingleDecl()) {
4170     const Decl *FoundDecl = Node.getSingleDecl();
4171     return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4172   }
4173   return false;
4174 }
4175 
4176 /// Matches a variable declaration that has an initializer expression
4177 /// that matches the given matcher.
4178 ///
4179 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4180 /// \code
4181 ///   bool y() { return true; }
4182 ///   bool x = y();
4183 /// \endcode
AST_MATCHER_P(VarDecl,hasInitializer,internal::Matcher<Expr>,InnerMatcher)4184 AST_MATCHER_P(
4185     VarDecl, hasInitializer, internal::Matcher<Expr>,
4186     InnerMatcher) {
4187   const Expr *Initializer = Node.getAnyInitializer();
4188   return (Initializer != nullptr &&
4189           InnerMatcher.matches(*Initializer, Finder, Builder));
4190 }
4191 
4192 /// \brief Matches a static variable with local scope.
4193 ///
4194 /// Example matches y (matcher = varDecl(isStaticLocal()))
4195 /// \code
4196 /// void f() {
4197 ///   int x;
4198 ///   static int y;
4199 /// }
4200 /// static int z;
4201 /// \endcode
AST_MATCHER(VarDecl,isStaticLocal)4202 AST_MATCHER(VarDecl, isStaticLocal) {
4203   return Node.isStaticLocal();
4204 }
4205 
4206 /// Matches a variable declaration that has function scope and is a
4207 /// non-static local variable.
4208 ///
4209 /// Example matches x (matcher = varDecl(hasLocalStorage())
4210 /// \code
4211 /// void f() {
4212 ///   int x;
4213 ///   static int y;
4214 /// }
4215 /// int z;
4216 /// \endcode
AST_MATCHER(VarDecl,hasLocalStorage)4217 AST_MATCHER(VarDecl, hasLocalStorage) {
4218   return Node.hasLocalStorage();
4219 }
4220 
4221 /// Matches a variable declaration that does not have local storage.
4222 ///
4223 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4224 /// \code
4225 /// void f() {
4226 ///   int x;
4227 ///   static int y;
4228 /// }
4229 /// int z;
4230 /// \endcode
AST_MATCHER(VarDecl,hasGlobalStorage)4231 AST_MATCHER(VarDecl, hasGlobalStorage) {
4232   return Node.hasGlobalStorage();
4233 }
4234 
4235 /// Matches a variable declaration that has automatic storage duration.
4236 ///
4237 /// Example matches x, but not y, z, or a.
4238 /// (matcher = varDecl(hasAutomaticStorageDuration())
4239 /// \code
4240 /// void f() {
4241 ///   int x;
4242 ///   static int y;
4243 ///   thread_local int z;
4244 /// }
4245 /// int a;
4246 /// \endcode
AST_MATCHER(VarDecl,hasAutomaticStorageDuration)4247 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4248   return Node.getStorageDuration() == SD_Automatic;
4249 }
4250 
4251 /// Matches a variable declaration that has static storage duration.
4252 /// It includes the variable declared at namespace scope and those declared
4253 /// with "static" and "extern" storage class specifiers.
4254 ///
4255 /// \code
4256 /// void f() {
4257 ///   int x;
4258 ///   static int y;
4259 ///   thread_local int z;
4260 /// }
4261 /// int a;
4262 /// static int b;
4263 /// extern int c;
4264 /// varDecl(hasStaticStorageDuration())
4265 ///   matches the function declaration y, a, b and c.
4266 /// \endcode
AST_MATCHER(VarDecl,hasStaticStorageDuration)4267 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4268   return Node.getStorageDuration() == SD_Static;
4269 }
4270 
4271 /// Matches a variable declaration that has thread storage duration.
4272 ///
4273 /// Example matches z, but not x, z, or a.
4274 /// (matcher = varDecl(hasThreadStorageDuration())
4275 /// \code
4276 /// void f() {
4277 ///   int x;
4278 ///   static int y;
4279 ///   thread_local int z;
4280 /// }
4281 /// int a;
4282 /// \endcode
AST_MATCHER(VarDecl,hasThreadStorageDuration)4283 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4284   return Node.getStorageDuration() == SD_Thread;
4285 }
4286 
4287 /// Matches a variable declaration that is an exception variable from
4288 /// a C++ catch block, or an Objective-C \@catch statement.
4289 ///
4290 /// Example matches x (matcher = varDecl(isExceptionVariable())
4291 /// \code
4292 /// void f(int y) {
4293 ///   try {
4294 ///   } catch (int x) {
4295 ///   }
4296 /// }
4297 /// \endcode
AST_MATCHER(VarDecl,isExceptionVariable)4298 AST_MATCHER(VarDecl, isExceptionVariable) {
4299   return Node.isExceptionVariable();
4300 }
4301 
4302 /// Checks that a call expression or a constructor call expression has
4303 /// a specific number of arguments (including absent default arguments).
4304 ///
4305 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4306 /// \code
4307 ///   void f(int x, int y);
4308 ///   f(0, 0);
4309 /// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,CXXUnresolvedConstructExpr,ObjCMessageExpr),unsigned,N)4310 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
4311                           AST_POLYMORPHIC_SUPPORTED_TYPES(
4312                               CallExpr, CXXConstructExpr,
4313                               CXXUnresolvedConstructExpr, ObjCMessageExpr),
4314                           unsigned, N) {
4315   unsigned NumArgs = Node.getNumArgs();
4316   if (!Finder->isTraversalIgnoringImplicitNodes())
4317     return NumArgs == N;
4318   while (NumArgs) {
4319     if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4320       break;
4321     --NumArgs;
4322   }
4323   return NumArgs == N;
4324 }
4325 
4326 /// Matches the n'th argument of a call expression or a constructor
4327 /// call expression.
4328 ///
4329 /// Example matches y in x(y)
4330 ///     (matcher = callExpr(hasArgument(0, declRefExpr())))
4331 /// \code
4332 ///   void x(int) { int y; x(y); }
4333 /// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,CXXUnresolvedConstructExpr,ObjCMessageExpr),unsigned,N,internal::Matcher<Expr>,InnerMatcher)4334 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
4335                            AST_POLYMORPHIC_SUPPORTED_TYPES(
4336                                CallExpr, CXXConstructExpr,
4337                                CXXUnresolvedConstructExpr, ObjCMessageExpr),
4338                            unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4339   if (N >= Node.getNumArgs())
4340     return false;
4341   const Expr *Arg = Node.getArg(N);
4342   if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4343     return false;
4344   return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4345 }
4346 
4347 /// Matches the n'th item of an initializer list expression.
4348 ///
4349 /// Example matches y.
4350 ///     (matcher = initListExpr(hasInit(0, expr())))
4351 /// \code
4352 ///   int x{y}.
4353 /// \endcode
AST_MATCHER_P2(InitListExpr,hasInit,unsigned,N,ast_matchers::internal::Matcher<Expr>,InnerMatcher)4354 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
4355                ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
4356   return N < Node.getNumInits() &&
4357           InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4358 }
4359 
4360 /// Matches declaration statements that contain a specific number of
4361 /// declarations.
4362 ///
4363 /// Example: Given
4364 /// \code
4365 ///   int a, b;
4366 ///   int c;
4367 ///   int d = 2, e;
4368 /// \endcode
4369 /// declCountIs(2)
4370 ///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
AST_MATCHER_P(DeclStmt,declCountIs,unsigned,N)4371 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4372   return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4373 }
4374 
4375 /// Matches the n'th declaration of a declaration statement.
4376 ///
4377 /// Note that this does not work for global declarations because the AST
4378 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4379 /// DeclStmt's.
4380 /// Example: Given non-global declarations
4381 /// \code
4382 ///   int a, b = 0;
4383 ///   int c;
4384 ///   int d = 2, e;
4385 /// \endcode
4386 /// declStmt(containsDeclaration(
4387 ///       0, varDecl(hasInitializer(anything()))))
4388 ///   matches only 'int d = 2, e;', and
4389 /// declStmt(containsDeclaration(1, varDecl()))
4390 /// \code
4391 ///   matches 'int a, b = 0' as well as 'int d = 2, e;'
4392 ///   but 'int c;' is not matched.
4393 /// \endcode
AST_MATCHER_P2(DeclStmt,containsDeclaration,unsigned,N,internal::Matcher<Decl>,InnerMatcher)4394 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4395                internal::Matcher<Decl>, InnerMatcher) {
4396   const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4397   if (N >= NumDecls)
4398     return false;
4399   DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4400   std::advance(Iterator, N);
4401   return InnerMatcher.matches(**Iterator, Finder, Builder);
4402 }
4403 
4404 /// Matches a C++ catch statement that has a catch-all handler.
4405 ///
4406 /// Given
4407 /// \code
4408 ///   try {
4409 ///     // ...
4410 ///   } catch (int) {
4411 ///     // ...
4412 ///   } catch (...) {
4413 ///     // ...
4414 ///   }
4415 /// \endcode
4416 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
AST_MATCHER(CXXCatchStmt,isCatchAll)4417 AST_MATCHER(CXXCatchStmt, isCatchAll) {
4418   return Node.getExceptionDecl() == nullptr;
4419 }
4420 
4421 /// Matches a constructor initializer.
4422 ///
4423 /// Given
4424 /// \code
4425 ///   struct Foo {
4426 ///     Foo() : foo_(1) { }
4427 ///     int foo_;
4428 ///   };
4429 /// \endcode
4430 /// cxxRecordDecl(has(cxxConstructorDecl(
4431 ///   hasAnyConstructorInitializer(anything())
4432 /// )))
4433 ///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl,hasAnyConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)4434 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4435               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4436   auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4437                                             Node.init_end(), Finder, Builder);
4438   if (MatchIt == Node.init_end())
4439     return false;
4440   return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4441 }
4442 
4443 /// Matches the field declaration of a constructor initializer.
4444 ///
4445 /// Given
4446 /// \code
4447 ///   struct Foo {
4448 ///     Foo() : foo_(1) { }
4449 ///     int foo_;
4450 ///   };
4451 /// \endcode
4452 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4453 ///     forField(hasName("foo_"))))))
4454 ///   matches Foo
4455 /// with forField matching foo_
AST_MATCHER_P(CXXCtorInitializer,forField,internal::Matcher<FieldDecl>,InnerMatcher)4456 AST_MATCHER_P(CXXCtorInitializer, forField,
4457               internal::Matcher<FieldDecl>, InnerMatcher) {
4458   const FieldDecl *NodeAsDecl = Node.getAnyMember();
4459   return (NodeAsDecl != nullptr &&
4460       InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4461 }
4462 
4463 /// Matches the initializer expression of a constructor initializer.
4464 ///
4465 /// Given
4466 /// \code
4467 ///   struct Foo {
4468 ///     Foo() : foo_(1) { }
4469 ///     int foo_;
4470 ///   };
4471 /// \endcode
4472 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4473 ///     withInitializer(integerLiteral(equals(1)))))))
4474 ///   matches Foo
4475 /// with withInitializer matching (1)
AST_MATCHER_P(CXXCtorInitializer,withInitializer,internal::Matcher<Expr>,InnerMatcher)4476 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
4477               internal::Matcher<Expr>, InnerMatcher) {
4478   const Expr* NodeAsExpr = Node.getInit();
4479   return (NodeAsExpr != nullptr &&
4480       InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4481 }
4482 
4483 /// Matches a constructor initializer if it is explicitly written in
4484 /// code (as opposed to implicitly added by the compiler).
4485 ///
4486 /// Given
4487 /// \code
4488 ///   struct Foo {
4489 ///     Foo() { }
4490 ///     Foo(int) : foo_("A") { }
4491 ///     string foo_;
4492 ///   };
4493 /// \endcode
4494 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4495 ///   will match Foo(int), but not Foo()
AST_MATCHER(CXXCtorInitializer,isWritten)4496 AST_MATCHER(CXXCtorInitializer, isWritten) {
4497   return Node.isWritten();
4498 }
4499 
4500 /// Matches a constructor initializer if it is initializing a base, as
4501 /// opposed to a member.
4502 ///
4503 /// Given
4504 /// \code
4505 ///   struct B {};
4506 ///   struct D : B {
4507 ///     int I;
4508 ///     D(int i) : I(i) {}
4509 ///   };
4510 ///   struct E : B {
4511 ///     E() : B() {}
4512 ///   };
4513 /// \endcode
4514 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4515 ///   will match E(), but not match D(int).
AST_MATCHER(CXXCtorInitializer,isBaseInitializer)4516 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4517   return Node.isBaseInitializer();
4518 }
4519 
4520 /// Matches a constructor initializer if it is initializing a member, as
4521 /// opposed to a base.
4522 ///
4523 /// Given
4524 /// \code
4525 ///   struct B {};
4526 ///   struct D : B {
4527 ///     int I;
4528 ///     D(int i) : I(i) {}
4529 ///   };
4530 ///   struct E : B {
4531 ///     E() : B() {}
4532 ///   };
4533 /// \endcode
4534 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4535 ///   will match D(int), but not match E().
AST_MATCHER(CXXCtorInitializer,isMemberInitializer)4536 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4537   return Node.isMemberInitializer();
4538 }
4539 
4540 /// Matches any argument of a call expression or a constructor call
4541 /// expression, or an ObjC-message-send expression.
4542 ///
4543 /// Given
4544 /// \code
4545 ///   void x(int, int, int) { int y; x(1, y, 42); }
4546 /// \endcode
4547 /// callExpr(hasAnyArgument(declRefExpr()))
4548 ///   matches x(1, y, 42)
4549 /// with hasAnyArgument(...)
4550 ///   matching y
4551 ///
4552 /// For ObjectiveC, given
4553 /// \code
4554 ///   @interface I - (void) f:(int) y; @end
4555 ///   void foo(I *i) { [i f:12]; }
4556 /// \endcode
4557 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4558 ///   matches [i f:12]
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,CXXUnresolvedConstructExpr,ObjCMessageExpr),internal::Matcher<Expr>,InnerMatcher)4559 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
4560                           AST_POLYMORPHIC_SUPPORTED_TYPES(
4561                               CallExpr, CXXConstructExpr,
4562                               CXXUnresolvedConstructExpr, ObjCMessageExpr),
4563                           internal::Matcher<Expr>, InnerMatcher) {
4564   for (const Expr *Arg : Node.arguments()) {
4565     if (Finder->isTraversalIgnoringImplicitNodes() &&
4566         isa<CXXDefaultArgExpr>(Arg))
4567       break;
4568     BoundNodesTreeBuilder Result(*Builder);
4569     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4570       *Builder = std::move(Result);
4571       return true;
4572     }
4573   }
4574   return false;
4575 }
4576 
4577 /// Matches any capture of a lambda expression.
4578 ///
4579 /// Given
4580 /// \code
4581 ///   void foo() {
4582 ///     int x;
4583 ///     auto f = [x](){};
4584 ///   }
4585 /// \endcode
4586 /// lambdaExpr(hasAnyCapture(anything()))
4587 ///   matches [x](){};
4588 AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>,
4589                        InnerMatcher, 0) {
4590   for (const LambdaCapture &Capture : Node.captures()) {
4591     if (Capture.capturesVariable()) {
4592       BoundNodesTreeBuilder Result(*Builder);
4593       if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) {
4594         *Builder = std::move(Result);
4595         return true;
4596       }
4597     }
4598   }
4599   return false;
4600 }
4601 
4602 /// Matches any capture of 'this' in a lambda expression.
4603 ///
4604 /// Given
4605 /// \code
4606 ///   struct foo {
4607 ///     void bar() {
4608 ///       auto f = [this](){};
4609 ///     }
4610 ///   }
4611 /// \endcode
4612 /// lambdaExpr(hasAnyCapture(cxxThisExpr()))
4613 ///   matches [this](){};
4614 AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture,
4615                        internal::Matcher<CXXThisExpr>, InnerMatcher, 1) {
4616   return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) {
4617     return LC.capturesThis();
4618   });
4619 }
4620 
4621 /// Matches a constructor call expression which uses list initialization.
AST_MATCHER(CXXConstructExpr,isListInitialization)4622 AST_MATCHER(CXXConstructExpr, isListInitialization) {
4623   return Node.isListInitialization();
4624 }
4625 
4626 /// Matches a constructor call expression which requires
4627 /// zero initialization.
4628 ///
4629 /// Given
4630 /// \code
4631 /// void foo() {
4632 ///   struct point { double x; double y; };
4633 ///   point pt[2] = { { 1.0, 2.0 } };
4634 /// }
4635 /// \endcode
4636 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
4637 /// will match the implicit array filler for pt[1].
AST_MATCHER(CXXConstructExpr,requiresZeroInitialization)4638 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
4639   return Node.requiresZeroInitialization();
4640 }
4641 
4642 /// Matches the n'th parameter of a function or an ObjC method
4643 /// declaration or a block.
4644 ///
4645 /// Given
4646 /// \code
4647 ///   class X { void f(int x) {} };
4648 /// \endcode
4649 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
4650 ///   matches f(int x) {}
4651 /// with hasParameter(...)
4652 ///   matching int x
4653 ///
4654 /// For ObjectiveC, given
4655 /// \code
4656 ///   @interface I - (void) f:(int) y; @end
4657 /// \endcode
4658 //
4659 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
4660 /// matches the declaration of method f with hasParameter
4661 /// matching y.
AST_POLYMORPHIC_MATCHER_P2(hasParameter,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,ObjCMethodDecl,BlockDecl),unsigned,N,internal::Matcher<ParmVarDecl>,InnerMatcher)4662 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
4663                            AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4664                                                            ObjCMethodDecl,
4665                                                            BlockDecl),
4666                            unsigned, N, internal::Matcher<ParmVarDecl>,
4667                            InnerMatcher) {
4668   return (N < Node.parameters().size()
4669           && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4670 }
4671 
4672 /// Matches all arguments and their respective ParmVarDecl.
4673 ///
4674 /// Given
4675 /// \code
4676 ///   void f(int i);
4677 ///   int y;
4678 ///   f(y);
4679 /// \endcode
4680 /// callExpr(
4681 ///   forEachArgumentWithParam(
4682 ///     declRefExpr(to(varDecl(hasName("y")))),
4683 ///     parmVarDecl(hasType(isInteger()))
4684 /// ))
4685 ///   matches f(y);
4686 /// with declRefExpr(...)
4687 ///   matching int y
4688 /// and parmVarDecl(...)
4689 ///   matching int i
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr),internal::Matcher<Expr>,ArgMatcher,internal::Matcher<ParmVarDecl>,ParamMatcher)4690 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4691                            AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
4692                                                            CXXConstructExpr),
4693                            internal::Matcher<Expr>, ArgMatcher,
4694                            internal::Matcher<ParmVarDecl>, ParamMatcher) {
4695   BoundNodesTreeBuilder Result;
4696   // The first argument of an overloaded member operator is the implicit object
4697   // argument of the method which should not be matched against a parameter, so
4698   // we skip over it here.
4699   BoundNodesTreeBuilder Matches;
4700   unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4701                               .matches(Node, Finder, &Matches)
4702                           ? 1
4703                           : 0;
4704   int ParamIndex = 0;
4705   bool Matched = false;
4706   for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
4707     BoundNodesTreeBuilder ArgMatches(*Builder);
4708     if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4709                            Finder, &ArgMatches)) {
4710       BoundNodesTreeBuilder ParamMatches(ArgMatches);
4711       if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4712                          hasParameter(ParamIndex, ParamMatcher)))),
4713                      callExpr(callee(functionDecl(
4714                          hasParameter(ParamIndex, ParamMatcher))))))
4715               .matches(Node, Finder, &ParamMatches)) {
4716         Result.addMatch(ParamMatches);
4717         Matched = true;
4718       }
4719     }
4720     ++ParamIndex;
4721   }
4722   *Builder = std::move(Result);
4723   return Matched;
4724 }
4725 
4726 /// Matches all arguments and their respective types for a \c CallExpr or
4727 /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
4728 /// it works on calls through function pointers as well.
4729 ///
4730 /// The difference is, that function pointers do not provide access to a
4731 /// \c ParmVarDecl, but only the \c QualType for each argument.
4732 ///
4733 /// Given
4734 /// \code
4735 ///   void f(int i);
4736 ///   int y;
4737 ///   f(y);
4738 ///   void (*f_ptr)(int) = f;
4739 ///   f_ptr(y);
4740 /// \endcode
4741 /// callExpr(
4742 ///   forEachArgumentWithParamType(
4743 ///     declRefExpr(to(varDecl(hasName("y")))),
4744 ///     qualType(isInteger()).bind("type)
4745 /// ))
4746 ///   matches f(y) and f_ptr(y)
4747 /// with declRefExpr(...)
4748 ///   matching int y
4749 /// and qualType(...)
4750 ///   matching int
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr),internal::Matcher<Expr>,ArgMatcher,internal::Matcher<QualType>,ParamMatcher)4751 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
4752                            AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
4753                                                            CXXConstructExpr),
4754                            internal::Matcher<Expr>, ArgMatcher,
4755                            internal::Matcher<QualType>, ParamMatcher) {
4756   BoundNodesTreeBuilder Result;
4757   // The first argument of an overloaded member operator is the implicit object
4758   // argument of the method which should not be matched against a parameter, so
4759   // we skip over it here.
4760   BoundNodesTreeBuilder Matches;
4761   unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4762                               .matches(Node, Finder, &Matches)
4763                           ? 1
4764                           : 0;
4765 
4766   const FunctionProtoType *FProto = nullptr;
4767 
4768   if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4769     if (const auto *Value =
4770             dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4771       QualType QT = Value->getType().getCanonicalType();
4772 
4773       // This does not necessarily lead to a `FunctionProtoType`,
4774       // e.g. K&R functions do not have a function prototype.
4775       if (QT->isFunctionPointerType())
4776         FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4777 
4778       if (QT->isMemberFunctionPointerType()) {
4779         const auto *MP = QT->getAs<MemberPointerType>();
4780         assert(MP && "Must be member-pointer if its a memberfunctionpointer");
4781         FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
4782         assert(FProto &&
4783                "The call must have happened through a member function "
4784                "pointer");
4785       }
4786     }
4787   }
4788 
4789   int ParamIndex = 0;
4790   bool Matched = false;
4791   unsigned NumArgs = Node.getNumArgs();
4792   if (FProto && FProto->isVariadic())
4793     NumArgs = std::min(NumArgs, FProto->getNumParams());
4794 
4795   for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
4796     BoundNodesTreeBuilder ArgMatches(*Builder);
4797     if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
4798                            &ArgMatches)) {
4799       BoundNodesTreeBuilder ParamMatches(ArgMatches);
4800 
4801       // This test is cheaper compared to the big matcher in the next if.
4802       // Therefore, please keep this order.
4803       if (FProto) {
4804         QualType ParamType = FProto->getParamType(ParamIndex);
4805         if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
4806           Result.addMatch(ParamMatches);
4807           Matched = true;
4808           continue;
4809         }
4810       }
4811       if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4812                          hasParameter(ParamIndex, hasType(ParamMatcher))))),
4813                      callExpr(callee(functionDecl(
4814                          hasParameter(ParamIndex, hasType(ParamMatcher)))))))
4815               .matches(Node, Finder, &ParamMatches)) {
4816         Result.addMatch(ParamMatches);
4817         Matched = true;
4818         continue;
4819       }
4820     }
4821   }
4822   *Builder = std::move(Result);
4823   return Matched;
4824 }
4825 
4826 /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
4827 /// list. The parameter list could be that of either a block, function, or
4828 /// objc-method.
4829 ///
4830 ///
4831 /// Given
4832 ///
4833 /// \code
4834 /// void f(int a, int b, int c) {
4835 /// }
4836 /// \endcode
4837 ///
4838 /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
4839 ///
4840 /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
AST_MATCHER_P(ParmVarDecl,isAtPosition,unsigned,N)4841 AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
4842   const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
4843 
4844   if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
4845     return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4846   if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
4847     return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4848   if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
4849     return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4850 
4851   return false;
4852 }
4853 
4854 /// Matches any parameter of a function or an ObjC method declaration or a
4855 /// block.
4856 ///
4857 /// Does not match the 'this' parameter of a method.
4858 ///
4859 /// Given
4860 /// \code
4861 ///   class X { void f(int x, int y, int z) {} };
4862 /// \endcode
4863 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
4864 ///   matches f(int x, int y, int z) {}
4865 /// with hasAnyParameter(...)
4866 ///   matching int y
4867 ///
4868 /// For ObjectiveC, given
4869 /// \code
4870 ///   @interface I - (void) f:(int) y; @end
4871 /// \endcode
4872 //
4873 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
4874 /// matches the declaration of method f with hasParameter
4875 /// matching y.
4876 ///
4877 /// For blocks, given
4878 /// \code
4879 ///   b = ^(int y) { printf("%d", y) };
4880 /// \endcode
4881 ///
4882 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
4883 /// matches the declaration of the block b with hasParameter
4884 /// matching y.
AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,ObjCMethodDecl,BlockDecl),internal::Matcher<ParmVarDecl>,InnerMatcher)4885 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
4886                           AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4887                                                           ObjCMethodDecl,
4888                                                           BlockDecl),
4889                           internal::Matcher<ParmVarDecl>,
4890                           InnerMatcher) {
4891   return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
4892                                     Node.param_end(), Finder,
4893                                     Builder) != Node.param_end();
4894 }
4895 
4896 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
4897 /// specific parameter count.
4898 ///
4899 /// Given
4900 /// \code
4901 ///   void f(int i) {}
4902 ///   void g(int i, int j) {}
4903 ///   void h(int i, int j);
4904 ///   void j(int i);
4905 ///   void k(int x, int y, int z, ...);
4906 /// \endcode
4907 /// functionDecl(parameterCountIs(2))
4908 ///   matches \c g and \c h
4909 /// functionProtoType(parameterCountIs(2))
4910 ///   matches \c g and \c h
4911 /// functionProtoType(parameterCountIs(3))
4912 ///   matches \c k
AST_POLYMORPHIC_MATCHER_P(parameterCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,FunctionProtoType),unsigned,N)4913 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
4914                           AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4915                                                           FunctionProtoType),
4916                           unsigned, N) {
4917   return Node.getNumParams() == N;
4918 }
4919 
4920 /// Matches \c FunctionDecls that have a noreturn attribute.
4921 ///
4922 /// Given
4923 /// \code
4924 ///   void nope();
4925 ///   [[noreturn]] void a();
4926 ///   __attribute__((noreturn)) void b();
4927 ///   struct c { [[noreturn]] c(); };
4928 /// \endcode
4929 /// functionDecl(isNoReturn())
4930 ///   matches all of those except
4931 /// \code
4932 ///   void nope();
4933 /// \endcode
AST_MATCHER(FunctionDecl,isNoReturn)4934 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
4935 
4936 /// Matches the return type of a function declaration.
4937 ///
4938 /// Given:
4939 /// \code
4940 ///   class X { int f() { return 1; } };
4941 /// \endcode
4942 /// cxxMethodDecl(returns(asString("int")))
4943 ///   matches int f() { return 1; }
AST_MATCHER_P(FunctionDecl,returns,internal::Matcher<QualType>,InnerMatcher)4944 AST_MATCHER_P(FunctionDecl, returns,
4945               internal::Matcher<QualType>, InnerMatcher) {
4946   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
4947 }
4948 
4949 /// Matches extern "C" function or variable declarations.
4950 ///
4951 /// Given:
4952 /// \code
4953 ///   extern "C" void f() {}
4954 ///   extern "C" { void g() {} }
4955 ///   void h() {}
4956 ///   extern "C" int x = 1;
4957 ///   extern "C" int y = 2;
4958 ///   int z = 3;
4959 /// \endcode
4960 /// functionDecl(isExternC())
4961 ///   matches the declaration of f and g, but not the declaration of h.
4962 /// varDecl(isExternC())
4963 ///   matches the declaration of x and y, but not the declaration of z.
AST_POLYMORPHIC_MATCHER(isExternC,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl))4964 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4965                                                                    VarDecl)) {
4966   return Node.isExternC();
4967 }
4968 
4969 /// Matches variable/function declarations that have "static" storage
4970 /// class specifier ("static" keyword) written in the source.
4971 ///
4972 /// Given:
4973 /// \code
4974 ///   static void f() {}
4975 ///   static int i = 0;
4976 ///   extern int j;
4977 ///   int k;
4978 /// \endcode
4979 /// functionDecl(isStaticStorageClass())
4980 ///   matches the function declaration f.
4981 /// varDecl(isStaticStorageClass())
4982 ///   matches the variable declaration i.
AST_POLYMORPHIC_MATCHER(isStaticStorageClass,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl))4983 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
4984                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4985                                                         VarDecl)) {
4986   return Node.getStorageClass() == SC_Static;
4987 }
4988 
4989 /// Matches deleted function declarations.
4990 ///
4991 /// Given:
4992 /// \code
4993 ///   void Func();
4994 ///   void DeletedFunc() = delete;
4995 /// \endcode
4996 /// functionDecl(isDeleted())
4997 ///   matches the declaration of DeletedFunc, but not Func.
AST_MATCHER(FunctionDecl,isDeleted)4998 AST_MATCHER(FunctionDecl, isDeleted) {
4999   return Node.isDeleted();
5000 }
5001 
5002 /// Matches defaulted function declarations.
5003 ///
5004 /// Given:
5005 /// \code
5006 ///   class A { ~A(); };
5007 ///   class B { ~B() = default; };
5008 /// \endcode
5009 /// functionDecl(isDefaulted())
5010 ///   matches the declaration of ~B, but not ~A.
AST_MATCHER(FunctionDecl,isDefaulted)5011 AST_MATCHER(FunctionDecl, isDefaulted) {
5012   return Node.isDefaulted();
5013 }
5014 
5015 /// Matches weak function declarations.
5016 ///
5017 /// Given:
5018 /// \code
5019 ///   void foo() __attribute__((__weakref__("__foo")));
5020 ///   void bar();
5021 /// \endcode
5022 /// functionDecl(isWeak())
5023 ///   matches the weak declaration "foo", but not "bar".
AST_MATCHER(FunctionDecl,isWeak)5024 AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5025 
5026 /// Matches functions that have a dynamic exception specification.
5027 ///
5028 /// Given:
5029 /// \code
5030 ///   void f();
5031 ///   void g() noexcept;
5032 ///   void h() noexcept(true);
5033 ///   void i() noexcept(false);
5034 ///   void j() throw();
5035 ///   void k() throw(int);
5036 ///   void l() throw(...);
5037 /// \endcode
5038 /// functionDecl(hasDynamicExceptionSpec()) and
5039 ///   functionProtoType(hasDynamicExceptionSpec())
5040 ///   match the declarations of j, k, and l, but not f, g, h, or i.
AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,FunctionProtoType))5041 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5042                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5043                                                         FunctionProtoType)) {
5044   if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5045     return FnTy->hasDynamicExceptionSpec();
5046   return false;
5047 }
5048 
5049 /// Matches functions that have a non-throwing exception specification.
5050 ///
5051 /// Given:
5052 /// \code
5053 ///   void f();
5054 ///   void g() noexcept;
5055 ///   void h() throw();
5056 ///   void i() throw(int);
5057 ///   void j() noexcept(false);
5058 /// \endcode
5059 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5060 ///   match the declarations of g, and h, but not f, i or j.
AST_POLYMORPHIC_MATCHER(isNoThrow,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,FunctionProtoType))5061 AST_POLYMORPHIC_MATCHER(isNoThrow,
5062                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5063                                                         FunctionProtoType)) {
5064   const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5065 
5066   // If the function does not have a prototype, then it is assumed to be a
5067   // throwing function (as it would if the function did not have any exception
5068   // specification).
5069   if (!FnTy)
5070     return false;
5071 
5072   // Assume the best for any unresolved exception specification.
5073   if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
5074     return true;
5075 
5076   return FnTy->isNothrow();
5077 }
5078 
5079 /// Matches constexpr variable and function declarations,
5080 ///        and if constexpr.
5081 ///
5082 /// Given:
5083 /// \code
5084 ///   constexpr int foo = 42;
5085 ///   constexpr int bar();
5086 ///   void baz() { if constexpr(1 > 0) {} }
5087 /// \endcode
5088 /// varDecl(isConstexpr())
5089 ///   matches the declaration of foo.
5090 /// functionDecl(isConstexpr())
5091 ///   matches the declaration of bar.
5092 /// ifStmt(isConstexpr())
5093 ///   matches the if statement in baz.
AST_POLYMORPHIC_MATCHER(isConstexpr,AST_POLYMORPHIC_SUPPORTED_TYPES (VarDecl,FunctionDecl,IfStmt))5094 AST_POLYMORPHIC_MATCHER(isConstexpr,
5095                         AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
5096                                                         FunctionDecl,
5097                                                         IfStmt)) {
5098   return Node.isConstexpr();
5099 }
5100 
5101 /// Matches selection statements with initializer.
5102 ///
5103 /// Given:
5104 /// \code
5105 ///  void foo() {
5106 ///    if (int i = foobar(); i > 0) {}
5107 ///    switch (int i = foobar(); i) {}
5108 ///    for (auto& a = get_range(); auto& x : a) {}
5109 ///  }
5110 ///  void bar() {
5111 ///    if (foobar() > 0) {}
5112 ///    switch (foobar()) {}
5113 ///    for (auto& x : get_range()) {}
5114 ///  }
5115 /// \endcode
5116 /// ifStmt(hasInitStatement(anything()))
5117 ///   matches the if statement in foo but not in bar.
5118 /// switchStmt(hasInitStatement(anything()))
5119 ///   matches the switch statement in foo but not in bar.
5120 /// cxxForRangeStmt(hasInitStatement(anything()))
5121 ///   matches the range for statement in foo but not in bar.
AST_POLYMORPHIC_MATCHER_P(hasInitStatement,AST_POLYMORPHIC_SUPPORTED_TYPES (IfStmt,SwitchStmt,CXXForRangeStmt),internal::Matcher<Stmt>,InnerMatcher)5122 AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
5123                           AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt,
5124                                                           CXXForRangeStmt),
5125                           internal::Matcher<Stmt>, InnerMatcher) {
5126   const Stmt *Init = Node.getInit();
5127   return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5128 }
5129 
5130 /// Matches the condition expression of an if statement, for loop,
5131 /// switch statement or conditional operator.
5132 ///
5133 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5134 /// \code
5135 ///   if (true) {}
5136 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasCondition,AST_POLYMORPHIC_SUPPORTED_TYPES (IfStmt,ForStmt,WhileStmt,DoStmt,SwitchStmt,AbstractConditionalOperator),internal::Matcher<Expr>,InnerMatcher)5137 AST_POLYMORPHIC_MATCHER_P(
5138     hasCondition,
5139     AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
5140                                     SwitchStmt, AbstractConditionalOperator),
5141     internal::Matcher<Expr>, InnerMatcher) {
5142   const Expr *const Condition = Node.getCond();
5143   return (Condition != nullptr &&
5144           InnerMatcher.matches(*Condition, Finder, Builder));
5145 }
5146 
5147 /// Matches the then-statement of an if statement.
5148 ///
5149 /// Examples matches the if statement
5150 ///   (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5151 /// \code
5152 ///   if (false) true; else false;
5153 /// \endcode
AST_MATCHER_P(IfStmt,hasThen,internal::Matcher<Stmt>,InnerMatcher)5154 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5155   const Stmt *const Then = Node.getThen();
5156   return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5157 }
5158 
5159 /// Matches the else-statement of an if statement.
5160 ///
5161 /// Examples matches the if statement
5162 ///   (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5163 /// \code
5164 ///   if (false) false; else true;
5165 /// \endcode
AST_MATCHER_P(IfStmt,hasElse,internal::Matcher<Stmt>,InnerMatcher)5166 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5167   const Stmt *const Else = Node.getElse();
5168   return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5169 }
5170 
5171 /// Matches if a node equals a previously bound node.
5172 ///
5173 /// Matches a node if it equals the node previously bound to \p ID.
5174 ///
5175 /// Given
5176 /// \code
5177 ///   class X { int a; int b; };
5178 /// \endcode
5179 /// cxxRecordDecl(
5180 ///     has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5181 ///     has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5182 ///   matches the class \c X, as \c a and \c b have the same type.
5183 ///
5184 /// Note that when multiple matches are involved via \c forEach* matchers,
5185 /// \c equalsBoundNodes acts as a filter.
5186 /// For example:
5187 /// compoundStmt(
5188 ///     forEachDescendant(varDecl().bind("d")),
5189 ///     forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5190 /// will trigger a match for each combination of variable declaration
5191 /// and reference to that variable declaration within a compound statement.
AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,AST_POLYMORPHIC_SUPPORTED_TYPES (Stmt,Decl,Type,QualType),std::string,ID)5192 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
5193                           AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
5194                                                           QualType),
5195                           std::string, ID) {
5196   // FIXME: Figure out whether it makes sense to allow this
5197   // on any other node types.
5198   // For *Loc it probably does not make sense, as those seem
5199   // unique. For NestedNameSepcifier it might make sense, as
5200   // those also have pointer identity, but I'm not sure whether
5201   // they're ever reused.
5202   internal::NotEqualsBoundNodePredicate Predicate;
5203   Predicate.ID = ID;
5204   Predicate.Node = DynTypedNode::create(Node);
5205   return Builder->removeBindings(Predicate);
5206 }
5207 
5208 /// Matches the condition variable statement in an if statement.
5209 ///
5210 /// Given
5211 /// \code
5212 ///   if (A* a = GetAPointer()) {}
5213 /// \endcode
5214 /// hasConditionVariableStatement(...)
5215 ///   matches 'A* a = GetAPointer()'.
AST_MATCHER_P(IfStmt,hasConditionVariableStatement,internal::Matcher<DeclStmt>,InnerMatcher)5216 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5217               internal::Matcher<DeclStmt>, InnerMatcher) {
5218   const DeclStmt* const DeclarationStatement =
5219     Node.getConditionVariableDeclStmt();
5220   return DeclarationStatement != nullptr &&
5221          InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5222 }
5223 
5224 /// Matches the index expression of an array subscript expression.
5225 ///
5226 /// Given
5227 /// \code
5228 ///   int i[5];
5229 ///   void f() { i[1] = 42; }
5230 /// \endcode
5231 /// arraySubscriptExpression(hasIndex(integerLiteral()))
5232 ///   matches \c i[1] with the \c integerLiteral() matching \c 1
AST_MATCHER_P(ArraySubscriptExpr,hasIndex,internal::Matcher<Expr>,InnerMatcher)5233 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
5234               internal::Matcher<Expr>, InnerMatcher) {
5235   if (const Expr* Expression = Node.getIdx())
5236     return InnerMatcher.matches(*Expression, Finder, Builder);
5237   return false;
5238 }
5239 
5240 /// Matches the base expression of an array subscript expression.
5241 ///
5242 /// Given
5243 /// \code
5244 ///   int i[5];
5245 ///   void f() { i[1] = 42; }
5246 /// \endcode
5247 /// arraySubscriptExpression(hasBase(implicitCastExpr(
5248 ///     hasSourceExpression(declRefExpr()))))
5249 ///   matches \c i[1] with the \c declRefExpr() matching \c i
AST_MATCHER_P(ArraySubscriptExpr,hasBase,internal::Matcher<Expr>,InnerMatcher)5250 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
5251               internal::Matcher<Expr>, InnerMatcher) {
5252   if (const Expr* Expression = Node.getBase())
5253     return InnerMatcher.matches(*Expression, Finder, Builder);
5254   return false;
5255 }
5256 
5257 /// Matches a 'for', 'while', 'do while' statement or a function
5258 /// definition that has a given body. Note that in case of functions
5259 /// this matcher only matches the definition itself and not the other
5260 /// declarations of the same function.
5261 ///
5262 /// Given
5263 /// \code
5264 ///   for (;;) {}
5265 /// \endcode
5266 /// hasBody(compoundStmt())
5267 ///   matches 'for (;;) {}'
5268 /// with compoundStmt()
5269 ///   matching '{}'
5270 ///
5271 /// Given
5272 /// \code
5273 ///   void f();
5274 ///   void f() {}
5275 /// \endcode
5276 /// hasBody(functionDecl())
5277 ///   matches 'void f() {}'
5278 /// with compoundStmt()
5279 ///   matching '{}'
5280 ///   but does not match 'void f();'
5281 
AST_POLYMORPHIC_MATCHER_P(hasBody,AST_POLYMORPHIC_SUPPORTED_TYPES (DoStmt,ForStmt,WhileStmt,CXXForRangeStmt,FunctionDecl),internal::Matcher<Stmt>,InnerMatcher)5282 AST_POLYMORPHIC_MATCHER_P(hasBody,
5283                           AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
5284                                                           WhileStmt,
5285                                                           CXXForRangeStmt,
5286                                                           FunctionDecl),
5287                           internal::Matcher<Stmt>, InnerMatcher) {
5288   if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5289     return false;
5290   const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5291   return (Statement != nullptr &&
5292           InnerMatcher.matches(*Statement, Finder, Builder));
5293 }
5294 
5295 /// Matches a function declaration that has a given body present in the AST.
5296 /// Note that this matcher matches all the declarations of a function whose
5297 /// body is present in the AST.
5298 ///
5299 /// Given
5300 /// \code
5301 ///   void f();
5302 ///   void f() {}
5303 ///   void g();
5304 /// \endcode
5305 /// functionDecl(hasAnyBody(compoundStmt()))
5306 ///   matches both 'void f();'
5307 ///   and 'void f() {}'
5308 /// with compoundStmt()
5309 ///   matching '{}'
5310 ///   but does not match 'void g();'
AST_MATCHER_P(FunctionDecl,hasAnyBody,internal::Matcher<Stmt>,InnerMatcher)5311 AST_MATCHER_P(FunctionDecl, hasAnyBody,
5312               internal::Matcher<Stmt>, InnerMatcher) {
5313   const Stmt *const Statement = Node.getBody();
5314   return (Statement != nullptr &&
5315           InnerMatcher.matches(*Statement, Finder, Builder));
5316 }
5317 
5318 
5319 /// Matches compound statements where at least one substatement matches
5320 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5321 ///
5322 /// Given
5323 /// \code
5324 ///   { {}; 1+2; }
5325 /// \endcode
5326 /// hasAnySubstatement(compoundStmt())
5327 ///   matches '{ {}; 1+2; }'
5328 /// with compoundStmt()
5329 ///   matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,AST_POLYMORPHIC_SUPPORTED_TYPES (CompoundStmt,StmtExpr),internal::Matcher<Stmt>,InnerMatcher)5330 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5331                           AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
5332                                                           StmtExpr),
5333                           internal::Matcher<Stmt>, InnerMatcher) {
5334   const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5335   return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5336                                           CS->body_end(), Finder,
5337                                           Builder) != CS->body_end();
5338 }
5339 
5340 /// Checks that a compound statement contains a specific number of
5341 /// child statements.
5342 ///
5343 /// Example: Given
5344 /// \code
5345 ///   { for (;;) {} }
5346 /// \endcode
5347 /// compoundStmt(statementCountIs(0)))
5348 ///   matches '{}'
5349 ///   but does not match the outer compound statement.
AST_MATCHER_P(CompoundStmt,statementCountIs,unsigned,N)5350 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5351   return Node.size() == N;
5352 }
5353 
5354 /// Matches literals that are equal to the given value of type ValueT.
5355 ///
5356 /// Given
5357 /// \code
5358 ///   f('\0', false, 3.14, 42);
5359 /// \endcode
5360 /// characterLiteral(equals(0))
5361 ///   matches '\0'
5362 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5363 ///   match false
5364 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5365 ///   match 3.14
5366 /// integerLiteral(equals(42))
5367 ///   matches 42
5368 ///
5369 /// Note that you cannot directly match a negative numeric literal because the
5370 /// minus sign is not part of the literal: It is a unary operator whose operand
5371 /// is the positive numeric literal. Instead, you must use a unaryOperator()
5372 /// matcher to match the minus sign:
5373 ///
5374 /// unaryOperator(hasOperatorName("-"),
5375 ///               hasUnaryOperand(integerLiteral(equals(13))))
5376 ///
5377 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5378 ///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5379 template <typename ValueT>
5380 internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5381                              void(internal::AllNodeBaseTypes), ValueT>
equals(const ValueT & Value)5382 equals(const ValueT &Value) {
5383   return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5384                                       void(internal::AllNodeBaseTypes), ValueT>(
5385       Value);
5386 }
5387 
5388 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
5389                           AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5390                                                           CXXBoolLiteralExpr,
5391                                                           IntegerLiteral),
5392                           bool, Value, 0) {
5393   return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5394     .matchesNode(Node);
5395 }
5396 
5397 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
5398                           AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5399                                                           CXXBoolLiteralExpr,
5400                                                           IntegerLiteral),
5401                           unsigned, Value, 1) {
5402   return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5403     .matchesNode(Node);
5404 }
5405 
5406 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
5407                           AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5408                                                           CXXBoolLiteralExpr,
5409                                                           FloatingLiteral,
5410                                                           IntegerLiteral),
5411                           double, Value, 2) {
5412   return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5413     .matchesNode(Node);
5414 }
5415 
5416 /// Matches the operator Name of operator expressions (binary or
5417 /// unary).
5418 ///
5419 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5420 /// \code
5421 ///   !(a || b)
5422 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasOperatorName,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator,UnaryOperator),std::string,Name)5423 AST_POLYMORPHIC_MATCHER_P(
5424     hasOperatorName,
5425     AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5426                                     CXXRewrittenBinaryOperator, UnaryOperator),
5427     std::string, Name) {
5428   if (Optional<StringRef> OpName = internal::getOpName(Node))
5429     return *OpName == Name;
5430   return false;
5431 }
5432 
5433 /// Matches operator expressions (binary or unary) that have any of the
5434 /// specified names.
5435 ///
5436 ///    hasAnyOperatorName("+", "-")
5437 ///  Is equivalent to
5438 ///    anyOf(hasOperatorName("+"), hasOperatorName("-"))
5439 extern const internal::VariadicFunction<
5440     internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5441                                  AST_POLYMORPHIC_SUPPORTED_TYPES(
5442                                      BinaryOperator, CXXOperatorCallExpr,
5443                                      CXXRewrittenBinaryOperator, UnaryOperator),
5444                                  std::vector<std::string>>,
5445     StringRef, internal::hasAnyOperatorNameFunc>
5446     hasAnyOperatorName;
5447 
5448 /// Matches all kinds of assignment operators.
5449 ///
5450 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5451 /// \code
5452 ///   if (a == b)
5453 ///     a += b;
5454 /// \endcode
5455 ///
5456 /// Example 2: matches s1 = s2
5457 ///            (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5458 /// \code
5459 ///   struct S { S& operator=(const S&); };
5460 ///   void x() { S s1, s2; s1 = s2; }
5461 /// \endcode
AST_POLYMORPHIC_MATCHER(isAssignmentOperator,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator))5462 AST_POLYMORPHIC_MATCHER(
5463     isAssignmentOperator,
5464     AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5465                                     CXXRewrittenBinaryOperator)) {
5466   return Node.isAssignmentOp();
5467 }
5468 
5469 /// Matches comparison operators.
5470 ///
5471 /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5472 /// \code
5473 ///   if (a == b)
5474 ///     a += b;
5475 /// \endcode
5476 ///
5477 /// Example 2: matches s1 < s2
5478 ///            (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5479 /// \code
5480 ///   struct S { bool operator<(const S& other); };
5481 ///   void x(S s1, S s2) { bool b1 = s1 < s2; }
5482 /// \endcode
AST_POLYMORPHIC_MATCHER(isComparisonOperator,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator))5483 AST_POLYMORPHIC_MATCHER(
5484     isComparisonOperator,
5485     AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5486                                     CXXRewrittenBinaryOperator)) {
5487   return Node.isComparisonOp();
5488 }
5489 
5490 /// Matches the left hand side of binary operator expressions.
5491 ///
5492 /// Example matches a (matcher = binaryOperator(hasLHS()))
5493 /// \code
5494 ///   a || b
5495 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasLHS,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator,ArraySubscriptExpr),internal::Matcher<Expr>,InnerMatcher)5496 AST_POLYMORPHIC_MATCHER_P(hasLHS,
5497                           AST_POLYMORPHIC_SUPPORTED_TYPES(
5498                               BinaryOperator, CXXOperatorCallExpr,
5499                               CXXRewrittenBinaryOperator, ArraySubscriptExpr),
5500                           internal::Matcher<Expr>, InnerMatcher) {
5501   const Expr *LeftHandSide = internal::getLHS(Node);
5502   return (LeftHandSide != nullptr &&
5503           InnerMatcher.matches(*LeftHandSide, Finder, Builder));
5504 }
5505 
5506 /// Matches the right hand side of binary operator expressions.
5507 ///
5508 /// Example matches b (matcher = binaryOperator(hasRHS()))
5509 /// \code
5510 ///   a || b
5511 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasRHS,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator,ArraySubscriptExpr),internal::Matcher<Expr>,InnerMatcher)5512 AST_POLYMORPHIC_MATCHER_P(hasRHS,
5513                           AST_POLYMORPHIC_SUPPORTED_TYPES(
5514                               BinaryOperator, CXXOperatorCallExpr,
5515                               CXXRewrittenBinaryOperator, ArraySubscriptExpr),
5516                           internal::Matcher<Expr>, InnerMatcher) {
5517   const Expr *RightHandSide = internal::getRHS(Node);
5518   return (RightHandSide != nullptr &&
5519           InnerMatcher.matches(*RightHandSide, Finder, Builder));
5520 }
5521 
5522 /// Matches if either the left hand side or the right hand side of a
5523 /// binary operator matches.
AST_POLYMORPHIC_MATCHER_P(hasEitherOperand,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator),internal::Matcher<Expr>,InnerMatcher)5524 AST_POLYMORPHIC_MATCHER_P(
5525     hasEitherOperand,
5526     AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5527                                     CXXRewrittenBinaryOperator),
5528     internal::Matcher<Expr>, InnerMatcher) {
5529   return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5530              anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
5531       .matches(Node, Finder, Builder);
5532 }
5533 
5534 /// Matches if both matchers match with opposite sides of the binary operator.
5535 ///
5536 /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
5537 ///                                              integerLiteral(equals(2)))
5538 /// \code
5539 ///   1 + 2 // Match
5540 ///   2 + 1 // Match
5541 ///   1 + 1 // No match
5542 ///   2 + 2 // No match
5543 /// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasOperands,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr,CXXRewrittenBinaryOperator),internal::Matcher<Expr>,Matcher1,internal::Matcher<Expr>,Matcher2)5544 AST_POLYMORPHIC_MATCHER_P2(
5545     hasOperands,
5546     AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5547                                     CXXRewrittenBinaryOperator),
5548     internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
5549   return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5550              anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
5551                    allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
5552       .matches(Node, Finder, Builder);
5553 }
5554 
5555 /// Matches if the operand of a unary operator matches.
5556 ///
5557 /// Example matches true (matcher = hasUnaryOperand(
5558 ///                                   cxxBoolLiteral(equals(true))))
5559 /// \code
5560 ///   !true
5561 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,AST_POLYMORPHIC_SUPPORTED_TYPES (UnaryOperator,CXXOperatorCallExpr),internal::Matcher<Expr>,InnerMatcher)5562 AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,
5563                           AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator,
5564                                                           CXXOperatorCallExpr),
5565                           internal::Matcher<Expr>, InnerMatcher) {
5566   const Expr *const Operand = internal::getSubExpr(Node);
5567   return (Operand != nullptr &&
5568           InnerMatcher.matches(*Operand, Finder, Builder));
5569 }
5570 
5571 /// Matches if the cast's source expression
5572 /// or opaque value's source expression matches the given matcher.
5573 ///
5574 /// Example 1: matches "a string"
5575 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
5576 /// \code
5577 /// class URL { URL(string); };
5578 /// URL url = "a string";
5579 /// \endcode
5580 ///
5581 /// Example 2: matches 'b' (matcher =
5582 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
5583 /// \code
5584 /// int a = b ?: 1;
5585 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,AST_POLYMORPHIC_SUPPORTED_TYPES (CastExpr,OpaqueValueExpr),internal::Matcher<Expr>,InnerMatcher)5586 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
5587                           AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
5588                                                           OpaqueValueExpr),
5589                           internal::Matcher<Expr>, InnerMatcher) {
5590   const Expr *const SubExpression =
5591       internal::GetSourceExpressionMatcher<NodeType>::get(Node);
5592   return (SubExpression != nullptr &&
5593           InnerMatcher.matches(*SubExpression, Finder, Builder));
5594 }
5595 
5596 /// Matches casts that has a given cast kind.
5597 ///
5598 /// Example: matches the implicit cast around \c 0
5599 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
5600 /// \code
5601 ///   int *p = 0;
5602 /// \endcode
5603 ///
5604 /// If the matcher is use from clang-query, CastKind parameter
5605 /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
AST_MATCHER_P(CastExpr,hasCastKind,CastKind,Kind)5606 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
5607   return Node.getCastKind() == Kind;
5608 }
5609 
5610 /// Matches casts whose destination type matches a given matcher.
5611 ///
5612 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
5613 /// actual casts "explicit" casts.)
AST_MATCHER_P(ExplicitCastExpr,hasDestinationType,internal::Matcher<QualType>,InnerMatcher)5614 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
5615               internal::Matcher<QualType>, InnerMatcher) {
5616   const QualType NodeType = Node.getTypeAsWritten();
5617   return InnerMatcher.matches(NodeType, Finder, Builder);
5618 }
5619 
5620 /// Matches implicit casts whose destination type matches a given
5621 /// matcher.
5622 ///
5623 /// FIXME: Unit test this matcher
AST_MATCHER_P(ImplicitCastExpr,hasImplicitDestinationType,internal::Matcher<QualType>,InnerMatcher)5624 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
5625               internal::Matcher<QualType>, InnerMatcher) {
5626   return InnerMatcher.matches(Node.getType(), Finder, Builder);
5627 }
5628 
5629 /// Matches TagDecl object that are spelled with "struct."
5630 ///
5631 /// Example matches S, but not C, U or E.
5632 /// \code
5633 ///   struct S {};
5634 ///   class C {};
5635 ///   union U {};
5636 ///   enum E {};
5637 /// \endcode
AST_MATCHER(TagDecl,isStruct)5638 AST_MATCHER(TagDecl, isStruct) {
5639   return Node.isStruct();
5640 }
5641 
5642 /// Matches TagDecl object that are spelled with "union."
5643 ///
5644 /// Example matches U, but not C, S or E.
5645 /// \code
5646 ///   struct S {};
5647 ///   class C {};
5648 ///   union U {};
5649 ///   enum E {};
5650 /// \endcode
AST_MATCHER(TagDecl,isUnion)5651 AST_MATCHER(TagDecl, isUnion) {
5652   return Node.isUnion();
5653 }
5654 
5655 /// Matches TagDecl object that are spelled with "class."
5656 ///
5657 /// Example matches C, but not S, U or E.
5658 /// \code
5659 ///   struct S {};
5660 ///   class C {};
5661 ///   union U {};
5662 ///   enum E {};
5663 /// \endcode
AST_MATCHER(TagDecl,isClass)5664 AST_MATCHER(TagDecl, isClass) {
5665   return Node.isClass();
5666 }
5667 
5668 /// Matches TagDecl object that are spelled with "enum."
5669 ///
5670 /// Example matches E, but not C, S or U.
5671 /// \code
5672 ///   struct S {};
5673 ///   class C {};
5674 ///   union U {};
5675 ///   enum E {};
5676 /// \endcode
AST_MATCHER(TagDecl,isEnum)5677 AST_MATCHER(TagDecl, isEnum) {
5678   return Node.isEnum();
5679 }
5680 
5681 /// Matches the true branch expression of a conditional operator.
5682 ///
5683 /// Example 1 (conditional ternary operator): matches a
5684 /// \code
5685 ///   condition ? a : b
5686 /// \endcode
5687 ///
5688 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
5689 /// \code
5690 ///   condition ?: b
5691 /// \endcode
AST_MATCHER_P(AbstractConditionalOperator,hasTrueExpression,internal::Matcher<Expr>,InnerMatcher)5692 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
5693               internal::Matcher<Expr>, InnerMatcher) {
5694   const Expr *Expression = Node.getTrueExpr();
5695   return (Expression != nullptr &&
5696           InnerMatcher.matches(*Expression, Finder, Builder));
5697 }
5698 
5699 /// Matches the false branch expression of a conditional operator
5700 /// (binary or ternary).
5701 ///
5702 /// Example matches b
5703 /// \code
5704 ///   condition ? a : b
5705 ///   condition ?: b
5706 /// \endcode
AST_MATCHER_P(AbstractConditionalOperator,hasFalseExpression,internal::Matcher<Expr>,InnerMatcher)5707 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
5708               internal::Matcher<Expr>, InnerMatcher) {
5709   const Expr *Expression = Node.getFalseExpr();
5710   return (Expression != nullptr &&
5711           InnerMatcher.matches(*Expression, Finder, Builder));
5712 }
5713 
5714 /// Matches if a declaration has a body attached.
5715 ///
5716 /// Example matches A, va, fa
5717 /// \code
5718 ///   class A {};
5719 ///   class B;  // Doesn't match, as it has no body.
5720 ///   int va;
5721 ///   extern int vb;  // Doesn't match, as it doesn't define the variable.
5722 ///   void fa() {}
5723 ///   void fb();  // Doesn't match, as it has no body.
5724 ///   @interface X
5725 ///   - (void)ma; // Doesn't match, interface is declaration.
5726 ///   @end
5727 ///   @implementation X
5728 ///   - (void)ma {}
5729 ///   @end
5730 /// \endcode
5731 ///
5732 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
5733 ///   Matcher<ObjCMethodDecl>
AST_POLYMORPHIC_MATCHER(isDefinition,AST_POLYMORPHIC_SUPPORTED_TYPES (TagDecl,VarDecl,ObjCMethodDecl,FunctionDecl))5734 AST_POLYMORPHIC_MATCHER(isDefinition,
5735                         AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
5736                                                         ObjCMethodDecl,
5737                                                         FunctionDecl)) {
5738   return Node.isThisDeclarationADefinition();
5739 }
5740 
5741 /// Matches if a function declaration is variadic.
5742 ///
5743 /// Example matches f, but not g or h. The function i will not match, even when
5744 /// compiled in C mode.
5745 /// \code
5746 ///   void f(...);
5747 ///   void g(int);
5748 ///   template <typename... Ts> void h(Ts...);
5749 ///   void i();
5750 /// \endcode
AST_MATCHER(FunctionDecl,isVariadic)5751 AST_MATCHER(FunctionDecl, isVariadic) {
5752   return Node.isVariadic();
5753 }
5754 
5755 /// Matches the class declaration that the given method declaration
5756 /// belongs to.
5757 ///
5758 /// FIXME: Generalize this for other kinds of declarations.
5759 /// FIXME: What other kind of declarations would we need to generalize
5760 /// this to?
5761 ///
5762 /// Example matches A() in the last line
5763 ///     (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
5764 ///         ofClass(hasName("A"))))))
5765 /// \code
5766 ///   class A {
5767 ///    public:
5768 ///     A();
5769 ///   };
5770 ///   A a = A();
5771 /// \endcode
AST_MATCHER_P(CXXMethodDecl,ofClass,internal::Matcher<CXXRecordDecl>,InnerMatcher)5772 AST_MATCHER_P(CXXMethodDecl, ofClass,
5773               internal::Matcher<CXXRecordDecl>, InnerMatcher) {
5774 
5775   ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
5776 
5777   const CXXRecordDecl *Parent = Node.getParent();
5778   return (Parent != nullptr &&
5779           InnerMatcher.matches(*Parent, Finder, Builder));
5780 }
5781 
5782 /// Matches each method overridden by the given method. This matcher may
5783 /// produce multiple matches.
5784 ///
5785 /// Given
5786 /// \code
5787 ///   class A { virtual void f(); };
5788 ///   class B : public A { void f(); };
5789 ///   class C : public B { void f(); };
5790 /// \endcode
5791 /// cxxMethodDecl(ofClass(hasName("C")),
5792 ///               forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5793 ///   matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
5794 ///   that B::f is not overridden by C::f).
5795 ///
5796 /// The check can produce multiple matches in case of multiple inheritance, e.g.
5797 /// \code
5798 ///   class A1 { virtual void f(); };
5799 ///   class A2 { virtual void f(); };
5800 ///   class C : public A1, public A2 { void f(); };
5801 /// \endcode
5802 /// cxxMethodDecl(ofClass(hasName("C")),
5803 ///               forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5804 ///   matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
5805 ///   once with "b" binding "A2::f" and "d" binding "C::f".
AST_MATCHER_P(CXXMethodDecl,forEachOverridden,internal::Matcher<CXXMethodDecl>,InnerMatcher)5806 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
5807               internal::Matcher<CXXMethodDecl>, InnerMatcher) {
5808   BoundNodesTreeBuilder Result;
5809   bool Matched = false;
5810   for (const auto *Overridden : Node.overridden_methods()) {
5811     BoundNodesTreeBuilder OverriddenBuilder(*Builder);
5812     const bool OverriddenMatched =
5813         InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
5814     if (OverriddenMatched) {
5815       Matched = true;
5816       Result.addMatch(OverriddenBuilder);
5817     }
5818   }
5819   *Builder = std::move(Result);
5820   return Matched;
5821 }
5822 
5823 /// Matches declarations of virtual methods and C++ base specifers that specify
5824 /// virtual inheritance.
5825 ///
5826 /// Example:
5827 /// \code
5828 ///   class A {
5829 ///    public:
5830 ///     virtual void x(); // matches x
5831 ///   };
5832 /// \endcode
5833 ///
5834 /// Example:
5835 /// \code
5836 ///   class Base {};
5837 ///   class DirectlyDerived : virtual Base {}; // matches Base
5838 ///   class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
5839 /// \endcode
5840 ///
5841 /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
AST_POLYMORPHIC_MATCHER(isVirtual,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXMethodDecl,CXXBaseSpecifier))5842 AST_POLYMORPHIC_MATCHER(isVirtual,
5843                         AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
5844                                                         CXXBaseSpecifier)) {
5845   return Node.isVirtual();
5846 }
5847 
5848 /// Matches if the given method declaration has an explicit "virtual".
5849 ///
5850 /// Given
5851 /// \code
5852 ///   class A {
5853 ///    public:
5854 ///     virtual void x();
5855 ///   };
5856 ///   class B : public A {
5857 ///    public:
5858 ///     void x();
5859 ///   };
5860 /// \endcode
5861 ///   matches A::x but not B::x
AST_MATCHER(CXXMethodDecl,isVirtualAsWritten)5862 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
5863   return Node.isVirtualAsWritten();
5864 }
5865 
5866 /// Matches if the given method or class declaration is final.
5867 ///
5868 /// Given:
5869 /// \code
5870 ///   class A final {};
5871 ///
5872 ///   struct B {
5873 ///     virtual void f();
5874 ///   };
5875 ///
5876 ///   struct C : B {
5877 ///     void f() final;
5878 ///   };
5879 /// \endcode
5880 /// matches A and C::f, but not B, C, or B::f
AST_POLYMORPHIC_MATCHER(isFinal,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXRecordDecl,CXXMethodDecl))5881 AST_POLYMORPHIC_MATCHER(isFinal,
5882                         AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
5883                                                         CXXMethodDecl)) {
5884   return Node.template hasAttr<FinalAttr>();
5885 }
5886 
5887 /// Matches if the given method declaration is pure.
5888 ///
5889 /// Given
5890 /// \code
5891 ///   class A {
5892 ///    public:
5893 ///     virtual void x() = 0;
5894 ///   };
5895 /// \endcode
5896 ///   matches A::x
AST_MATCHER(CXXMethodDecl,isPure)5897 AST_MATCHER(CXXMethodDecl, isPure) {
5898   return Node.isPure();
5899 }
5900 
5901 /// Matches if the given method declaration is const.
5902 ///
5903 /// Given
5904 /// \code
5905 /// struct A {
5906 ///   void foo() const;
5907 ///   void bar();
5908 /// };
5909 /// \endcode
5910 ///
5911 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
AST_MATCHER(CXXMethodDecl,isConst)5912 AST_MATCHER(CXXMethodDecl, isConst) {
5913   return Node.isConst();
5914 }
5915 
5916 /// Matches if the given method declaration declares a copy assignment
5917 /// operator.
5918 ///
5919 /// Given
5920 /// \code
5921 /// struct A {
5922 ///   A &operator=(const A &);
5923 ///   A &operator=(A &&);
5924 /// };
5925 /// \endcode
5926 ///
5927 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
5928 /// the second one.
AST_MATCHER(CXXMethodDecl,isCopyAssignmentOperator)5929 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
5930   return Node.isCopyAssignmentOperator();
5931 }
5932 
5933 /// Matches if the given method declaration declares a move assignment
5934 /// operator.
5935 ///
5936 /// Given
5937 /// \code
5938 /// struct A {
5939 ///   A &operator=(const A &);
5940 ///   A &operator=(A &&);
5941 /// };
5942 /// \endcode
5943 ///
5944 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
5945 /// the first one.
AST_MATCHER(CXXMethodDecl,isMoveAssignmentOperator)5946 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
5947   return Node.isMoveAssignmentOperator();
5948 }
5949 
5950 /// Matches if the given method declaration overrides another method.
5951 ///
5952 /// Given
5953 /// \code
5954 ///   class A {
5955 ///    public:
5956 ///     virtual void x();
5957 ///   };
5958 ///   class B : public A {
5959 ///    public:
5960 ///     virtual void x();
5961 ///   };
5962 /// \endcode
5963 ///   matches B::x
AST_MATCHER(CXXMethodDecl,isOverride)5964 AST_MATCHER(CXXMethodDecl, isOverride) {
5965   return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
5966 }
5967 
5968 /// Matches method declarations that are user-provided.
5969 ///
5970 /// Given
5971 /// \code
5972 ///   struct S {
5973 ///     S(); // #1
5974 ///     S(const S &) = default; // #2
5975 ///     S(S &&) = delete; // #3
5976 ///   };
5977 /// \endcode
5978 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
AST_MATCHER(CXXMethodDecl,isUserProvided)5979 AST_MATCHER(CXXMethodDecl, isUserProvided) {
5980   return Node.isUserProvided();
5981 }
5982 
5983 /// Matches member expressions that are called with '->' as opposed
5984 /// to '.'.
5985 ///
5986 /// Member calls on the implicit this pointer match as called with '->'.
5987 ///
5988 /// Given
5989 /// \code
5990 ///   class Y {
5991 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
5992 ///     template <class T> void f() { this->f<T>(); f<T>(); }
5993 ///     int a;
5994 ///     static int b;
5995 ///   };
5996 ///   template <class T>
5997 ///   class Z {
5998 ///     void x() { this->m; }
5999 ///   };
6000 /// \endcode
6001 /// memberExpr(isArrow())
6002 ///   matches this->x, x, y.x, a, this->b
6003 /// cxxDependentScopeMemberExpr(isArrow())
6004 ///   matches this->m
6005 /// unresolvedMemberExpr(isArrow())
6006 ///   matches this->f<T>, f<T>
AST_POLYMORPHIC_MATCHER(isArrow,AST_POLYMORPHIC_SUPPORTED_TYPES (MemberExpr,UnresolvedMemberExpr,CXXDependentScopeMemberExpr))6007 AST_POLYMORPHIC_MATCHER(
6008     isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
6009                                              CXXDependentScopeMemberExpr)) {
6010   return Node.isArrow();
6011 }
6012 
6013 /// Matches QualType nodes that are of integer type.
6014 ///
6015 /// Given
6016 /// \code
6017 ///   void a(int);
6018 ///   void b(long);
6019 ///   void c(double);
6020 /// \endcode
6021 /// functionDecl(hasAnyParameter(hasType(isInteger())))
6022 /// matches "a(int)", "b(long)", but not "c(double)".
AST_MATCHER(QualType,isInteger)6023 AST_MATCHER(QualType, isInteger) {
6024     return Node->isIntegerType();
6025 }
6026 
6027 /// Matches QualType nodes that are of unsigned integer type.
6028 ///
6029 /// Given
6030 /// \code
6031 ///   void a(int);
6032 ///   void b(unsigned long);
6033 ///   void c(double);
6034 /// \endcode
6035 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6036 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
AST_MATCHER(QualType,isUnsignedInteger)6037 AST_MATCHER(QualType, isUnsignedInteger) {
6038     return Node->isUnsignedIntegerType();
6039 }
6040 
6041 /// Matches QualType nodes that are of signed integer type.
6042 ///
6043 /// Given
6044 /// \code
6045 ///   void a(int);
6046 ///   void b(unsigned long);
6047 ///   void c(double);
6048 /// \endcode
6049 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6050 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
AST_MATCHER(QualType,isSignedInteger)6051 AST_MATCHER(QualType, isSignedInteger) {
6052     return Node->isSignedIntegerType();
6053 }
6054 
6055 /// Matches QualType nodes that are of character type.
6056 ///
6057 /// Given
6058 /// \code
6059 ///   void a(char);
6060 ///   void b(wchar_t);
6061 ///   void c(double);
6062 /// \endcode
6063 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6064 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
AST_MATCHER(QualType,isAnyCharacter)6065 AST_MATCHER(QualType, isAnyCharacter) {
6066     return Node->isAnyCharacterType();
6067 }
6068 
6069 /// Matches QualType nodes that are of any pointer type; this includes
6070 /// the Objective-C object pointer type, which is different despite being
6071 /// syntactically similar.
6072 ///
6073 /// Given
6074 /// \code
6075 ///   int *i = nullptr;
6076 ///
6077 ///   @interface Foo
6078 ///   @end
6079 ///   Foo *f;
6080 ///
6081 ///   int j;
6082 /// \endcode
6083 /// varDecl(hasType(isAnyPointer()))
6084 ///   matches "int *i" and "Foo *f", but not "int j".
AST_MATCHER(QualType,isAnyPointer)6085 AST_MATCHER(QualType, isAnyPointer) {
6086   return Node->isAnyPointerType();
6087 }
6088 
6089 /// Matches QualType nodes that are const-qualified, i.e., that
6090 /// include "top-level" const.
6091 ///
6092 /// Given
6093 /// \code
6094 ///   void a(int);
6095 ///   void b(int const);
6096 ///   void c(const int);
6097 ///   void d(const int*);
6098 ///   void e(int const) {};
6099 /// \endcode
6100 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6101 ///   matches "void b(int const)", "void c(const int)" and
6102 ///   "void e(int const) {}". It does not match d as there
6103 ///   is no top-level const on the parameter type "const int *".
AST_MATCHER(QualType,isConstQualified)6104 AST_MATCHER(QualType, isConstQualified) {
6105   return Node.isConstQualified();
6106 }
6107 
6108 /// Matches QualType nodes that are volatile-qualified, i.e., that
6109 /// include "top-level" volatile.
6110 ///
6111 /// Given
6112 /// \code
6113 ///   void a(int);
6114 ///   void b(int volatile);
6115 ///   void c(volatile int);
6116 ///   void d(volatile int*);
6117 ///   void e(int volatile) {};
6118 /// \endcode
6119 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6120 ///   matches "void b(int volatile)", "void c(volatile int)" and
6121 ///   "void e(int volatile) {}". It does not match d as there
6122 ///   is no top-level volatile on the parameter type "volatile int *".
AST_MATCHER(QualType,isVolatileQualified)6123 AST_MATCHER(QualType, isVolatileQualified) {
6124   return Node.isVolatileQualified();
6125 }
6126 
6127 /// Matches QualType nodes that have local CV-qualifiers attached to
6128 /// the node, not hidden within a typedef.
6129 ///
6130 /// Given
6131 /// \code
6132 ///   typedef const int const_int;
6133 ///   const_int i;
6134 ///   int *const j;
6135 ///   int *volatile k;
6136 ///   int m;
6137 /// \endcode
6138 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
6139 /// \c i is const-qualified but the qualifier is not local.
AST_MATCHER(QualType,hasLocalQualifiers)6140 AST_MATCHER(QualType, hasLocalQualifiers) {
6141   return Node.hasLocalQualifiers();
6142 }
6143 
6144 /// Matches a member expression where the member is matched by a
6145 /// given matcher.
6146 ///
6147 /// Given
6148 /// \code
6149 ///   struct { int first, second; } first, second;
6150 ///   int i(second.first);
6151 ///   int j(first.second);
6152 /// \endcode
6153 /// memberExpr(member(hasName("first")))
6154 ///   matches second.first
6155 ///   but not first.second (because the member name there is "second").
AST_MATCHER_P(MemberExpr,member,internal::Matcher<ValueDecl>,InnerMatcher)6156 AST_MATCHER_P(MemberExpr, member,
6157               internal::Matcher<ValueDecl>, InnerMatcher) {
6158   return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
6159 }
6160 
6161 /// Matches a member expression where the object expression is matched by a
6162 /// given matcher. Implicit object expressions are included; that is, it matches
6163 /// use of implicit `this`.
6164 ///
6165 /// Given
6166 /// \code
6167 ///   struct X {
6168 ///     int m;
6169 ///     int f(X x) { x.m; return m; }
6170 ///   };
6171 /// \endcode
6172 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
6173 ///   matches `x.m`, but not `m`; however,
6174 /// memberExpr(hasObjectExpression(hasType(pointsTo(
6175 //      cxxRecordDecl(hasName("X"))))))
6176 ///   matches `m` (aka. `this->m`), but not `x.m`.
AST_POLYMORPHIC_MATCHER_P(hasObjectExpression,AST_POLYMORPHIC_SUPPORTED_TYPES (MemberExpr,UnresolvedMemberExpr,CXXDependentScopeMemberExpr),internal::Matcher<Expr>,InnerMatcher)6177 AST_POLYMORPHIC_MATCHER_P(
6178     hasObjectExpression,
6179     AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
6180                                     CXXDependentScopeMemberExpr),
6181     internal::Matcher<Expr>, InnerMatcher) {
6182   if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
6183     if (E->isImplicitAccess())
6184       return false;
6185   if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
6186     if (E->isImplicitAccess())
6187       return false;
6188   return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
6189 }
6190 
6191 /// Matches any using shadow declaration.
6192 ///
6193 /// Given
6194 /// \code
6195 ///   namespace X { void b(); }
6196 ///   using X::b;
6197 /// \endcode
6198 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
6199 ///   matches \code using X::b \endcode
AST_MATCHER_P(UsingDecl,hasAnyUsingShadowDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)6200 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
6201               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
6202   return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
6203                                     Node.shadow_end(), Finder,
6204                                     Builder) != Node.shadow_end();
6205 }
6206 
6207 /// Matches a using shadow declaration where the target declaration is
6208 /// matched by the given matcher.
6209 ///
6210 /// Given
6211 /// \code
6212 ///   namespace X { int a; void b(); }
6213 ///   using X::a;
6214 ///   using X::b;
6215 /// \endcode
6216 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
6217 ///   matches \code using X::b \endcode
6218 ///   but not \code using X::a \endcode
AST_MATCHER_P(UsingShadowDecl,hasTargetDecl,internal::Matcher<NamedDecl>,InnerMatcher)6219 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
6220               internal::Matcher<NamedDecl>, InnerMatcher) {
6221   return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
6222 }
6223 
6224 /// Matches template instantiations of function, class, or static
6225 /// member variable template instantiations.
6226 ///
6227 /// Given
6228 /// \code
6229 ///   template <typename T> class X {}; class A {}; X<A> x;
6230 /// \endcode
6231 /// or
6232 /// \code
6233 ///   template <typename T> class X {}; class A {}; template class X<A>;
6234 /// \endcode
6235 /// or
6236 /// \code
6237 ///   template <typename T> class X {}; class A {}; extern template class X<A>;
6238 /// \endcode
6239 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6240 ///   matches the template instantiation of X<A>.
6241 ///
6242 /// But given
6243 /// \code
6244 ///   template <typename T>  class X {}; class A {};
6245 ///   template <> class X<A> {}; X<A> x;
6246 /// \endcode
6247 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6248 ///   does not match, as X<A> is an explicit template specialization.
6249 ///
6250 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl,CXXRecordDecl))6251 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
6252                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
6253                                                         CXXRecordDecl)) {
6254   return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
6255           Node.getTemplateSpecializationKind() ==
6256               TSK_ExplicitInstantiationDefinition ||
6257           Node.getTemplateSpecializationKind() ==
6258               TSK_ExplicitInstantiationDeclaration);
6259 }
6260 
6261 /// Matches declarations that are template instantiations or are inside
6262 /// template instantiations.
6263 ///
6264 /// Given
6265 /// \code
6266 ///   template<typename T> void A(T t) { T i; }
6267 ///   A(0);
6268 ///   A(0U);
6269 /// \endcode
6270 /// functionDecl(isInstantiated())
6271 ///   matches 'A(int) {...};' and 'A(unsigned) {...}'.
AST_MATCHER_FUNCTION(internal::Matcher<Decl>,isInstantiated)6272 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
6273   auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6274                                     functionDecl(isTemplateInstantiation())));
6275   return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
6276 }
6277 
6278 /// Matches statements inside of a template instantiation.
6279 ///
6280 /// Given
6281 /// \code
6282 ///   int j;
6283 ///   template<typename T> void A(T t) { T i; j += 42;}
6284 ///   A(0);
6285 ///   A(0U);
6286 /// \endcode
6287 /// declStmt(isInTemplateInstantiation())
6288 ///   matches 'int i;' and 'unsigned i'.
6289 /// unless(stmt(isInTemplateInstantiation()))
6290 ///   will NOT match j += 42; as it's shared between the template definition and
6291 ///   instantiation.
AST_MATCHER_FUNCTION(internal::Matcher<Stmt>,isInTemplateInstantiation)6292 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
6293   return stmt(
6294       hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6295                              functionDecl(isTemplateInstantiation())))));
6296 }
6297 
6298 /// Matches explicit template specializations of function, class, or
6299 /// static member variable template instantiations.
6300 ///
6301 /// Given
6302 /// \code
6303 ///   template<typename T> void A(T t) { }
6304 ///   template<> void A(int N) { }
6305 /// \endcode
6306 /// functionDecl(isExplicitTemplateSpecialization())
6307 ///   matches the specialization A<int>().
6308 ///
6309 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl,CXXRecordDecl))6310 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
6311                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
6312                                                         CXXRecordDecl)) {
6313   return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
6314 }
6315 
6316 /// Matches \c TypeLocs for which the given inner
6317 /// QualType-matcher matches.
6318 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
6319                                 internal::Matcher<QualType>, InnerMatcher, 0) {
6320   return internal::BindableMatcher<TypeLoc>(
6321       new internal::TypeLocTypeMatcher(InnerMatcher));
6322 }
6323 
6324 /// Matches type \c bool.
6325 ///
6326 /// Given
6327 /// \code
6328 ///  struct S { bool func(); };
6329 /// \endcode
6330 /// functionDecl(returns(booleanType()))
6331 ///   matches "bool func();"
AST_MATCHER(Type,booleanType)6332 AST_MATCHER(Type, booleanType) {
6333   return Node.isBooleanType();
6334 }
6335 
6336 /// Matches type \c void.
6337 ///
6338 /// Given
6339 /// \code
6340 ///  struct S { void func(); };
6341 /// \endcode
6342 /// functionDecl(returns(voidType()))
6343 ///   matches "void func();"
AST_MATCHER(Type,voidType)6344 AST_MATCHER(Type, voidType) {
6345   return Node.isVoidType();
6346 }
6347 
6348 template <typename NodeType>
6349 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
6350 
6351 /// Matches builtin Types.
6352 ///
6353 /// Given
6354 /// \code
6355 ///   struct A {};
6356 ///   A a;
6357 ///   int b;
6358 ///   float c;
6359 ///   bool d;
6360 /// \endcode
6361 /// builtinType()
6362 ///   matches "int b", "float c" and "bool d"
6363 extern const AstTypeMatcher<BuiltinType> builtinType;
6364 
6365 /// Matches all kinds of arrays.
6366 ///
6367 /// Given
6368 /// \code
6369 ///   int a[] = { 2, 3 };
6370 ///   int b[4];
6371 ///   void f() { int c[a[0]]; }
6372 /// \endcode
6373 /// arrayType()
6374 ///   matches "int a[]", "int b[4]" and "int c[a[0]]";
6375 extern const AstTypeMatcher<ArrayType> arrayType;
6376 
6377 /// Matches C99 complex types.
6378 ///
6379 /// Given
6380 /// \code
6381 ///   _Complex float f;
6382 /// \endcode
6383 /// complexType()
6384 ///   matches "_Complex float f"
6385 extern const AstTypeMatcher<ComplexType> complexType;
6386 
6387 /// Matches any real floating-point type (float, double, long double).
6388 ///
6389 /// Given
6390 /// \code
6391 ///   int i;
6392 ///   float f;
6393 /// \endcode
6394 /// realFloatingPointType()
6395 ///   matches "float f" but not "int i"
AST_MATCHER(Type,realFloatingPointType)6396 AST_MATCHER(Type, realFloatingPointType) {
6397   return Node.isRealFloatingType();
6398 }
6399 
6400 /// Matches arrays and C99 complex types that have a specific element
6401 /// type.
6402 ///
6403 /// Given
6404 /// \code
6405 ///   struct A {};
6406 ///   A a[7];
6407 ///   int b[7];
6408 /// \endcode
6409 /// arrayType(hasElementType(builtinType()))
6410 ///   matches "int b[7]"
6411 ///
6412 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
6413 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
6414                                   AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
6415                                                                   ComplexType));
6416 
6417 /// Matches C arrays with a specified constant size.
6418 ///
6419 /// Given
6420 /// \code
6421 ///   void() {
6422 ///     int a[2];
6423 ///     int b[] = { 2, 3 };
6424 ///     int c[b[0]];
6425 ///   }
6426 /// \endcode
6427 /// constantArrayType()
6428 ///   matches "int a[2]"
6429 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
6430 
6431 /// Matches nodes that have the specified size.
6432 ///
6433 /// Given
6434 /// \code
6435 ///   int a[42];
6436 ///   int b[2 * 21];
6437 ///   int c[41], d[43];
6438 ///   char *s = "abcd";
6439 ///   wchar_t *ws = L"abcd";
6440 ///   char *w = "a";
6441 /// \endcode
6442 /// constantArrayType(hasSize(42))
6443 ///   matches "int a[42]" and "int b[2 * 21]"
6444 /// stringLiteral(hasSize(4))
6445 ///   matches "abcd", L"abcd"
AST_POLYMORPHIC_MATCHER_P(hasSize,AST_POLYMORPHIC_SUPPORTED_TYPES (ConstantArrayType,StringLiteral),unsigned,N)6446 AST_POLYMORPHIC_MATCHER_P(hasSize,
6447                           AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
6448                                                           StringLiteral),
6449                           unsigned, N) {
6450   return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
6451 }
6452 
6453 /// Matches C++ arrays whose size is a value-dependent expression.
6454 ///
6455 /// Given
6456 /// \code
6457 ///   template<typename T, int Size>
6458 ///   class array {
6459 ///     T data[Size];
6460 ///   };
6461 /// \endcode
6462 /// dependentSizedArrayType
6463 ///   matches "T data[Size]"
6464 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
6465 
6466 /// Matches C arrays with unspecified size.
6467 ///
6468 /// Given
6469 /// \code
6470 ///   int a[] = { 2, 3 };
6471 ///   int b[42];
6472 ///   void f(int c[]) { int d[a[0]]; };
6473 /// \endcode
6474 /// incompleteArrayType()
6475 ///   matches "int a[]" and "int c[]"
6476 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
6477 
6478 /// Matches C arrays with a specified size that is not an
6479 /// integer-constant-expression.
6480 ///
6481 /// Given
6482 /// \code
6483 ///   void f() {
6484 ///     int a[] = { 2, 3 }
6485 ///     int b[42];
6486 ///     int c[a[0]];
6487 ///   }
6488 /// \endcode
6489 /// variableArrayType()
6490 ///   matches "int c[a[0]]"
6491 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
6492 
6493 /// Matches \c VariableArrayType nodes that have a specific size
6494 /// expression.
6495 ///
6496 /// Given
6497 /// \code
6498 ///   void f(int b) {
6499 ///     int a[b];
6500 ///   }
6501 /// \endcode
6502 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
6503 ///   varDecl(hasName("b")))))))
6504 ///   matches "int a[b]"
AST_MATCHER_P(VariableArrayType,hasSizeExpr,internal::Matcher<Expr>,InnerMatcher)6505 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
6506               internal::Matcher<Expr>, InnerMatcher) {
6507   return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
6508 }
6509 
6510 /// Matches atomic types.
6511 ///
6512 /// Given
6513 /// \code
6514 ///   _Atomic(int) i;
6515 /// \endcode
6516 /// atomicType()
6517 ///   matches "_Atomic(int) i"
6518 extern const AstTypeMatcher<AtomicType> atomicType;
6519 
6520 /// Matches atomic types with a specific value type.
6521 ///
6522 /// Given
6523 /// \code
6524 ///   _Atomic(int) i;
6525 ///   _Atomic(float) f;
6526 /// \endcode
6527 /// atomicType(hasValueType(isInteger()))
6528 ///  matches "_Atomic(int) i"
6529 ///
6530 /// Usable as: Matcher<AtomicType>
6531 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
6532                                   AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
6533 
6534 /// Matches types nodes representing C++11 auto types.
6535 ///
6536 /// Given:
6537 /// \code
6538 ///   auto n = 4;
6539 ///   int v[] = { 2, 3 }
6540 ///   for (auto i : v) { }
6541 /// \endcode
6542 /// autoType()
6543 ///   matches "auto n" and "auto i"
6544 extern const AstTypeMatcher<AutoType> autoType;
6545 
6546 /// Matches types nodes representing C++11 decltype(<expr>) types.
6547 ///
6548 /// Given:
6549 /// \code
6550 ///   short i = 1;
6551 ///   int j = 42;
6552 ///   decltype(i + j) result = i + j;
6553 /// \endcode
6554 /// decltypeType()
6555 ///   matches "decltype(i + j)"
6556 extern const AstTypeMatcher<DecltypeType> decltypeType;
6557 
6558 /// Matches \c AutoType nodes where the deduced type is a specific type.
6559 ///
6560 /// Note: There is no \c TypeLoc for the deduced type and thus no
6561 /// \c getDeducedLoc() matcher.
6562 ///
6563 /// Given
6564 /// \code
6565 ///   auto a = 1;
6566 ///   auto b = 2.0;
6567 /// \endcode
6568 /// autoType(hasDeducedType(isInteger()))
6569 ///   matches "auto a"
6570 ///
6571 /// Usable as: Matcher<AutoType>
6572 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
6573                           AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
6574 
6575 /// Matches \c DecltypeType nodes to find out the underlying type.
6576 ///
6577 /// Given
6578 /// \code
6579 ///   decltype(1) a = 1;
6580 ///   decltype(2.0) b = 2.0;
6581 /// \endcode
6582 /// decltypeType(hasUnderlyingType(isInteger()))
6583 ///   matches the type of "a"
6584 ///
6585 /// Usable as: Matcher<DecltypeType>
6586 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
6587                           AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
6588 
6589 /// Matches \c FunctionType nodes.
6590 ///
6591 /// Given
6592 /// \code
6593 ///   int (*f)(int);
6594 ///   void g();
6595 /// \endcode
6596 /// functionType()
6597 ///   matches "int (*f)(int)" and the type of "g".
6598 extern const AstTypeMatcher<FunctionType> functionType;
6599 
6600 /// Matches \c FunctionProtoType nodes.
6601 ///
6602 /// Given
6603 /// \code
6604 ///   int (*f)(int);
6605 ///   void g();
6606 /// \endcode
6607 /// functionProtoType()
6608 ///   matches "int (*f)(int)" and the type of "g" in C++ mode.
6609 ///   In C mode, "g" is not matched because it does not contain a prototype.
6610 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
6611 
6612 /// Matches \c ParenType nodes.
6613 ///
6614 /// Given
6615 /// \code
6616 ///   int (*ptr_to_array)[4];
6617 ///   int *array_of_ptrs[4];
6618 /// \endcode
6619 ///
6620 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
6621 /// \c array_of_ptrs.
6622 extern const AstTypeMatcher<ParenType> parenType;
6623 
6624 /// Matches \c ParenType nodes where the inner type is a specific type.
6625 ///
6626 /// Given
6627 /// \code
6628 ///   int (*ptr_to_array)[4];
6629 ///   int (*ptr_to_func)(int);
6630 /// \endcode
6631 ///
6632 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
6633 /// \c ptr_to_func but not \c ptr_to_array.
6634 ///
6635 /// Usable as: Matcher<ParenType>
6636 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
6637                           AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
6638 
6639 /// Matches block pointer types, i.e. types syntactically represented as
6640 /// "void (^)(int)".
6641 ///
6642 /// The \c pointee is always required to be a \c FunctionType.
6643 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
6644 
6645 /// Matches member pointer types.
6646 /// Given
6647 /// \code
6648 ///   struct A { int i; }
6649 ///   A::* ptr = A::i;
6650 /// \endcode
6651 /// memberPointerType()
6652 ///   matches "A::* ptr"
6653 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
6654 
6655 /// Matches pointer types, but does not match Objective-C object pointer
6656 /// types.
6657 ///
6658 /// Given
6659 /// \code
6660 ///   int *a;
6661 ///   int &b = *a;
6662 ///   int c = 5;
6663 ///
6664 ///   @interface Foo
6665 ///   @end
6666 ///   Foo *f;
6667 /// \endcode
6668 /// pointerType()
6669 ///   matches "int *a", but does not match "Foo *f".
6670 extern const AstTypeMatcher<PointerType> pointerType;
6671 
6672 /// Matches an Objective-C object pointer type, which is different from
6673 /// a pointer type, despite being syntactically similar.
6674 ///
6675 /// Given
6676 /// \code
6677 ///   int *a;
6678 ///
6679 ///   @interface Foo
6680 ///   @end
6681 ///   Foo *f;
6682 /// \endcode
6683 /// pointerType()
6684 ///   matches "Foo *f", but does not match "int *a".
6685 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
6686 
6687 /// Matches both lvalue and rvalue reference types.
6688 ///
6689 /// Given
6690 /// \code
6691 ///   int *a;
6692 ///   int &b = *a;
6693 ///   int &&c = 1;
6694 ///   auto &d = b;
6695 ///   auto &&e = c;
6696 ///   auto &&f = 2;
6697 ///   int g = 5;
6698 /// \endcode
6699 ///
6700 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
6701 extern const AstTypeMatcher<ReferenceType> referenceType;
6702 
6703 /// Matches lvalue reference types.
6704 ///
6705 /// Given:
6706 /// \code
6707 ///   int *a;
6708 ///   int &b = *a;
6709 ///   int &&c = 1;
6710 ///   auto &d = b;
6711 ///   auto &&e = c;
6712 ///   auto &&f = 2;
6713 ///   int g = 5;
6714 /// \endcode
6715 ///
6716 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
6717 /// matched since the type is deduced as int& by reference collapsing rules.
6718 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
6719 
6720 /// Matches rvalue reference types.
6721 ///
6722 /// Given:
6723 /// \code
6724 ///   int *a;
6725 ///   int &b = *a;
6726 ///   int &&c = 1;
6727 ///   auto &d = b;
6728 ///   auto &&e = c;
6729 ///   auto &&f = 2;
6730 ///   int g = 5;
6731 /// \endcode
6732 ///
6733 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
6734 /// matched as it is deduced to int& by reference collapsing rules.
6735 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
6736 
6737 /// Narrows PointerType (and similar) matchers to those where the
6738 /// \c pointee matches a given matcher.
6739 ///
6740 /// Given
6741 /// \code
6742 ///   int *a;
6743 ///   int const *b;
6744 ///   float const *f;
6745 /// \endcode
6746 /// pointerType(pointee(isConstQualified(), isInteger()))
6747 ///   matches "int const *b"
6748 ///
6749 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
6750 ///   Matcher<PointerType>, Matcher<ReferenceType>
6751 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
6752     pointee, getPointee,
6753     AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
6754                                     PointerType, ReferenceType));
6755 
6756 /// Matches typedef types.
6757 ///
6758 /// Given
6759 /// \code
6760 ///   typedef int X;
6761 /// \endcode
6762 /// typedefType()
6763 ///   matches "typedef int X"
6764 extern const AstTypeMatcher<TypedefType> typedefType;
6765 
6766 /// Matches enum types.
6767 ///
6768 /// Given
6769 /// \code
6770 ///   enum C { Green };
6771 ///   enum class S { Red };
6772 ///
6773 ///   C c;
6774 ///   S s;
6775 /// \endcode
6776 //
6777 /// \c enumType() matches the type of the variable declarations of both \c c and
6778 /// \c s.
6779 extern const AstTypeMatcher<EnumType> enumType;
6780 
6781 /// Matches template specialization types.
6782 ///
6783 /// Given
6784 /// \code
6785 ///   template <typename T>
6786 ///   class C { };
6787 ///
6788 ///   template class C<int>;  // A
6789 ///   C<char> var;            // B
6790 /// \endcode
6791 ///
6792 /// \c templateSpecializationType() matches the type of the explicit
6793 /// instantiation in \c A and the type of the variable declaration in \c B.
6794 extern const AstTypeMatcher<TemplateSpecializationType>
6795     templateSpecializationType;
6796 
6797 /// Matches C++17 deduced template specialization types, e.g. deduced class
6798 /// template types.
6799 ///
6800 /// Given
6801 /// \code
6802 ///   template <typename T>
6803 ///   class C { public: C(T); };
6804 ///
6805 ///   C c(123);
6806 /// \endcode
6807 /// \c deducedTemplateSpecializationType() matches the type in the declaration
6808 /// of the variable \c c.
6809 extern const AstTypeMatcher<DeducedTemplateSpecializationType>
6810     deducedTemplateSpecializationType;
6811 
6812 /// Matches types nodes representing unary type transformations.
6813 ///
6814 /// Given:
6815 /// \code
6816 ///   typedef __underlying_type(T) type;
6817 /// \endcode
6818 /// unaryTransformType()
6819 ///   matches "__underlying_type(T)"
6820 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
6821 
6822 /// Matches record types (e.g. structs, classes).
6823 ///
6824 /// Given
6825 /// \code
6826 ///   class C {};
6827 ///   struct S {};
6828 ///
6829 ///   C c;
6830 ///   S s;
6831 /// \endcode
6832 ///
6833 /// \c recordType() matches the type of the variable declarations of both \c c
6834 /// and \c s.
6835 extern const AstTypeMatcher<RecordType> recordType;
6836 
6837 /// Matches tag types (record and enum types).
6838 ///
6839 /// Given
6840 /// \code
6841 ///   enum E {};
6842 ///   class C {};
6843 ///
6844 ///   E e;
6845 ///   C c;
6846 /// \endcode
6847 ///
6848 /// \c tagType() matches the type of the variable declarations of both \c e
6849 /// and \c c.
6850 extern const AstTypeMatcher<TagType> tagType;
6851 
6852 /// Matches types specified with an elaborated type keyword or with a
6853 /// qualified name.
6854 ///
6855 /// Given
6856 /// \code
6857 ///   namespace N {
6858 ///     namespace M {
6859 ///       class D {};
6860 ///     }
6861 ///   }
6862 ///   class C {};
6863 ///
6864 ///   class C c;
6865 ///   N::M::D d;
6866 /// \endcode
6867 ///
6868 /// \c elaboratedType() matches the type of the variable declarations of both
6869 /// \c c and \c d.
6870 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
6871 
6872 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
6873 /// matches \c InnerMatcher if the qualifier exists.
6874 ///
6875 /// Given
6876 /// \code
6877 ///   namespace N {
6878 ///     namespace M {
6879 ///       class D {};
6880 ///     }
6881 ///   }
6882 ///   N::M::D d;
6883 /// \endcode
6884 ///
6885 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
6886 /// matches the type of the variable declaration of \c d.
AST_MATCHER_P(ElaboratedType,hasQualifier,internal::Matcher<NestedNameSpecifier>,InnerMatcher)6887 AST_MATCHER_P(ElaboratedType, hasQualifier,
6888               internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
6889   if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
6890     return InnerMatcher.matches(*Qualifier, Finder, Builder);
6891 
6892   return false;
6893 }
6894 
6895 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
6896 ///
6897 /// Given
6898 /// \code
6899 ///   namespace N {
6900 ///     namespace M {
6901 ///       class D {};
6902 ///     }
6903 ///   }
6904 ///   N::M::D d;
6905 /// \endcode
6906 ///
6907 /// \c elaboratedType(namesType(recordType(
6908 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
6909 /// declaration of \c d.
AST_MATCHER_P(ElaboratedType,namesType,internal::Matcher<QualType>,InnerMatcher)6910 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
6911               InnerMatcher) {
6912   return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
6913 }
6914 
6915 /// Matches types that represent the result of substituting a type for a
6916 /// template type parameter.
6917 ///
6918 /// Given
6919 /// \code
6920 ///   template <typename T>
6921 ///   void F(T t) {
6922 ///     int i = 1 + t;
6923 ///   }
6924 /// \endcode
6925 ///
6926 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
6927 extern const AstTypeMatcher<SubstTemplateTypeParmType>
6928     substTemplateTypeParmType;
6929 
6930 /// Matches template type parameter substitutions that have a replacement
6931 /// type that matches the provided matcher.
6932 ///
6933 /// Given
6934 /// \code
6935 ///   template <typename T>
6936 ///   double F(T t);
6937 ///   int i;
6938 ///   double j = F(i);
6939 /// \endcode
6940 ///
6941 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
6942 AST_TYPE_TRAVERSE_MATCHER(
6943     hasReplacementType, getReplacementType,
6944     AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
6945 
6946 /// Matches template type parameter types.
6947 ///
6948 /// Example matches T, but not int.
6949 ///     (matcher = templateTypeParmType())
6950 /// \code
6951 ///   template <typename T> void f(int i);
6952 /// \endcode
6953 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
6954 
6955 /// Matches injected class name types.
6956 ///
6957 /// Example matches S s, but not S<T> s.
6958 ///     (matcher = parmVarDecl(hasType(injectedClassNameType())))
6959 /// \code
6960 ///   template <typename T> struct S {
6961 ///     void f(S s);
6962 ///     void g(S<T> s);
6963 ///   };
6964 /// \endcode
6965 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
6966 
6967 /// Matches decayed type
6968 /// Example matches i[] in declaration of f.
6969 ///     (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
6970 /// Example matches i[1].
6971 ///     (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
6972 /// \code
6973 ///   void f(int i[]) {
6974 ///     i[1] = 0;
6975 ///   }
6976 /// \endcode
6977 extern const AstTypeMatcher<DecayedType> decayedType;
6978 
6979 /// Matches the decayed type, whoes decayed type matches \c InnerMatcher
AST_MATCHER_P(DecayedType,hasDecayedType,internal::Matcher<QualType>,InnerType)6980 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
6981               InnerType) {
6982   return InnerType.matches(Node.getDecayedType(), Finder, Builder);
6983 }
6984 
6985 /// Matches declarations whose declaration context, interpreted as a
6986 /// Decl, matches \c InnerMatcher.
6987 ///
6988 /// Given
6989 /// \code
6990 ///   namespace N {
6991 ///     namespace M {
6992 ///       class D {};
6993 ///     }
6994 ///   }
6995 /// \endcode
6996 ///
6997 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
6998 /// declaration of \c class \c D.
AST_MATCHER_P(Decl,hasDeclContext,internal::Matcher<Decl>,InnerMatcher)6999 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
7000   const DeclContext *DC = Node.getDeclContext();
7001   if (!DC) return false;
7002   return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
7003 }
7004 
7005 /// Matches nested name specifiers.
7006 ///
7007 /// Given
7008 /// \code
7009 ///   namespace ns {
7010 ///     struct A { static void f(); };
7011 ///     void A::f() {}
7012 ///     void g() { A::f(); }
7013 ///   }
7014 ///   ns::A a;
7015 /// \endcode
7016 /// nestedNameSpecifier()
7017 ///   matches "ns::" and both "A::"
7018 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
7019     nestedNameSpecifier;
7020 
7021 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
7022 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
7023     nestedNameSpecifierLoc;
7024 
7025 /// Matches \c NestedNameSpecifierLocs for which the given inner
7026 /// NestedNameSpecifier-matcher matches.
7027 AST_MATCHER_FUNCTION_P_OVERLOAD(
7028     internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
7029     internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
7030   return internal::BindableMatcher<NestedNameSpecifierLoc>(
7031       new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
7032           InnerMatcher));
7033 }
7034 
7035 /// Matches nested name specifiers that specify a type matching the
7036 /// given \c QualType matcher without qualifiers.
7037 ///
7038 /// Given
7039 /// \code
7040 ///   struct A { struct B { struct C {}; }; };
7041 ///   A::B::C c;
7042 /// \endcode
7043 /// nestedNameSpecifier(specifiesType(
7044 ///   hasDeclaration(cxxRecordDecl(hasName("A")))
7045 /// ))
7046 ///   matches "A::"
AST_MATCHER_P(NestedNameSpecifier,specifiesType,internal::Matcher<QualType>,InnerMatcher)7047 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
7048               internal::Matcher<QualType>, InnerMatcher) {
7049   if (!Node.getAsType())
7050     return false;
7051   return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
7052 }
7053 
7054 /// Matches nested name specifier locs that specify a type matching the
7055 /// given \c TypeLoc.
7056 ///
7057 /// Given
7058 /// \code
7059 ///   struct A { struct B { struct C {}; }; };
7060 ///   A::B::C c;
7061 /// \endcode
7062 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
7063 ///   hasDeclaration(cxxRecordDecl(hasName("A")))))))
7064 ///   matches "A::"
AST_MATCHER_P(NestedNameSpecifierLoc,specifiesTypeLoc,internal::Matcher<TypeLoc>,InnerMatcher)7065 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
7066               internal::Matcher<TypeLoc>, InnerMatcher) {
7067   return Node && Node.getNestedNameSpecifier()->getAsType() &&
7068          InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
7069 }
7070 
7071 /// Matches on the prefix of a \c NestedNameSpecifier.
7072 ///
7073 /// Given
7074 /// \code
7075 ///   struct A { struct B { struct C {}; }; };
7076 ///   A::B::C c;
7077 /// \endcode
7078 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
7079 ///   matches "A::"
7080 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
7081                        internal::Matcher<NestedNameSpecifier>, InnerMatcher,
7082                        0) {
7083   const NestedNameSpecifier *NextNode = Node.getPrefix();
7084   if (!NextNode)
7085     return false;
7086   return InnerMatcher.matches(*NextNode, Finder, Builder);
7087 }
7088 
7089 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
7090 ///
7091 /// Given
7092 /// \code
7093 ///   struct A { struct B { struct C {}; }; };
7094 ///   A::B::C c;
7095 /// \endcode
7096 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
7097 ///   matches "A::"
7098 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
7099                        internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
7100                        1) {
7101   NestedNameSpecifierLoc NextNode = Node.getPrefix();
7102   if (!NextNode)
7103     return false;
7104   return InnerMatcher.matches(NextNode, Finder, Builder);
7105 }
7106 
7107 /// Matches nested name specifiers that specify a namespace matching the
7108 /// given namespace matcher.
7109 ///
7110 /// Given
7111 /// \code
7112 ///   namespace ns { struct A {}; }
7113 ///   ns::A a;
7114 /// \endcode
7115 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
7116 ///   matches "ns::"
AST_MATCHER_P(NestedNameSpecifier,specifiesNamespace,internal::Matcher<NamespaceDecl>,InnerMatcher)7117 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
7118               internal::Matcher<NamespaceDecl>, InnerMatcher) {
7119   if (!Node.getAsNamespace())
7120     return false;
7121   return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
7122 }
7123 
7124 /// Overloads for the \c equalsNode matcher.
7125 /// FIXME: Implement for other node types.
7126 /// @{
7127 
7128 /// Matches if a node equals another node.
7129 ///
7130 /// \c Decl has pointer identity in the AST.
7131 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
7132   return &Node == Other;
7133 }
7134 /// Matches if a node equals another node.
7135 ///
7136 /// \c Stmt has pointer identity in the AST.
7137 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
7138   return &Node == Other;
7139 }
7140 /// Matches if a node equals another node.
7141 ///
7142 /// \c Type has pointer identity in the AST.
7143 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
7144     return &Node == Other;
7145 }
7146 
7147 /// @}
7148 
7149 /// Matches each case or default statement belonging to the given switch
7150 /// statement. This matcher may produce multiple matches.
7151 ///
7152 /// Given
7153 /// \code
7154 ///   switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
7155 /// \endcode
7156 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
7157 ///   matches four times, with "c" binding each of "case 1:", "case 2:",
7158 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
7159 /// "switch (1)", "switch (2)" and "switch (2)".
AST_MATCHER_P(SwitchStmt,forEachSwitchCase,internal::Matcher<SwitchCase>,InnerMatcher)7160 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
7161               InnerMatcher) {
7162   BoundNodesTreeBuilder Result;
7163   // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
7164   // iteration order. We should use the more general iterating matchers once
7165   // they are capable of expressing this matcher (for example, it should ignore
7166   // case statements belonging to nested switch statements).
7167   bool Matched = false;
7168   for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
7169        SC = SC->getNextSwitchCase()) {
7170     BoundNodesTreeBuilder CaseBuilder(*Builder);
7171     bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
7172     if (CaseMatched) {
7173       Matched = true;
7174       Result.addMatch(CaseBuilder);
7175     }
7176   }
7177   *Builder = std::move(Result);
7178   return Matched;
7179 }
7180 
7181 /// Matches each constructor initializer in a constructor definition.
7182 ///
7183 /// Given
7184 /// \code
7185 ///   class A { A() : i(42), j(42) {} int i; int j; };
7186 /// \endcode
7187 /// cxxConstructorDecl(forEachConstructorInitializer(
7188 ///   forField(decl().bind("x"))
7189 /// ))
7190 ///   will trigger two matches, binding for 'i' and 'j' respectively.
AST_MATCHER_P(CXXConstructorDecl,forEachConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)7191 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
7192               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
7193   BoundNodesTreeBuilder Result;
7194   bool Matched = false;
7195   for (const auto *I : Node.inits()) {
7196     if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
7197       continue;
7198     BoundNodesTreeBuilder InitBuilder(*Builder);
7199     if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
7200       Matched = true;
7201       Result.addMatch(InitBuilder);
7202     }
7203   }
7204   *Builder = std::move(Result);
7205   return Matched;
7206 }
7207 
7208 /// Matches constructor declarations that are copy constructors.
7209 ///
7210 /// Given
7211 /// \code
7212 ///   struct S {
7213 ///     S(); // #1
7214 ///     S(const S &); // #2
7215 ///     S(S &&); // #3
7216 ///   };
7217 /// \endcode
7218 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
AST_MATCHER(CXXConstructorDecl,isCopyConstructor)7219 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
7220   return Node.isCopyConstructor();
7221 }
7222 
7223 /// Matches constructor declarations that are move constructors.
7224 ///
7225 /// Given
7226 /// \code
7227 ///   struct S {
7228 ///     S(); // #1
7229 ///     S(const S &); // #2
7230 ///     S(S &&); // #3
7231 ///   };
7232 /// \endcode
7233 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
AST_MATCHER(CXXConstructorDecl,isMoveConstructor)7234 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
7235   return Node.isMoveConstructor();
7236 }
7237 
7238 /// Matches constructor declarations that are default constructors.
7239 ///
7240 /// Given
7241 /// \code
7242 ///   struct S {
7243 ///     S(); // #1
7244 ///     S(const S &); // #2
7245 ///     S(S &&); // #3
7246 ///   };
7247 /// \endcode
7248 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
AST_MATCHER(CXXConstructorDecl,isDefaultConstructor)7249 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
7250   return Node.isDefaultConstructor();
7251 }
7252 
7253 /// Matches constructors that delegate to another constructor.
7254 ///
7255 /// Given
7256 /// \code
7257 ///   struct S {
7258 ///     S(); // #1
7259 ///     S(int) {} // #2
7260 ///     S(S &&) : S() {} // #3
7261 ///   };
7262 ///   S::S() : S(0) {} // #4
7263 /// \endcode
7264 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
7265 /// #1 or #2.
AST_MATCHER(CXXConstructorDecl,isDelegatingConstructor)7266 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
7267   return Node.isDelegatingConstructor();
7268 }
7269 
7270 /// Matches constructor, conversion function, and deduction guide declarations
7271 /// that have an explicit specifier if this explicit specifier is resolved to
7272 /// true.
7273 ///
7274 /// Given
7275 /// \code
7276 ///   template<bool b>
7277 ///   struct S {
7278 ///     S(int); // #1
7279 ///     explicit S(double); // #2
7280 ///     operator int(); // #3
7281 ///     explicit operator bool(); // #4
7282 ///     explicit(false) S(bool) // # 7
7283 ///     explicit(true) S(char) // # 8
7284 ///     explicit(b) S(S) // # 9
7285 ///   };
7286 ///   S(int) -> S<true> // #5
7287 ///   explicit S(double) -> S<false> // #6
7288 /// \endcode
7289 /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
7290 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
7291 /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
AST_POLYMORPHIC_MATCHER(isExplicit,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXConstructorDecl,CXXConversionDecl,CXXDeductionGuideDecl))7292 AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
7293                                         CXXConstructorDecl, CXXConversionDecl,
7294                                         CXXDeductionGuideDecl)) {
7295   return Node.isExplicit();
7296 }
7297 
7298 /// Matches the expression in an explicit specifier if present in the given
7299 /// declaration.
7300 ///
7301 /// Given
7302 /// \code
7303 ///   template<bool b>
7304 ///   struct S {
7305 ///     S(int); // #1
7306 ///     explicit S(double); // #2
7307 ///     operator int(); // #3
7308 ///     explicit operator bool(); // #4
7309 ///     explicit(false) S(bool) // # 7
7310 ///     explicit(true) S(char) // # 8
7311 ///     explicit(b) S(S) // # 9
7312 ///   };
7313 ///   S(int) -> S<true> // #5
7314 ///   explicit S(double) -> S<false> // #6
7315 /// \endcode
7316 /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
7317 /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
7318 /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
AST_MATCHER_P(FunctionDecl,hasExplicitSpecifier,internal::Matcher<Expr>,InnerMatcher)7319 AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
7320               InnerMatcher) {
7321   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
7322   if (!ES.getExpr())
7323     return false;
7324 
7325   ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
7326 
7327   return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
7328 }
7329 
7330 /// Matches function and namespace declarations that are marked with
7331 /// the inline keyword.
7332 ///
7333 /// Given
7334 /// \code
7335 ///   inline void f();
7336 ///   void g();
7337 ///   namespace n {
7338 ///   inline namespace m {}
7339 ///   }
7340 /// \endcode
7341 /// functionDecl(isInline()) will match ::f().
7342 /// namespaceDecl(isInline()) will match n::m.
AST_POLYMORPHIC_MATCHER(isInline,AST_POLYMORPHIC_SUPPORTED_TYPES (NamespaceDecl,FunctionDecl))7343 AST_POLYMORPHIC_MATCHER(isInline,
7344                         AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
7345                                                         FunctionDecl)) {
7346   // This is required because the spelling of the function used to determine
7347   // whether inline is specified or not differs between the polymorphic types.
7348   if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
7349     return FD->isInlineSpecified();
7350   else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
7351     return NSD->isInline();
7352   llvm_unreachable("Not a valid polymorphic type");
7353 }
7354 
7355 /// Matches anonymous namespace declarations.
7356 ///
7357 /// Given
7358 /// \code
7359 ///   namespace n {
7360 ///   namespace {} // #1
7361 ///   }
7362 /// \endcode
7363 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
AST_MATCHER(NamespaceDecl,isAnonymous)7364 AST_MATCHER(NamespaceDecl, isAnonymous) {
7365   return Node.isAnonymousNamespace();
7366 }
7367 
7368 /// Matches declarations in the namespace `std`, but not in nested namespaces.
7369 ///
7370 /// Given
7371 /// \code
7372 ///   class vector {};
7373 ///   namespace foo {
7374 ///     class vector {};
7375 ///     namespace std {
7376 ///       class vector {};
7377 ///     }
7378 ///   }
7379 ///   namespace std {
7380 ///     inline namespace __1 {
7381 ///       class vector {}; // #1
7382 ///       namespace experimental {
7383 ///         class vector {};
7384 ///       }
7385 ///     }
7386 ///   }
7387 /// \endcode
7388 /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
AST_MATCHER(Decl,isInStdNamespace)7389 AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
7390 
7391 /// If the given case statement does not use the GNU case range
7392 /// extension, matches the constant given in the statement.
7393 ///
7394 /// Given
7395 /// \code
7396 ///   switch (1) { case 1: case 1+1: case 3 ... 4: ; }
7397 /// \endcode
7398 /// caseStmt(hasCaseConstant(integerLiteral()))
7399 ///   matches "case 1:"
AST_MATCHER_P(CaseStmt,hasCaseConstant,internal::Matcher<Expr>,InnerMatcher)7400 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
7401               InnerMatcher) {
7402   if (Node.getRHS())
7403     return false;
7404 
7405   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
7406 }
7407 
7408 /// Matches declaration that has a given attribute.
7409 ///
7410 /// Given
7411 /// \code
7412 ///   __attribute__((device)) void f() { ... }
7413 /// \endcode
7414 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
7415 /// f. If the matcher is used from clang-query, attr::Kind parameter should be
7416 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
AST_MATCHER_P(Decl,hasAttr,attr::Kind,AttrKind)7417 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
7418   for (const auto *Attr : Node.attrs()) {
7419     if (Attr->getKind() == AttrKind)
7420       return true;
7421   }
7422   return false;
7423 }
7424 
7425 /// Matches the return value expression of a return statement
7426 ///
7427 /// Given
7428 /// \code
7429 ///   return a + b;
7430 /// \endcode
7431 /// hasReturnValue(binaryOperator())
7432 ///   matches 'return a + b'
7433 /// with binaryOperator()
7434 ///   matching 'a + b'
AST_MATCHER_P(ReturnStmt,hasReturnValue,internal::Matcher<Expr>,InnerMatcher)7435 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
7436               InnerMatcher) {
7437   if (const auto *RetValue = Node.getRetValue())
7438     return InnerMatcher.matches(*RetValue, Finder, Builder);
7439   return false;
7440 }
7441 
7442 /// Matches CUDA kernel call expression.
7443 ///
7444 /// Example matches,
7445 /// \code
7446 ///   kernel<<<i,j>>>();
7447 /// \endcode
7448 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
7449     cudaKernelCallExpr;
7450 
7451 /// Matches expressions that resolve to a null pointer constant, such as
7452 /// GNU's __null, C++11's nullptr, or C's NULL macro.
7453 ///
7454 /// Given:
7455 /// \code
7456 ///   void *v1 = NULL;
7457 ///   void *v2 = nullptr;
7458 ///   void *v3 = __null; // GNU extension
7459 ///   char *cp = (char *)0;
7460 ///   int *ip = 0;
7461 ///   int i = 0;
7462 /// \endcode
7463 /// expr(nullPointerConstant())
7464 ///   matches the initializer for v1, v2, v3, cp, and ip. Does not match the
7465 ///   initializer for i.
AST_MATCHER_FUNCTION(internal::Matcher<Expr>,nullPointerConstant)7466 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
7467   return anyOf(
7468       gnuNullExpr(), cxxNullPtrLiteralExpr(),
7469       integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
7470 }
7471 
7472 /// Matches the DecompositionDecl the binding belongs to.
7473 ///
7474 /// For example, in:
7475 /// \code
7476 /// void foo()
7477 /// {
7478 ///     int arr[3];
7479 ///     auto &[f, s, t] = arr;
7480 ///
7481 ///     f = 42;
7482 /// }
7483 /// \endcode
7484 /// The matcher:
7485 /// \code
7486 ///   bindingDecl(hasName("f"),
7487 ///                 forDecomposition(decompositionDecl())
7488 /// \endcode
7489 /// matches 'f' in 'auto &[f, s, t]'.
AST_MATCHER_P(BindingDecl,forDecomposition,internal::Matcher<ValueDecl>,InnerMatcher)7490 AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>,
7491               InnerMatcher) {
7492   if (const ValueDecl *VD = Node.getDecomposedDecl())
7493     return InnerMatcher.matches(*VD, Finder, Builder);
7494   return false;
7495 }
7496 
7497 /// Matches the Nth binding of a DecompositionDecl.
7498 ///
7499 /// For example, in:
7500 /// \code
7501 /// void foo()
7502 /// {
7503 ///     int arr[3];
7504 ///     auto &[f, s, t] = arr;
7505 ///
7506 ///     f = 42;
7507 /// }
7508 /// \endcode
7509 /// The matcher:
7510 /// \code
7511 ///   decompositionDecl(hasBinding(0,
7512 ///   bindingDecl(hasName("f").bind("fBinding"))))
7513 /// \endcode
7514 /// matches the decomposition decl with 'f' bound to "fBinding".
AST_MATCHER_P2(DecompositionDecl,hasBinding,unsigned,N,internal::Matcher<BindingDecl>,InnerMatcher)7515 AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N,
7516                internal::Matcher<BindingDecl>, InnerMatcher) {
7517   if (Node.bindings().size() <= N)
7518     return false;
7519   return InnerMatcher.matches(*Node.bindings()[N], Finder, Builder);
7520 }
7521 
7522 /// Matches any binding of a DecompositionDecl.
7523 ///
7524 /// For example, in:
7525 /// \code
7526 /// void foo()
7527 /// {
7528 ///     int arr[3];
7529 ///     auto &[f, s, t] = arr;
7530 ///
7531 ///     f = 42;
7532 /// }
7533 /// \endcode
7534 /// The matcher:
7535 /// \code
7536 ///   decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding"))))
7537 /// \endcode
7538 /// matches the decomposition decl with 'f' bound to "fBinding".
AST_MATCHER_P(DecompositionDecl,hasAnyBinding,internal::Matcher<BindingDecl>,InnerMatcher)7539 AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>,
7540               InnerMatcher) {
7541   return llvm::any_of(Node.bindings(), [&](const auto *Binding) {
7542     return InnerMatcher.matches(*Binding, Finder, Builder);
7543   });
7544 }
7545 
7546 /// Matches declaration of the function the statement belongs to.
7547 ///
7548 /// Deprecated. Use forCallable() to correctly handle the situation when
7549 /// the declaration is not a function (but a block or an Objective-C method).
7550 /// forFunction() not only fails to take non-functions into account but also
7551 /// may match the wrong declaration in their presence.
7552 ///
7553 /// Given:
7554 /// \code
7555 /// F& operator=(const F& o) {
7556 ///   std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
7557 ///   return *this;
7558 /// }
7559 /// \endcode
7560 /// returnStmt(forFunction(hasName("operator=")))
7561 ///   matches 'return *this'
7562 ///   but does not match 'return v > 0'
AST_MATCHER_P(Stmt,forFunction,internal::Matcher<FunctionDecl>,InnerMatcher)7563 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
7564               InnerMatcher) {
7565   const auto &Parents = Finder->getASTContext().getParents(Node);
7566 
7567   llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
7568   while (!Stack.empty()) {
7569     const auto &CurNode = Stack.back();
7570     Stack.pop_back();
7571     if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
7572       if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
7573         return true;
7574       }
7575     } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
7576       if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
7577                                Builder)) {
7578         return true;
7579       }
7580     } else {
7581       for (const auto &Parent : Finder->getASTContext().getParents(CurNode))
7582         Stack.push_back(Parent);
7583     }
7584   }
7585   return false;
7586 }
7587 
7588 /// Matches declaration of the function, method, or block the statement
7589 /// belongs to.
7590 ///
7591 /// Given:
7592 /// \code
7593 /// F& operator=(const F& o) {
7594 ///   std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
7595 ///   return *this;
7596 /// }
7597 /// \endcode
7598 /// returnStmt(forCallable(functionDecl(hasName("operator="))))
7599 ///   matches 'return *this'
7600 ///   but does not match 'return v > 0'
7601 ///
7602 /// Given:
7603 /// \code
7604 /// -(void) foo {
7605 ///   int x = 1;
7606 ///   dispatch_sync(queue, ^{ int y = 2; });
7607 /// }
7608 /// \endcode
7609 /// declStmt(forCallable(objcMethodDecl()))
7610 ///   matches 'int x = 1'
7611 ///   but does not match 'int y = 2'.
7612 /// whereas declStmt(forCallable(blockDecl()))
7613 ///   matches 'int y = 2'
7614 ///   but does not match 'int x = 1'.
AST_MATCHER_P(Stmt,forCallable,internal::Matcher<Decl>,InnerMatcher)7615 AST_MATCHER_P(Stmt, forCallable, internal::Matcher<Decl>, InnerMatcher) {
7616   const auto &Parents = Finder->getASTContext().getParents(Node);
7617 
7618   llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
7619   while (!Stack.empty()) {
7620     const auto &CurNode = Stack.back();
7621     Stack.pop_back();
7622     if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
7623       if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
7624         return true;
7625       }
7626     } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
7627       if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
7628                                Builder)) {
7629         return true;
7630       }
7631     } else if (const auto *ObjCMethodDeclNode = CurNode.get<ObjCMethodDecl>()) {
7632       if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, Builder)) {
7633         return true;
7634       }
7635     } else if (const auto *BlockDeclNode = CurNode.get<BlockDecl>()) {
7636       if (InnerMatcher.matches(*BlockDeclNode, Finder, Builder)) {
7637         return true;
7638       }
7639     } else {
7640       for (const auto &Parent : Finder->getASTContext().getParents(CurNode))
7641         Stack.push_back(Parent);
7642     }
7643   }
7644   return false;
7645 }
7646 
7647 /// Matches a declaration that has external formal linkage.
7648 ///
7649 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
7650 /// \code
7651 /// void f() {
7652 ///   int x;
7653 ///   static int y;
7654 /// }
7655 /// int z;
7656 /// \endcode
7657 ///
7658 /// Example matches f() because it has external formal linkage despite being
7659 /// unique to the translation unit as though it has internal likage
7660 /// (matcher = functionDecl(hasExternalFormalLinkage()))
7661 ///
7662 /// \code
7663 /// namespace {
7664 /// void f() {}
7665 /// }
7666 /// \endcode
AST_MATCHER(NamedDecl,hasExternalFormalLinkage)7667 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
7668   return Node.hasExternalFormalLinkage();
7669 }
7670 
7671 /// Matches a declaration that has default arguments.
7672 ///
7673 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
7674 /// \code
7675 /// void x(int val) {}
7676 /// void y(int val = 0) {}
7677 /// \endcode
7678 ///
7679 /// Deprecated. Use hasInitializer() instead to be able to
7680 /// match on the contents of the default argument.  For example:
7681 ///
7682 /// \code
7683 /// void x(int val = 7) {}
7684 /// void y(int val = 42) {}
7685 /// \endcode
7686 /// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
7687 ///   matches the parameter of y
7688 ///
7689 /// A matcher such as
7690 ///   parmVarDecl(hasInitializer(anything()))
7691 /// is equivalent to parmVarDecl(hasDefaultArgument()).
AST_MATCHER(ParmVarDecl,hasDefaultArgument)7692 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
7693   return Node.hasDefaultArg();
7694 }
7695 
7696 /// Matches array new expressions.
7697 ///
7698 /// Given:
7699 /// \code
7700 ///   MyClass *p1 = new MyClass[10];
7701 /// \endcode
7702 /// cxxNewExpr(isArray())
7703 ///   matches the expression 'new MyClass[10]'.
AST_MATCHER(CXXNewExpr,isArray)7704 AST_MATCHER(CXXNewExpr, isArray) {
7705   return Node.isArray();
7706 }
7707 
7708 /// Matches placement new expression arguments.
7709 ///
7710 /// Given:
7711 /// \code
7712 ///   MyClass *p1 = new (Storage, 16) MyClass();
7713 /// \endcode
7714 /// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
7715 ///   matches the expression 'new (Storage, 16) MyClass()'.
AST_MATCHER_P2(CXXNewExpr,hasPlacementArg,unsigned,Index,internal::Matcher<Expr>,InnerMatcher)7716 AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
7717                internal::Matcher<Expr>, InnerMatcher) {
7718   return Node.getNumPlacementArgs() > Index &&
7719          InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
7720 }
7721 
7722 /// Matches any placement new expression arguments.
7723 ///
7724 /// Given:
7725 /// \code
7726 ///   MyClass *p1 = new (Storage) MyClass();
7727 /// \endcode
7728 /// cxxNewExpr(hasAnyPlacementArg(anything()))
7729 ///   matches the expression 'new (Storage, 16) MyClass()'.
AST_MATCHER_P(CXXNewExpr,hasAnyPlacementArg,internal::Matcher<Expr>,InnerMatcher)7730 AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
7731               InnerMatcher) {
7732   return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
7733     return InnerMatcher.matches(*Arg, Finder, Builder);
7734   });
7735 }
7736 
7737 /// Matches array new expressions with a given array size.
7738 ///
7739 /// Given:
7740 /// \code
7741 ///   MyClass *p1 = new MyClass[10];
7742 /// \endcode
7743 /// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
7744 ///   matches the expression 'new MyClass[10]'.
AST_MATCHER_P(CXXNewExpr,hasArraySize,internal::Matcher<Expr>,InnerMatcher)7745 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
7746   return Node.isArray() && *Node.getArraySize() &&
7747          InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
7748 }
7749 
7750 /// Matches a class declaration that is defined.
7751 ///
7752 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
7753 /// \code
7754 /// class x {};
7755 /// class y;
7756 /// \endcode
AST_MATCHER(CXXRecordDecl,hasDefinition)7757 AST_MATCHER(CXXRecordDecl, hasDefinition) {
7758   return Node.hasDefinition();
7759 }
7760 
7761 /// Matches C++11 scoped enum declaration.
7762 ///
7763 /// Example matches Y (matcher = enumDecl(isScoped()))
7764 /// \code
7765 /// enum X {};
7766 /// enum class Y {};
7767 /// \endcode
AST_MATCHER(EnumDecl,isScoped)7768 AST_MATCHER(EnumDecl, isScoped) {
7769   return Node.isScoped();
7770 }
7771 
7772 /// Matches a function declared with a trailing return type.
7773 ///
7774 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
7775 /// \code
7776 /// int X() {}
7777 /// auto Y() -> int {}
7778 /// \endcode
AST_MATCHER(FunctionDecl,hasTrailingReturn)7779 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
7780   if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
7781     return F->hasTrailingReturn();
7782   return false;
7783 }
7784 
7785 /// Matches expressions that match InnerMatcher that are possibly wrapped in an
7786 /// elidable constructor and other corresponding bookkeeping nodes.
7787 ///
7788 /// In C++17, elidable copy constructors are no longer being generated in the
7789 /// AST as it is not permitted by the standard. They are, however, part of the
7790 /// AST in C++14 and earlier. So, a matcher must abstract over these differences
7791 /// to work in all language modes. This matcher skips elidable constructor-call
7792 /// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
7793 /// various implicit nodes inside the constructor calls, all of which will not
7794 /// appear in the C++17 AST.
7795 ///
7796 /// Given
7797 ///
7798 /// \code
7799 /// struct H {};
7800 /// H G();
7801 /// void f() {
7802 ///   H D = G();
7803 /// }
7804 /// \endcode
7805 ///
7806 /// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
7807 /// matches ``H D = G()`` in C++11 through C++17 (and beyond).
AST_MATCHER_P(Expr,ignoringElidableConstructorCall,ast_matchers::internal::Matcher<Expr>,InnerMatcher)7808 AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
7809               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
7810   // E tracks the node that we are examining.
7811   const Expr *E = &Node;
7812   // If present, remove an outer `ExprWithCleanups` corresponding to the
7813   // underlying `CXXConstructExpr`. This check won't cover all cases of added
7814   // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
7815   // EWC is placed on the outermost node of the expression, which this may not
7816   // be), but, it still improves the coverage of this matcher.
7817   if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
7818     E = CleanupsExpr->getSubExpr();
7819   if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
7820     if (CtorExpr->isElidable()) {
7821       if (const auto *MaterializeTemp =
7822               dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
7823         return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
7824                                     Builder);
7825       }
7826     }
7827   }
7828   return InnerMatcher.matches(Node, Finder, Builder);
7829 }
7830 
7831 //----------------------------------------------------------------------------//
7832 // OpenMP handling.
7833 //----------------------------------------------------------------------------//
7834 
7835 /// Matches any ``#pragma omp`` executable directive.
7836 ///
7837 /// Given
7838 ///
7839 /// \code
7840 ///   #pragma omp parallel
7841 ///   #pragma omp parallel default(none)
7842 ///   #pragma omp taskyield
7843 /// \endcode
7844 ///
7845 /// ``ompExecutableDirective()`` matches ``omp parallel``,
7846 /// ``omp parallel default(none)`` and ``omp taskyield``.
7847 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
7848     ompExecutableDirective;
7849 
7850 /// Matches standalone OpenMP directives,
7851 /// i.e., directives that can't have a structured block.
7852 ///
7853 /// Given
7854 ///
7855 /// \code
7856 ///   #pragma omp parallel
7857 ///   {}
7858 ///   #pragma omp taskyield
7859 /// \endcode
7860 ///
7861 /// ``ompExecutableDirective(isStandaloneDirective()))`` matches
7862 /// ``omp taskyield``.
AST_MATCHER(OMPExecutableDirective,isStandaloneDirective)7863 AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
7864   return Node.isStandaloneDirective();
7865 }
7866 
7867 /// Matches the structured-block of the OpenMP executable directive
7868 ///
7869 /// Prerequisite: the executable directive must not be standalone directive.
7870 /// If it is, it will never match.
7871 ///
7872 /// Given
7873 ///
7874 /// \code
7875 ///    #pragma omp parallel
7876 ///    ;
7877 ///    #pragma omp parallel
7878 ///    {}
7879 /// \endcode
7880 ///
7881 /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
AST_MATCHER_P(OMPExecutableDirective,hasStructuredBlock,internal::Matcher<Stmt>,InnerMatcher)7882 AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
7883               internal::Matcher<Stmt>, InnerMatcher) {
7884   if (Node.isStandaloneDirective())
7885     return false; // Standalone directives have no structured blocks.
7886   return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
7887 }
7888 
7889 /// Matches any clause in an OpenMP directive.
7890 ///
7891 /// Given
7892 ///
7893 /// \code
7894 ///   #pragma omp parallel
7895 ///   #pragma omp parallel default(none)
7896 /// \endcode
7897 ///
7898 /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
7899 /// ``omp parallel default(none)``.
AST_MATCHER_P(OMPExecutableDirective,hasAnyClause,internal::Matcher<OMPClause>,InnerMatcher)7900 AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
7901               internal::Matcher<OMPClause>, InnerMatcher) {
7902   ArrayRef<OMPClause *> Clauses = Node.clauses();
7903   return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
7904                                     Clauses.end(), Finder,
7905                                     Builder) != Clauses.end();
7906 }
7907 
7908 /// Matches OpenMP ``default`` clause.
7909 ///
7910 /// Given
7911 ///
7912 /// \code
7913 ///   #pragma omp parallel default(none)
7914 ///   #pragma omp parallel default(shared)
7915 ///   #pragma omp parallel default(firstprivate)
7916 ///   #pragma omp parallel
7917 /// \endcode
7918 ///
7919 /// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and
7920 /// ``default(firstprivate)``
7921 extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
7922     ompDefaultClause;
7923 
7924 /// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
7925 ///
7926 /// Given
7927 ///
7928 /// \code
7929 ///   #pragma omp parallel
7930 ///   #pragma omp parallel default(none)
7931 ///   #pragma omp parallel default(shared)
7932 ///   #pragma omp parallel default(firstprivate)
7933 /// \endcode
7934 ///
7935 /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
AST_MATCHER(OMPDefaultClause,isNoneKind)7936 AST_MATCHER(OMPDefaultClause, isNoneKind) {
7937   return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
7938 }
7939 
7940 /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
7941 ///
7942 /// Given
7943 ///
7944 /// \code
7945 ///   #pragma omp parallel
7946 ///   #pragma omp parallel default(none)
7947 ///   #pragma omp parallel default(shared)
7948 ///   #pragma omp parallel default(firstprivate)
7949 /// \endcode
7950 ///
7951 /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
AST_MATCHER(OMPDefaultClause,isSharedKind)7952 AST_MATCHER(OMPDefaultClause, isSharedKind) {
7953   return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
7954 }
7955 
7956 /// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
7957 /// specified.
7958 ///
7959 /// Given
7960 ///
7961 /// \code
7962 ///   #pragma omp parallel
7963 ///   #pragma omp parallel default(none)
7964 ///   #pragma omp parallel default(shared)
7965 ///   #pragma omp parallel default(firstprivate)
7966 /// \endcode
7967 ///
7968 /// ``ompDefaultClause(isFirstPrivateKind())`` matches only
7969 /// ``default(firstprivate)``.
AST_MATCHER(OMPDefaultClause,isFirstPrivateKind)7970 AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
7971   return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
7972 }
7973 
7974 /// Matches if the OpenMP directive is allowed to contain the specified OpenMP
7975 /// clause kind.
7976 ///
7977 /// Given
7978 ///
7979 /// \code
7980 ///   #pragma omp parallel
7981 ///   #pragma omp parallel for
7982 ///   #pragma omp          for
7983 /// \endcode
7984 ///
7985 /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
7986 /// ``omp parallel`` and ``omp parallel for``.
7987 ///
7988 /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
7989 /// should be passed as a quoted string. e.g.,
7990 /// ``isAllowedToContainClauseKind("OMPC_default").``
AST_MATCHER_P(OMPExecutableDirective,isAllowedToContainClauseKind,OpenMPClauseKind,CKind)7991 AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
7992               OpenMPClauseKind, CKind) {
7993   return llvm::omp::isAllowedClauseForDirective(
7994       Node.getDirectiveKind(), CKind,
7995       Finder->getASTContext().getLangOpts().OpenMP);
7996 }
7997 
7998 //----------------------------------------------------------------------------//
7999 // End OpenMP handling.
8000 //----------------------------------------------------------------------------//
8001 
8002 } // namespace ast_matchers
8003 } // namespace clang
8004 
8005 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
8006