clang  15.0.0git
ASTMatchers.h
Go to the documentation of this file.
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"
49 #include "clang/AST/Attr.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"
61 #include "clang/AST/OpenMPClause.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"
74 #include "clang/Basic/AttrKinds.h"
78 #include "clang/Basic/LLVM.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>
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.
124  const IDToNodeMap &getMap() const {
125  return MyBoundNodes.getMap();
126  }
127 
128 private:
130 
131  /// Create BoundNodes from a pre-filled map of bindings.
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 using LambdaCaptureMatcher = internal::Matcher<LambdaCapture>;
152 using AttrMatcher = internal::Matcher<Attr>;
153 /// @}
154 
155 /// Matches any node.
156 ///
157 /// Useful when another matcher requires a child matcher, but there's no
158 /// additional constraint. This will often be used with an explicit conversion
159 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
160 ///
161 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
162 /// \code
163 /// "int* p" and "void f()" in
164 /// int* p;
165 /// void f();
166 /// \endcode
167 ///
168 /// Usable as: Any Matcher
169 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
170 
171 /// Matches the top declaration context.
172 ///
173 /// Given
174 /// \code
175 /// int X;
176 /// namespace NS {
177 /// int Y;
178 /// } // namespace NS
179 /// \endcode
180 /// decl(hasDeclContext(translationUnitDecl()))
181 /// matches "int X", but not "int Y".
182 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
184 
185 /// Matches typedef declarations.
186 ///
187 /// Given
188 /// \code
189 /// typedef int X;
190 /// using Y = int;
191 /// \endcode
192 /// typedefDecl()
193 /// matches "typedef int X", but not "using Y = int"
194 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
195  typedefDecl;
196 
197 /// Matches typedef name declarations.
198 ///
199 /// Given
200 /// \code
201 /// typedef int X;
202 /// using Y = int;
203 /// \endcode
204 /// typedefNameDecl()
205 /// matches "typedef int X" and "using Y = int"
206 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
208 
209 /// Matches type alias declarations.
210 ///
211 /// Given
212 /// \code
213 /// typedef int X;
214 /// using Y = int;
215 /// \endcode
216 /// typeAliasDecl()
217 /// matches "using Y = int", but not "typedef int X"
218 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
220 
221 /// Matches type alias template declarations.
222 ///
223 /// typeAliasTemplateDecl() matches
224 /// \code
225 /// template <typename T>
226 /// using Y = X<T>;
227 /// \endcode
228 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
230 
231 /// Matches AST nodes that were expanded within the main-file.
232 ///
233 /// Example matches X but not Y
234 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
235 /// \code
236 /// #include <Y.h>
237 /// class X {};
238 /// \endcode
239 /// Y.h:
240 /// \code
241 /// class Y {};
242 /// \endcode
243 ///
244 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
245 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
247  auto &SourceManager = Finder->getASTContext().getSourceManager();
249  SourceManager.getExpansionLoc(Node.getBeginLoc()));
250 }
251 
252 /// Matches AST nodes that were expanded within system-header-files.
253 ///
254 /// Example matches Y but not X
255 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
256 /// \code
257 /// #include <SystemHeader.h>
258 /// class X {};
259 /// \endcode
260 /// SystemHeader.h:
261 /// \code
262 /// class Y {};
263 /// \endcode
264 ///
265 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
266 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
268  auto &SourceManager = Finder->getASTContext().getSourceManager();
269  auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
270  if (ExpansionLoc.isInvalid()) {
271  return false;
272  }
273  return SourceManager.isInSystemHeader(ExpansionLoc);
274 }
275 
276 /// Matches AST nodes that were expanded within files whose name is
277 /// partially matching a given regex.
278 ///
279 /// Example matches Y but not X
280 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
281 /// \code
282 /// #include "ASTMatcher.h"
283 /// class X {};
284 /// \endcode
285 /// ASTMatcher.h:
286 /// \code
287 /// class Y {};
288 /// \endcode
289 ///
290 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
291 AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
293  TypeLoc),
294  RegExp) {
295  auto &SourceManager = Finder->getASTContext().getSourceManager();
296  auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
297  if (ExpansionLoc.isInvalid()) {
298  return false;
299  }
300  auto FileEntry =
302  if (!FileEntry) {
303  return false;
304  }
305 
306  auto Filename = FileEntry->getName();
307  return RegExp->match(Filename);
308 }
309 
310 /// Matches statements that are (transitively) expanded from the named macro.
311 /// Does not match if only part of the statement is expanded from that macro or
312 /// if different parts of the statement are expanded from different
313 /// appearances of the macro.
314 AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
316  std::string, MacroName) {
317  // Verifies that the statement' beginning and ending are both expanded from
318  // the same instance of the given macro.
319  auto& Context = Finder->getASTContext();
321  internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
322  if (!B) return false;
324  internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
325  if (!E) return false;
326  return *B == *E;
327 }
328 
329 /// Matches declarations.
330 ///
331 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
332 /// \code
333 /// void X();
334 /// class C {
335 /// friend X;
336 /// };
337 /// \endcode
338 extern const internal::VariadicAllOfMatcher<Decl> decl;
339 
340 /// Matches decomposition-declarations.
341 ///
342 /// Examples matches the declaration node with \c foo and \c bar, but not
343 /// \c number.
344 /// (matcher = declStmt(has(decompositionDecl())))
345 ///
346 /// \code
347 /// int number = 42;
348 /// auto [foo, bar] = std::make_pair{42, 42};
349 /// \endcode
350 extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl>
352 
353 /// Matches binding declarations
354 /// Example matches \c foo and \c bar
355 /// (matcher = bindingDecl()
356 ///
357 /// \code
358 /// auto [foo, bar] = std::make_pair{42, 42};
359 /// \endcode
360 extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl>
361  bindingDecl;
362 
363 /// Matches a declaration of a linkage specification.
364 ///
365 /// Given
366 /// \code
367 /// extern "C" {}
368 /// \endcode
369 /// linkageSpecDecl()
370 /// matches "extern "C" {}"
371 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
373 
374 /// Matches a declaration of anything that could have a name.
375 ///
376 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
377 /// \code
378 /// typedef int X;
379 /// struct S {
380 /// union {
381 /// int i;
382 /// } U;
383 /// };
384 /// \endcode
385 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
386 
387 /// Matches a declaration of label.
388 ///
389 /// Given
390 /// \code
391 /// goto FOO;
392 /// FOO: bar();
393 /// \endcode
394 /// labelDecl()
395 /// matches 'FOO:'
396 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
397 
398 /// Matches a declaration of a namespace.
399 ///
400 /// Given
401 /// \code
402 /// namespace {}
403 /// namespace test {}
404 /// \endcode
405 /// namespaceDecl()
406 /// matches "namespace {}" and "namespace test {}"
407 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
409 
410 /// Matches a declaration of a namespace alias.
411 ///
412 /// Given
413 /// \code
414 /// namespace test {}
415 /// namespace alias = ::test;
416 /// \endcode
417 /// namespaceAliasDecl()
418 /// matches "namespace alias" but not "namespace test"
419 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
421 
422 /// Matches class, struct, and union declarations.
423 ///
424 /// Example matches \c X, \c Z, \c U, and \c S
425 /// \code
426 /// class X;
427 /// template<class T> class Z {};
428 /// struct S {};
429 /// union U {};
430 /// \endcode
431 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
432 
433 /// Matches C++ class declarations.
434 ///
435 /// Example matches \c X, \c Z
436 /// \code
437 /// class X;
438 /// template<class T> class Z {};
439 /// \endcode
440 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
442 
443 /// Matches C++ class template declarations.
444 ///
445 /// Example matches \c Z
446 /// \code
447 /// template<class T> class Z {};
448 /// \endcode
449 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
451 
452 /// Matches C++ class template specializations.
453 ///
454 /// Given
455 /// \code
456 /// template<typename T> class A {};
457 /// template<> class A<double> {};
458 /// A<int> a;
459 /// \endcode
460 /// classTemplateSpecializationDecl()
461 /// matches the specializations \c A<int> and \c A<double>
462 extern const internal::VariadicDynCastAllOfMatcher<
465 
466 /// Matches C++ class template partial specializations.
467 ///
468 /// Given
469 /// \code
470 /// template<class T1, class T2, int I>
471 /// class A {};
472 ///
473 /// template<class T, int I>
474 /// class A<T, T*, I> {};
475 ///
476 /// template<>
477 /// class A<int, int, 1> {};
478 /// \endcode
479 /// classTemplatePartialSpecializationDecl()
480 /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
481 extern const internal::VariadicDynCastAllOfMatcher<
484 
485 /// Matches declarator declarations (field, variable, function
486 /// and non-type template parameter declarations).
487 ///
488 /// Given
489 /// \code
490 /// class X { int y; };
491 /// \endcode
492 /// declaratorDecl()
493 /// matches \c int y.
494 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
496 
497 /// Matches parameter variable declarations.
498 ///
499 /// Given
500 /// \code
501 /// void f(int x);
502 /// \endcode
503 /// parmVarDecl()
504 /// matches \c int x.
505 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
506  parmVarDecl;
507 
508 /// Matches C++ access specifier declarations.
509 ///
510 /// Given
511 /// \code
512 /// class C {
513 /// public:
514 /// int a;
515 /// };
516 /// \endcode
517 /// accessSpecDecl()
518 /// matches 'public:'
519 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
521 
522 /// Matches class bases.
523 ///
524 /// Examples matches \c public virtual B.
525 /// \code
526 /// class B {};
527 /// class C : public virtual B {};
528 /// \endcode
529 extern const internal::VariadicAllOfMatcher<CXXBaseSpecifier> cxxBaseSpecifier;
530 
531 /// Matches constructor initializers.
532 ///
533 /// Examples matches \c i(42).
534 /// \code
535 /// class C {
536 /// C() : i(42) {}
537 /// int i;
538 /// };
539 /// \endcode
540 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
542 
543 /// Matches template arguments.
544 ///
545 /// Given
546 /// \code
547 /// template <typename T> struct C {};
548 /// C<int> c;
549 /// \endcode
550 /// templateArgument()
551 /// matches 'int' in C<int>.
552 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
553 
554 /// Matches template arguments (with location info).
555 ///
556 /// Given
557 /// \code
558 /// template <typename T> struct C {};
559 /// C<int> c;
560 /// \endcode
561 /// templateArgumentLoc()
562 /// matches 'int' in C<int>.
563 extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
565 
566 /// Matches template name.
567 ///
568 /// Given
569 /// \code
570 /// template <typename T> class X { };
571 /// X<int> xi;
572 /// \endcode
573 /// templateName()
574 /// matches 'X' in X<int>.
575 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
576 
577 /// Matches non-type template parameter declarations.
578 ///
579 /// Given
580 /// \code
581 /// template <typename T, int N> struct C {};
582 /// \endcode
583 /// nonTypeTemplateParmDecl()
584 /// matches 'N', but not 'T'.
585 extern const internal::VariadicDynCastAllOfMatcher<Decl,
588 
589 /// Matches template type parameter declarations.
590 ///
591 /// Given
592 /// \code
593 /// template <typename T, int N> struct C {};
594 /// \endcode
595 /// templateTypeParmDecl()
596 /// matches 'T', but not 'N'.
597 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
599 
600 /// Matches template template parameter declarations.
601 ///
602 /// Given
603 /// \code
604 /// template <template <typename> class Z, int N> struct C {};
605 /// \endcode
606 /// templateTypeParmDecl()
607 /// matches 'Z', but not 'N'.
608 extern const internal::VariadicDynCastAllOfMatcher<Decl,
611 
612 /// Matches public C++ declarations and C++ base specifers that specify public
613 /// inheritance.
614 ///
615 /// Examples:
616 /// \code
617 /// class C {
618 /// public: int a; // fieldDecl(isPublic()) matches 'a'
619 /// protected: int b;
620 /// private: int c;
621 /// };
622 /// \endcode
623 ///
624 /// \code
625 /// class Base {};
626 /// class Derived1 : public Base {}; // matches 'Base'
627 /// struct Derived2 : Base {}; // matches 'Base'
628 /// \endcode
631  CXXBaseSpecifier)) {
632  return getAccessSpecifier(Node) == AS_public;
633 }
634 
635 /// Matches protected C++ declarations and C++ base specifers that specify
636 /// protected inheritance.
637 ///
638 /// Examples:
639 /// \code
640 /// class C {
641 /// public: int a;
642 /// protected: int b; // fieldDecl(isProtected()) matches 'b'
643 /// private: int c;
644 /// };
645 /// \endcode
646 ///
647 /// \code
648 /// class Base {};
649 /// class Derived : protected Base {}; // matches 'Base'
650 /// \endcode
653  CXXBaseSpecifier)) {
654  return getAccessSpecifier(Node) == AS_protected;
655 }
656 
657 /// Matches private C++ declarations and C++ base specifers that specify private
658 /// inheritance.
659 ///
660 /// Examples:
661 /// \code
662 /// class C {
663 /// public: int a;
664 /// protected: int b;
665 /// private: int c; // fieldDecl(isPrivate()) matches 'c'
666 /// };
667 /// \endcode
668 ///
669 /// \code
670 /// struct Base {};
671 /// struct Derived1 : private Base {}; // matches 'Base'
672 /// class Derived2 : Base {}; // matches 'Base'
673 /// \endcode
676  CXXBaseSpecifier)) {
677  return getAccessSpecifier(Node) == AS_private;
678 }
679 
680 /// Matches non-static data members that are bit-fields.
681 ///
682 /// Given
683 /// \code
684 /// class C {
685 /// int a : 2;
686 /// int b;
687 /// };
688 /// \endcode
689 /// fieldDecl(isBitField())
690 /// matches 'int a;' but not 'int b;'.
691 AST_MATCHER(FieldDecl, isBitField) {
692  return Node.isBitField();
693 }
694 
695 /// Matches non-static data members that are bit-fields of the specified
696 /// bit width.
697 ///
698 /// Given
699 /// \code
700 /// class C {
701 /// int a : 2;
702 /// int b : 4;
703 /// int c : 2;
704 /// };
705 /// \endcode
706 /// fieldDecl(hasBitWidth(2))
707 /// matches 'int a;' and 'int c;' but not 'int b;'.
708 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
709  return Node.isBitField() &&
710  Node.getBitWidthValue(Finder->getASTContext()) == Width;
711 }
712 
713 /// Matches non-static data members that have an in-class initializer.
714 ///
715 /// Given
716 /// \code
717 /// class C {
718 /// int a = 2;
719 /// int b = 3;
720 /// int c;
721 /// };
722 /// \endcode
723 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
724 /// matches 'int a;' but not 'int b;'.
725 /// fieldDecl(hasInClassInitializer(anything()))
726 /// matches 'int a;' and 'int b;' but not 'int c;'.
727 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
728  InnerMatcher) {
729  const Expr *Initializer = Node.getInClassInitializer();
730  return (Initializer != nullptr &&
731  InnerMatcher.matches(*Initializer, Finder, Builder));
732 }
733 
734 /// Determines whether the function is "main", which is the entry point
735 /// into an executable program.
737  return Node.isMain();
738 }
739 
740 /// Matches the specialized template of a specialization declaration.
741 ///
742 /// Given
743 /// \code
744 /// template<typename T> class A {}; #1
745 /// template<> class A<int> {}; #2
746 /// \endcode
747 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
748 /// matches '#2' with classTemplateDecl() matching the class template
749 /// declaration of 'A' at #1.
751  internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
752  const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
753  return (Decl != nullptr &&
754  InnerMatcher.matches(*Decl, Finder, Builder));
755 }
756 
757 /// Matches an entity that has been implicitly added by the compiler (e.g.
758 /// implicit default/copy constructors).
761  LambdaCapture)) {
762  return Node.isImplicit();
763 }
764 
765 /// Matches classTemplateSpecializations, templateSpecializationType and
766 /// functionDecl that have at least one TemplateArgument matching the given
767 /// InnerMatcher.
768 ///
769 /// Given
770 /// \code
771 /// template<typename T> class A {};
772 /// template<> class A<double> {};
773 /// A<int> a;
774 ///
775 /// template<typename T> f() {};
776 /// void func() { f<int>(); };
777 /// \endcode
778 ///
779 /// \endcode
780 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
781 /// refersToType(asString("int"))))
782 /// matches the specialization \c A<int>
783 ///
784 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
785 /// matches the specialization \c f<int>
787  hasAnyTemplateArgument,
790  FunctionDecl),
791  internal::Matcher<TemplateArgument>, InnerMatcher) {
793  internal::getTemplateSpecializationArgs(Node);
794  return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
795  Builder) != List.end();
796 }
797 
798 /// Causes all nested matchers to be matched with the specified traversal kind.
799 ///
800 /// Given
801 /// \code
802 /// void foo()
803 /// {
804 /// int i = 3.0;
805 /// }
806 /// \endcode
807 /// The matcher
808 /// \code
809 /// traverse(TK_IgnoreUnlessSpelledInSource,
810 /// varDecl(hasInitializer(floatLiteral().bind("init")))
811 /// )
812 /// \endcode
813 /// matches the variable declaration with "init" bound to the "3.0".
814 template <typename T>
815 internal::Matcher<T> traverse(TraversalKind TK,
816  const internal::Matcher<T> &InnerMatcher) {
817  return internal::DynTypedMatcher::constructRestrictedWrapper(
818  new internal::TraversalMatcher<T>(TK, InnerMatcher),
819  InnerMatcher.getID().first)
820  .template unconditionalConvertTo<T>();
821 }
822 
823 template <typename T>
824 internal::BindableMatcher<T>
825 traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
826  return internal::BindableMatcher<T>(
827  internal::DynTypedMatcher::constructRestrictedWrapper(
828  new internal::TraversalMatcher<T>(TK, InnerMatcher),
829  InnerMatcher.getID().first)
830  .template unconditionalConvertTo<T>());
831 }
832 
833 template <typename... T>
834 internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
836  const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
837  return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
838  TK, InnerMatcher);
839 }
840 
841 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
842  typename T, typename ToTypes>
843 internal::TraversalWrapper<
844  internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
845 traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
846  ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
847  return internal::TraversalWrapper<
848  internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
849  ToTypes>>(TK, InnerMatcher);
850 }
851 
852 template <template <typename T, typename... P> class MatcherT, typename... P,
853  typename ReturnTypesF>
854 internal::TraversalWrapper<
855  internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>
856 traverse(TraversalKind TK,
857  const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>
858  &InnerMatcher) {
859  return internal::TraversalWrapper<
860  internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK,
861  InnerMatcher);
862 }
863 
864 template <typename... T>
865 internal::Matcher<typename internal::GetClade<T...>::Type>
866 traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
867  return traverse(TK, InnerMatcher.with());
868 }
869 
870 /// Matches expressions that match InnerMatcher after any implicit AST
871 /// nodes are stripped off.
872 ///
873 /// Parentheses and explicit casts are not discarded.
874 /// Given
875 /// \code
876 /// class C {};
877 /// C a = C();
878 /// C b;
879 /// C c = b;
880 /// \endcode
881 /// The matchers
882 /// \code
883 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
884 /// \endcode
885 /// would match the declarations for a, b, and c.
886 /// While
887 /// \code
888 /// varDecl(hasInitializer(cxxConstructExpr()))
889 /// \endcode
890 /// only match the declarations for b and c.
891 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
892  InnerMatcher) {
893  return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
894 }
895 
896 /// Matches expressions that match InnerMatcher after any implicit casts
897 /// are stripped off.
898 ///
899 /// Parentheses and explicit casts are not discarded.
900 /// Given
901 /// \code
902 /// int arr[5];
903 /// int a = 0;
904 /// char b = 0;
905 /// const int c = a;
906 /// int *d = arr;
907 /// long e = (long) 0l;
908 /// \endcode
909 /// The matchers
910 /// \code
911 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
912 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
913 /// \endcode
914 /// would match the declarations for a, b, c, and d, but not e.
915 /// While
916 /// \code
917 /// varDecl(hasInitializer(integerLiteral()))
918 /// varDecl(hasInitializer(declRefExpr()))
919 /// \endcode
920 /// only match the declarations for a.
921 AST_MATCHER_P(Expr, ignoringImpCasts,
922  internal::Matcher<Expr>, InnerMatcher) {
923  return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
924 }
925 
926 /// Matches expressions that match InnerMatcher after parentheses and
927 /// casts are stripped off.
928 ///
929 /// Implicit and non-C Style casts are also discarded.
930 /// Given
931 /// \code
932 /// int a = 0;
933 /// char b = (0);
934 /// void* c = reinterpret_cast<char*>(0);
935 /// char d = char(0);
936 /// \endcode
937 /// The matcher
938 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
939 /// would match the declarations for a, b, c, and d.
940 /// while
941 /// varDecl(hasInitializer(integerLiteral()))
942 /// only match the declaration for a.
943 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
944  return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
945 }
946 
947 /// Matches expressions that match InnerMatcher after implicit casts and
948 /// parentheses are stripped off.
949 ///
950 /// Explicit casts are not discarded.
951 /// Given
952 /// \code
953 /// int arr[5];
954 /// int a = 0;
955 /// char b = (0);
956 /// const int c = a;
957 /// int *d = (arr);
958 /// long e = ((long) 0l);
959 /// \endcode
960 /// The matchers
961 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
962 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
963 /// would match the declarations for a, b, c, and d, but not e.
964 /// while
965 /// varDecl(hasInitializer(integerLiteral()))
966 /// varDecl(hasInitializer(declRefExpr()))
967 /// would only match the declaration for a.
968 AST_MATCHER_P(Expr, ignoringParenImpCasts,
969  internal::Matcher<Expr>, InnerMatcher) {
970  return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
971 }
972 
973 /// Matches types that match InnerMatcher after any parens are stripped.
974 ///
975 /// Given
976 /// \code
977 /// void (*fp)(void);
978 /// \endcode
979 /// The matcher
980 /// \code
981 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
982 /// \endcode
983 /// would match the declaration for fp.
984 AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
985  InnerMatcher, 0) {
986  return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
987 }
988 
989 /// Overload \c ignoringParens for \c Expr.
990 ///
991 /// Given
992 /// \code
993 /// const char* str = ("my-string");
994 /// \endcode
995 /// The matcher
996 /// \code
997 /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
998 /// \endcode
999 /// would match the implicit cast resulting from the assignment.
1000 AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
1001  InnerMatcher, 1) {
1002  const Expr *E = Node.IgnoreParens();
1003  return InnerMatcher.matches(*E, Finder, Builder);
1004 }
1005 
1006 /// Matches expressions that are instantiation-dependent even if it is
1007 /// neither type- nor value-dependent.
1008 ///
1009 /// In the following example, the expression sizeof(sizeof(T() + T()))
1010 /// is instantiation-dependent (since it involves a template parameter T),
1011 /// but is neither type- nor value-dependent, since the type of the inner
1012 /// sizeof is known (std::size_t) and therefore the size of the outer
1013 /// sizeof is known.
1014 /// \code
1015 /// template<typename T>
1016 /// void f(T x, T y) { sizeof(sizeof(T() + T()); }
1017 /// \endcode
1018 /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
1019 AST_MATCHER(Expr, isInstantiationDependent) {
1020  return Node.isInstantiationDependent();
1021 }
1022 
1023 /// Matches expressions that are type-dependent because the template type
1024 /// is not yet instantiated.
1025 ///
1026 /// For example, the expressions "x" and "x + y" are type-dependent in
1027 /// the following code, but "y" is not type-dependent:
1028 /// \code
1029 /// template<typename T>
1030 /// void add(T x, int y) {
1031 /// x + y;
1032 /// }
1033 /// \endcode
1034 /// expr(isTypeDependent()) matches x + y
1035 AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
1036 
1037 /// Matches expression that are value-dependent because they contain a
1038 /// non-type template parameter.
1039 ///
1040 /// For example, the array bound of "Chars" in the following example is
1041 /// value-dependent.
1042 /// \code
1043 /// template<int Size> int f() { return Size; }
1044 /// \endcode
1045 /// expr(isValueDependent()) matches return Size
1046 AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
1047 
1048 /// Matches classTemplateSpecializations, templateSpecializationType and
1049 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
1050 ///
1051 /// Given
1052 /// \code
1053 /// template<typename T, typename U> class A {};
1054 /// A<bool, int> b;
1055 /// A<int, bool> c;
1056 ///
1057 /// template<typename T> void f() {}
1058 /// void func() { f<int>(); };
1059 /// \endcode
1060 /// classTemplateSpecializationDecl(hasTemplateArgument(
1061 /// 1, refersToType(asString("int"))))
1062 /// matches the specialization \c A<bool, int>
1063 ///
1064 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1065 /// matches the specialization \c f<int>
1067  hasTemplateArgument,
1070  FunctionDecl),
1071  unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1073  internal::getTemplateSpecializationArgs(Node);
1074  if (List.size() <= N)
1075  return false;
1076  return InnerMatcher.matches(List[N], Finder, Builder);
1077 }
1078 
1079 /// Matches if the number of template arguments equals \p N.
1080 ///
1081 /// Given
1082 /// \code
1083 /// template<typename T> struct C {};
1084 /// C<int> c;
1085 /// \endcode
1086 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1087 /// matches C<int>.
1089  templateArgumentCountIs,
1092  unsigned, N) {
1093  return internal::getTemplateSpecializationArgs(Node).size() == N;
1094 }
1095 
1096 /// Matches a TemplateArgument that refers to a certain type.
1097 ///
1098 /// Given
1099 /// \code
1100 /// struct X {};
1101 /// template<typename T> struct A {};
1102 /// A<X> a;
1103 /// \endcode
1104 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1105 /// refersToType(class(hasName("X")))))
1106 /// matches the specialization \c A<X>
1108  internal::Matcher<QualType>, InnerMatcher) {
1109  if (Node.getKind() != TemplateArgument::Type)
1110  return false;
1111  return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1112 }
1113 
1114 /// Matches a TemplateArgument that refers to a certain template.
1115 ///
1116 /// Given
1117 /// \code
1118 /// template<template <typename> class S> class X {};
1119 /// template<typename T> class Y {};
1120 /// X<Y> xi;
1121 /// \endcode
1122 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1123 /// refersToTemplate(templateName())))
1124 /// matches the specialization \c X<Y>
1126  internal::Matcher<TemplateName>, InnerMatcher) {
1127  if (Node.getKind() != TemplateArgument::Template)
1128  return false;
1129  return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1130 }
1131 
1132 /// Matches a canonical TemplateArgument that refers to a certain
1133 /// declaration.
1134 ///
1135 /// Given
1136 /// \code
1137 /// struct B { int next; };
1138 /// template<int(B::*next_ptr)> struct A {};
1139 /// A<&B::next> a;
1140 /// \endcode
1141 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1142 /// refersToDeclaration(fieldDecl(hasName("next")))))
1143 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1144 /// \c B::next
1145 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1146  internal::Matcher<Decl>, InnerMatcher) {
1147  if (Node.getKind() == TemplateArgument::Declaration)
1148  return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1149  return false;
1150 }
1151 
1152 /// Matches a sugar TemplateArgument that refers to a certain expression.
1153 ///
1154 /// Given
1155 /// \code
1156 /// struct B { int next; };
1157 /// template<int(B::*next_ptr)> struct A {};
1158 /// A<&B::next> a;
1159 /// \endcode
1160 /// templateSpecializationType(hasAnyTemplateArgument(
1161 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1162 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1163 /// \c B::next
1164 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1165  if (Node.getKind() == TemplateArgument::Expression)
1166  return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1167  return false;
1168 }
1169 
1170 /// Matches a TemplateArgument that is an integral value.
1171 ///
1172 /// Given
1173 /// \code
1174 /// template<int T> struct C {};
1175 /// C<42> c;
1176 /// \endcode
1177 /// classTemplateSpecializationDecl(
1178 /// hasAnyTemplateArgument(isIntegral()))
1179 /// matches the implicit instantiation of C in C<42>
1180 /// with isIntegral() matching 42.
1182  return Node.getKind() == TemplateArgument::Integral;
1183 }
1184 
1185 /// Matches a TemplateArgument that refers to an integral type.
1186 ///
1187 /// Given
1188 /// \code
1189 /// template<int T> struct C {};
1190 /// C<42> c;
1191 /// \endcode
1192 /// classTemplateSpecializationDecl(
1193 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1194 /// matches the implicit instantiation of C in C<42>.
1195 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1196  internal::Matcher<QualType>, InnerMatcher) {
1197  if (Node.getKind() != TemplateArgument::Integral)
1198  return false;
1199  return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1200 }
1201 
1202 /// Matches a TemplateArgument of integral type with a given value.
1203 ///
1204 /// Note that 'Value' is a string as the template argument's value is
1205 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
1206 /// representation of that integral value in base 10.
1207 ///
1208 /// Given
1209 /// \code
1210 /// template<int T> struct C {};
1211 /// C<42> c;
1212 /// \endcode
1213 /// classTemplateSpecializationDecl(
1214 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
1215 /// matches the implicit instantiation of C in C<42>.
1216 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1217  std::string, Value) {
1218  if (Node.getKind() != TemplateArgument::Integral)
1219  return false;
1220  return toString(Node.getAsIntegral(), 10) == Value;
1221 }
1222 
1223 /// Matches an Objective-C autorelease pool statement.
1224 ///
1225 /// Given
1226 /// \code
1227 /// @autoreleasepool {
1228 /// int x = 0;
1229 /// }
1230 /// \endcode
1231 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1232 /// inside the autorelease pool.
1233 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1235 
1236 /// Matches any value declaration.
1237 ///
1238 /// Example matches A, B, C and F
1239 /// \code
1240 /// enum X { A, B, C };
1241 /// void F();
1242 /// \endcode
1243 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1244 
1245 /// Matches C++ constructor declarations.
1246 ///
1247 /// Example matches Foo::Foo() and Foo::Foo(int)
1248 /// \code
1249 /// class Foo {
1250 /// public:
1251 /// Foo();
1252 /// Foo(int);
1253 /// int DoSomething();
1254 /// };
1255 /// \endcode
1256 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1258 
1259 /// Matches explicit C++ destructor declarations.
1260 ///
1261 /// Example matches Foo::~Foo()
1262 /// \code
1263 /// class Foo {
1264 /// public:
1265 /// virtual ~Foo();
1266 /// };
1267 /// \endcode
1268 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1270 
1271 /// Matches enum declarations.
1272 ///
1273 /// Example matches X
1274 /// \code
1275 /// enum X {
1276 /// A, B, C
1277 /// };
1278 /// \endcode
1279 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1280 
1281 /// Matches enum constants.
1282 ///
1283 /// Example matches A, B, C
1284 /// \code
1285 /// enum X {
1286 /// A, B, C
1287 /// };
1288 /// \endcode
1289 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1291 
1292 /// Matches tag declarations.
1293 ///
1294 /// Example matches X, Z, U, S, E
1295 /// \code
1296 /// class X;
1297 /// template<class T> class Z {};
1298 /// struct S {};
1299 /// union U {};
1300 /// enum E {
1301 /// A, B, C
1302 /// };
1303 /// \endcode
1304 extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1305 
1306 /// Matches method declarations.
1307 ///
1308 /// Example matches y
1309 /// \code
1310 /// class X { void y(); };
1311 /// \endcode
1312 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1313  cxxMethodDecl;
1314 
1315 /// Matches conversion operator declarations.
1316 ///
1317 /// Example matches the operator.
1318 /// \code
1319 /// class X { operator int() const; };
1320 /// \endcode
1321 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1323 
1324 /// Matches user-defined and implicitly generated deduction guide.
1325 ///
1326 /// Example matches the deduction guide.
1327 /// \code
1328 /// template<typename T>
1329 /// class X { X(int) };
1330 /// X(int) -> X<int>;
1331 /// \endcode
1332 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1334 
1335 /// Matches variable declarations.
1336 ///
1337 /// Note: this does not match declarations of member variables, which are
1338 /// "field" declarations in Clang parlance.
1339 ///
1340 /// Example matches a
1341 /// \code
1342 /// int a;
1343 /// \endcode
1344 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1345 
1346 /// Matches field declarations.
1347 ///
1348 /// Given
1349 /// \code
1350 /// class X { int m; };
1351 /// \endcode
1352 /// fieldDecl()
1353 /// matches 'm'.
1354 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1355 
1356 /// Matches indirect field declarations.
1357 ///
1358 /// Given
1359 /// \code
1360 /// struct X { struct { int a; }; };
1361 /// \endcode
1362 /// indirectFieldDecl()
1363 /// matches 'a'.
1364 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1366 
1367 /// Matches function declarations.
1368 ///
1369 /// Example matches f
1370 /// \code
1371 /// void f();
1372 /// \endcode
1373 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1374  functionDecl;
1375 
1376 /// Matches C++ function template declarations.
1377 ///
1378 /// Example matches f
1379 /// \code
1380 /// template<class T> void f(T t) {}
1381 /// \endcode
1382 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1384 
1385 /// Matches friend declarations.
1386 ///
1387 /// Given
1388 /// \code
1389 /// class X { friend void foo(); };
1390 /// \endcode
1391 /// friendDecl()
1392 /// matches 'friend void foo()'.
1393 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1394 
1395 /// Matches statements.
1396 ///
1397 /// Given
1398 /// \code
1399 /// { ++a; }
1400 /// \endcode
1401 /// stmt()
1402 /// matches both the compound statement '{ ++a; }' and '++a'.
1403 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1404 
1405 /// Matches declaration statements.
1406 ///
1407 /// Given
1408 /// \code
1409 /// int a;
1410 /// \endcode
1411 /// declStmt()
1412 /// matches 'int a'.
1413 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1414 
1415 /// Matches member expressions.
1416 ///
1417 /// Given
1418 /// \code
1419 /// class Y {
1420 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1421 /// int a; static int b;
1422 /// };
1423 /// \endcode
1424 /// memberExpr()
1425 /// matches this->x, x, y.x, a, this->b
1426 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1427 
1428 /// Matches unresolved member expressions.
1429 ///
1430 /// Given
1431 /// \code
1432 /// struct X {
1433 /// template <class T> void f();
1434 /// void g();
1435 /// };
1436 /// template <class T> void h() { X x; x.f<T>(); x.g(); }
1437 /// \endcode
1438 /// unresolvedMemberExpr()
1439 /// matches x.f<T>
1440 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1442 
1443 /// Matches member expressions where the actual member referenced could not be
1444 /// resolved because the base expression or the member name was dependent.
1445 ///
1446 /// Given
1447 /// \code
1448 /// template <class T> void f() { T t; t.g(); }
1449 /// \endcode
1450 /// cxxDependentScopeMemberExpr()
1451 /// matches t.g
1452 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1455 
1456 /// Matches call expressions.
1457 ///
1458 /// Example matches x.y() and y()
1459 /// \code
1460 /// X x;
1461 /// x.y();
1462 /// y();
1463 /// \endcode
1464 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1465 
1466 /// Matches call expressions which were resolved using ADL.
1467 ///
1468 /// Example matches y(x) but not y(42) or NS::y(x).
1469 /// \code
1470 /// namespace NS {
1471 /// struct X {};
1472 /// void y(X);
1473 /// }
1474 ///
1475 /// void y(...);
1476 ///
1477 /// void test() {
1478 /// NS::X x;
1479 /// y(x); // Matches
1480 /// NS::y(x); // Doesn't match
1481 /// y(42); // Doesn't match
1482 /// using NS::y;
1483 /// y(x); // Found by both unqualified lookup and ADL, doesn't match
1484 // }
1485 /// \endcode
1486 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1487 
1488 /// Matches lambda expressions.
1489 ///
1490 /// Example matches [&](){return 5;}
1491 /// \code
1492 /// [&](){return 5;}
1493 /// \endcode
1494 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1495 
1496 /// Matches member call expressions.
1497 ///
1498 /// Example matches x.y()
1499 /// \code
1500 /// X x;
1501 /// x.y();
1502 /// \endcode
1503 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1505 
1506 /// Matches ObjectiveC Message invocation expressions.
1507 ///
1508 /// The innermost message send invokes the "alloc" class method on the
1509 /// NSString class, while the outermost message send invokes the
1510 /// "initWithString" instance method on the object returned from
1511 /// NSString's "alloc". This matcher should match both message sends.
1512 /// \code
1513 /// [[NSString alloc] initWithString:@"Hello"]
1514 /// \endcode
1515 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1517 
1518 /// Matches Objective-C interface declarations.
1519 ///
1520 /// Example matches Foo
1521 /// \code
1522 /// @interface Foo
1523 /// @end
1524 /// \endcode
1525 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1527 
1528 /// Matches Objective-C implementation declarations.
1529 ///
1530 /// Example matches Foo
1531 /// \code
1532 /// @implementation Foo
1533 /// @end
1534 /// \endcode
1535 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1537 
1538 /// Matches Objective-C protocol declarations.
1539 ///
1540 /// Example matches FooDelegate
1541 /// \code
1542 /// @protocol FooDelegate
1543 /// @end
1544 /// \endcode
1545 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1547 
1548 /// Matches Objective-C category declarations.
1549 ///
1550 /// Example matches Foo (Additions)
1551 /// \code
1552 /// @interface Foo (Additions)
1553 /// @end
1554 /// \endcode
1555 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1557 
1558 /// Matches Objective-C category definitions.
1559 ///
1560 /// Example matches Foo (Additions)
1561 /// \code
1562 /// @implementation Foo (Additions)
1563 /// @end
1564 /// \endcode
1565 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1567 
1568 /// Matches Objective-C method declarations.
1569 ///
1570 /// Example matches both declaration and definition of -[Foo method]
1571 /// \code
1572 /// @interface Foo
1573 /// - (void)method;
1574 /// @end
1575 ///
1576 /// @implementation Foo
1577 /// - (void)method {}
1578 /// @end
1579 /// \endcode
1580 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1582 
1583 /// Matches block declarations.
1584 ///
1585 /// Example matches the declaration of the nameless block printing an input
1586 /// integer.
1587 ///
1588 /// \code
1589 /// myFunc(^(int p) {
1590 /// printf("%d", p);
1591 /// })
1592 /// \endcode
1593 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1594  blockDecl;
1595 
1596 /// Matches Objective-C instance variable declarations.
1597 ///
1598 /// Example matches _enabled
1599 /// \code
1600 /// @implementation Foo {
1601 /// BOOL _enabled;
1602 /// }
1603 /// @end
1604 /// \endcode
1605 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1606  objcIvarDecl;
1607 
1608 /// Matches Objective-C property declarations.
1609 ///
1610 /// Example matches enabled
1611 /// \code
1612 /// @interface Foo
1613 /// @property BOOL enabled;
1614 /// @end
1615 /// \endcode
1616 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1618 
1619 /// Matches Objective-C \@throw statements.
1620 ///
1621 /// Example matches \@throw
1622 /// \code
1623 /// @throw obj;
1624 /// \endcode
1625 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1626  objcThrowStmt;
1627 
1628 /// Matches Objective-C @try statements.
1629 ///
1630 /// Example matches @try
1631 /// \code
1632 /// @try {}
1633 /// @catch (...) {}
1634 /// \endcode
1635 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1636  objcTryStmt;
1637 
1638 /// Matches Objective-C @catch statements.
1639 ///
1640 /// Example matches @catch
1641 /// \code
1642 /// @try {}
1643 /// @catch (...) {}
1644 /// \endcode
1645 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1646  objcCatchStmt;
1647 
1648 /// Matches Objective-C @finally statements.
1649 ///
1650 /// Example matches @finally
1651 /// \code
1652 /// @try {}
1653 /// @finally {}
1654 /// \endcode
1655 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1657 
1658 /// Matches expressions that introduce cleanups to be run at the end
1659 /// of the sub-expression's evaluation.
1660 ///
1661 /// Example matches std::string()
1662 /// \code
1663 /// const std::string str = std::string();
1664 /// \endcode
1665 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1667 
1668 /// Matches init list expressions.
1669 ///
1670 /// Given
1671 /// \code
1672 /// int a[] = { 1, 2 };
1673 /// struct B { int x, y; };
1674 /// B b = { 5, 6 };
1675 /// \endcode
1676 /// initListExpr()
1677 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1678 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1679  initListExpr;
1680 
1681 /// Matches the syntactic form of init list expressions
1682 /// (if expression have it).
1683 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1684  internal::Matcher<Expr>, InnerMatcher) {
1685  const Expr *SyntForm = Node.getSyntacticForm();
1686  return (SyntForm != nullptr &&
1687  InnerMatcher.matches(*SyntForm, Finder, Builder));
1688 }
1689 
1690 /// Matches C++ initializer list expressions.
1691 ///
1692 /// Given
1693 /// \code
1694 /// std::vector<int> a({ 1, 2, 3 });
1695 /// std::vector<int> b = { 4, 5 };
1696 /// int c[] = { 6, 7 };
1697 /// std::pair<int, int> d = { 8, 9 };
1698 /// \endcode
1699 /// cxxStdInitializerListExpr()
1700 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1701 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1704 
1705 /// Matches implicit initializers of init list expressions.
1706 ///
1707 /// Given
1708 /// \code
1709 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1710 /// \endcode
1711 /// implicitValueInitExpr()
1712 /// matches "[0].y" (implicitly)
1713 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1715 
1716 /// Matches paren list expressions.
1717 /// ParenListExprs don't have a predefined type and are used for late parsing.
1718 /// In the final AST, they can be met in template declarations.
1719 ///
1720 /// Given
1721 /// \code
1722 /// template<typename T> class X {
1723 /// void f() {
1724 /// X x(*this);
1725 /// int a = 0, b = 1; int i = (a, b);
1726 /// }
1727 /// };
1728 /// \endcode
1729 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1730 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1731 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1732  parenListExpr;
1733 
1734 /// Matches substitutions of non-type template parameters.
1735 ///
1736 /// Given
1737 /// \code
1738 /// template <int N>
1739 /// struct A { static const int n = N; };
1740 /// struct B : public A<42> {};
1741 /// \endcode
1742 /// substNonTypeTemplateParmExpr()
1743 /// matches "N" in the right-hand side of "static const int n = N;"
1744 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1747 
1748 /// Matches using declarations.
1749 ///
1750 /// Given
1751 /// \code
1752 /// namespace X { int x; }
1753 /// using X::x;
1754 /// \endcode
1755 /// usingDecl()
1756 /// matches \code using X::x \endcode
1757 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1758 
1759 /// Matches using-enum declarations.
1760 ///
1761 /// Given
1762 /// \code
1763 /// namespace X { enum x {...}; }
1764 /// using enum X::x;
1765 /// \endcode
1766 /// usingEnumDecl()
1767 /// matches \code using enum X::x \endcode
1768 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1769  usingEnumDecl;
1770 
1771 /// Matches using namespace declarations.
1772 ///
1773 /// Given
1774 /// \code
1775 /// namespace X { int x; }
1776 /// using namespace X;
1777 /// \endcode
1778 /// usingDirectiveDecl()
1779 /// matches \code using namespace X \endcode
1780 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1782 
1783 /// Matches reference to a name that can be looked up during parsing
1784 /// but could not be resolved to a specific declaration.
1785 ///
1786 /// Given
1787 /// \code
1788 /// template<typename T>
1789 /// T foo() { T a; return a; }
1790 /// template<typename T>
1791 /// void bar() {
1792 /// foo<T>();
1793 /// }
1794 /// \endcode
1795 /// unresolvedLookupExpr()
1796 /// matches \code foo<T>() \endcode
1797 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1799 
1800 /// Matches unresolved using value declarations.
1801 ///
1802 /// Given
1803 /// \code
1804 /// template<typename X>
1805 /// class C : private X {
1806 /// using X::x;
1807 /// };
1808 /// \endcode
1809 /// unresolvedUsingValueDecl()
1810 /// matches \code using X::x \endcode
1811 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1814 
1815 /// Matches unresolved using value declarations that involve the
1816 /// typename.
1817 ///
1818 /// Given
1819 /// \code
1820 /// template <typename T>
1821 /// struct Base { typedef T Foo; };
1822 ///
1823 /// template<typename T>
1824 /// struct S : private Base<T> {
1825 /// using typename Base<T>::Foo;
1826 /// };
1827 /// \endcode
1828 /// unresolvedUsingTypenameDecl()
1829 /// matches \code using Base<T>::Foo \endcode
1830 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1833 
1834 /// Matches a constant expression wrapper.
1835 ///
1836 /// Example matches the constant in the case statement:
1837 /// (matcher = constantExpr())
1838 /// \code
1839 /// switch (a) {
1840 /// case 37: break;
1841 /// }
1842 /// \endcode
1843 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1844  constantExpr;
1845 
1846 /// Matches parentheses used in expressions.
1847 ///
1848 /// Example matches (foo() + 1)
1849 /// \code
1850 /// int foo() { return 1; }
1851 /// int a = (foo() + 1);
1852 /// \endcode
1853 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1854 
1855 /// Matches constructor call expressions (including implicit ones).
1856 ///
1857 /// Example matches string(ptr, n) and ptr within arguments of f
1858 /// (matcher = cxxConstructExpr())
1859 /// \code
1860 /// void f(const string &a, const string &b);
1861 /// char *ptr;
1862 /// int n;
1863 /// f(string(ptr, n), ptr);
1864 /// \endcode
1865 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1867 
1868 /// Matches unresolved constructor call expressions.
1869 ///
1870 /// Example matches T(t) in return statement of f
1871 /// (matcher = cxxUnresolvedConstructExpr())
1872 /// \code
1873 /// template <typename T>
1874 /// void f(const T& t) { return T(t); }
1875 /// \endcode
1876 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1879 
1880 /// Matches implicit and explicit this expressions.
1881 ///
1882 /// Example matches the implicit this expression in "return i".
1883 /// (matcher = cxxThisExpr())
1884 /// \code
1885 /// struct foo {
1886 /// int i;
1887 /// int f() { return i; }
1888 /// };
1889 /// \endcode
1890 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1891  cxxThisExpr;
1892 
1893 /// Matches nodes where temporaries are created.
1894 ///
1895 /// Example matches FunctionTakesString(GetStringByValue())
1896 /// (matcher = cxxBindTemporaryExpr())
1897 /// \code
1898 /// FunctionTakesString(GetStringByValue());
1899 /// FunctionTakesStringByPointer(GetStringPointer());
1900 /// \endcode
1901 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1903 
1904 /// Matches nodes where temporaries are materialized.
1905 ///
1906 /// Example: Given
1907 /// \code
1908 /// struct T {void func();};
1909 /// T f();
1910 /// void g(T);
1911 /// \endcode
1912 /// materializeTemporaryExpr() matches 'f()' in these statements
1913 /// \code
1914 /// T u(f());
1915 /// g(f());
1916 /// f().func();
1917 /// \endcode
1918 /// but does not match
1919 /// \code
1920 /// f();
1921 /// \endcode
1922 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1925 
1926 /// Matches new expressions.
1927 ///
1928 /// Given
1929 /// \code
1930 /// new X;
1931 /// \endcode
1932 /// cxxNewExpr()
1933 /// matches 'new X'.
1934 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1935 
1936 /// Matches delete expressions.
1937 ///
1938 /// Given
1939 /// \code
1940 /// delete X;
1941 /// \endcode
1942 /// cxxDeleteExpr()
1943 /// matches 'delete X'.
1944 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1945  cxxDeleteExpr;
1946 
1947 /// Matches noexcept expressions.
1948 ///
1949 /// Given
1950 /// \code
1951 /// bool a() noexcept;
1952 /// bool b() noexcept(true);
1953 /// bool c() noexcept(false);
1954 /// bool d() noexcept(noexcept(a()));
1955 /// bool e = noexcept(b()) || noexcept(c());
1956 /// \endcode
1957 /// cxxNoexceptExpr()
1958 /// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1959 /// doesn't match the noexcept specifier in the declarations a, b, c or d.
1960 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1962 
1963 /// Matches array subscript expressions.
1964 ///
1965 /// Given
1966 /// \code
1967 /// int i = a[1];
1968 /// \endcode
1969 /// arraySubscriptExpr()
1970 /// matches "a[1]"
1971 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1973 
1974 /// Matches the value of a default argument at the call site.
1975 ///
1976 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1977 /// default value of the second parameter in the call expression f(42)
1978 /// (matcher = cxxDefaultArgExpr())
1979 /// \code
1980 /// void f(int x, int y = 0);
1981 /// f(42);
1982 /// \endcode
1983 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1985 
1986 /// Matches overloaded operator calls.
1987 ///
1988 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1989 /// binaryOperator matcher.
1990 /// Currently it does not match operators such as new delete.
1991 /// FIXME: figure out why these do not match?
1992 ///
1993 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1994 /// (matcher = cxxOperatorCallExpr())
1995 /// \code
1996 /// ostream &operator<< (ostream &out, int i) { };
1997 /// ostream &o; int b = 1, c = 1;
1998 /// o << b << c;
1999 /// \endcode
2000 /// See also the binaryOperation() matcher for more-general matching of binary
2001 /// uses of this AST node.
2002 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2004 
2005 /// Matches rewritten binary operators
2006 ///
2007 /// Example matches use of "<":
2008 /// \code
2009 /// #include <compare>
2010 /// struct HasSpaceshipMem {
2011 /// int a;
2012 /// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2013 /// };
2014 /// void compare() {
2015 /// HasSpaceshipMem hs1, hs2;
2016 /// if (hs1 < hs2)
2017 /// return;
2018 /// }
2019 /// \endcode
2020 /// See also the binaryOperation() matcher for more-general matching
2021 /// of this AST node.
2022 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2025 
2026 /// Matches expressions.
2027 ///
2028 /// Example matches x()
2029 /// \code
2030 /// void f() { x(); }
2031 /// \endcode
2032 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2033 
2034 /// Matches expressions that refer to declarations.
2035 ///
2036 /// Example matches x in if (x)
2037 /// \code
2038 /// bool x;
2039 /// if (x) {}
2040 /// \endcode
2041 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2042  declRefExpr;
2043 
2044 /// Matches a reference to an ObjCIvar.
2045 ///
2046 /// Example: matches "a" in "init" method:
2047 /// \code
2048 /// @implementation A {
2049 /// NSString *a;
2050 /// }
2051 /// - (void) init {
2052 /// a = @"hello";
2053 /// }
2054 /// \endcode
2055 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2057 
2058 /// Matches a reference to a block.
2059 ///
2060 /// Example: matches "^{}":
2061 /// \code
2062 /// void f() { ^{}(); }
2063 /// \endcode
2064 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2065 
2066 /// Matches if statements.
2067 ///
2068 /// Example matches 'if (x) {}'
2069 /// \code
2070 /// if (x) {}
2071 /// \endcode
2072 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2073 
2074 /// Matches for statements.
2075 ///
2076 /// Example matches 'for (;;) {}'
2077 /// \code
2078 /// for (;;) {}
2079 /// int i[] = {1, 2, 3}; for (auto a : i);
2080 /// \endcode
2081 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2082 
2083 /// Matches the increment statement of a for loop.
2084 ///
2085 /// Example:
2086 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2087 /// matches '++x' in
2088 /// \code
2089 /// for (x; x < N; ++x) { }
2090 /// \endcode
2091 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2092  InnerMatcher) {
2093  const Stmt *const Increment = Node.getInc();
2094  return (Increment != nullptr &&
2095  InnerMatcher.matches(*Increment, Finder, Builder));
2096 }
2097 
2098 /// Matches the initialization statement of a for loop.
2099 ///
2100 /// Example:
2101 /// forStmt(hasLoopInit(declStmt()))
2102 /// matches 'int x = 0' in
2103 /// \code
2104 /// for (int x = 0; x < N; ++x) { }
2105 /// \endcode
2106 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2107  InnerMatcher) {
2108  const Stmt *const Init = Node.getInit();
2109  return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2110 }
2111 
2112 /// Matches range-based for statements.
2113 ///
2114 /// cxxForRangeStmt() matches 'for (auto a : i)'
2115 /// \code
2116 /// int i[] = {1, 2, 3}; for (auto a : i);
2117 /// for(int j = 0; j < 5; ++j);
2118 /// \endcode
2119 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2121 
2122 /// Matches the initialization statement of a for loop.
2123 ///
2124 /// Example:
2125 /// forStmt(hasLoopVariable(anything()))
2126 /// matches 'int x' in
2127 /// \code
2128 /// for (int x : a) { }
2129 /// \endcode
2130 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2131  InnerMatcher) {
2132  const VarDecl *const Var = Node.getLoopVariable();
2133  return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2134 }
2135 
2136 /// Matches the range initialization statement of a for loop.
2137 ///
2138 /// Example:
2139 /// forStmt(hasRangeInit(anything()))
2140 /// matches 'a' in
2141 /// \code
2142 /// for (int x : a) { }
2143 /// \endcode
2144 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2145  InnerMatcher) {
2146  const Expr *const Init = Node.getRangeInit();
2147  return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2148 }
2149 
2150 /// Matches while statements.
2151 ///
2152 /// Given
2153 /// \code
2154 /// while (true) {}
2155 /// \endcode
2156 /// whileStmt()
2157 /// matches 'while (true) {}'.
2158 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2159 
2160 /// Matches do statements.
2161 ///
2162 /// Given
2163 /// \code
2164 /// do {} while (true);
2165 /// \endcode
2166 /// doStmt()
2167 /// matches 'do {} while(true)'
2168 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2169 
2170 /// Matches break statements.
2171 ///
2172 /// Given
2173 /// \code
2174 /// while (true) { break; }
2175 /// \endcode
2176 /// breakStmt()
2177 /// matches 'break'
2178 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2179 
2180 /// Matches continue statements.
2181 ///
2182 /// Given
2183 /// \code
2184 /// while (true) { continue; }
2185 /// \endcode
2186 /// continueStmt()
2187 /// matches 'continue'
2188 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2189  continueStmt;
2190 
2191 /// Matches co_return statements.
2192 ///
2193 /// Given
2194 /// \code
2195 /// while (true) { co_return; }
2196 /// \endcode
2197 /// coreturnStmt()
2198 /// matches 'co_return'
2199 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2200  coreturnStmt;
2201 
2202 /// Matches return statements.
2203 ///
2204 /// Given
2205 /// \code
2206 /// return 1;
2207 /// \endcode
2208 /// returnStmt()
2209 /// matches 'return 1'
2210 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2211 
2212 /// Matches goto statements.
2213 ///
2214 /// Given
2215 /// \code
2216 /// goto FOO;
2217 /// FOO: bar();
2218 /// \endcode
2219 /// gotoStmt()
2220 /// matches 'goto FOO'
2221 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2222 
2223 /// Matches label statements.
2224 ///
2225 /// Given
2226 /// \code
2227 /// goto FOO;
2228 /// FOO: bar();
2229 /// \endcode
2230 /// labelStmt()
2231 /// matches 'FOO:'
2232 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2233 
2234 /// Matches address of label statements (GNU extension).
2235 ///
2236 /// Given
2237 /// \code
2238 /// FOO: bar();
2239 /// void *ptr = &&FOO;
2240 /// goto *bar;
2241 /// \endcode
2242 /// addrLabelExpr()
2243 /// matches '&&FOO'
2244 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2245  addrLabelExpr;
2246 
2247 /// Matches switch statements.
2248 ///
2249 /// Given
2250 /// \code
2251 /// switch(a) { case 42: break; default: break; }
2252 /// \endcode
2253 /// switchStmt()
2254 /// matches 'switch(a)'.
2255 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2256 
2257 /// Matches case and default statements inside switch statements.
2258 ///
2259 /// Given
2260 /// \code
2261 /// switch(a) { case 42: break; default: break; }
2262 /// \endcode
2263 /// switchCase()
2264 /// matches 'case 42:' and 'default:'.
2265 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2266 
2267 /// Matches case statements inside switch statements.
2268 ///
2269 /// Given
2270 /// \code
2271 /// switch(a) { case 42: break; default: break; }
2272 /// \endcode
2273 /// caseStmt()
2274 /// matches 'case 42:'.
2275 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2276 
2277 /// Matches default statements inside switch statements.
2278 ///
2279 /// Given
2280 /// \code
2281 /// switch(a) { case 42: break; default: break; }
2282 /// \endcode
2283 /// defaultStmt()
2284 /// matches 'default:'.
2285 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2286  defaultStmt;
2287 
2288 /// Matches compound statements.
2289 ///
2290 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2291 /// \code
2292 /// for (;;) {{}}
2293 /// \endcode
2294 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2295  compoundStmt;
2296 
2297 /// Matches catch statements.
2298 ///
2299 /// \code
2300 /// try {} catch(int i) {}
2301 /// \endcode
2302 /// cxxCatchStmt()
2303 /// matches 'catch(int i)'
2304 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2305  cxxCatchStmt;
2306 
2307 /// Matches try statements.
2308 ///
2309 /// \code
2310 /// try {} catch(int i) {}
2311 /// \endcode
2312 /// cxxTryStmt()
2313 /// matches 'try {}'
2314 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2315 
2316 /// Matches throw expressions.
2317 ///
2318 /// \code
2319 /// try { throw 5; } catch(int i) {}
2320 /// \endcode
2321 /// cxxThrowExpr()
2322 /// matches 'throw 5'
2323 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2324  cxxThrowExpr;
2325 
2326 /// Matches null statements.
2327 ///
2328 /// \code
2329 /// foo();;
2330 /// \endcode
2331 /// nullStmt()
2332 /// matches the second ';'
2333 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2334 
2335 /// Matches asm statements.
2336 ///
2337 /// \code
2338 /// int i = 100;
2339 /// __asm("mov al, 2");
2340 /// \endcode
2341 /// asmStmt()
2342 /// matches '__asm("mov al, 2")'
2343 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2344 
2345 /// Matches bool literals.
2346 ///
2347 /// Example matches true
2348 /// \code
2349 /// true
2350 /// \endcode
2351 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2353 
2354 /// Matches string literals (also matches wide string literals).
2355 ///
2356 /// Example matches "abcd", L"abcd"
2357 /// \code
2358 /// char *s = "abcd";
2359 /// wchar_t *ws = L"abcd";
2360 /// \endcode
2361 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2362  stringLiteral;
2363 
2364 /// Matches character literals (also matches wchar_t).
2365 ///
2366 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2367 /// though.
2368 ///
2369 /// Example matches 'a', L'a'
2370 /// \code
2371 /// char ch = 'a';
2372 /// wchar_t chw = L'a';
2373 /// \endcode
2374 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2376 
2377 /// Matches integer literals of all sizes / encodings, e.g.
2378 /// 1, 1L, 0x1 and 1U.
2379 ///
2380 /// Does not match character-encoded integers such as L'a'.
2381 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2383 
2384 /// Matches float literals of all sizes / encodings, e.g.
2385 /// 1.0, 1.0f, 1.0L and 1e10.
2386 ///
2387 /// Does not match implicit conversions such as
2388 /// \code
2389 /// float a = 10;
2390 /// \endcode
2391 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2392  floatLiteral;
2393 
2394 /// Matches imaginary literals, which are based on integer and floating
2395 /// point literals e.g.: 1i, 1.0i
2396 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2398 
2399 /// Matches fixed point literals
2400 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2402 
2403 /// Matches user defined literal operator call.
2404 ///
2405 /// Example match: "foo"_suffix
2406 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2408 
2409 /// Matches compound (i.e. non-scalar) literals
2410 ///
2411 /// Example match: {1}, (1, 2)
2412 /// \code
2413 /// int array[4] = {1};
2414 /// vector int myvec = (vector int)(1, 2);
2415 /// \endcode
2416 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2418 
2419 /// Matches co_await expressions.
2420 ///
2421 /// Given
2422 /// \code
2423 /// co_await 1;
2424 /// \endcode
2425 /// coawaitExpr()
2426 /// matches 'co_await 1'
2427 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2428  coawaitExpr;
2429 /// Matches co_await expressions where the type of the promise is dependent
2430 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2432 /// Matches co_yield expressions.
2433 ///
2434 /// Given
2435 /// \code
2436 /// co_yield 1;
2437 /// \endcode
2438 /// coyieldExpr()
2439 /// matches 'co_yield 1'
2440 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2441  coyieldExpr;
2442 
2443 /// Matches nullptr literal.
2444 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2446 
2447 /// Matches GNU __builtin_choose_expr.
2448 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2449  chooseExpr;
2450 
2451 /// Matches GNU __null expression.
2452 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2453  gnuNullExpr;
2454 
2455 /// Matches C11 _Generic expression.
2456 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2458 
2459 /// Matches atomic builtins.
2460 /// Example matches __atomic_load_n(ptr, 1)
2461 /// \code
2462 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2463 /// \endcode
2464 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2465 
2466 /// Matches statement expression (GNU extension).
2467 ///
2468 /// Example match: ({ int X = 4; X; })
2469 /// \code
2470 /// int C = ({ int X = 4; X; });
2471 /// \endcode
2472 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2473 
2474 /// Matches binary operator expressions.
2475 ///
2476 /// Example matches a || b
2477 /// \code
2478 /// !(a || b)
2479 /// \endcode
2480 /// See also the binaryOperation() matcher for more-general matching.
2481 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2483 
2484 /// Matches unary operator expressions.
2485 ///
2486 /// Example matches !a
2487 /// \code
2488 /// !a || b
2489 /// \endcode
2490 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2491  unaryOperator;
2492 
2493 /// Matches conditional operator expressions.
2494 ///
2495 /// Example matches a ? b : c
2496 /// \code
2497 /// (a ? b : c) + 42
2498 /// \endcode
2499 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2501 
2502 /// Matches binary conditional operator expressions (GNU extension).
2503 ///
2504 /// Example matches a ?: b
2505 /// \code
2506 /// (a ?: b) + 42;
2507 /// \endcode
2508 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2511 
2512 /// Matches opaque value expressions. They are used as helpers
2513 /// to reference another expressions and can be met
2514 /// in BinaryConditionalOperators, for example.
2515 ///
2516 /// Example matches 'a'
2517 /// \code
2518 /// (a ?: c) + 42;
2519 /// \endcode
2520 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2522 
2523 /// Matches a C++ static_assert declaration.
2524 ///
2525 /// Example:
2526 /// staticAssertDecl()
2527 /// matches
2528 /// static_assert(sizeof(S) == sizeof(int))
2529 /// in
2530 /// \code
2531 /// struct S {
2532 /// int x;
2533 /// };
2534 /// static_assert(sizeof(S) == sizeof(int));
2535 /// \endcode
2536 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2538 
2539 /// Matches a reinterpret_cast expression.
2540 ///
2541 /// Either the source expression or the destination type can be matched
2542 /// using has(), but hasDestinationType() is more specific and can be
2543 /// more readable.
2544 ///
2545 /// Example matches reinterpret_cast<char*>(&p) in
2546 /// \code
2547 /// void* p = reinterpret_cast<char*>(&p);
2548 /// \endcode
2549 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2551 
2552 /// Matches a C++ static_cast expression.
2553 ///
2554 /// \see hasDestinationType
2555 /// \see reinterpretCast
2556 ///
2557 /// Example:
2558 /// cxxStaticCastExpr()
2559 /// matches
2560 /// static_cast<long>(8)
2561 /// in
2562 /// \code
2563 /// long eight(static_cast<long>(8));
2564 /// \endcode
2565 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2567 
2568 /// Matches a dynamic_cast expression.
2569 ///
2570 /// Example:
2571 /// cxxDynamicCastExpr()
2572 /// matches
2573 /// dynamic_cast<D*>(&b);
2574 /// in
2575 /// \code
2576 /// struct B { virtual ~B() {} }; struct D : B {};
2577 /// B b;
2578 /// D* p = dynamic_cast<D*>(&b);
2579 /// \endcode
2580 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2582 
2583 /// Matches a const_cast expression.
2584 ///
2585 /// Example: Matches const_cast<int*>(&r) in
2586 /// \code
2587 /// int n = 42;
2588 /// const int &r(n);
2589 /// int* p = const_cast<int*>(&r);
2590 /// \endcode
2591 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2593 
2594 /// Matches a C-style cast expression.
2595 ///
2596 /// Example: Matches (int) 2.2f in
2597 /// \code
2598 /// int i = (int) 2.2f;
2599 /// \endcode
2600 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2602 
2603 /// Matches explicit cast expressions.
2604 ///
2605 /// Matches any cast expression written in user code, whether it be a
2606 /// C-style cast, a functional-style cast, or a keyword cast.
2607 ///
2608 /// Does not match implicit conversions.
2609 ///
2610 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2611 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2612 /// actual cast expressions.
2613 ///
2614 /// \see hasDestinationType.
2615 ///
2616 /// Example: matches all five of the casts in
2617 /// \code
2618 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2619 /// \endcode
2620 /// but does not match the implicit conversion in
2621 /// \code
2622 /// long ell = 42;
2623 /// \endcode
2624 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2626 
2627 /// Matches the implicit cast nodes of Clang's AST.
2628 ///
2629 /// This matches many different places, including function call return value
2630 /// eliding, as well as any type conversions.
2631 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2633 
2634 /// Matches any cast nodes of Clang's AST.
2635 ///
2636 /// Example: castExpr() matches each of the following:
2637 /// \code
2638 /// (int) 3;
2639 /// const_cast<Expr *>(SubExpr);
2640 /// char c = 0;
2641 /// \endcode
2642 /// but does not match
2643 /// \code
2644 /// int i = (0);
2645 /// int k = 0;
2646 /// \endcode
2647 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2648 
2649 /// Matches functional cast expressions
2650 ///
2651 /// Example: Matches Foo(bar);
2652 /// \code
2653 /// Foo f = bar;
2654 /// Foo g = (Foo) bar;
2655 /// Foo h = Foo(bar);
2656 /// \endcode
2657 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2659 
2660 /// Matches functional cast expressions having N != 1 arguments
2661 ///
2662 /// Example: Matches Foo(bar, bar)
2663 /// \code
2664 /// Foo h = Foo(bar, bar);
2665 /// \endcode
2666 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2668 
2669 /// Matches predefined identifier expressions [C99 6.4.2.2].
2670 ///
2671 /// Example: Matches __func__
2672 /// \code
2673 /// printf("%s", __func__);
2674 /// \endcode
2675 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2677 
2678 /// Matches C99 designated initializer expressions [C99 6.7.8].
2679 ///
2680 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2681 /// \code
2682 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2683 /// \endcode
2684 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2686 
2687 /// Matches designated initializer expressions that contain
2688 /// a specific number of designators.
2689 ///
2690 /// Example: Given
2691 /// \code
2692 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2693 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2694 /// \endcode
2695 /// designatorCountIs(2)
2696 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2697 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2698 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2699  return Node.size() == N;
2700 }
2701 
2702 /// Matches \c QualTypes in the clang AST.
2703 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2704 
2705 /// Matches \c Types in the clang AST.
2706 extern const internal::VariadicAllOfMatcher<Type> type;
2707 
2708 /// Matches \c TypeLocs in the clang AST.
2709 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2710 
2711 /// Matches if any of the given matchers matches.
2712 ///
2713 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2714 /// matching submatcher.
2715 ///
2716 /// For example, in:
2717 /// \code
2718 /// class A { int a; int b; };
2719 /// \endcode
2720 /// The matcher:
2721 /// \code
2722 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2723 /// has(fieldDecl(hasName("b")).bind("v"))))
2724 /// \endcode
2725 /// will generate two results binding "v", the first of which binds
2726 /// the field declaration of \c a, the second the field declaration of
2727 /// \c b.
2728 ///
2729 /// Usable as: Any Matcher
2730 extern const internal::VariadicOperatorMatcherFunc<
2732  eachOf;
2733 
2734 /// Matches if any of the given matchers matches.
2735 ///
2736 /// Usable as: Any Matcher
2737 extern const internal::VariadicOperatorMatcherFunc<
2739  anyOf;
2740 
2741 /// Matches if all given matchers match.
2742 ///
2743 /// Usable as: Any Matcher
2744 extern const internal::VariadicOperatorMatcherFunc<
2746  allOf;
2747 
2748 /// Matches any node regardless of the submatcher.
2749 ///
2750 /// However, \c optionally will retain any bindings generated by the submatcher.
2751 /// Useful when additional information which may or may not present about a main
2752 /// matching node is desired.
2753 ///
2754 /// For example, in:
2755 /// \code
2756 /// class Foo {
2757 /// int bar;
2758 /// }
2759 /// \endcode
2760 /// The matcher:
2761 /// \code
2762 /// cxxRecordDecl(
2763 /// optionally(has(
2764 /// fieldDecl(hasName("bar")).bind("var")
2765 /// ))).bind("record")
2766 /// \endcode
2767 /// will produce a result binding for both "record" and "var".
2768 /// The matcher will produce a "record" binding for even if there is no data
2769 /// member named "bar" in that class.
2770 ///
2771 /// Usable as: Any Matcher
2772 extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2773 
2774 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2775 ///
2776 /// Given
2777 /// \code
2778 /// Foo x = bar;
2779 /// int y = sizeof(x) + alignof(x);
2780 /// \endcode
2781 /// unaryExprOrTypeTraitExpr()
2782 /// matches \c sizeof(x) and \c alignof(x)
2783 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2786 
2787 /// Matches any of the \p NodeMatchers with InnerMatchers nested within
2788 ///
2789 /// Given
2790 /// \code
2791 /// if (true);
2792 /// for (; true; );
2793 /// \endcode
2794 /// with the matcher
2795 /// \code
2796 /// mapAnyOf(ifStmt, forStmt).with(
2797 /// hasCondition(cxxBoolLiteralExpr(equals(true)))
2798 /// ).bind("trueCond")
2799 /// \endcode
2800 /// matches the \c if and the \c for. It is equivalent to:
2801 /// \code
2802 /// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2803 /// anyOf(
2804 /// ifStmt(trueCond).bind("trueCond"),
2805 /// forStmt(trueCond).bind("trueCond")
2806 /// );
2807 /// \endcode
2808 ///
2809 /// The with() chain-call accepts zero or more matchers which are combined
2810 /// as-if with allOf() in each of the node matchers.
2811 /// Usable as: Any Matcher
2812 template <typename T, typename... U>
2813 auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2814  return internal::MapAnyOfHelper<U...>();
2815 }
2816 
2817 /// Matches nodes which can be used with binary operators.
2818 ///
2819 /// The code
2820 /// \code
2821 /// var1 != var2;
2822 /// \endcode
2823 /// might be represented in the clang AST as a binaryOperator, a
2824 /// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2825 ///
2826 /// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2827 /// least one is a class type (cxxOperatorCallExpr)
2828 /// * whether the code appears in a template declaration, if at least one of the
2829 /// vars is a dependent-type (binaryOperator)
2830 /// * whether the code relies on a rewritten binary operator, such as a
2831 /// spaceship operator or an inverted equality operator
2832 /// (cxxRewrittenBinaryOperator)
2833 ///
2834 /// This matcher elides details in places where the matchers for the nodes are
2835 /// compatible.
2836 ///
2837 /// Given
2838 /// \code
2839 /// binaryOperation(
2840 /// hasOperatorName("!="),
2841 /// hasLHS(expr().bind("lhs")),
2842 /// hasRHS(expr().bind("rhs"))
2843 /// )
2844 /// \endcode
2845 /// matches each use of "!=" in:
2846 /// \code
2847 /// struct S{
2848 /// bool operator!=(const S&) const;
2849 /// };
2850 ///
2851 /// void foo()
2852 /// {
2853 /// 1 != 2;
2854 /// S() != S();
2855 /// }
2856 ///
2857 /// template<typename T>
2858 /// void templ()
2859 /// {
2860 /// 1 != 2;
2861 /// T() != S();
2862 /// }
2863 /// struct HasOpEq
2864 /// {
2865 /// bool operator==(const HasOpEq &) const;
2866 /// };
2867 ///
2868 /// void inverse()
2869 /// {
2870 /// HasOpEq s1;
2871 /// HasOpEq s2;
2872 /// if (s1 != s2)
2873 /// return;
2874 /// }
2875 ///
2876 /// struct HasSpaceship
2877 /// {
2878 /// bool operator<=>(const HasOpEq &) const;
2879 /// };
2880 ///
2881 /// void use_spaceship()
2882 /// {
2883 /// HasSpaceship s1;
2884 /// HasSpaceship s2;
2885 /// if (s1 != s2)
2886 /// return;
2887 /// }
2888 /// \endcode
2889 extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2892 
2893 /// Matches function calls and constructor calls
2894 ///
2895 /// Because CallExpr and CXXConstructExpr do not share a common
2896 /// base class with API accessing arguments etc, AST Matchers for code
2897 /// which should match both are typically duplicated. This matcher
2898 /// removes the need for duplication.
2899 ///
2900 /// Given code
2901 /// \code
2902 /// struct ConstructorTakesInt
2903 /// {
2904 /// ConstructorTakesInt(int i) {}
2905 /// };
2906 ///
2907 /// void callTakesInt(int i)
2908 /// {
2909 /// }
2910 ///
2911 /// void doCall()
2912 /// {
2913 /// callTakesInt(42);
2914 /// }
2915 ///
2916 /// void doConstruct()
2917 /// {
2918 /// ConstructorTakesInt cti(42);
2919 /// }
2920 /// \endcode
2921 ///
2922 /// The matcher
2923 /// \code
2924 /// invocation(hasArgument(0, integerLiteral(equals(42))))
2925 /// \endcode
2926 /// matches the expression in both doCall and doConstruct
2927 extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
2928 
2929 /// Matches unary expressions that have a specific type of argument.
2930 ///
2931 /// Given
2932 /// \code
2933 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2934 /// \endcode
2935 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2936 /// matches \c sizeof(a) and \c alignof(c)
2938  internal::Matcher<QualType>, InnerMatcher) {
2939  const QualType ArgumentType = Node.getTypeOfArgument();
2940  return InnerMatcher.matches(ArgumentType, Finder, Builder);
2941 }
2942 
2943 /// Matches unary expressions of a certain kind.
2944 ///
2945 /// Given
2946 /// \code
2947 /// int x;
2948 /// int s = sizeof(x) + alignof(x)
2949 /// \endcode
2950 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2951 /// matches \c sizeof(x)
2952 ///
2953 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2954 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2956  return Node.getKind() == Kind;
2957 }
2958 
2959 /// Same as unaryExprOrTypeTraitExpr, but only matching
2960 /// alignof.
2961 inline internal::BindableMatcher<Stmt> alignOfExpr(
2962  const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2964  allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2965  InnerMatcher)));
2966 }
2967 
2968 /// Same as unaryExprOrTypeTraitExpr, but only matching
2969 /// sizeof.
2970 inline internal::BindableMatcher<Stmt> sizeOfExpr(
2971  const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2973  allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2974 }
2975 
2976 /// Matches NamedDecl nodes that have the specified name.
2977 ///
2978 /// Supports specifying enclosing namespaces or classes by prefixing the name
2979 /// with '<enclosing>::'.
2980 /// Does not match typedefs of an underlying type with the given name.
2981 ///
2982 /// Example matches X (Name == "X")
2983 /// \code
2984 /// class X;
2985 /// \endcode
2986 ///
2987 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2988 /// \code
2989 /// namespace a { namespace b { class X; } }
2990 /// \endcode
2991 inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
2992  return internal::Matcher<NamedDecl>(
2993  new internal::HasNameMatcher({std::string(Name)}));
2994 }
2995 
2996 /// Matches NamedDecl nodes that have any of the specified names.
2997 ///
2998 /// This matcher is only provided as a performance optimization of hasName.
2999 /// \code
3000 /// hasAnyName(a, b, c)
3001 /// \endcode
3002 /// is equivalent to, but faster than
3003 /// \code
3004 /// anyOf(hasName(a), hasName(b), hasName(c))
3005 /// \endcode
3006 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3008  hasAnyName;
3009 
3010 /// Matches NamedDecl nodes whose fully qualified names contain
3011 /// a substring matched by the given RegExp.
3012 ///
3013 /// Supports specifying enclosing namespaces or classes by
3014 /// prefixing the name with '<enclosing>::'. Does not match typedefs
3015 /// of an underlying type with the given name.
3016 ///
3017 /// Example matches X (regexp == "::X")
3018 /// \code
3019 /// class X;
3020 /// \endcode
3021 ///
3022 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3023 /// \code
3024 /// namespace foo { namespace bar { class X; } }
3025 /// \endcode
3026 AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3027  std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3028  return RegExp->match(FullNameString);
3029 }
3030 
3031 /// Matches overloaded operator names.
3032 ///
3033 /// Matches overloaded operator names specified in strings without the
3034 /// "operator" prefix: e.g. "<<".
3035 ///
3036 /// Given:
3037 /// \code
3038 /// class A { int operator*(); };
3039 /// const A &operator<<(const A &a, const A &b);
3040 /// A a;
3041 /// a << a; // <-- This matches
3042 /// \endcode
3043 ///
3044 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3045 /// specified line and
3046 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3047 /// matches the declaration of \c A.
3048 ///
3049 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3050 inline internal::PolymorphicMatcher<
3051  internal::HasOverloadedOperatorNameMatcher,
3053  std::vector<std::string>>
3054 hasOverloadedOperatorName(StringRef Name) {
3055  return internal::PolymorphicMatcher<
3056  internal::HasOverloadedOperatorNameMatcher,
3058  std::vector<std::string>>({std::string(Name)});
3059 }
3060 
3061 /// Matches overloaded operator names.
3062 ///
3063 /// Matches overloaded operator names specified in strings without the
3064 /// "operator" prefix: e.g. "<<".
3065 ///
3066 /// hasAnyOverloadedOperatorName("+", "-")
3067 /// Is equivalent to
3068 /// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3069 extern const internal::VariadicFunction<
3070  internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3073  std::vector<std::string>>,
3076 
3077 /// Matches template-dependent, but known, member names.
3078 ///
3079 /// In template declarations, dependent members are not resolved and so can
3080 /// not be matched to particular named declarations.
3081 ///
3082 /// This matcher allows to match on the known name of members.
3083 ///
3084 /// Given
3085 /// \code
3086 /// template <typename T>
3087 /// struct S {
3088 /// void mem();
3089 /// };
3090 /// template <typename T>
3091 /// void x() {
3092 /// S<T> s;
3093 /// s.mem();
3094 /// }
3095 /// \endcode
3096 /// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3098  return Node.getMember().getAsString() == N;
3099 }
3100 
3101 /// Matches template-dependent, but known, member names against an already-bound
3102 /// node
3103 ///
3104 /// In template declarations, dependent members are not resolved and so can
3105 /// not be matched to particular named declarations.
3106 ///
3107 /// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3108 /// and CXXMethodDecl nodes.
3109 ///
3110 /// Given
3111 /// \code
3112 /// template <typename T>
3113 /// struct S {
3114 /// void mem();
3115 /// };
3116 /// template <typename T>
3117 /// void x() {
3118 /// S<T> s;
3119 /// s.mem();
3120 /// }
3121 /// \endcode
3122 /// The matcher
3123 /// @code
3124 /// \c cxxDependentScopeMemberExpr(
3125 /// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3126 /// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3127 /// cxxMethodDecl(hasName("mem")).bind("templMem")
3128 /// )))))
3129 /// )))),
3130 /// memberHasSameNameAsBoundNode("templMem")
3131 /// )
3132 /// @endcode
3133 /// first matches and binds the @c mem member of the @c S template, then
3134 /// compares its name to the usage in @c s.mem() in the @c x function template
3135 AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3136  std::string, BindingID) {
3137  auto MemberName = Node.getMember().getAsString();
3138 
3139  return Builder->removeBindings(
3140  [this, MemberName](const BoundNodesMap &Nodes) {
3141  const auto &BN = Nodes.getNode(this->BindingID);
3142  if (const auto *ND = BN.get<NamedDecl>()) {
3143  if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3144  return true;
3145  return ND->getName() != MemberName;
3146  }
3147  return true;
3148  });
3149 }
3150 
3151 /// Matches C++ classes that are directly or indirectly derived from a class
3152 /// matching \c Base, or Objective-C classes that directly or indirectly
3153 /// subclass a class matching \c Base.
3154 ///
3155 /// Note that a class is not considered to be derived from itself.
3156 ///
3157 /// Example matches Y, Z, C (Base == hasName("X"))
3158 /// \code
3159 /// class X;
3160 /// class Y : public X {}; // directly derived
3161 /// class Z : public Y {}; // indirectly derived
3162 /// typedef X A;
3163 /// typedef A B;
3164 /// class C : public B {}; // derived from a typedef of X
3165 /// \endcode
3166 ///
3167 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
3168 /// \code
3169 /// class Foo;
3170 /// typedef Foo X;
3171 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
3172 /// \endcode
3173 ///
3174 /// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3175 /// \code
3176 /// @interface NSObject @end
3177 /// @interface Bar : NSObject @end
3178 /// \endcode
3179 ///
3180 /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3182  isDerivedFrom,
3184  internal::Matcher<NamedDecl>, Base) {
3185  // Check if the node is a C++ struct/union/class.
3186  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3187  return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3188 
3189  // The node must be an Objective-C class.
3190  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3191  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3192  /*Directly=*/false);
3193 }
3194 
3195 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3197  isDerivedFrom,
3199  std::string, BaseName, 1) {
3200  if (BaseName.empty())
3201  return false;
3202 
3203  const auto M = isDerivedFrom(hasName(BaseName));
3204 
3205  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3206  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3207 
3208  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3209  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3210 }
3211 
3212 /// Matches C++ classes that have a direct or indirect base matching \p
3213 /// BaseSpecMatcher.
3214 ///
3215 /// Example:
3216 /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3217 /// \code
3218 /// class Foo;
3219 /// class Bar : Foo {};
3220 /// class Baz : Bar {};
3221 /// class SpecialBase;
3222 /// class Proxy : SpecialBase {}; // matches Proxy
3223 /// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3224 /// \endcode
3225 ///
3226 // FIXME: Refactor this and isDerivedFrom to reuse implementation.
3227 AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3228  BaseSpecMatcher) {
3229  return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3230 }
3231 
3232 /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3233 ///
3234 /// Example:
3235 /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3236 /// \code
3237 /// class Foo;
3238 /// class Bar : Foo {};
3239 /// class Baz : Bar {};
3240 /// class SpecialBase;
3241 /// class Proxy : SpecialBase {}; // matches Proxy
3242 /// class IndirectlyDerived : Proxy {}; // doesn't match
3243 /// \endcode
3244 AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3245  BaseSpecMatcher) {
3246  return Node.hasDefinition() &&
3247  llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3248  return BaseSpecMatcher.matches(Base, Finder, Builder);
3249  });
3250 }
3251 
3252 /// Similar to \c isDerivedFrom(), but also matches classes that directly
3253 /// match \c Base.
3255  isSameOrDerivedFrom,
3257  internal::Matcher<NamedDecl>, Base, 0) {
3258  const auto M = anyOf(Base, isDerivedFrom(Base));
3259 
3260  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3261  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3262 
3263  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3264  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3265 }
3266 
3267 /// Overloaded method as shortcut for
3268 /// \c isSameOrDerivedFrom(hasName(...)).
3270  isSameOrDerivedFrom,
3272  std::string, BaseName, 1) {
3273  if (BaseName.empty())
3274  return false;
3275 
3276  const auto M = isSameOrDerivedFrom(hasName(BaseName));
3277 
3278  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3279  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3280 
3281  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3282  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3283 }
3284 
3285 /// Matches C++ or Objective-C classes that are directly derived from a class
3286 /// matching \c Base.
3287 ///
3288 /// Note that a class is not considered to be derived from itself.
3289 ///
3290 /// Example matches Y, C (Base == hasName("X"))
3291 /// \code
3292 /// class X;
3293 /// class Y : public X {}; // directly derived
3294 /// class Z : public Y {}; // indirectly derived
3295 /// typedef X A;
3296 /// typedef A B;
3297 /// class C : public B {}; // derived from a typedef of X
3298 /// \endcode
3299 ///
3300 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
3301 /// \code
3302 /// class Foo;
3303 /// typedef Foo X;
3304 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
3305 /// \endcode
3307  isDirectlyDerivedFrom,
3309  internal::Matcher<NamedDecl>, Base, 0) {
3310  // Check if the node is a C++ struct/union/class.
3311  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3312  return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3313 
3314  // The node must be an Objective-C class.
3315  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3316  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3317  /*Directly=*/true);
3318 }
3319 
3320 /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3322  isDirectlyDerivedFrom,
3324  std::string, BaseName, 1) {
3325  if (BaseName.empty())
3326  return false;
3327  const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3328 
3329  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3330  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3331 
3332  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3333  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3334 }
3335 /// Matches the first method of a class or struct that satisfies \c
3336 /// InnerMatcher.
3337 ///
3338 /// Given:
3339 /// \code
3340 /// class A { void func(); };
3341 /// class B { void member(); };
3342 /// \endcode
3343 ///
3344 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3345 /// \c A but not \c B.
3346 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3347  InnerMatcher) {
3348  BoundNodesTreeBuilder Result(*Builder);
3349  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3350  Node.method_end(), Finder, &Result);
3351  if (MatchIt == Node.method_end())
3352  return false;
3353 
3354  if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3355  return false;
3356  *Builder = std::move(Result);
3357  return true;
3358 }
3359 
3360 /// Matches the generated class of lambda expressions.
3361 ///
3362 /// Given:
3363 /// \code
3364 /// auto x = []{};
3365 /// \endcode
3366 ///
3367 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3368 /// \c decltype(x)
3370  return Node.isLambda();
3371 }
3372 
3373 /// Matches AST nodes that have child AST nodes that match the
3374 /// provided matcher.
3375 ///
3376 /// Example matches X, Y
3377 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3378 /// \code
3379 /// class X {}; // Matches X, because X::X is a class of name X inside X.
3380 /// class Y { class X {}; };
3381 /// class Z { class Y { class X {}; }; }; // Does not match Z.
3382 /// \endcode
3383 ///
3384 /// ChildT must be an AST base type.
3385 ///
3386 /// Usable as: Any Matcher
3387 /// Note that has is direct matcher, so it also matches things like implicit
3388 /// casts and paren casts. If you are matching with expr then you should
3389 /// probably consider using ignoringParenImpCasts like:
3390 /// has(ignoringParenImpCasts(expr())).
3391 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3392 
3393 /// Matches AST nodes that have descendant AST nodes that match the
3394 /// provided matcher.
3395 ///
3396 /// Example matches X, Y, Z
3397 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3398 /// \code
3399 /// class X {}; // Matches X, because X::X is a class of name X inside X.
3400 /// class Y { class X {}; };
3401 /// class Z { class Y { class X {}; }; };
3402 /// \endcode
3403 ///
3404 /// DescendantT must be an AST base type.
3405 ///
3406 /// Usable as: Any Matcher
3407 extern const internal::ArgumentAdaptingMatcherFunc<
3408  internal::HasDescendantMatcher>
3409  hasDescendant;
3410 
3411 /// Matches AST nodes that have child AST nodes that match the
3412 /// provided matcher.
3413 ///
3414 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3415 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3416 /// \code
3417 /// class X {};
3418 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3419 /// // inside Y.
3420 /// class Z { class Y { class X {}; }; }; // Does not match Z.
3421 /// \endcode
3422 ///
3423 /// ChildT must be an AST base type.
3424 ///
3425 /// As opposed to 'has', 'forEach' will cause a match for each result that
3426 /// matches instead of only on the first one.
3427 ///
3428 /// Usable as: Any Matcher
3429 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3430  forEach;
3431 
3432 /// Matches AST nodes that have descendant AST nodes that match the
3433 /// provided matcher.
3434 ///
3435 /// Example matches X, A, A::X, B, B::C, B::C::X
3436 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3437 /// \code
3438 /// class X {};
3439 /// class A { class X {}; }; // Matches A, because A::X is a class of name
3440 /// // X inside A.
3441 /// class B { class C { class X {}; }; };
3442 /// \endcode
3443 ///
3444 /// DescendantT must be an AST base type.
3445 ///
3446 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3447 /// each result that matches instead of only on the first one.
3448 ///
3449 /// Note: Recursively combined ForEachDescendant can cause many matches:
3450 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3451 /// forEachDescendant(cxxRecordDecl())
3452 /// )))
3453 /// will match 10 times (plus injected class name matches) on:
3454 /// \code
3455 /// class A { class B { class C { class D { class E {}; }; }; }; };
3456 /// \endcode
3457 ///
3458 /// Usable as: Any Matcher
3459 extern const internal::ArgumentAdaptingMatcherFunc<
3460  internal::ForEachDescendantMatcher>
3462 
3463 /// Matches if the node or any descendant matches.
3464 ///
3465 /// Generates results for each match.
3466 ///
3467 /// For example, in:
3468 /// \code
3469 /// class A { class B {}; class C {}; };
3470 /// \endcode
3471 /// The matcher:
3472 /// \code
3473 /// cxxRecordDecl(hasName("::A"),
3474 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3475 /// \endcode
3476 /// will generate results for \c A, \c B and \c C.
3477 ///
3478 /// Usable as: Any Matcher
3479 template <typename T>
3480 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3481  return eachOf(Matcher, forEachDescendant(Matcher));
3482 }
3483 
3484 /// Matches AST nodes that have a parent that matches the provided
3485 /// matcher.
3486 ///
3487 /// Given
3488 /// \code
3489 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3490 /// \endcode
3491 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3492 ///
3493 /// Usable as: Any Matcher
3494 extern const internal::ArgumentAdaptingMatcherFunc<
3495  internal::HasParentMatcher,
3496  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3497  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3498  hasParent;
3499 
3500 /// Matches AST nodes that have an ancestor that matches the provided
3501 /// matcher.
3502 ///
3503 /// Given
3504 /// \code
3505 /// void f() { if (true) { int x = 42; } }
3506 /// void g() { for (;;) { int x = 43; } }
3507 /// \endcode
3508 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3509 ///
3510 /// Usable as: Any Matcher
3511 extern const internal::ArgumentAdaptingMatcherFunc<
3512  internal::HasAncestorMatcher,
3513  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3514  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3515  hasAncestor;
3516 
3517 /// Matches if the provided matcher does not match.
3518 ///
3519 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3520 /// \code
3521 /// class X {};
3522 /// class Y {};
3523 /// \endcode
3524 ///
3525 /// Usable as: Any Matcher
3526 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3527 
3528 /// Matches a node if the declaration associated with that node
3529 /// matches the given matcher.
3530 ///
3531 /// The associated declaration is:
3532 /// - for type nodes, the declaration of the underlying type
3533 /// - for CallExpr, the declaration of the callee
3534 /// - for MemberExpr, the declaration of the referenced member
3535 /// - for CXXConstructExpr, the declaration of the constructor
3536 /// - for CXXNewExpr, the declaration of the operator new
3537 /// - for ObjCIvarExpr, the declaration of the ivar
3538 ///
3539 /// For type nodes, hasDeclaration will generally match the declaration of the
3540 /// sugared type. Given
3541 /// \code
3542 /// class X {};
3543 /// typedef X Y;
3544 /// Y y;
3545 /// \endcode
3546 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3547 /// typedefDecl. A common use case is to match the underlying, desugared type.
3548 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3549 /// \code
3550 /// varDecl(hasType(hasUnqualifiedDesugaredType(
3551 /// recordType(hasDeclaration(decl())))))
3552 /// \endcode
3553 /// In this matcher, the decl will match the CXXRecordDecl of class X.
3554 ///
3555 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3556 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3557 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3558 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3559 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3560 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3561 /// Matcher<UnresolvedUsingType>
3562 inline internal::PolymorphicMatcher<
3563  internal::HasDeclarationMatcher,
3564  void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3565 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3566  return internal::PolymorphicMatcher<
3567  internal::HasDeclarationMatcher,
3568  void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3569  InnerMatcher);
3570 }
3571 
3572 /// Matches a \c NamedDecl whose underlying declaration matches the given
3573 /// matcher.
3574 ///
3575 /// Given
3576 /// \code
3577 /// namespace N { template<class T> void f(T t); }
3578 /// template <class T> void g() { using N::f; f(T()); }
3579 /// \endcode
3580 /// \c unresolvedLookupExpr(hasAnyDeclaration(
3581 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3582 /// matches the use of \c f in \c g() .
3583 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3584  InnerMatcher) {
3585  const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3586 
3587  return UnderlyingDecl != nullptr &&
3588  InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3589 }
3590 
3591 /// Matches on the implicit object argument of a member call expression, after
3592 /// stripping off any parentheses or implicit casts.
3593 ///
3594 /// Given
3595 /// \code
3596 /// class Y { public: void m(); };
3597 /// Y g();
3598 /// class X : public Y {};
3599 /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3600 /// \endcode
3601 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3602 /// matches `y.m()` and `(g()).m()`.
3603 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3604 /// matches `x.m()`.
3605 /// cxxMemberCallExpr(on(callExpr()))
3606 /// matches `(g()).m()`.
3607 ///
3608 /// FIXME: Overload to allow directly matching types?
3609 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3610  InnerMatcher) {
3611  const Expr *ExprNode = Node.getImplicitObjectArgument()
3612  ->IgnoreParenImpCasts();
3613  return (ExprNode != nullptr &&
3614  InnerMatcher.matches(*ExprNode, Finder, Builder));
3615 }
3616 
3617 
3618 /// Matches on the receiver of an ObjectiveC Message expression.
3619 ///
3620 /// Example
3621 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3622 /// matches the [webView ...] message invocation.
3623 /// \code
3624 /// NSString *webViewJavaScript = ...
3625 /// UIWebView *webView = ...
3626 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3627 /// \endcode
3628 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3629  InnerMatcher) {
3630  const QualType TypeDecl = Node.getReceiverType();
3631  return InnerMatcher.matches(TypeDecl, Finder, Builder);
3632 }
3633 
3634 /// Returns true when the Objective-C method declaration is a class method.
3635 ///
3636 /// Example
3637 /// matcher = objcMethodDecl(isClassMethod())
3638 /// matches
3639 /// \code
3640 /// @interface I + (void)foo; @end
3641 /// \endcode
3642 /// but not
3643 /// \code
3644 /// @interface I - (void)bar; @end
3645 /// \endcode
3646 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
3647  return Node.isClassMethod();
3648 }
3649 
3650 /// Returns true when the Objective-C method declaration is an instance method.
3651 ///
3652 /// Example
3653 /// matcher = objcMethodDecl(isInstanceMethod())
3654 /// matches
3655 /// \code
3656 /// @interface I - (void)bar; @end
3657 /// \endcode
3658 /// but not
3659 /// \code
3660 /// @interface I + (void)foo; @end
3661 /// \endcode
3663  return Node.isInstanceMethod();
3664 }
3665 
3666 /// Returns true when the Objective-C message is sent to a class.
3667 ///
3668 /// Example
3669 /// matcher = objcMessageExpr(isClassMessage())
3670 /// matches
3671 /// \code
3672 /// [NSString stringWithFormat:@"format"];
3673 /// \endcode
3674 /// but not
3675 /// \code
3676 /// NSString *x = @"hello";
3677 /// [x containsString:@"h"];
3678 /// \endcode
3679 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
3680  return Node.isClassMessage();
3681 }
3682 
3683 /// Returns true when the Objective-C message is sent to an instance.
3684 ///
3685 /// Example
3686 /// matcher = objcMessageExpr(isInstanceMessage())
3687 /// matches
3688 /// \code
3689 /// NSString *x = @"hello";
3690 /// [x containsString:@"h"];
3691 /// \endcode
3692 /// but not
3693 /// \code
3694 /// [NSString stringWithFormat:@"format"];
3695 /// \endcode
3696 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3697  return Node.isInstanceMessage();
3698 }
3699 
3700 /// Matches if the Objective-C message is sent to an instance,
3701 /// and the inner matcher matches on that instance.
3702 ///
3703 /// For example the method call in
3704 /// \code
3705 /// NSString *x = @"hello";
3706 /// [x containsString:@"h"];
3707 /// \endcode
3708 /// is matched by
3709 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3710 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3711  InnerMatcher) {
3712  const Expr *ReceiverNode = Node.getInstanceReceiver();
3713  return (ReceiverNode != nullptr &&
3714  InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3715  Builder));
3716 }
3717 
3718 /// Matches when BaseName == Selector.getAsString()
3719 ///
3720 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3721 /// matches the outer message expr in the code below, but NOT the message
3722 /// invocation for self.bodyView.
3723 /// \code
3724 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3725 /// \endcode
3726 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3727  Selector Sel = Node.getSelector();
3728  return BaseName == Sel.getAsString();
3729 }
3730 
3731 /// Matches when at least one of the supplied string equals to the
3732 /// Selector.getAsString()
3733 ///
3734 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3735 /// matches both of the expressions below:
3736 /// \code
3737 /// [myObj methodA:argA];
3738 /// [myObj methodB:argB];
3739 /// \endcode
3740 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3741  StringRef,
3744 
3745 /// Matches ObjC selectors whose name contains
3746 /// a substring matched by the given RegExp.
3747 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3748 /// matches the outer message expr in the code below, but NOT the message
3749 /// invocation for self.bodyView.
3750 /// \code
3751 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3752 /// \endcode
3753 AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3754  std::string SelectorString = Node.getSelector().getAsString();
3755  return RegExp->match(SelectorString);
3756 }
3757 
3758 /// Matches when the selector is the empty selector
3759 ///
3760 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3761 /// represent an error condition in the tree!
3762 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3763  return Node.getSelector().isNull();
3764 }
3765 
3766 /// Matches when the selector is a Unary Selector
3767 ///
3768 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3769 /// matches self.bodyView in the code below, but NOT the outer message
3770 /// invocation of "loadHTMLString:baseURL:".
3771 /// \code
3772 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3773 /// \endcode
3774 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3775  return Node.getSelector().isUnarySelector();
3776 }
3777 
3778 /// Matches when the selector is a keyword selector
3779 ///
3780 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3781 /// message expression in
3782 ///
3783 /// \code
3784 /// UIWebView *webView = ...;
3785 /// CGRect bodyFrame = webView.frame;
3786 /// bodyFrame.size.height = self.bodyContentHeight;
3787 /// webView.frame = bodyFrame;
3788 /// // ^---- matches here
3789 /// \endcode
3790 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3791  return Node.getSelector().isKeywordSelector();
3792 }
3793 
3794 /// Matches when the selector has the specified number of arguments
3795 ///
3796 /// matcher = objCMessageExpr(numSelectorArgs(0));
3797 /// matches self.bodyView in the code below
3798 ///
3799 /// matcher = objCMessageExpr(numSelectorArgs(2));
3800 /// matches the invocation of "loadHTMLString:baseURL:" but not that
3801 /// of self.bodyView
3802 /// \code
3803 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3804 /// \endcode
3805 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3806  return Node.getSelector().getNumArgs() == N;
3807 }
3808 
3809 /// Matches if the call expression's callee expression matches.
3810 ///
3811 /// Given
3812 /// \code
3813 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3814 /// void f() { f(); }
3815 /// \endcode
3816 /// callExpr(callee(expr()))
3817 /// matches this->x(), x(), y.x(), f()
3818 /// with callee(...)
3819 /// matching this->x, x, y.x, f respectively
3820 ///
3821 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3822 /// because this introduces ambiguous overloads with calls to Callee taking a
3823 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3824 /// implemented in terms of implicit casts.
3825 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3826  InnerMatcher) {
3827  const Expr *ExprNode = Node.getCallee();
3828  return (ExprNode != nullptr &&
3829  InnerMatcher.matches(*ExprNode, Finder, Builder));
3830 }
3831 
3832 /// Matches if the call expression's callee's declaration matches the
3833 /// given matcher.
3834 ///
3835 /// Example matches y.x() (matcher = callExpr(callee(
3836 /// cxxMethodDecl(hasName("x")))))
3837 /// \code
3838 /// class Y { public: void x(); };
3839 /// void z() { Y y; y.x(); }
3840 /// \endcode
3841 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3842  1) {
3843  return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3844 }
3845 
3846 /// Matches if the expression's or declaration's type matches a type
3847 /// matcher.
3848 ///
3849 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3850 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3851 /// and U (matcher = typedefDecl(hasType(asString("int")))
3852 /// and friend class X (matcher = friendDecl(hasType("X"))
3853 /// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3854 /// asString("class X")))
3855 /// \code
3856 /// class X {};
3857 /// void y(X &x) { x; X z; }
3858 /// typedef int U;
3859 /// class Y { friend class X; };
3860 /// class Z : public virtual X {};
3861 /// \endcode
3863  hasType,
3866  internal::Matcher<QualType>, InnerMatcher, 0) {
3868  if (!QT.isNull())
3869  return InnerMatcher.matches(QT, Finder, Builder);
3870  return false;
3871 }
3872 
3873 /// Overloaded to match the declaration of the expression's or value
3874 /// declaration's type.
3875 ///
3876 /// In case of a value declaration (for example a variable declaration),
3877 /// this resolves one layer of indirection. For example, in the value
3878 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3879 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3880 /// declaration of x.
3881 ///
3882 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3883 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3884 /// and friend class X (matcher = friendDecl(hasType("X"))
3885 /// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3886 /// cxxRecordDecl(hasName("X"))))
3887 /// \code
3888 /// class X {};
3889 /// void y(X &x) { x; X z; }
3890 /// class Y { friend class X; };
3891 /// class Z : public virtual X {};
3892 /// \endcode
3893 ///
3894 /// Example matches class Derived
3895 /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
3896 /// \code
3897 /// class Base {};
3898 /// class Derived : Base {};
3899 /// \endcode
3900 ///
3901 /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
3902 /// Matcher<CXXBaseSpecifier>
3904  hasType,
3907  internal::Matcher<Decl>, InnerMatcher, 1) {
3909  if (!QT.isNull())
3910  return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3911  return false;
3912 }
3913 
3914 /// Matches if the type location of a node matches the inner matcher.
3915 ///
3916 /// Examples:
3917 /// \code
3918 /// int x;
3919 /// \endcode
3920 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3921 /// matches int x
3922 ///
3923 /// \code
3924 /// auto x = int(3);
3925 /// \code
3926 /// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
3927 /// matches int(3)
3928 ///
3929 /// \code
3930 /// struct Foo { Foo(int, int); };
3931 /// auto x = Foo(1, 2);
3932 /// \code
3933 /// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
3934 /// matches Foo(1, 2)
3935 ///
3936 /// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
3937 /// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
3938 /// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
3939 /// Matcher<CXXUnresolvedConstructExpr>,
3940 /// Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>,
3941 /// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
3942 /// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
3943 /// Matcher<TypedefNameDecl>
3945  hasTypeLoc,
3951  TypedefNameDecl),
3952  internal::Matcher<TypeLoc>, Inner) {
3953  TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
3954  if (source == nullptr) {
3955  // This happens for example for implicit destructors.
3956  return false;
3957  }
3958  return Inner.matches(source->getTypeLoc(), Finder, Builder);
3959 }
3960 
3961 /// Matches if the matched type is represented by the given string.
3962 ///
3963 /// Given
3964 /// \code
3965 /// class Y { public: void x(); };
3966 /// void z() { Y* y; y->x(); }
3967 /// \endcode
3968 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3969 /// matches y->x()
3971  return Name == Node.getAsString();
3972 }
3973 
3974 /// Matches if the matched type is a pointer type and the pointee type
3975 /// matches the specified matcher.
3976 ///
3977 /// Example matches y->x()
3978 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3979 /// cxxRecordDecl(hasName("Y")))))))
3980 /// \code
3981 /// class Y { public: void x(); };
3982 /// void z() { Y *y; y->x(); }
3983 /// \endcode
3985  QualType, pointsTo, internal::Matcher<QualType>,
3986  InnerMatcher) {
3987  return (!Node.isNull() && Node->isAnyPointerType() &&
3988  InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3989 }
3990 
3991 /// Overloaded to match the pointee type's declaration.
3992 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3993  InnerMatcher, 1) {
3994  return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3995  .matches(Node, Finder, Builder);
3996 }
3997 
3998 /// Matches if the matched type matches the unqualified desugared
3999 /// type of the matched node.
4000 ///
4001 /// For example, in:
4002 /// \code
4003 /// class A {};
4004 /// using B = A;
4005 /// \endcode
4006 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4007 /// both B and A.
4008 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4009  InnerMatcher) {
4010  return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4011  Builder);
4012 }
4013 
4014 /// Matches if the matched type is a reference type and the referenced
4015 /// type matches the specified matcher.
4016 ///
4017 /// Example matches X &x and const X &y
4018 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4019 /// \code
4020 /// class X {
4021 /// void a(X b) {
4022 /// X &x = b;
4023 /// const X &y = b;
4024 /// }
4025 /// };
4026 /// \endcode
4027 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4028  InnerMatcher) {
4029  return (!Node.isNull() && Node->isReferenceType() &&
4030  InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4031 }
4032 
4033 /// Matches QualTypes whose canonical type matches InnerMatcher.
4034 ///
4035 /// Given:
4036 /// \code
4037 /// typedef int &int_ref;
4038 /// int a;
4039 /// int_ref b = a;
4040 /// \endcode
4041 ///
4042 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4043 /// declaration of b but \c
4044 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4045 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4046  InnerMatcher) {
4047  if (Node.isNull())
4048  return false;
4049  return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4050 }
4051 
4052 /// Overloaded to match the referenced type's declaration.
4053 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4054  InnerMatcher, 1) {
4055  return references(qualType(hasDeclaration(InnerMatcher)))
4056  .matches(Node, Finder, Builder);
4057 }
4058 
4059 /// Matches on the implicit object argument of a member call expression. Unlike
4060 /// `on`, matches the argument directly without stripping away anything.
4061 ///
4062 /// Given
4063 /// \code
4064 /// class Y { public: void m(); };
4065 /// Y g();
4066 /// class X : public Y { void g(); };
4067 /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4068 /// \endcode
4069 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4070 /// cxxRecordDecl(hasName("Y")))))
4071 /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
4072 /// cxxMemberCallExpr(on(callExpr()))
4073 /// does not match `(g()).m()`, because the parens are not ignored.
4074 ///
4075 /// FIXME: Overload to allow directly matching types?
4076 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4077  internal::Matcher<Expr>, InnerMatcher) {
4078  const Expr *ExprNode = Node.getImplicitObjectArgument();
4079  return (ExprNode != nullptr &&
4080  InnerMatcher.matches(*ExprNode, Finder, Builder));
4081 }
4082 
4083 /// Matches if the type of the expression's implicit object argument either
4084 /// matches the InnerMatcher, or is a pointer to a type that matches the
4085 /// InnerMatcher.
4086 ///
4087 /// Given
4088 /// \code
4089 /// class Y { public: void m(); };
4090 /// class X : public Y { void g(); };
4091 /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4092 /// \endcode
4093 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4094 /// cxxRecordDecl(hasName("Y")))))
4095 /// matches `y.m()`, `p->m()` and `x.m()`.
4096 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4097 /// cxxRecordDecl(hasName("X")))))
4098 /// matches `x.g()`.
4100  internal::Matcher<QualType>, InnerMatcher, 0) {
4101  return onImplicitObjectArgument(
4102  anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4103  .matches(Node, Finder, Builder);
4104 }
4105 
4106 /// Overloaded to match the type's declaration.
4108  internal::Matcher<Decl>, InnerMatcher, 1) {
4109  return onImplicitObjectArgument(
4110  anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4111  .matches(Node, Finder, Builder);
4112 }
4113 
4114 /// Matches a DeclRefExpr that refers to a declaration that matches the
4115 /// specified matcher.
4116 ///
4117 /// Example matches x in if(x)
4118 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4119 /// \code
4120 /// bool x;
4121 /// if (x) {}
4122 /// \endcode
4123 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4124  InnerMatcher) {
4125  const Decl *DeclNode = Node.getDecl();
4126  return (DeclNode != nullptr &&
4127  InnerMatcher.matches(*DeclNode, Finder, Builder));
4128 }
4129 
4130 /// Matches if a node refers to a declaration through a specific
4131 /// using shadow declaration.
4132 ///
4133 /// Examples:
4134 /// \code
4135 /// namespace a { int f(); }
4136 /// using a::f;
4137 /// int x = f();
4138 /// \endcode
4139 /// declRefExpr(throughUsingDecl(anything()))
4140 /// matches \c f
4141 ///
4142 /// \code
4143 /// namespace a { class X{}; }
4144 /// using a::X;
4145 /// X x;
4146 /// \code
4147 /// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4148 /// matches \c X
4149 ///
4150 /// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4151 AST_POLYMORPHIC_MATCHER_P(throughUsingDecl,
4153  UsingType),
4154  internal::Matcher<UsingShadowDecl>, Inner) {
4155  const NamedDecl *FoundDecl = Node.getFoundDecl();
4156  if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4157  return Inner.matches(*UsingDecl, Finder, Builder);
4158  return false;
4159 }
4160 
4161 /// Matches an \c OverloadExpr if any of the declarations in the set of
4162 /// overloads matches the given matcher.
4163 ///
4164 /// Given
4165 /// \code
4166 /// template <typename T> void foo(T);
4167 /// template <typename T> void bar(T);
4168 /// template <typename T> void baz(T t) {
4169 /// foo(t);
4170 /// bar(t);
4171 /// }
4172 /// \endcode
4173 /// unresolvedLookupExpr(hasAnyDeclaration(
4174 /// functionTemplateDecl(hasName("foo"))))
4175 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4176 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4177  InnerMatcher) {
4178  return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4179  Node.decls_end(), Finder,
4180  Builder) != Node.decls_end();
4181 }
4182 
4183 /// Matches the Decl of a DeclStmt which has a single declaration.
4184 ///
4185 /// Given
4186 /// \code
4187 /// int a, b;
4188 /// int c;
4189 /// \endcode
4190 /// declStmt(hasSingleDecl(anything()))
4191 /// matches 'int c;' but not 'int a, b;'.
4192 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4193  if (Node.isSingleDecl()) {
4194  const Decl *FoundDecl = Node.getSingleDecl();
4195  return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4196  }
4197  return false;
4198 }
4199 
4200 /// Matches a variable declaration that has an initializer expression
4201 /// that matches the given matcher.
4202 ///
4203 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4204 /// \code
4205 /// bool y() { return true; }
4206 /// bool x = y();
4207 /// \endcode
4209  VarDecl, hasInitializer, internal::Matcher<Expr>,
4210  InnerMatcher) {
4211  const Expr *Initializer = Node.getAnyInitializer();
4212  return (Initializer != nullptr &&
4213  InnerMatcher.matches(*Initializer, Finder, Builder));
4214 }
4215 
4216 /// Matches a variable serving as the implicit variable for a lambda init-
4217 /// capture.
4218 ///
4219 /// Example matches x (matcher = varDecl(isInitCapture()))
4220 /// \code
4221 /// auto f = [x=3]() { return x; };
4222 /// \endcode
4223 AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4224 
4225 /// Matches each lambda capture in a lambda expression.
4226 ///
4227 /// Given
4228 /// \code
4229 /// int main() {
4230 /// int x, y;
4231 /// float z;
4232 /// auto f = [=]() { return x + y + z; };
4233 /// }
4234 /// \endcode
4235 /// lambdaExpr(forEachLambdaCapture(
4236 /// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4237 /// will trigger two matches, binding for 'x' and 'y' respectively.
4238 AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4239  internal::Matcher<LambdaCapture>, InnerMatcher) {
4240  BoundNodesTreeBuilder Result;
4241  bool Matched = false;
4242  for (const auto &Capture : Node.captures()) {
4243  if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4244  continue;
4245  BoundNodesTreeBuilder CaptureBuilder(*Builder);
4246  if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4247  Matched = true;
4248  Result.addMatch(CaptureBuilder);
4249  }
4250  }
4251  *Builder = std::move(Result);
4252  return Matched;
4253 }
4254 
4255 /// \brief Matches a static variable with local scope.
4256 ///
4257 /// Example matches y (matcher = varDecl(isStaticLocal()))
4258 /// \code
4259 /// void f() {
4260 /// int x;
4261 /// static int y;
4262 /// }
4263 /// static int z;
4264 /// \endcode
4265 AST_MATCHER(VarDecl, isStaticLocal) {
4266  return Node.isStaticLocal();
4267 }
4268 
4269 /// Matches a variable declaration that has function scope and is a
4270 /// non-static local variable.
4271 ///
4272 /// Example matches x (matcher = varDecl(hasLocalStorage())
4273 /// \code
4274 /// void f() {
4275 /// int x;
4276 /// static int y;
4277 /// }
4278 /// int z;
4279 /// \endcode
4280 AST_MATCHER(VarDecl, hasLocalStorage) {
4281  return Node.hasLocalStorage();
4282 }
4283 
4284 /// Matches a variable declaration that does not have local storage.
4285 ///
4286 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4287 /// \code
4288 /// void f() {
4289 /// int x;
4290 /// static int y;
4291 /// }
4292 /// int z;
4293 /// \endcode
4294 AST_MATCHER(VarDecl, hasGlobalStorage) {
4295  return Node.hasGlobalStorage();
4296 }
4297 
4298 /// Matches a variable declaration that has automatic storage duration.
4299 ///
4300 /// Example matches x, but not y, z, or a.
4301 /// (matcher = varDecl(hasAutomaticStorageDuration())
4302 /// \code
4303 /// void f() {
4304 /// int x;
4305 /// static int y;
4306 /// thread_local int z;
4307 /// }
4308 /// int a;
4309 /// \endcode
4310 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4311  return Node.getStorageDuration() == SD_Automatic;
4312 }
4313 
4314 /// Matches a variable declaration that has static storage duration.
4315 /// It includes the variable declared at namespace scope and those declared
4316 /// with "static" and "extern" storage class specifiers.
4317 ///
4318 /// \code
4319 /// void f() {
4320 /// int x;
4321 /// static int y;
4322 /// thread_local int z;
4323 /// }
4324 /// int a;
4325 /// static int b;
4326 /// extern int c;
4327 /// varDecl(hasStaticStorageDuration())
4328 /// matches the function declaration y, a, b and c.
4329 /// \endcode
4330 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4331  return Node.getStorageDuration() == SD_Static;
4332 }
4333 
4334 /// Matches a variable declaration that has thread storage duration.
4335 ///
4336 /// Example matches z, but not x, z, or a.
4337 /// (matcher = varDecl(hasThreadStorageDuration())
4338 /// \code
4339 /// void f() {
4340 /// int x;
4341 /// static int y;
4342 /// thread_local int z;
4343 /// }
4344 /// int a;
4345 /// \endcode
4346 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4347  return Node.getStorageDuration() == SD_Thread;
4348 }
4349 
4350 /// Matches a variable declaration that is an exception variable from
4351 /// a C++ catch block, or an Objective-C \@catch statement.
4352 ///
4353 /// Example matches x (matcher = varDecl(isExceptionVariable())
4354 /// \code
4355 /// void f(int y) {
4356 /// try {
4357 /// } catch (int x) {
4358 /// }
4359 /// }
4360 /// \endcode
4361 AST_MATCHER(VarDecl, isExceptionVariable) {
4362  return Node.isExceptionVariable();
4363 }
4364 
4365 /// Checks that a call expression or a constructor call expression has
4366 /// a specific number of arguments (including absent default arguments).
4367 ///
4368 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4369 /// \code
4370 /// void f(int x, int y);
4371 /// f(0, 0);
4372 /// \endcode
4377  unsigned, N) {
4378  unsigned NumArgs = Node.getNumArgs();
4379  if (!Finder->isTraversalIgnoringImplicitNodes())
4380  return NumArgs == N;
4381  while (NumArgs) {
4382  if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4383  break;
4384  --NumArgs;
4385  }
4386  return NumArgs == N;
4387 }
4388 
4389 /// Matches the n'th argument of a call expression or a constructor
4390 /// call expression.
4391 ///
4392 /// Example matches y in x(y)
4393 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
4394 /// \code
4395 /// void x(int) { int y; x(y); }
4396 /// \endcode
4401  unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4402  if (N >= Node.getNumArgs())
4403  return false;
4404  const Expr *Arg = Node.getArg(N);
4405  if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4406  return false;
4407  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4408 }
4409 
4410 /// Matches the n'th item of an initializer list expression.
4411 ///
4412 /// Example matches y.
4413 /// (matcher = initListExpr(hasInit(0, expr())))
4414 /// \code
4415 /// int x{y}.
4416 /// \endcode
4417 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
4418  ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
4419  return N < Node.getNumInits() &&
4420  InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4421 }
4422 
4423 /// Matches declaration statements that contain a specific number of
4424 /// declarations.
4425 ///
4426 /// Example: Given
4427 /// \code
4428 /// int a, b;
4429 /// int c;
4430 /// int d = 2, e;
4431 /// \endcode
4432 /// declCountIs(2)
4433 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4434 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4435  return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4436 }
4437 
4438 /// Matches the n'th declaration of a declaration statement.
4439 ///
4440 /// Note that this does not work for global declarations because the AST
4441 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4442 /// DeclStmt's.
4443 /// Example: Given non-global declarations
4444 /// \code
4445 /// int a, b = 0;
4446 /// int c;
4447 /// int d = 2, e;
4448 /// \endcode
4449 /// declStmt(containsDeclaration(
4450 /// 0, varDecl(hasInitializer(anything()))))
4451 /// matches only 'int d = 2, e;', and
4452 /// declStmt(containsDeclaration(1, varDecl()))
4453 /// \code
4454 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
4455 /// but 'int c;' is not matched.
4456 /// \endcode
4457 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4458  internal::Matcher<Decl>, InnerMatcher) {
4459  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4460  if (N >= NumDecls)
4461  return false;
4462  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4463  std::advance(Iterator, N);
4464  return InnerMatcher.matches(**Iterator, Finder, Builder);
4465 }
4466 
4467 /// Matches a C++ catch statement that has a catch-all handler.
4468 ///
4469 /// Given
4470 /// \code
4471 /// try {
4472 /// // ...
4473 /// } catch (int) {
4474 /// // ...
4475 /// } catch (...) {
4476 /// // ...
4477 /// }
4478 /// \endcode
4479 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4481  return Node.getExceptionDecl() == nullptr;
4482 }
4483 
4484 /// Matches a constructor initializer.
4485 ///
4486 /// Given
4487 /// \code
4488 /// struct Foo {
4489 /// Foo() : foo_(1) { }
4490 /// int foo_;
4491 /// };
4492 /// \endcode
4493 /// cxxRecordDecl(has(cxxConstructorDecl(
4494 /// hasAnyConstructorInitializer(anything())
4495 /// )))
4496 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4497 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4498  internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4499  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4500  Node.init_end(), Finder, Builder);
4501  if (MatchIt == Node.init_end())
4502  return false;
4503  return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4504 }
4505 
4506 /// Matches the field declaration of a constructor initializer.
4507 ///
4508 /// Given
4509 /// \code
4510 /// struct Foo {
4511 /// Foo() : foo_(1) { }
4512 /// int foo_;
4513 /// };
4514 /// \endcode
4515 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4516 /// forField(hasName("foo_"))))))
4517 /// matches Foo
4518 /// with forField matching foo_
4520  internal::Matcher<FieldDecl>, InnerMatcher) {
4521  const FieldDecl *NodeAsDecl = Node.getAnyMember();
4522  return (NodeAsDecl != nullptr &&
4523  InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4524 }
4525 
4526 /// Matches the initializer expression of a constructor initializer.
4527 ///
4528 /// Given
4529 /// \code
4530 /// struct Foo {
4531 /// Foo() : foo_(1) { }
4532 /// int foo_;
4533 /// };
4534 /// \endcode
4535 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4536 /// withInitializer(integerLiteral(equals(1)))))))
4537 /// matches Foo
4538 /// with withInitializer matching (1)
4540  internal::Matcher<Expr>, InnerMatcher) {
4541  const Expr* NodeAsExpr = Node.getInit();
4542  return (NodeAsExpr != nullptr &&
4543  InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4544 }
4545 
4546 /// Matches a constructor initializer if it is explicitly written in
4547 /// code (as opposed to implicitly added by the compiler).
4548 ///
4549 /// Given
4550 /// \code
4551 /// struct Foo {
4552 /// Foo() { }
4553 /// Foo(int) : foo_("A") { }
4554 /// string foo_;
4555 /// };
4556 /// \endcode
4557 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4558 /// will match Foo(int), but not Foo()
4560  return Node.isWritten();
4561 }
4562 
4563 /// Matches a constructor initializer if it is initializing a base, as
4564 /// opposed to a member.
4565 ///
4566 /// Given
4567 /// \code
4568 /// struct B {};
4569 /// struct D : B {
4570 /// int I;
4571 /// D(int i) : I(i) {}
4572 /// };
4573 /// struct E : B {
4574 /// E() : B() {}
4575 /// };
4576 /// \endcode
4577 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4578 /// will match E(), but not match D(int).
4579 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4580  return Node.isBaseInitializer();
4581 }
4582 
4583 /// Matches a constructor initializer if it is initializing a member, as
4584 /// opposed to a base.
4585 ///
4586 /// Given
4587 /// \code
4588 /// struct B {};
4589 /// struct D : B {
4590 /// int I;
4591 /// D(int i) : I(i) {}
4592 /// };
4593 /// struct E : B {
4594 /// E() : B() {}
4595 /// };
4596 /// \endcode
4597 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4598 /// will match D(int), but not match E().
4599 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4600  return Node.isMemberInitializer();
4601 }
4602 
4603 /// Matches any argument of a call expression or a constructor call
4604 /// expression, or an ObjC-message-send expression.
4605 ///
4606 /// Given
4607 /// \code
4608 /// void x(int, int, int) { int y; x(1, y, 42); }
4609 /// \endcode
4610 /// callExpr(hasAnyArgument(declRefExpr()))
4611 /// matches x(1, y, 42)
4612 /// with hasAnyArgument(...)
4613 /// matching y
4614 ///
4615 /// For ObjectiveC, given
4616 /// \code
4617 /// @interface I - (void) f:(int) y; @end
4618 /// void foo(I *i) { [i f:12]; }
4619 /// \endcode
4620 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4621 /// matches [i f:12]
4626  internal::Matcher<Expr>, InnerMatcher) {
4627  for (const Expr *Arg : Node.arguments()) {
4628  if (Finder->isTraversalIgnoringImplicitNodes() &&
4629  isa<CXXDefaultArgExpr>(Arg))
4630  break;
4631  BoundNodesTreeBuilder Result(*Builder);
4632  if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4633  *Builder = std::move(Result);
4634  return true;
4635  }
4636  }
4637  return false;
4638 }
4639 
4640 /// Matches lambda captures.
4641 ///
4642 /// Given
4643 /// \code
4644 /// int main() {
4645 /// int x;
4646 /// auto f = [x](){};
4647 /// auto g = [x = 1](){};
4648 /// }
4649 /// \endcode
4650 /// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4651 /// `lambdaCapture()` matches `x` and `x=1`.
4652 extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4653 
4654 /// Matches any capture in a lambda expression.
4655 ///
4656 /// Given
4657 /// \code
4658 /// void foo() {
4659 /// int t = 5;
4660 /// auto f = [=](){ return t; };
4661 /// }
4662 /// \endcode
4663 /// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4664 /// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4665 /// both match `[=](){ return t; }`.
4666 AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4667  InnerMatcher) {
4668  for (const LambdaCapture &Capture : Node.captures()) {
4669  clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4670  if (InnerMatcher.matches(Capture, Finder, &Result)) {
4671  *Builder = std::move(Result);
4672  return true;
4673  }
4674  }
4675  return false;
4676 }
4677 
4678 /// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4679 /// `VarDecl` can be a separate variable that is captured by value or
4680 /// reference, or a synthesized variable if the capture has an initializer.
4681 ///
4682 /// Given
4683 /// \code
4684 /// void foo() {
4685 /// int x;
4686 /// auto f = [x](){};
4687 /// auto g = [x = 1](){};
4688 /// }
4689 /// \endcode
4690 /// In the matcher
4691 /// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4692 /// capturesVar(hasName("x")) matches `x` and `x = 1`.
4693 AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<VarDecl>,
4694  InnerMatcher) {
4695  auto *capturedVar = Node.getCapturedVar();
4696  return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
4697 }
4698 
4699 /// Matches a `LambdaCapture` that refers to 'this'.
4700 ///
4701 /// Given
4702 /// \code
4703 /// class C {
4704 /// int cc;
4705 /// int f() {
4706 /// auto l = [this]() { return cc; };
4707 /// return l();
4708 /// }
4709 /// };
4710 /// \endcode
4711 /// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
4712 /// matches `[this]() { return cc; }`.
4713 AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
4714 
4715 /// Matches a constructor call expression which uses list initialization.
4716 AST_MATCHER(CXXConstructExpr, isListInitialization) {
4717  return Node.isListInitialization();
4718 }
4719 
4720 /// Matches a constructor call expression which requires
4721 /// zero initialization.
4722 ///
4723 /// Given
4724 /// \code
4725 /// void foo() {
4726 /// struct point { double x; double y; };
4727 /// point pt[2] = { { 1.0, 2.0 } };
4728 /// }
4729 /// \endcode
4730 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
4731 /// will match the implicit array filler for pt[1].
4732 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
4733  return Node.requiresZeroInitialization();
4734 }
4735 
4736 /// Matches the n'th parameter of a function or an ObjC method
4737 /// declaration or a block.
4738 ///
4739 /// Given
4740 /// \code
4741 /// class X { void f(int x) {} };
4742 /// \endcode
4743 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
4744 /// matches f(int x) {}
4745 /// with hasParameter(...)
4746 /// matching int x
4747 ///
4748 /// For ObjectiveC, given
4749 /// \code
4750 /// @interface I - (void) f:(int) y; @end
4751 /// \endcode
4752 //
4753 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
4754 /// matches the declaration of method f with hasParameter
4755 /// matching y.
4759  BlockDecl),
4760  unsigned, N, internal::Matcher<ParmVarDecl>,
4761  InnerMatcher) {
4762  return (N < Node.parameters().size()
4763  && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4764 }
4765 
4766 /// Matches all arguments and their respective ParmVarDecl.
4767 ///
4768 /// Given
4769 /// \code
4770 /// void f(int i);
4771 /// int y;
4772 /// f(y);
4773 /// \endcode
4774 /// callExpr(
4775 /// forEachArgumentWithParam(
4776 /// declRefExpr(to(varDecl(hasName("y")))),
4777 /// parmVarDecl(hasType(isInteger()))
4778 /// ))
4779 /// matches f(y);
4780 /// with declRefExpr(...)
4781 /// matching int y
4782 /// and parmVarDecl(...)
4783 /// matching int i
4784 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4787  internal::Matcher<Expr>, ArgMatcher,
4788  internal::Matcher<ParmVarDecl>, ParamMatcher) {
4789  BoundNodesTreeBuilder Result;
4790  // The first argument of an overloaded member operator is the implicit object
4791  // argument of the method which should not be matched against a parameter, so
4792  // we skip over it here.
4793  BoundNodesTreeBuilder Matches;
4794  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4795  .matches(Node, Finder, &Matches)
4796  ? 1
4797  : 0;
4798  int ParamIndex = 0;
4799  bool Matched = false;
4800  for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
4801  BoundNodesTreeBuilder ArgMatches(*Builder);
4802  if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4803  Finder, &ArgMatches)) {
4804  BoundNodesTreeBuilder ParamMatches(ArgMatches);
4806  hasParameter(ParamIndex, ParamMatcher)))),
4807  callExpr(callee(functionDecl(
4808  hasParameter(ParamIndex, ParamMatcher))))))
4809  .matches(Node, Finder, &ParamMatches)) {
4810  Result.addMatch(ParamMatches);
4811  Matched = true;
4812  }
4813  }
4814  ++ParamIndex;
4815  }
4816  *Builder = std::move(Result);
4817  return Matched;
4818 }
4819 
4820 /// Matches all arguments and their respective types for a \c CallExpr or
4821 /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
4822 /// it works on calls through function pointers as well.
4823 ///
4824 /// The difference is, that function pointers do not provide access to a
4825 /// \c ParmVarDecl, but only the \c QualType for each argument.
4826 ///
4827 /// Given
4828 /// \code
4829 /// void f(int i);
4830 /// int y;
4831 /// f(y);
4832 /// void (*f_ptr)(int) = f;
4833 /// f_ptr(y);
4834 /// \endcode
4835 /// callExpr(
4836 /// forEachArgumentWithParamType(
4837 /// declRefExpr(to(varDecl(hasName("y")))),
4838 /// qualType(isInteger()).bind("type)
4839 /// ))
4840 /// matches f(y) and f_ptr(y)
4841 /// with declRefExpr(...)
4842 /// matching int y
4843 /// and qualType(...)
4844 /// matching int
4845 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
4848  internal::Matcher<Expr>, ArgMatcher,
4849  internal::Matcher<QualType>, ParamMatcher) {
4850  BoundNodesTreeBuilder Result;
4851  // The first argument of an overloaded member operator is the implicit object
4852  // argument of the method which should not be matched against a parameter, so
4853  // we skip over it here.
4854  BoundNodesTreeBuilder Matches;
4855  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4856  .matches(Node, Finder, &Matches)
4857  ? 1
4858  : 0;
4859 
4860  const FunctionProtoType *FProto = nullptr;
4861 
4862  if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4863  if (const auto *Value =
4864  dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4865  QualType QT = Value->getType().getCanonicalType();
4866 
4867  // This does not necessarily lead to a `FunctionProtoType`,
4868  // e.g. K&R functions do not have a function prototype.
4869  if (QT->isFunctionPointerType())
4870  FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4871 
4872  if (QT->isMemberFunctionPointerType()) {
4873  const auto *MP = QT->getAs<MemberPointerType>();
4874  assert(MP && "Must be member-pointer if its a memberfunctionpointer");
4875  FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
4876  assert(FProto &&
4877  "The call must have happened through a member function "
4878  "pointer");
4879  }
4880  }
4881  }
4882 
4883  unsigned ParamIndex = 0;
4884  bool Matched = false;
4885  unsigned NumArgs = Node.getNumArgs();
4886  if (FProto && FProto->isVariadic())
4887  NumArgs = std::min(NumArgs, FProto->getNumParams());
4888 
4889  for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
4890  BoundNodesTreeBuilder ArgMatches(*Builder);
4891  if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
4892  &ArgMatches)) {
4893  BoundNodesTreeBuilder ParamMatches(ArgMatches);
4894 
4895  // This test is cheaper compared to the big matcher in the next if.
4896  // Therefore, please keep this order.
4897  if (FProto && FProto->getNumParams() > ParamIndex) {
4898  QualType ParamType = FProto->getParamType(ParamIndex);
4899  if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
4900  Result.addMatch(ParamMatches);
4901  Matched = true;
4902  continue;
4903  }
4904  }
4906  hasParameter(ParamIndex, hasType(ParamMatcher))))),
4907  callExpr(callee(functionDecl(
4908  hasParameter(ParamIndex, hasType(ParamMatcher)))))))
4909  .matches(Node, Finder, &ParamMatches)) {
4910  Result.addMatch(ParamMatches);
4911  Matched = true;
4912  continue;
4913  }
4914  }
4915  }
4916  *Builder = std::move(Result);
4917  return Matched;
4918 }
4919 
4920 /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
4921 /// list. The parameter list could be that of either a block, function, or
4922 /// objc-method.
4923 ///
4924 ///
4925 /// Given
4926 ///
4927 /// \code
4928 /// void f(int a, int b, int c) {
4929 /// }
4930 /// \endcode
4931 ///
4932 /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
4933 ///
4934 /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
4935 AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
4936  const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
4937 
4938  if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
4939  return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4940  if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
4941  return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4942  if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
4943  return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4944 
4945  return false;
4946 }
4947 
4948 /// Matches any parameter of a function or an ObjC method declaration or a
4949 /// block.
4950 ///
4951 /// Does not match the 'this' parameter of a method.
4952 ///
4953 /// Given
4954 /// \code
4955 /// class X { void f(int x, int y, int z) {} };
4956 /// \endcode
4957 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
4958 /// matches f(int x, int y, int z) {}
4959 /// with hasAnyParameter(...)
4960 /// matching int y
4961 ///
4962 /// For ObjectiveC, given
4963 /// \code
4964 /// @interface I - (void) f:(int) y; @end
4965 /// \endcode
4966 //
4967 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
4968 /// matches the declaration of method f with hasParameter
4969 /// matching y.
4970 ///
4971 /// For blocks, given
4972 /// \code
4973 /// b = ^(int y) { printf("%d", y) };
4974 /// \endcode
4975 ///
4976 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
4977 /// matches the declaration of the block b with hasParameter
4978 /// matching y.
4982  BlockDecl),
4983  internal::Matcher<ParmVarDecl>,
4984  InnerMatcher) {
4985  return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
4986  Node.param_end(), Finder,
4987  Builder) != Node.param_end();
4988 }
4989 
4990 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
4991 /// specific parameter count.
4992 ///
4993 /// Given
4994 /// \code
4995 /// void f(int i) {}
4996 /// void g(int i, int j) {}
4997 /// void h(int i, int j);
4998 /// void j(int i);
4999 /// void k(int x, int y, int z, ...);
5000 /// \endcode
5001 /// functionDecl(parameterCountIs(2))
5002 /// matches \c g and \c h
5003 /// functionProtoType(parameterCountIs(2))
5004 /// matches \c g and \c h
5005 /// functionProtoType(parameterCountIs(3))
5006 /// matches \c k
5007 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
5010  unsigned, N) {
5011  return Node.getNumParams() == N;
5012 }
5013 
5014 /// Matches classTemplateSpecialization, templateSpecializationType and
5015 /// functionDecl nodes where the template argument matches the inner matcher.
5016 /// This matcher may produce multiple matches.
5017 ///
5018 /// Given
5019 /// \code
5020 /// template <typename T, unsigned N, unsigned M>
5021 /// struct Matrix {};
5022 ///
5023 /// constexpr unsigned R = 2;
5024 /// Matrix<int, R * 2, R * 4> M;
5025 ///
5026 /// template <typename T, typename U>
5027 /// void f(T&& t, U&& u) {}
5028 ///
5029 /// bool B = false;
5030 /// f(R, B);
5031 /// \endcode
5032 /// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5033 /// matches twice, with expr() matching 'R * 2' and 'R * 4'
5034 /// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5035 /// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5036 /// and 'bool'
5038  forEachTemplateArgument,
5041  clang::ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
5042  ArrayRef<TemplateArgument> TemplateArgs =
5043  clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5044  clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5045  bool Matched = false;
5046  for (const auto &Arg : TemplateArgs) {
5047  clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5048  if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5049  Matched = true;
5050  Result.addMatch(ArgBuilder);
5051  }
5052  }
5053  *Builder = std::move(Result);
5054  return Matched;
5055 }
5056 
5057 /// Matches \c FunctionDecls that have a noreturn attribute.
5058 ///
5059 /// Given
5060 /// \code
5061 /// void nope();
5062 /// [[noreturn]] void a();
5063 /// __attribute__((noreturn)) void b();
5064 /// struct c { [[noreturn]] c(); };
5065 /// \endcode
5066 /// functionDecl(isNoReturn())
5067 /// matches all of those except
5068 /// \code
5069 /// void nope();
5070 /// \endcode
5071 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5072 
5073 /// Matches the return type of a function declaration.
5074 ///
5075 /// Given:
5076 /// \code
5077 /// class X { int f() { return 1; } };
5078 /// \endcode
5079 /// cxxMethodDecl(returns(asString("int")))
5080 /// matches int f() { return 1; }
5082  internal::Matcher<QualType>, InnerMatcher) {
5083  return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5084 }
5085 
5086 /// Matches extern "C" function or variable declarations.
5087 ///
5088 /// Given:
5089 /// \code
5090 /// extern "C" void f() {}
5091 /// extern "C" { void g() {} }
5092 /// void h() {}
5093 /// extern "C" int x = 1;
5094 /// extern "C" int y = 2;
5095 /// int z = 3;
5096 /// \endcode
5097 /// functionDecl(isExternC())
5098 /// matches the declaration of f and g, but not the declaration of h.
5099 /// varDecl(isExternC())
5100 /// matches the declaration of x and y, but not the declaration of z.
5102  VarDecl)) {
5103  return Node.isExternC();
5104 }
5105 
5106 /// Matches variable/function declarations that have "static" storage
5107 /// class specifier ("static" keyword) written in the source.
5108 ///
5109 /// Given:
5110 /// \code
5111 /// static void f() {}
5112 /// static int i = 0;
5113 /// extern int j;
5114 /// int k;
5115 /// \endcode
5116 /// functionDecl(isStaticStorageClass())
5117 /// matches the function declaration f.
5118 /// varDecl(isStaticStorageClass())
5119 /// matches the variable declaration i.
5120 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5122  VarDecl)) {
5123  return Node.getStorageClass() == SC_Static;
5124 }
5125 
5126 /// Matches deleted function declarations.
5127 ///
5128 /// Given:
5129 /// \code
5130 /// void Func();
5131 /// void DeletedFunc() = delete;
5132 /// \endcode
5133 /// functionDecl(isDeleted())
5134 /// matches the declaration of DeletedFunc, but not Func.
5136  return Node.isDeleted();
5137 }
5138 
5139 /// Matches defaulted function declarations.
5140 ///
5141 /// Given:
5142 /// \code
5143 /// class A { ~A(); };
5144 /// class B { ~B() = default; };
5145 /// \endcode
5146 /// functionDecl(isDefaulted())
5147 /// matches the declaration of ~B, but not ~A.
5148 AST_MATCHER(FunctionDecl, isDefaulted) {
5149  return Node.isDefaulted();
5150 }
5151 
5152 /// Matches weak function declarations.
5153 ///
5154 /// Given:
5155 /// \code
5156 /// void foo() __attribute__((__weakref__("__foo")));
5157 /// void bar();
5158 /// \endcode
5159 /// functionDecl(isWeak())
5160 /// matches the weak declaration "foo", but not "bar".
5161 AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5162 
5163 /// Matches functions that have a dynamic exception specification.
5164 ///
5165 /// Given:
5166 /// \code
5167 /// void f();
5168 /// void g() noexcept;
5169 /// void h() noexcept(true);
5170 /// void i() noexcept(false);
5171 /// void j() throw();
5172 /// void k() throw(int);
5173 /// void l() throw(...);
5174 /// \endcode
5175 /// functionDecl(hasDynamicExceptionSpec()) and
5176 /// functionProtoType(hasDynamicExceptionSpec())
5177 /// match the declarations of j, k, and l, but not f, g, h, or i.
5178 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5180  FunctionProtoType)) {
5181  if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5182  return FnTy->hasDynamicExceptionSpec();
5183  return false;
5184 }
5185 
5186 /// Matches functions that have a non-throwing exception specification.
5187 ///
5188 /// Given:
5189 /// \code
5190 /// void f();
5191 /// void g() noexcept;
5192 /// void h() throw();
5193 /// void i() throw(int);
5194 /// void j() noexcept(false);
5195 /// \endcode
5196 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5197 /// match the declarations of g, and h, but not f, i or j.
5200  FunctionProtoType)) {
5201  const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5202 
5203  // If the function does not have a prototype, then it is assumed to be a
5204  // throwing function (as it would if the function did not have any exception
5205  // specification).
5206  if (!FnTy)
5207  return false;
5208 
5209  // Assume the best for any unresolved exception specification.
5211  return true;
5212 
5213  return FnTy->isNothrow();
5214 }
5215 
5216 /// Matches consteval function declarations and if consteval/if ! consteval
5217 /// statements.
5218 ///
5219 /// Given:
5220 /// \code
5221 /// consteval int a();
5222 /// void b() { if consteval {} }
5223 /// void c() { if ! consteval {} }
5224 /// void d() { if ! consteval {} else {} }
5225 /// \endcode
5226 /// functionDecl(isConsteval())
5227 /// matches the declaration of "int a()".
5228 /// ifStmt(isConsteval())
5229 /// matches the if statement in "void b()", "void c()", "void d()".
5232  return Node.isConsteval();
5233 }
5234 
5235 /// Matches constexpr variable and function declarations,
5236 /// and if constexpr.
5237 ///
5238 /// Given:
5239 /// \code
5240 /// constexpr int foo = 42;
5241 /// constexpr int bar();
5242 /// void baz() { if constexpr(1 > 0) {} }
5243 /// \endcode
5244 /// varDecl(isConstexpr())
5245 /// matches the declaration of foo.
5246 /// functionDecl(isConstexpr())
5247 /// matches the declaration of bar.
5248 /// ifStmt(isConstexpr())
5249 /// matches the if statement in baz.
5252  FunctionDecl,
5253  IfStmt)) {
5254  return Node.isConstexpr();
5255 }
5256 
5257 /// Matches constinit variable declarations.
5258 ///
5259 /// Given:
5260 /// \code
5261 /// constinit int foo = 42;
5262 /// constinit const char* bar = "bar";
5263 /// int baz = 42;
5264 /// [[clang::require_constant_initialization]] int xyz = 42;
5265 /// \endcode
5266 /// varDecl(isConstinit())
5267 /// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5268 AST_MATCHER(VarDecl, isConstinit) {
5269  if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5270  return CIA->isConstinit();
5271  return false;
5272 }
5273 
5274 /// Matches selection statements with initializer.
5275 ///
5276 /// Given:
5277 /// \code
5278 /// void foo() {
5279 /// if (int i = foobar(); i > 0) {}
5280 /// switch (int i = foobar(); i) {}
5281 /// for (auto& a = get_range(); auto& x : a) {}
5282 /// }
5283 /// void bar() {
5284 /// if (foobar() > 0) {}
5285 /// switch (foobar()) {}
5286 /// for (auto& x : get_range()) {}
5287 /// }
5288 /// \endcode
5289 /// ifStmt(hasInitStatement(anything()))
5290 /// matches the if statement in foo but not in bar.
5291 /// switchStmt(hasInitStatement(anything()))
5292 /// matches the switch statement in foo but not in bar.
5293 /// cxxForRangeStmt(hasInitStatement(anything()))
5294 /// matches the range for statement in foo but not in bar.
5295 AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
5297  CXXForRangeStmt),
5298  internal::Matcher<Stmt>, InnerMatcher) {
5299  const Stmt *Init = Node.getInit();
5300  return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5301 }
5302 
5303 /// Matches the condition expression of an if statement, for loop,
5304 /// switch statement or conditional operator.
5305 ///
5306 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5307 /// \code
5308 /// if (true) {}
5309 /// \endcode
5311  hasCondition,
5314  internal::Matcher<Expr>, InnerMatcher) {
5315  const Expr *const Condition = Node.getCond();
5316  return (Condition != nullptr &&
5317  InnerMatcher.matches(*Condition, Finder, Builder));
5318 }
5319 
5320 /// Matches the then-statement of an if statement.
5321 ///
5322 /// Examples matches the if statement
5323 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5324 /// \code
5325 /// if (false) true; else false;
5326 /// \endcode
5327 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5328  const Stmt *const Then = Node.getThen();
5329  return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5330 }
5331 
5332 /// Matches the else-statement of an if statement.
5333 ///
5334 /// Examples matches the if statement
5335 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5336 /// \code
5337 /// if (false) false; else true;
5338 /// \endcode
5339 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5340  const Stmt *const Else = Node.getElse();
5341  return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5342 }
5343 
5344 /// Matches if a node equals a previously bound node.
5345 ///
5346 /// Matches a node if it equals the node previously bound to \p ID.
5347 ///
5348 /// Given
5349 /// \code
5350 /// class X { int a; int b; };
5351 /// \endcode
5352 /// cxxRecordDecl(
5353 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5354 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5355 /// matches the class \c X, as \c a and \c b have the same type.
5356 ///
5357 /// Note that when multiple matches are involved via \c forEach* matchers,
5358 /// \c equalsBoundNodes acts as a filter.
5359 /// For example:
5360 /// compoundStmt(
5361 /// forEachDescendant(varDecl().bind("d")),
5362 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5363 /// will trigger a match for each combination of variable declaration
5364 /// and reference to that variable declaration within a compound statement.
5367  QualType),
5368  std::string, ID) {
5369  // FIXME: Figure out whether it makes sense to allow this
5370  // on any other node types.
5371  // For *Loc it probably does not make sense, as those seem
5372  // unique. For NestedNameSepcifier it might make sense, as
5373  // those also have pointer identity, but I'm not sure whether
5374  // they're ever reused.
5375  internal::NotEqualsBoundNodePredicate Predicate;
5376  Predicate.ID = ID;
5377  Predicate.Node = DynTypedNode::create(Node);
5378  return Builder->removeBindings(Predicate);
5379 }
5380 
5381 /// Matches the condition variable statement in an if statement.
5382 ///
5383 /// Given
5384 /// \code
5385 /// if (A* a = GetAPointer()) {}
5386 /// \endcode
5387 /// hasConditionVariableStatement(...)
5388 /// matches 'A* a = GetAPointer()'.
5389 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5390  internal::Matcher<DeclStmt>, InnerMatcher) {
5391  const DeclStmt* const DeclarationStatement =
5392  Node.getConditionVariableDeclStmt();
5393  return DeclarationStatement != nullptr &&
5394  InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5395 }
5396 
5397 /// Matches the index expression of an array subscript expression.
5398 ///
5399 /// Given
5400 /// \code
5401 /// int i[5];
5402 /// void f() { i[1] = 42; }
5403 /// \endcode
5404 /// arraySubscriptExpression(hasIndex(integerLiteral()))
5405 /// matches \c i[1] with the \c integerLiteral() matching \c 1
5407  internal::Matcher<Expr>, InnerMatcher) {
5408  if (const Expr* Expression = Node.getIdx())
5409  return InnerMatcher.matches(*Expression, Finder, Builder);
5410  return false;
5411 }
5412 
5413 /// Matches the base expression of an array subscript expression.
5414 ///
5415 /// Given
5416 /// \code
5417 /// int i[5];
5418 /// void f() { i[1] = 42; }
5419 /// \endcode
5420 /// arraySubscriptExpression(hasBase(implicitCastExpr(
5421 /// hasSourceExpression(declRefExpr()))))
5422 /// matches \c i[1] with the \c declRefExpr() matching \c i
5424  internal::Matcher<Expr>, InnerMatcher) {
5425  if (const Expr* Expression = Node.getBase())
5426  return InnerMatcher.matches(*Expression, Finder, Builder);
5427  return false;
5428 }
5429 
5430 /// Matches a 'for', 'while', 'do while' statement or a function
5431 /// definition that has a given body. Note that in case of functions
5432 /// this matcher only matches the definition itself and not the other
5433 /// declarations of the same function.
5434 ///
5435 /// Given
5436 /// \code
5437 /// for (;;) {}
5438 /// \endcode
5439 /// hasBody(compoundStmt())
5440 /// matches 'for (;;) {}'
5441 /// with compoundStmt()
5442 /// matching '{}'
5443 ///
5444 /// Given
5445 /// \code
5446 /// void f();
5447 /// void f() {}
5448 /// \endcode
5449 /// hasBody(functionDecl())
5450 /// matches 'void f() {}'
5451 /// with compoundStmt()
5452 /// matching '{}'
5453 /// but does not match 'void f();'
5454 
5457  WhileStmt,
5459  FunctionDecl),
5460  internal::Matcher<Stmt>, InnerMatcher) {
5461  if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5462  return false;
5463  const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5464  return (Statement != nullptr &&
5465  InnerMatcher.matches(*Statement, Finder, Builder));
5466 }
5467 
5468 /// Matches a function declaration that has a given body present in the AST.
5469 /// Note that this matcher matches all the declarations of a function whose
5470 /// body is present in the AST.
5471 ///
5472 /// Given
5473 /// \code
5474 /// void f();
5475 /// void f() {}
5476 /// void g();
5477 /// \endcode
5478 /// functionDecl(hasAnyBody(compoundStmt()))
5479 /// matches both 'void f();'
5480 /// and 'void f() {}'
5481 /// with compoundStmt()
5482 /// matching '{}'
5483 /// but does not match 'void g();'
5485  internal::Matcher<Stmt>, InnerMatcher) {
5486  const Stmt *const Statement = Node.getBody();
5487  return (Statement != nullptr &&
5488  InnerMatcher.matches(*Statement, Finder, Builder));
5489 }
5490 
5491 
5492 /// Matches compound statements where at least one substatement matches
5493 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5494 ///
5495 /// Given
5496 /// \code
5497 /// { {}; 1+2; }
5498 /// \endcode
5499 /// hasAnySubstatement(compoundStmt())
5500 /// matches '{ {}; 1+2; }'
5501 /// with compoundStmt()
5502 /// matching '{}'
5503 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5505  StmtExpr),
5506  internal::Matcher<Stmt>, InnerMatcher) {
5507  const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5508  return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5509  CS->body_end(), Finder,
5510  Builder) != CS->body_end();
5511 }
5512 
5513 /// Checks that a compound statement contains a specific number of
5514 /// child statements.
5515 ///
5516 /// Example: Given
5517 /// \code
5518 /// { for (;;) {} }
5519 /// \endcode
5520 /// compoundStmt(statementCountIs(0)))
5521 /// matches '{}'
5522 /// but does not match the outer compound statement.
5523 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5524  return Node.size() == N;
5525 }
5526 
5527 /// Matches literals that are equal to the given value of type ValueT.
5528 ///
5529 /// Given
5530 /// \code
5531 /// f('\0', false, 3.14, 42);
5532 /// \endcode
5533 /// characterLiteral(equals(0))
5534 /// matches '\0'
5535 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5536 /// match false
5537 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5538 /// match 3.14
5539 /// integerLiteral(equals(42))
5540 /// matches 42
5541 ///
5542 /// Note that you cannot directly match a negative numeric literal because the
5543 /// minus sign is not part of the literal: It is a unary operator whose operand
5544 /// is the positive numeric literal. Instead, you must use a unaryOperator()
5545 /// matcher to match the minus sign:
5546 ///
5547 /// unaryOperator(hasOperatorName("-"),
5548 /// hasUnaryOperand(integerLiteral(equals(13))))
5549 ///
5550 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5551 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5552 template <typename ValueT>
5553 internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5554  void(internal::AllNodeBaseTypes), ValueT>
5555 equals(const ValueT &Value) {
5556  return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5557  void(internal::AllNodeBaseTypes), ValueT>(
5558  Value);
5559 }
5560 
5564  IntegerLiteral),
5565  bool, Value, 0) {
5566  return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5567  .matchesNode(Node);
5568 }
5569 
5573  IntegerLiteral),
5574  unsigned, Value, 1) {
5575  return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5576  .matchesNode(Node);
5577 }
5578 
5583  IntegerLiteral),
5584  double, Value, 2) {
5585  return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5586  .matchesNode(Node);
5587 }
5588 
5589 /// Matches the operator Name of operator expressions (binary or
5590 /// unary).
5591 ///
5592 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5593 /// \code
5594 /// !(a || b)
5595 /// \endcode
5597  hasOperatorName,
5600  std::string, Name) {
5601  if (Optional<StringRef> OpName = internal::getOpName(Node))
5602  return *OpName == Name;
5603  return false;
5604 }
5605 
5606 /// Matches operator expressions (binary or unary) that have any of the
5607 /// specified names.
5608 ///
5609 /// hasAnyOperatorName("+", "-")
5610 /// Is equivalent to
5611 /// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5612 extern const internal::VariadicFunction<
5613  internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5617  std::vector<std::string>>,
5620 
5621 /// Matches all kinds of assignment operators.
5622 ///
5623 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5624 /// \code
5625 /// if (a == b)
5626 /// a += b;
5627 /// \endcode
5628 ///
5629 /// Example 2: matches s1 = s2
5630 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5631 /// \code
5632 /// struct S { S& operator=(const S&); };
5633 /// void x() { S s1, s2; s1 = s2; }
5634 /// \endcode
5636  isAssignmentOperator,
5639  return Node.isAssignmentOp();
5640 }
5641 
5642 /// Matches comparison operators.
5643 ///
5644 /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5645 /// \code
5646 /// if (a == b)
5647 /// a += b;
5648 /// \endcode
5649 ///
5650 /// Example 2: matches s1 < s2
5651 /// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5652 /// \code
5653 /// struct S { bool operator<(const S& other); };
5654 /// void x(S s1, S s2) { bool b1 = s1 < s2; }
5655 /// \endcode
5660  return Node.isComparisonOp();
5661 }
5662 
5663 /// Matches the left hand side of binary operator expressions.
5664 ///
5665 /// Example matches a (matcher = binaryOperator(hasLHS()))
5666 /// \code
5667 /// a || b
5668 /// \endcode
5673  internal::Matcher<Expr>, InnerMatcher) {
5674  const Expr *LeftHandSide = internal::getLHS(Node);
5675  return (LeftHandSide != nullptr &&
5676  InnerMatcher.matches(*LeftHandSide, Finder, Builder));
5677 }
5678 
5679 /// Matches the right hand side of binary operator expressions.
5680 ///
5681 /// Example matches b (matcher = binaryOperator(hasRHS()))
5682 /// \code
5683 /// a || b
5684 /// \endcode
5689  internal::Matcher<Expr>, InnerMatcher) {
5690  const Expr *RightHandSide = internal::getRHS(Node);
5691  return (RightHandSide != nullptr &&
5692  InnerMatcher.matches(*RightHandSide, Finder, Builder));
5693 }
5694 
5695 /// Matches if either the left hand side or the right hand side of a
5696 /// binary operator matches.
5698  hasEitherOperand,
5701  internal::Matcher<Expr>, InnerMatcher) {
5702  return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5703  anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
5704  .matches(Node, Finder, Builder);
5705 }
5706 
5707 /// Matches if both matchers match with opposite sides of the binary operator.
5708 ///
5709 /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
5710 /// integerLiteral(equals(2)))
5711 /// \code
5712 /// 1 + 2 // Match
5713 /// 2 + 1 // Match
5714 /// 1 + 1 // No match
5715 /// 2 + 2 // No match
5716 /// \endcode
5718  hasOperands,
5721  internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
5722  return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5723  anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
5724  allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
5725  .matches(Node, Finder, Builder);
5726 }
5727 
5728 /// Matches if the operand of a unary operator matches.
5729 ///
5730 /// Example matches true (matcher = hasUnaryOperand(
5731 /// cxxBoolLiteral(equals(true))))
5732 /// \code
5733 /// !true
5734 /// \endcode
5738  internal::Matcher<Expr>, InnerMatcher) {
5739  const Expr *const Operand = internal::getSubExpr(Node);
5740  return (Operand != nullptr &&
5741  InnerMatcher.matches(*Operand, Finder, Builder));
5742 }
5743 
5744 /// Matches if the cast's source expression
5745 /// or opaque value's source expression matches the given matcher.
5746 ///
5747 /// Example 1: matches "a string"
5748 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
5749 /// \code
5750 /// class URL { URL(string); };
5751 /// URL url = "a string";
5752 /// \endcode
5753 ///
5754 /// Example 2: matches 'b' (matcher =
5755 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
5756 /// \code
5757 /// int a = b ?: 1;
5758 /// \endcode
5759 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
5761  OpaqueValueExpr),
5762  internal::Matcher<Expr>, InnerMatcher) {
5763  const Expr *const SubExpression =
5764  internal::GetSourceExpressionMatcher<NodeType>::get(Node);
5765  return (SubExpression != nullptr &&
5766  InnerMatcher.matches(*SubExpression, Finder, Builder));
5767 }
5768 
5769 /// Matches casts that has a given cast kind.
5770 ///
5771 /// Example: matches the implicit cast around \c 0
5772 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
5773 /// \code
5774 /// int *p = 0;
5775 /// \endcode
5776 ///
5777 /// If the matcher is use from clang-query, CastKind parameter
5778 /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
5780  return Node.getCastKind() == Kind;
5781 }
5782 
5783 /// Matches casts whose destination type matches a given matcher.
5784 ///
5785 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
5786 /// actual casts "explicit" casts.)
5787 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
5788  internal::Matcher<QualType>, InnerMatcher) {
5789  const QualType NodeType = Node.getTypeAsWritten();
5790  return InnerMatcher.matches(NodeType, Finder, Builder);
5791 }
5792 
5793 /// Matches implicit casts whose destination type matches a given
5794 /// matcher.
5795 ///
5796 /// FIXME: Unit test this matcher
5797 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
5798  internal::Matcher<QualType>, InnerMatcher) {
5799  return InnerMatcher.matches(Node.getType(), Finder, Builder);
5800 }
5801 
5802 /// Matches TagDecl object that are spelled with "struct."
5803 ///
5804 /// Example matches S, but not C, U or E.
5805 /// \code
5806 /// struct S {};
5807 /// class C {};
5808 /// union U {};
5809 /// enum E {};
5810 /// \endcode
5811 AST_MATCHER(TagDecl, isStruct) {
5812  return Node.isStruct();
5813 }
5814 
5815 /// Matches TagDecl object that are spelled with "union."
5816 ///
5817 /// Example matches U, but not C, S or E.
5818 /// \code
5819 /// struct S {};
5820 /// class C {};
5821 /// union U {};
5822 /// enum E {};
5823 /// \endcode
5825  return Node.isUnion();
5826 }
5827 
5828 /// Matches TagDecl object that are spelled with "class."
5829 ///
5830 /// Example matches C, but not S, U or E.
5831 /// \code
5832 /// struct S {};
5833 /// class C {};
5834 /// union U {};
5835 /// enum E {};
5836 /// \endcode
5838  return Node.isClass();
5839 }
5840 
5841 /// Matches TagDecl object that are spelled with "enum."
5842 ///
5843 /// Example matches E, but not C, S or U.
5844 /// \code
5845 /// struct S {};
5846 /// class C {};
5847 /// union U {};
5848 /// enum E {};
5849 /// \endcode
5851  return Node.isEnum();
5852 }
5853 
5854 /// Matches the true branch expression of a conditional operator.
5855 ///
5856 /// Example 1 (conditional ternary operator): matches a
5857 /// \code
5858 /// condition ? a : b
5859 /// \endcode
5860 ///
5861 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
5862 /// \code
5863 /// condition ?: b
5864 /// \endcode
5866  internal::Matcher<Expr>, InnerMatcher) {
5867  const Expr *Expression = Node.getTrueExpr();
5868  return (Expression != nullptr &&
5869  InnerMatcher.matches(*Expression, Finder, Builder));
5870 }
5871 
5872 /// Matches the false branch expression of a conditional operator
5873 /// (binary or ternary).
5874 ///
5875 /// Example matches b
5876 /// \code
5877 /// condition ? a : b
5878 /// condition ?: b
5879 /// \endcode
5881  internal::Matcher<Expr>, InnerMatcher) {
5882  const Expr *Expression = Node.getFalseExpr();
5883  return (Expression != nullptr &&
5884  InnerMatcher.matches(*Expression, Finder, Builder));
5885 }
5886 
5887 /// Matches if a declaration has a body attached.
5888 ///
5889 /// Example matches A, va, fa
5890 /// \code
5891 /// class A {};
5892 /// class B; // Doesn't match, as it has no body.
5893 /// int va;
5894 /// extern int vb; // Doesn't match, as it doesn't define the variable.
5895 /// void fa() {}
5896 /// void fb(); // Doesn't match, as it has no body.
5897 /// @interface X
5898 /// - (void)ma; // Doesn't match, interface is declaration.
5899 /// @end
5900 /// @implementation X
5901 /// - (void)ma {}
5902 /// @end
5903 /// \endcode
5904 ///
5905 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
5906 /// Matcher<ObjCMethodDecl>
5910  FunctionDecl)) {
5911  return Node.isThisDeclarationADefinition();
5912 }
5913 
5914 /// Matches if a function declaration is variadic.
5915 ///
5916 /// Example matches f, but not g or h. The function i will not match, even when
5917 /// compiled in C mode.
5918 /// \code
5919 /// void f(...);
5920 /// void g(int);
5921 /// template <typename... Ts> void h(Ts...);
5922 /// void i();
5923 /// \endcode
5925  return Node.isVariadic();
5926 }
5927 
5928 /// Matches the class declaration that the given method declaration
5929 /// belongs to.
5930 ///
5931 /// FIXME: Generalize this for other kinds of declarations.
5932 /// FIXME: What other kind of declarations would we need to generalize
5933 /// this to?
5934 ///
5935 /// Example matches A() in the last line
5936 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
5937 /// ofClass(hasName("A"))))))
5938 /// \code
5939 /// class A {
5940 /// public:
5941 /// A();
5942 /// };
5943 /// A a = A();
5944 /// \endcode
5946  internal::Matcher<CXXRecordDecl>, InnerMatcher) {
5947 
5948  ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
5949 
5950  const CXXRecordDecl *Parent = Node.getParent();
5951  return (Parent != nullptr &&
5952  InnerMatcher.matches(*Parent, Finder, Builder));
5953 }
5954 
5955 /// Matches each method overridden by the given method. This matcher may
5956 /// produce multiple matches.
5957 ///
5958 /// Given
5959 /// \code
5960 /// class A { virtual void f(); };
5961 /// class B : public A { void f(); };
5962 /// class C : public B { void f(); };
5963 /// \endcode
5964 /// cxxMethodDecl(ofClass(hasName("C")),
5965 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5966 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
5967 /// that B::f is not overridden by C::f).
5968 ///
5969 /// The check can produce multiple matches in case of multiple inheritance, e.g.
5970 /// \code
5971 /// class A1 { virtual void f(); };
5972 /// class A2 { virtual void f(); };
5973 /// class C : public A1, public A2 { void f(); };
5974 /// \endcode
5975 /// cxxMethodDecl(ofClass(hasName("C")),
5976 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5977 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
5978 /// once with "b" binding "A2::f" and "d" binding "C::f".
5979 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
5980  internal::Matcher<CXXMethodDecl>, InnerMatcher) {
5981  BoundNodesTreeBuilder Result;
5982  bool Matched = false;
5983  for (const auto *Overridden : Node.overridden_methods()) {
5984  BoundNodesTreeBuilder OverriddenBuilder(*Builder);
5985  const bool OverriddenMatched =
5986  InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
5987  if (OverriddenMatched) {
5988  Matched = true;
5989  Result.addMatch(OverriddenBuilder);
5990  }
5991  }
5992  *Builder = std::move(Result);
5993  return Matched;
5994 }
5995 
5996 /// Matches declarations of virtual methods and C++ base specifers that specify
5997 /// virtual inheritance.
5998 ///
5999 /// Example:
6000 /// \code
6001 /// class A {
6002 /// public:
6003 /// virtual void x(); // matches x
6004 /// };
6005 /// \endcode
6006 ///
6007 /// Example:
6008 /// \code
6009 /// class Base {};
6010 /// class DirectlyDerived : virtual Base {}; // matches Base
6011 /// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
6012 /// \endcode
6013 ///
6014 /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
6017  CXXBaseSpecifier)) {
6018  return Node.isVirtual();
6019 }
6020 
6021 /// Matches if the given method declaration has an explicit "virtual".
6022 ///
6023 /// Given
6024 /// \code
6025 /// class A {
6026 /// public:
6027 /// virtual void x();
6028 /// };
6029 /// class B : public A {
6030 /// public:
6031 /// void x();
6032 /// };
6033 /// \endcode
6034 /// matches A::x but not B::x
6035 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
6036  return Node.isVirtualAsWritten();
6037 }
6038 
6039 AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
6040  return Node.isInheritingConstructor();
6041 }
6042 
6043 /// Matches if the given method or class declaration is final.
6044 ///
6045 /// Given:
6046 /// \code
6047 /// class A final {};
6048 ///
6049 /// struct B {
6050 /// virtual void f();
6051 /// };
6052 ///
6053 /// struct C : B {
6054 /// void f() final;
6055 /// };
6056 /// \endcode
6057 /// matches A and C::f, but not B, C, or B::f
6060  CXXMethodDecl)) {
6061  return Node.template hasAttr<FinalAttr>();
6062 }
6063 
6064 /// Matches if the given method declaration is pure.
6065 ///
6066 /// Given
6067 /// \code
6068 /// class A {
6069 /// public:
6070 /// virtual void x() = 0;
6071 /// };
6072 /// \endcode
6073 /// matches A::x
6075  return Node.isPure();
6076 }
6077 
6078 /// Matches if the given method declaration is const.
6079 ///
6080 /// Given
6081 /// \code
6082 /// struct A {
6083 /// void foo() const;
6084 /// void bar();
6085 /// };
6086 /// \endcode
6087 ///
6088 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
6090  return Node.isConst();
6091 }
6092 
6093 /// Matches if the given method declaration declares a copy assignment
6094 /// operator.
6095 ///
6096 /// Given
6097 /// \code
6098 /// struct A {
6099 /// A &operator=(const A &);
6100 /// A &operator=(A &&);
6101 /// };
6102 /// \endcode
6103 ///
6104 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
6105 /// the second one.
6106 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
6107  return Node.isCopyAssignmentOperator();
6108 }
6109 
6110 /// Matches if the given method declaration declares a move assignment
6111 /// operator.
6112 ///
6113 /// Given
6114 /// \code
6115 /// struct A {
6116 /// A &operator=(const A &);
6117 /// A &operator=(A &&);
6118 /// };
6119 /// \endcode
6120 ///
6121 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
6122 /// the first one.
6123 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
6124  return Node.isMoveAssignmentOperator();
6125 }
6126 
6127 /// Matches if the given method declaration overrides another method.
6128 ///
6129 /// Given
6130 /// \code
6131 /// class A {
6132 /// public:
6133 /// virtual void x();
6134 /// };
6135 /// class B : public A {
6136 /// public:
6137 /// virtual void x();
6138 /// };
6139 /// \endcode
6140 /// matches B::x
6142  return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
6143 }
6144 
6145 /// Matches method declarations that are user-provided.
6146 ///
6147 /// Given
6148 /// \code
6149 /// struct S {
6150 /// S(); // #1
6151 /// S(const S &) = default; // #2
6152 /// S(S &&) = delete; // #3
6153 /// };
6154 /// \endcode
6155 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
6156 AST_MATCHER(CXXMethodDecl, isUserProvided) {
6157  return Node.isUserProvided();
6158 }
6159 
6160 /// Matches member expressions that are called with '->' as opposed
6161 /// to '.'.
6162 ///
6163 /// Member calls on the implicit this pointer match as called with '->'.
6164 ///
6165 /// Given
6166 /// \code
6167 /// class Y {
6168 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
6169 /// template <class T> void f() { this->f<T>(); f<T>(); }
6170 /// int a;
6171 /// static int b;
6172 /// };
6173 /// template <class T>
6174 /// class Z {
6175 /// void x() { this->m; }
6176 /// };
6177 /// \endcode
6178 /// memberExpr(isArrow())
6179 /// matches this->x, x, y.x, a, this->b
6180 /// cxxDependentScopeMemberExpr(isArrow())
6181 /// matches this->m
6182 /// unresolvedMemberExpr(isArrow())
6183 /// matches this->f<T>, f<T>
6187  return Node.isArrow();
6188 }
6189 
6190 /// Matches QualType nodes that are of integer type.
6191 ///
6192 /// Given
6193 /// \code
6194 /// void a(int);
6195 /// void b(long);
6196 /// void c(double);
6197 /// \endcode
6198 /// functionDecl(hasAnyParameter(hasType(isInteger())))
6199 /// matches "a(int)", "b(long)", but not "c(double)".
6200 AST_MATCHER(QualType, isInteger) {
6201  return Node->isIntegerType();
6202 }
6203 
6204 /// Matches QualType nodes that are of unsigned integer type.
6205 ///
6206 /// Given
6207 /// \code
6208 /// void a(int);
6209 /// void b(unsigned long);
6210 /// void c(double);
6211 /// \endcode
6212 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6213 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
6214 AST_MATCHER(QualType, isUnsignedInteger) {
6215  return Node->isUnsignedIntegerType();
6216 }
6217 
6218 /// Matches QualType nodes that are of signed integer type.
6219 ///
6220 /// Given
6221 /// \code
6222 /// void a(int);
6223 /// void b(unsigned long);
6224 /// void c(double);
6225 /// \endcode
6226 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6227 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
6228 AST_MATCHER(QualType, isSignedInteger) {
6229  return Node->isSignedIntegerType();
6230 }
6231 
6232 /// Matches QualType nodes that are of character type.
6233 ///
6234 /// Given
6235 /// \code
6236 /// void a(char);
6237 /// void b(wchar_t);
6238 /// void c(double);
6239 /// \endcode
6240 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6241 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
6242 AST_MATCHER(QualType, isAnyCharacter) {
6243  return Node->isAnyCharacterType();
6244 }
6245 
6246 /// Matches QualType nodes that are of any pointer type; this includes
6247 /// the Objective-C object pointer type, which is different despite being
6248 /// syntactically similar.
6249 ///
6250 /// Given
6251 /// \code
6252 /// int *i = nullptr;
6253 ///
6254 /// @interface Foo
6255 /// @end
6256 /// Foo *f;
6257 ///
6258 /// int j;
6259 /// \endcode
6260 /// varDecl(hasType(isAnyPointer()))
6261 /// matches "int *i" and "Foo *f", but not "int j".
6262 AST_MATCHER(QualType, isAnyPointer) {
6263  return Node->isAnyPointerType();
6264 }
6265 
6266 /// Matches QualType nodes that are const-qualified, i.e., that
6267 /// include "top-level" const.
6268 ///
6269 /// Given
6270 /// \code
6271 /// void a(int);
6272 /// void b(int const);
6273 /// void c(const int);
6274 /// void d(const int*);
6275 /// void e(int const) {};
6276 /// \endcode
6277 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6278 /// matches "void b(int const)", "void c(const int)" and
6279 /// "void e(int const) {}". It does not match d as there
6280 /// is no top-level const on the parameter type "const int *".
6281 AST_MATCHER(QualType, isConstQualified) {
6282  return Node.isConstQualified();
6283 }
6284 
6285 /// Matches QualType nodes that are volatile-qualified, i.e., that
6286 /// include "top-level" volatile.
6287 ///
6288 /// Given
6289 /// \code
6290 /// void a(int);
6291 /// void b(int volatile);
6292 /// void c(volatile int);
6293 /// void d(volatile int*);
6294 /// void e(int volatile) {};
6295 /// \endcode
6296 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6297 /// matches "void b(int volatile)", "void c(volatile int)" and
6298 /// "void e(int volatile) {}". It does not match d as there
6299 /// is no top-level volatile on the parameter type "volatile int *".
6300 AST_MATCHER(QualType, isVolatileQualified) {
6301  return Node.isVolatileQualified();
6302 }
6303 
6304 /// Matches QualType nodes that have local CV-qualifiers attached to
6305 /// the node, not hidden within a typedef.
6306 ///
6307 /// Given
6308 /// \code
6309 /// typedef const int const_int;
6310 /// const_int i;
6311 /// int *const j;
6312 /// int *volatile k;
6313 /// int m;
6314 /// \endcode
6315 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
6316 /// \c i is const-qualified but the qualifier is not local.
6317 AST_MATCHER(QualType, hasLocalQualifiers) {
6318  return Node.hasLocalQualifiers();
6319 }
6320 
6321 /// Matches a member expression where the member is matched by a
6322 /// given matcher.
6323 ///
6324 /// Given
6325 /// \code
6326 /// struct { int first, second; } first, second;
6327 /// int i(second.first);
6328 /// int j(first.second);
6329 /// \endcode
6330 /// memberExpr(member(hasName("first")))
6331 /// matches second.first
6332 /// but not first.second (because the member name there is "second").
6334  internal::Matcher<ValueDecl>, InnerMatcher) {
6335  return