clang  16.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 ObjectiveC String literal expressions.
1519 ///
1520 /// Example matches @"abcd"
1521 /// \code
1522 /// NSString *s = @"abcd";
1523 /// \endcode
1524 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
1526 
1527 /// Matches Objective-C interface declarations.
1528 ///
1529 /// Example matches Foo
1530 /// \code
1531 /// @interface Foo
1532 /// @end
1533 /// \endcode
1534 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1536 
1537 /// Matches Objective-C implementation declarations.
1538 ///
1539 /// Example matches Foo
1540 /// \code
1541 /// @implementation Foo
1542 /// @end
1543 /// \endcode
1544 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1546 
1547 /// Matches Objective-C protocol declarations.
1548 ///
1549 /// Example matches FooDelegate
1550 /// \code
1551 /// @protocol FooDelegate
1552 /// @end
1553 /// \endcode
1554 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1556 
1557 /// Matches Objective-C category declarations.
1558 ///
1559 /// Example matches Foo (Additions)
1560 /// \code
1561 /// @interface Foo (Additions)
1562 /// @end
1563 /// \endcode
1564 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1566 
1567 /// Matches Objective-C category definitions.
1568 ///
1569 /// Example matches Foo (Additions)
1570 /// \code
1571 /// @implementation Foo (Additions)
1572 /// @end
1573 /// \endcode
1574 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1576 
1577 /// Matches Objective-C method declarations.
1578 ///
1579 /// Example matches both declaration and definition of -[Foo method]
1580 /// \code
1581 /// @interface Foo
1582 /// - (void)method;
1583 /// @end
1584 ///
1585 /// @implementation Foo
1586 /// - (void)method {}
1587 /// @end
1588 /// \endcode
1589 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1591 
1592 /// Matches block declarations.
1593 ///
1594 /// Example matches the declaration of the nameless block printing an input
1595 /// integer.
1596 ///
1597 /// \code
1598 /// myFunc(^(int p) {
1599 /// printf("%d", p);
1600 /// })
1601 /// \endcode
1602 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1603  blockDecl;
1604 
1605 /// Matches Objective-C instance variable declarations.
1606 ///
1607 /// Example matches _enabled
1608 /// \code
1609 /// @implementation Foo {
1610 /// BOOL _enabled;
1611 /// }
1612 /// @end
1613 /// \endcode
1614 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1615  objcIvarDecl;
1616 
1617 /// Matches Objective-C property declarations.
1618 ///
1619 /// Example matches enabled
1620 /// \code
1621 /// @interface Foo
1622 /// @property BOOL enabled;
1623 /// @end
1624 /// \endcode
1625 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1627 
1628 /// Matches Objective-C \@throw statements.
1629 ///
1630 /// Example matches \@throw
1631 /// \code
1632 /// @throw obj;
1633 /// \endcode
1634 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1635  objcThrowStmt;
1636 
1637 /// Matches Objective-C @try statements.
1638 ///
1639 /// Example matches @try
1640 /// \code
1641 /// @try {}
1642 /// @catch (...) {}
1643 /// \endcode
1644 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1645  objcTryStmt;
1646 
1647 /// Matches Objective-C @catch statements.
1648 ///
1649 /// Example matches @catch
1650 /// \code
1651 /// @try {}
1652 /// @catch (...) {}
1653 /// \endcode
1654 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1655  objcCatchStmt;
1656 
1657 /// Matches Objective-C @finally statements.
1658 ///
1659 /// Example matches @finally
1660 /// \code
1661 /// @try {}
1662 /// @finally {}
1663 /// \endcode
1664 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1666 
1667 /// Matches expressions that introduce cleanups to be run at the end
1668 /// of the sub-expression's evaluation.
1669 ///
1670 /// Example matches std::string()
1671 /// \code
1672 /// const std::string str = std::string();
1673 /// \endcode
1674 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1676 
1677 /// Matches init list expressions.
1678 ///
1679 /// Given
1680 /// \code
1681 /// int a[] = { 1, 2 };
1682 /// struct B { int x, y; };
1683 /// B b = { 5, 6 };
1684 /// \endcode
1685 /// initListExpr()
1686 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1687 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1688  initListExpr;
1689 
1690 /// Matches the syntactic form of init list expressions
1691 /// (if expression have it).
1692 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1693  internal::Matcher<Expr>, InnerMatcher) {
1694  const Expr *SyntForm = Node.getSyntacticForm();
1695  return (SyntForm != nullptr &&
1696  InnerMatcher.matches(*SyntForm, Finder, Builder));
1697 }
1698 
1699 /// Matches C++ initializer list expressions.
1700 ///
1701 /// Given
1702 /// \code
1703 /// std::vector<int> a({ 1, 2, 3 });
1704 /// std::vector<int> b = { 4, 5 };
1705 /// int c[] = { 6, 7 };
1706 /// std::pair<int, int> d = { 8, 9 };
1707 /// \endcode
1708 /// cxxStdInitializerListExpr()
1709 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1710 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1713 
1714 /// Matches implicit initializers of init list expressions.
1715 ///
1716 /// Given
1717 /// \code
1718 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1719 /// \endcode
1720 /// implicitValueInitExpr()
1721 /// matches "[0].y" (implicitly)
1722 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1724 
1725 /// Matches paren list expressions.
1726 /// ParenListExprs don't have a predefined type and are used for late parsing.
1727 /// In the final AST, they can be met in template declarations.
1728 ///
1729 /// Given
1730 /// \code
1731 /// template<typename T> class X {
1732 /// void f() {
1733 /// X x(*this);
1734 /// int a = 0, b = 1; int i = (a, b);
1735 /// }
1736 /// };
1737 /// \endcode
1738 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1739 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1740 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1741  parenListExpr;
1742 
1743 /// Matches substitutions of non-type template parameters.
1744 ///
1745 /// Given
1746 /// \code
1747 /// template <int N>
1748 /// struct A { static const int n = N; };
1749 /// struct B : public A<42> {};
1750 /// \endcode
1751 /// substNonTypeTemplateParmExpr()
1752 /// matches "N" in the right-hand side of "static const int n = N;"
1753 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1756 
1757 /// Matches using declarations.
1758 ///
1759 /// Given
1760 /// \code
1761 /// namespace X { int x; }
1762 /// using X::x;
1763 /// \endcode
1764 /// usingDecl()
1765 /// matches \code using X::x \endcode
1766 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1767 
1768 /// Matches using-enum declarations.
1769 ///
1770 /// Given
1771 /// \code
1772 /// namespace X { enum x {...}; }
1773 /// using enum X::x;
1774 /// \endcode
1775 /// usingEnumDecl()
1776 /// matches \code using enum X::x \endcode
1777 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1778  usingEnumDecl;
1779 
1780 /// Matches using namespace declarations.
1781 ///
1782 /// Given
1783 /// \code
1784 /// namespace X { int x; }
1785 /// using namespace X;
1786 /// \endcode
1787 /// usingDirectiveDecl()
1788 /// matches \code using namespace X \endcode
1789 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1791 
1792 /// Matches reference to a name that can be looked up during parsing
1793 /// but could not be resolved to a specific declaration.
1794 ///
1795 /// Given
1796 /// \code
1797 /// template<typename T>
1798 /// T foo() { T a; return a; }
1799 /// template<typename T>
1800 /// void bar() {
1801 /// foo<T>();
1802 /// }
1803 /// \endcode
1804 /// unresolvedLookupExpr()
1805 /// matches \code foo<T>() \endcode
1806 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1808 
1809 /// Matches unresolved using value declarations.
1810 ///
1811 /// Given
1812 /// \code
1813 /// template<typename X>
1814 /// class C : private X {
1815 /// using X::x;
1816 /// };
1817 /// \endcode
1818 /// unresolvedUsingValueDecl()
1819 /// matches \code using X::x \endcode
1820 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1823 
1824 /// Matches unresolved using value declarations that involve the
1825 /// typename.
1826 ///
1827 /// Given
1828 /// \code
1829 /// template <typename T>
1830 /// struct Base { typedef T Foo; };
1831 ///
1832 /// template<typename T>
1833 /// struct S : private Base<T> {
1834 /// using typename Base<T>::Foo;
1835 /// };
1836 /// \endcode
1837 /// unresolvedUsingTypenameDecl()
1838 /// matches \code using Base<T>::Foo \endcode
1839 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1842 
1843 /// Matches a constant expression wrapper.
1844 ///
1845 /// Example matches the constant in the case statement:
1846 /// (matcher = constantExpr())
1847 /// \code
1848 /// switch (a) {
1849 /// case 37: break;
1850 /// }
1851 /// \endcode
1852 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1853  constantExpr;
1854 
1855 /// Matches parentheses used in expressions.
1856 ///
1857 /// Example matches (foo() + 1)
1858 /// \code
1859 /// int foo() { return 1; }
1860 /// int a = (foo() + 1);
1861 /// \endcode
1862 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1863 
1864 /// Matches constructor call expressions (including implicit ones).
1865 ///
1866 /// Example matches string(ptr, n) and ptr within arguments of f
1867 /// (matcher = cxxConstructExpr())
1868 /// \code
1869 /// void f(const string &a, const string &b);
1870 /// char *ptr;
1871 /// int n;
1872 /// f(string(ptr, n), ptr);
1873 /// \endcode
1874 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1876 
1877 /// Matches unresolved constructor call expressions.
1878 ///
1879 /// Example matches T(t) in return statement of f
1880 /// (matcher = cxxUnresolvedConstructExpr())
1881 /// \code
1882 /// template <typename T>
1883 /// void f(const T& t) { return T(t); }
1884 /// \endcode
1885 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1888 
1889 /// Matches implicit and explicit this expressions.
1890 ///
1891 /// Example matches the implicit this expression in "return i".
1892 /// (matcher = cxxThisExpr())
1893 /// \code
1894 /// struct foo {
1895 /// int i;
1896 /// int f() { return i; }
1897 /// };
1898 /// \endcode
1899 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1900  cxxThisExpr;
1901 
1902 /// Matches nodes where temporaries are created.
1903 ///
1904 /// Example matches FunctionTakesString(GetStringByValue())
1905 /// (matcher = cxxBindTemporaryExpr())
1906 /// \code
1907 /// FunctionTakesString(GetStringByValue());
1908 /// FunctionTakesStringByPointer(GetStringPointer());
1909 /// \endcode
1910 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1912 
1913 /// Matches nodes where temporaries are materialized.
1914 ///
1915 /// Example: Given
1916 /// \code
1917 /// struct T {void func();};
1918 /// T f();
1919 /// void g(T);
1920 /// \endcode
1921 /// materializeTemporaryExpr() matches 'f()' in these statements
1922 /// \code
1923 /// T u(f());
1924 /// g(f());
1925 /// f().func();
1926 /// \endcode
1927 /// but does not match
1928 /// \code
1929 /// f();
1930 /// \endcode
1931 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1934 
1935 /// Matches new expressions.
1936 ///
1937 /// Given
1938 /// \code
1939 /// new X;
1940 /// \endcode
1941 /// cxxNewExpr()
1942 /// matches 'new X'.
1943 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1944 
1945 /// Matches delete expressions.
1946 ///
1947 /// Given
1948 /// \code
1949 /// delete X;
1950 /// \endcode
1951 /// cxxDeleteExpr()
1952 /// matches 'delete X'.
1953 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1954  cxxDeleteExpr;
1955 
1956 /// Matches noexcept expressions.
1957 ///
1958 /// Given
1959 /// \code
1960 /// bool a() noexcept;
1961 /// bool b() noexcept(true);
1962 /// bool c() noexcept(false);
1963 /// bool d() noexcept(noexcept(a()));
1964 /// bool e = noexcept(b()) || noexcept(c());
1965 /// \endcode
1966 /// cxxNoexceptExpr()
1967 /// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1968 /// doesn't match the noexcept specifier in the declarations a, b, c or d.
1969 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1971 
1972 /// Matches array subscript expressions.
1973 ///
1974 /// Given
1975 /// \code
1976 /// int i = a[1];
1977 /// \endcode
1978 /// arraySubscriptExpr()
1979 /// matches "a[1]"
1980 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1982 
1983 /// Matches the value of a default argument at the call site.
1984 ///
1985 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1986 /// default value of the second parameter in the call expression f(42)
1987 /// (matcher = cxxDefaultArgExpr())
1988 /// \code
1989 /// void f(int x, int y = 0);
1990 /// f(42);
1991 /// \endcode
1992 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1994 
1995 /// Matches overloaded operator calls.
1996 ///
1997 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1998 /// binaryOperator matcher.
1999 /// Currently it does not match operators such as new delete.
2000 /// FIXME: figure out why these do not match?
2001 ///
2002 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
2003 /// (matcher = cxxOperatorCallExpr())
2004 /// \code
2005 /// ostream &operator<< (ostream &out, int i) { };
2006 /// ostream &o; int b = 1, c = 1;
2007 /// o << b << c;
2008 /// \endcode
2009 /// See also the binaryOperation() matcher for more-general matching of binary
2010 /// uses of this AST node.
2011 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2013 
2014 /// Matches rewritten binary operators
2015 ///
2016 /// Example matches use of "<":
2017 /// \code
2018 /// #include <compare>
2019 /// struct HasSpaceshipMem {
2020 /// int a;
2021 /// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2022 /// };
2023 /// void compare() {
2024 /// HasSpaceshipMem hs1, hs2;
2025 /// if (hs1 < hs2)
2026 /// return;
2027 /// }
2028 /// \endcode
2029 /// See also the binaryOperation() matcher for more-general matching
2030 /// of this AST node.
2031 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2034 
2035 /// Matches expressions.
2036 ///
2037 /// Example matches x()
2038 /// \code
2039 /// void f() { x(); }
2040 /// \endcode
2041 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2042 
2043 /// Matches expressions that refer to declarations.
2044 ///
2045 /// Example matches x in if (x)
2046 /// \code
2047 /// bool x;
2048 /// if (x) {}
2049 /// \endcode
2050 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2051  declRefExpr;
2052 
2053 /// Matches a reference to an ObjCIvar.
2054 ///
2055 /// Example: matches "a" in "init" method:
2056 /// \code
2057 /// @implementation A {
2058 /// NSString *a;
2059 /// }
2060 /// - (void) init {
2061 /// a = @"hello";
2062 /// }
2063 /// \endcode
2064 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2066 
2067 /// Matches a reference to a block.
2068 ///
2069 /// Example: matches "^{}":
2070 /// \code
2071 /// void f() { ^{}(); }
2072 /// \endcode
2073 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2074 
2075 /// Matches if statements.
2076 ///
2077 /// Example matches 'if (x) {}'
2078 /// \code
2079 /// if (x) {}
2080 /// \endcode
2081 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2082 
2083 /// Matches for statements.
2084 ///
2085 /// Example matches 'for (;;) {}'
2086 /// \code
2087 /// for (;;) {}
2088 /// int i[] = {1, 2, 3}; for (auto a : i);
2089 /// \endcode
2090 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2091 
2092 /// Matches the increment statement of a for loop.
2093 ///
2094 /// Example:
2095 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2096 /// matches '++x' in
2097 /// \code
2098 /// for (x; x < N; ++x) { }
2099 /// \endcode
2100 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2101  InnerMatcher) {
2102  const Stmt *const Increment = Node.getInc();
2103  return (Increment != nullptr &&
2104  InnerMatcher.matches(*Increment, Finder, Builder));
2105 }
2106 
2107 /// Matches the initialization statement of a for loop.
2108 ///
2109 /// Example:
2110 /// forStmt(hasLoopInit(declStmt()))
2111 /// matches 'int x = 0' in
2112 /// \code
2113 /// for (int x = 0; x < N; ++x) { }
2114 /// \endcode
2115 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2116  InnerMatcher) {
2117  const Stmt *const Init = Node.getInit();
2118  return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2119 }
2120 
2121 /// Matches range-based for statements.
2122 ///
2123 /// cxxForRangeStmt() matches 'for (auto a : i)'
2124 /// \code
2125 /// int i[] = {1, 2, 3}; for (auto a : i);
2126 /// for(int j = 0; j < 5; ++j);
2127 /// \endcode
2128 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2130 
2131 /// Matches the initialization statement of a for loop.
2132 ///
2133 /// Example:
2134 /// forStmt(hasLoopVariable(anything()))
2135 /// matches 'int x' in
2136 /// \code
2137 /// for (int x : a) { }
2138 /// \endcode
2139 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2140  InnerMatcher) {
2141  const VarDecl *const Var = Node.getLoopVariable();
2142  return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2143 }
2144 
2145 /// Matches the range initialization statement of a for loop.
2146 ///
2147 /// Example:
2148 /// forStmt(hasRangeInit(anything()))
2149 /// matches 'a' in
2150 /// \code
2151 /// for (int x : a) { }
2152 /// \endcode
2153 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2154  InnerMatcher) {
2155  const Expr *const Init = Node.getRangeInit();
2156  return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2157 }
2158 
2159 /// Matches while statements.
2160 ///
2161 /// Given
2162 /// \code
2163 /// while (true) {}
2164 /// \endcode
2165 /// whileStmt()
2166 /// matches 'while (true) {}'.
2167 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2168 
2169 /// Matches do statements.
2170 ///
2171 /// Given
2172 /// \code
2173 /// do {} while (true);
2174 /// \endcode
2175 /// doStmt()
2176 /// matches 'do {} while(true)'
2177 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2178 
2179 /// Matches break statements.
2180 ///
2181 /// Given
2182 /// \code
2183 /// while (true) { break; }
2184 /// \endcode
2185 /// breakStmt()
2186 /// matches 'break'
2187 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2188 
2189 /// Matches continue statements.
2190 ///
2191 /// Given
2192 /// \code
2193 /// while (true) { continue; }
2194 /// \endcode
2195 /// continueStmt()
2196 /// matches 'continue'
2197 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2198  continueStmt;
2199 
2200 /// Matches co_return statements.
2201 ///
2202 /// Given
2203 /// \code
2204 /// while (true) { co_return; }
2205 /// \endcode
2206 /// coreturnStmt()
2207 /// matches 'co_return'
2208 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2209  coreturnStmt;
2210 
2211 /// Matches return statements.
2212 ///
2213 /// Given
2214 /// \code
2215 /// return 1;
2216 /// \endcode
2217 /// returnStmt()
2218 /// matches 'return 1'
2219 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2220 
2221 /// Matches goto statements.
2222 ///
2223 /// Given
2224 /// \code
2225 /// goto FOO;
2226 /// FOO: bar();
2227 /// \endcode
2228 /// gotoStmt()
2229 /// matches 'goto FOO'
2230 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2231 
2232 /// Matches label statements.
2233 ///
2234 /// Given
2235 /// \code
2236 /// goto FOO;
2237 /// FOO: bar();
2238 /// \endcode
2239 /// labelStmt()
2240 /// matches 'FOO:'
2241 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2242 
2243 /// Matches address of label statements (GNU extension).
2244 ///
2245 /// Given
2246 /// \code
2247 /// FOO: bar();
2248 /// void *ptr = &&FOO;
2249 /// goto *bar;
2250 /// \endcode
2251 /// addrLabelExpr()
2252 /// matches '&&FOO'
2253 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2254  addrLabelExpr;
2255 
2256 /// Matches switch statements.
2257 ///
2258 /// Given
2259 /// \code
2260 /// switch(a) { case 42: break; default: break; }
2261 /// \endcode
2262 /// switchStmt()
2263 /// matches 'switch(a)'.
2264 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2265 
2266 /// Matches case and default statements inside switch statements.
2267 ///
2268 /// Given
2269 /// \code
2270 /// switch(a) { case 42: break; default: break; }
2271 /// \endcode
2272 /// switchCase()
2273 /// matches 'case 42:' and 'default:'.
2274 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2275 
2276 /// Matches case statements inside switch statements.
2277 ///
2278 /// Given
2279 /// \code
2280 /// switch(a) { case 42: break; default: break; }
2281 /// \endcode
2282 /// caseStmt()
2283 /// matches 'case 42:'.
2284 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2285 
2286 /// Matches default statements inside switch statements.
2287 ///
2288 /// Given
2289 /// \code
2290 /// switch(a) { case 42: break; default: break; }
2291 /// \endcode
2292 /// defaultStmt()
2293 /// matches 'default:'.
2294 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2295  defaultStmt;
2296 
2297 /// Matches compound statements.
2298 ///
2299 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2300 /// \code
2301 /// for (;;) {{}}
2302 /// \endcode
2303 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2304  compoundStmt;
2305 
2306 /// Matches catch statements.
2307 ///
2308 /// \code
2309 /// try {} catch(int i) {}
2310 /// \endcode
2311 /// cxxCatchStmt()
2312 /// matches 'catch(int i)'
2313 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2314  cxxCatchStmt;
2315 
2316 /// Matches try statements.
2317 ///
2318 /// \code
2319 /// try {} catch(int i) {}
2320 /// \endcode
2321 /// cxxTryStmt()
2322 /// matches 'try {}'
2323 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2324 
2325 /// Matches throw expressions.
2326 ///
2327 /// \code
2328 /// try { throw 5; } catch(int i) {}
2329 /// \endcode
2330 /// cxxThrowExpr()
2331 /// matches 'throw 5'
2332 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2333  cxxThrowExpr;
2334 
2335 /// Matches null statements.
2336 ///
2337 /// \code
2338 /// foo();;
2339 /// \endcode
2340 /// nullStmt()
2341 /// matches the second ';'
2342 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2343 
2344 /// Matches asm statements.
2345 ///
2346 /// \code
2347 /// int i = 100;
2348 /// __asm("mov al, 2");
2349 /// \endcode
2350 /// asmStmt()
2351 /// matches '__asm("mov al, 2")'
2352 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2353 
2354 /// Matches bool literals.
2355 ///
2356 /// Example matches true
2357 /// \code
2358 /// true
2359 /// \endcode
2360 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2362 
2363 /// Matches string literals (also matches wide string literals).
2364 ///
2365 /// Example matches "abcd", L"abcd"
2366 /// \code
2367 /// char *s = "abcd";
2368 /// wchar_t *ws = L"abcd";
2369 /// \endcode
2370 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2371  stringLiteral;
2372 
2373 /// Matches character literals (also matches wchar_t).
2374 ///
2375 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2376 /// though.
2377 ///
2378 /// Example matches 'a', L'a'
2379 /// \code
2380 /// char ch = 'a';
2381 /// wchar_t chw = L'a';
2382 /// \endcode
2383 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2385 
2386 /// Matches integer literals of all sizes / encodings, e.g.
2387 /// 1, 1L, 0x1 and 1U.
2388 ///
2389 /// Does not match character-encoded integers such as L'a'.
2390 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2392 
2393 /// Matches float literals of all sizes / encodings, e.g.
2394 /// 1.0, 1.0f, 1.0L and 1e10.
2395 ///
2396 /// Does not match implicit conversions such as
2397 /// \code
2398 /// float a = 10;
2399 /// \endcode
2400 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2401  floatLiteral;
2402 
2403 /// Matches imaginary literals, which are based on integer and floating
2404 /// point literals e.g.: 1i, 1.0i
2405 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2407 
2408 /// Matches fixed point literals
2409 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2411 
2412 /// Matches user defined literal operator call.
2413 ///
2414 /// Example match: "foo"_suffix
2415 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2417 
2418 /// Matches compound (i.e. non-scalar) literals
2419 ///
2420 /// Example match: {1}, (1, 2)
2421 /// \code
2422 /// int array[4] = {1};
2423 /// vector int myvec = (vector int)(1, 2);
2424 /// \endcode
2425 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2427 
2428 /// Matches co_await expressions.
2429 ///
2430 /// Given
2431 /// \code
2432 /// co_await 1;
2433 /// \endcode
2434 /// coawaitExpr()
2435 /// matches 'co_await 1'
2436 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2437  coawaitExpr;
2438 /// Matches co_await expressions where the type of the promise is dependent
2439 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2441 /// Matches co_yield expressions.
2442 ///
2443 /// Given
2444 /// \code
2445 /// co_yield 1;
2446 /// \endcode
2447 /// coyieldExpr()
2448 /// matches 'co_yield 1'
2449 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2450  coyieldExpr;
2451 
2452 /// Matches nullptr literal.
2453 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2455 
2456 /// Matches GNU __builtin_choose_expr.
2457 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2458  chooseExpr;
2459 
2460 /// Matches GNU __null expression.
2461 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2462  gnuNullExpr;
2463 
2464 /// Matches C11 _Generic expression.
2465 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2467 
2468 /// Matches atomic builtins.
2469 /// Example matches __atomic_load_n(ptr, 1)
2470 /// \code
2471 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2472 /// \endcode
2473 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2474 
2475 /// Matches statement expression (GNU extension).
2476 ///
2477 /// Example match: ({ int X = 4; X; })
2478 /// \code
2479 /// int C = ({ int X = 4; X; });
2480 /// \endcode
2481 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2482 
2483 /// Matches binary operator expressions.
2484 ///
2485 /// Example matches a || b
2486 /// \code
2487 /// !(a || b)
2488 /// \endcode
2489 /// See also the binaryOperation() matcher for more-general matching.
2490 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2492 
2493 /// Matches unary operator expressions.
2494 ///
2495 /// Example matches !a
2496 /// \code
2497 /// !a || b
2498 /// \endcode
2499 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2500  unaryOperator;
2501 
2502 /// Matches conditional operator expressions.
2503 ///
2504 /// Example matches a ? b : c
2505 /// \code
2506 /// (a ? b : c) + 42
2507 /// \endcode
2508 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2510 
2511 /// Matches binary conditional operator expressions (GNU extension).
2512 ///
2513 /// Example matches a ?: b
2514 /// \code
2515 /// (a ?: b) + 42;
2516 /// \endcode
2517 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2520 
2521 /// Matches opaque value expressions. They are used as helpers
2522 /// to reference another expressions and can be met
2523 /// in BinaryConditionalOperators, for example.
2524 ///
2525 /// Example matches 'a'
2526 /// \code
2527 /// (a ?: c) + 42;
2528 /// \endcode
2529 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2531 
2532 /// Matches a C++ static_assert declaration.
2533 ///
2534 /// Example:
2535 /// staticAssertDecl()
2536 /// matches
2537 /// static_assert(sizeof(S) == sizeof(int))
2538 /// in
2539 /// \code
2540 /// struct S {
2541 /// int x;
2542 /// };
2543 /// static_assert(sizeof(S) == sizeof(int));
2544 /// \endcode
2545 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2547 
2548 /// Matches a reinterpret_cast expression.
2549 ///
2550 /// Either the source expression or the destination type can be matched
2551 /// using has(), but hasDestinationType() is more specific and can be
2552 /// more readable.
2553 ///
2554 /// Example matches reinterpret_cast<char*>(&p) in
2555 /// \code
2556 /// void* p = reinterpret_cast<char*>(&p);
2557 /// \endcode
2558 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2560 
2561 /// Matches a C++ static_cast expression.
2562 ///
2563 /// \see hasDestinationType
2564 /// \see reinterpretCast
2565 ///
2566 /// Example:
2567 /// cxxStaticCastExpr()
2568 /// matches
2569 /// static_cast<long>(8)
2570 /// in
2571 /// \code
2572 /// long eight(static_cast<long>(8));
2573 /// \endcode
2574 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2576 
2577 /// Matches a dynamic_cast expression.
2578 ///
2579 /// Example:
2580 /// cxxDynamicCastExpr()
2581 /// matches
2582 /// dynamic_cast<D*>(&b);
2583 /// in
2584 /// \code
2585 /// struct B { virtual ~B() {} }; struct D : B {};
2586 /// B b;
2587 /// D* p = dynamic_cast<D*>(&b);
2588 /// \endcode
2589 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2591 
2592 /// Matches a const_cast expression.
2593 ///
2594 /// Example: Matches const_cast<int*>(&r) in
2595 /// \code
2596 /// int n = 42;
2597 /// const int &r(n);
2598 /// int* p = const_cast<int*>(&r);
2599 /// \endcode
2600 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2602 
2603 /// Matches a C-style cast expression.
2604 ///
2605 /// Example: Matches (int) 2.2f in
2606 /// \code
2607 /// int i = (int) 2.2f;
2608 /// \endcode
2609 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2611 
2612 /// Matches explicit cast expressions.
2613 ///
2614 /// Matches any cast expression written in user code, whether it be a
2615 /// C-style cast, a functional-style cast, or a keyword cast.
2616 ///
2617 /// Does not match implicit conversions.
2618 ///
2619 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2620 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2621 /// actual cast expressions.
2622 ///
2623 /// \see hasDestinationType.
2624 ///
2625 /// Example: matches all five of the casts in
2626 /// \code
2627 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2628 /// \endcode
2629 /// but does not match the implicit conversion in
2630 /// \code
2631 /// long ell = 42;
2632 /// \endcode
2633 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2635 
2636 /// Matches the implicit cast nodes of Clang's AST.
2637 ///
2638 /// This matches many different places, including function call return value
2639 /// eliding, as well as any type conversions.
2640 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2642 
2643 /// Matches any cast nodes of Clang's AST.
2644 ///
2645 /// Example: castExpr() matches each of the following:
2646 /// \code
2647 /// (int) 3;
2648 /// const_cast<Expr *>(SubExpr);
2649 /// char c = 0;
2650 /// \endcode
2651 /// but does not match
2652 /// \code
2653 /// int i = (0);
2654 /// int k = 0;
2655 /// \endcode
2656 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2657 
2658 /// Matches functional cast expressions
2659 ///
2660 /// Example: Matches Foo(bar);
2661 /// \code
2662 /// Foo f = bar;
2663 /// Foo g = (Foo) bar;
2664 /// Foo h = Foo(bar);
2665 /// \endcode
2666 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2668 
2669 /// Matches functional cast expressions having N != 1 arguments
2670 ///
2671 /// Example: Matches Foo(bar, bar)
2672 /// \code
2673 /// Foo h = Foo(bar, bar);
2674 /// \endcode
2675 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2677 
2678 /// Matches predefined identifier expressions [C99 6.4.2.2].
2679 ///
2680 /// Example: Matches __func__
2681 /// \code
2682 /// printf("%s", __func__);
2683 /// \endcode
2684 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2686 
2687 /// Matches C99 designated initializer expressions [C99 6.7.8].
2688 ///
2689 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2690 /// \code
2691 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2692 /// \endcode
2693 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2695 
2696 /// Matches designated initializer expressions that contain
2697 /// a specific number of designators.
2698 ///
2699 /// Example: Given
2700 /// \code
2701 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2702 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2703 /// \endcode
2704 /// designatorCountIs(2)
2705 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2706 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2707 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2708  return Node.size() == N;
2709 }
2710 
2711 /// Matches \c QualTypes in the clang AST.
2712 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2713 
2714 /// Matches \c Types in the clang AST.
2715 extern const internal::VariadicAllOfMatcher<Type> type;
2716 
2717 /// Matches \c TypeLocs in the clang AST.
2718 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2719 
2720 /// Matches if any of the given matchers matches.
2721 ///
2722 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2723 /// matching submatcher.
2724 ///
2725 /// For example, in:
2726 /// \code
2727 /// class A { int a; int b; };
2728 /// \endcode
2729 /// The matcher:
2730 /// \code
2731 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2732 /// has(fieldDecl(hasName("b")).bind("v"))))
2733 /// \endcode
2734 /// will generate two results binding "v", the first of which binds
2735 /// the field declaration of \c a, the second the field declaration of
2736 /// \c b.
2737 ///
2738 /// Usable as: Any Matcher
2739 extern const internal::VariadicOperatorMatcherFunc<
2741  eachOf;
2742 
2743 /// Matches if any of the given matchers matches.
2744 ///
2745 /// Usable as: Any Matcher
2746 extern const internal::VariadicOperatorMatcherFunc<
2748  anyOf;
2749 
2750 /// Matches if all given matchers match.
2751 ///
2752 /// Usable as: Any Matcher
2753 extern const internal::VariadicOperatorMatcherFunc<
2755  allOf;
2756 
2757 /// Matches any node regardless of the submatcher.
2758 ///
2759 /// However, \c optionally will retain any bindings generated by the submatcher.
2760 /// Useful when additional information which may or may not present about a main
2761 /// matching node is desired.
2762 ///
2763 /// For example, in:
2764 /// \code
2765 /// class Foo {
2766 /// int bar;
2767 /// }
2768 /// \endcode
2769 /// The matcher:
2770 /// \code
2771 /// cxxRecordDecl(
2772 /// optionally(has(
2773 /// fieldDecl(hasName("bar")).bind("var")
2774 /// ))).bind("record")
2775 /// \endcode
2776 /// will produce a result binding for both "record" and "var".
2777 /// The matcher will produce a "record" binding for even if there is no data
2778 /// member named "bar" in that class.
2779 ///
2780 /// Usable as: Any Matcher
2781 extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2782 
2783 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2784 ///
2785 /// Given
2786 /// \code
2787 /// Foo x = bar;
2788 /// int y = sizeof(x) + alignof(x);
2789 /// \endcode
2790 /// unaryExprOrTypeTraitExpr()
2791 /// matches \c sizeof(x) and \c alignof(x)
2792 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2795 
2796 /// Matches any of the \p NodeMatchers with InnerMatchers nested within
2797 ///
2798 /// Given
2799 /// \code
2800 /// if (true);
2801 /// for (; true; );
2802 /// \endcode
2803 /// with the matcher
2804 /// \code
2805 /// mapAnyOf(ifStmt, forStmt).with(
2806 /// hasCondition(cxxBoolLiteralExpr(equals(true)))
2807 /// ).bind("trueCond")
2808 /// \endcode
2809 /// matches the \c if and the \c for. It is equivalent to:
2810 /// \code
2811 /// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2812 /// anyOf(
2813 /// ifStmt(trueCond).bind("trueCond"),
2814 /// forStmt(trueCond).bind("trueCond")
2815 /// );
2816 /// \endcode
2817 ///
2818 /// The with() chain-call accepts zero or more matchers which are combined
2819 /// as-if with allOf() in each of the node matchers.
2820 /// Usable as: Any Matcher
2821 template <typename T, typename... U>
2822 auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2823  return internal::MapAnyOfHelper<U...>();
2824 }
2825 
2826 /// Matches nodes which can be used with binary operators.
2827 ///
2828 /// The code
2829 /// \code
2830 /// var1 != var2;
2831 /// \endcode
2832 /// might be represented in the clang AST as a binaryOperator, a
2833 /// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2834 ///
2835 /// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2836 /// least one is a class type (cxxOperatorCallExpr)
2837 /// * whether the code appears in a template declaration, if at least one of the
2838 /// vars is a dependent-type (binaryOperator)
2839 /// * whether the code relies on a rewritten binary operator, such as a
2840 /// spaceship operator or an inverted equality operator
2841 /// (cxxRewrittenBinaryOperator)
2842 ///
2843 /// This matcher elides details in places where the matchers for the nodes are
2844 /// compatible.
2845 ///
2846 /// Given
2847 /// \code
2848 /// binaryOperation(
2849 /// hasOperatorName("!="),
2850 /// hasLHS(expr().bind("lhs")),
2851 /// hasRHS(expr().bind("rhs"))
2852 /// )
2853 /// \endcode
2854 /// matches each use of "!=" in:
2855 /// \code
2856 /// struct S{
2857 /// bool operator!=(const S&) const;
2858 /// };
2859 ///
2860 /// void foo()
2861 /// {
2862 /// 1 != 2;
2863 /// S() != S();
2864 /// }
2865 ///
2866 /// template<typename T>
2867 /// void templ()
2868 /// {
2869 /// 1 != 2;
2870 /// T() != S();
2871 /// }
2872 /// struct HasOpEq
2873 /// {
2874 /// bool operator==(const HasOpEq &) const;
2875 /// };
2876 ///
2877 /// void inverse()
2878 /// {
2879 /// HasOpEq s1;
2880 /// HasOpEq s2;
2881 /// if (s1 != s2)
2882 /// return;
2883 /// }
2884 ///
2885 /// struct HasSpaceship
2886 /// {
2887 /// bool operator<=>(const HasOpEq &) const;
2888 /// };
2889 ///
2890 /// void use_spaceship()
2891 /// {
2892 /// HasSpaceship s1;
2893 /// HasSpaceship s2;
2894 /// if (s1 != s2)
2895 /// return;
2896 /// }
2897 /// \endcode
2898 extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2901 
2902 /// Matches function calls and constructor calls
2903 ///
2904 /// Because CallExpr and CXXConstructExpr do not share a common
2905 /// base class with API accessing arguments etc, AST Matchers for code
2906 /// which should match both are typically duplicated. This matcher
2907 /// removes the need for duplication.
2908 ///
2909 /// Given code
2910 /// \code
2911 /// struct ConstructorTakesInt
2912 /// {
2913 /// ConstructorTakesInt(int i) {}
2914 /// };
2915 ///
2916 /// void callTakesInt(int i)
2917 /// {
2918 /// }
2919 ///
2920 /// void doCall()
2921 /// {
2922 /// callTakesInt(42);
2923 /// }
2924 ///
2925 /// void doConstruct()
2926 /// {
2927 /// ConstructorTakesInt cti(42);
2928 /// }
2929 /// \endcode
2930 ///
2931 /// The matcher
2932 /// \code
2933 /// invocation(hasArgument(0, integerLiteral(equals(42))))
2934 /// \endcode
2935 /// matches the expression in both doCall and doConstruct
2936 extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
2937 
2938 /// Matches unary expressions that have a specific type of argument.
2939 ///
2940 /// Given
2941 /// \code
2942 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2943 /// \endcode
2944 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2945 /// matches \c sizeof(a) and \c alignof(c)
2947  internal::Matcher<QualType>, InnerMatcher) {
2948  const QualType ArgumentType = Node.getTypeOfArgument();
2949  return InnerMatcher.matches(ArgumentType, Finder, Builder);
2950 }
2951 
2952 /// Matches unary expressions of a certain kind.
2953 ///
2954 /// Given
2955 /// \code
2956 /// int x;
2957 /// int s = sizeof(x) + alignof(x)
2958 /// \endcode
2959 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2960 /// matches \c sizeof(x)
2961 ///
2962 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2963 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2965  return Node.getKind() == Kind;
2966 }
2967 
2968 /// Same as unaryExprOrTypeTraitExpr, but only matching
2969 /// alignof.
2970 inline internal::BindableMatcher<Stmt> alignOfExpr(
2971  const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2973  allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2974  InnerMatcher)));
2975 }
2976 
2977 /// Same as unaryExprOrTypeTraitExpr, but only matching
2978 /// sizeof.
2979 inline internal::BindableMatcher<Stmt> sizeOfExpr(
2980  const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2982  allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2983 }
2984 
2985 /// Matches NamedDecl nodes that have the specified name.
2986 ///
2987 /// Supports specifying enclosing namespaces or classes by prefixing the name
2988 /// with '<enclosing>::'.
2989 /// Does not match typedefs of an underlying type with the given name.
2990 ///
2991 /// Example matches X (Name == "X")
2992 /// \code
2993 /// class X;
2994 /// \endcode
2995 ///
2996 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2997 /// \code
2998 /// namespace a { namespace b { class X; } }
2999 /// \endcode
3000 inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3001  return internal::Matcher<NamedDecl>(
3002  new internal::HasNameMatcher({std::string(Name)}));
3003 }
3004 
3005 /// Matches NamedDecl nodes that have any of the specified names.
3006 ///
3007 /// This matcher is only provided as a performance optimization of hasName.
3008 /// \code
3009 /// hasAnyName(a, b, c)
3010 /// \endcode
3011 /// is equivalent to, but faster than
3012 /// \code
3013 /// anyOf(hasName(a), hasName(b), hasName(c))
3014 /// \endcode
3015 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3017  hasAnyName;
3018 
3019 /// Matches NamedDecl nodes whose fully qualified names contain
3020 /// a substring matched by the given RegExp.
3021 ///
3022 /// Supports specifying enclosing namespaces or classes by
3023 /// prefixing the name with '<enclosing>::'. Does not match typedefs
3024 /// of an underlying type with the given name.
3025 ///
3026 /// Example matches X (regexp == "::X")
3027 /// \code
3028 /// class X;
3029 /// \endcode
3030 ///
3031 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3032 /// \code
3033 /// namespace foo { namespace bar { class X; } }
3034 /// \endcode
3035 AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3036  std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3037  return RegExp->match(FullNameString);
3038 }
3039 
3040 /// Matches overloaded operator names.
3041 ///
3042 /// Matches overloaded operator names specified in strings without the
3043 /// "operator" prefix: e.g. "<<".
3044 ///
3045 /// Given:
3046 /// \code
3047 /// class A { int operator*(); };
3048 /// const A &operator<<(const A &a, const A &b);
3049 /// A a;
3050 /// a << a; // <-- This matches
3051 /// \endcode
3052 ///
3053 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3054 /// specified line and
3055 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3056 /// matches the declaration of \c A.
3057 ///
3058 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3059 inline internal::PolymorphicMatcher<
3060  internal::HasOverloadedOperatorNameMatcher,
3062  std::vector<std::string>>
3063 hasOverloadedOperatorName(StringRef Name) {
3064  return internal::PolymorphicMatcher<
3065  internal::HasOverloadedOperatorNameMatcher,
3067  std::vector<std::string>>({std::string(Name)});
3068 }
3069 
3070 /// Matches overloaded operator names.
3071 ///
3072 /// Matches overloaded operator names specified in strings without the
3073 /// "operator" prefix: e.g. "<<".
3074 ///
3075 /// hasAnyOverloadedOperatorName("+", "-")
3076 /// Is equivalent to
3077 /// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3078 extern const internal::VariadicFunction<
3079  internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3082  std::vector<std::string>>,
3085 
3086 /// Matches template-dependent, but known, member names.
3087 ///
3088 /// In template declarations, dependent members are not resolved and so can
3089 /// not be matched to particular named declarations.
3090 ///
3091 /// This matcher allows to match on the known name of members.
3092 ///
3093 /// Given
3094 /// \code
3095 /// template <typename T>
3096 /// struct S {
3097 /// void mem();
3098 /// };
3099 /// template <typename T>
3100 /// void x() {
3101 /// S<T> s;
3102 /// s.mem();
3103 /// }
3104 /// \endcode
3105 /// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3107  return Node.getMember().getAsString() == N;
3108 }
3109 
3110 /// Matches template-dependent, but known, member names against an already-bound
3111 /// node
3112 ///
3113 /// In template declarations, dependent members are not resolved and so can
3114 /// not be matched to particular named declarations.
3115 ///
3116 /// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3117 /// and CXXMethodDecl nodes.
3118 ///
3119 /// Given
3120 /// \code
3121 /// template <typename T>
3122 /// struct S {
3123 /// void mem();
3124 /// };
3125 /// template <typename T>
3126 /// void x() {
3127 /// S<T> s;
3128 /// s.mem();
3129 /// }
3130 /// \endcode
3131 /// The matcher
3132 /// @code
3133 /// \c cxxDependentScopeMemberExpr(
3134 /// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3135 /// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3136 /// cxxMethodDecl(hasName("mem")).bind("templMem")
3137 /// )))))
3138 /// )))),
3139 /// memberHasSameNameAsBoundNode("templMem")
3140 /// )
3141 /// @endcode
3142 /// first matches and binds the @c mem member of the @c S template, then
3143 /// compares its name to the usage in @c s.mem() in the @c x function template
3144 AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3145  std::string, BindingID) {
3146  auto MemberName = Node.getMember().getAsString();
3147 
3148  return Builder->removeBindings(
3149  [this, MemberName](const BoundNodesMap &Nodes) {
3150  const auto &BN = Nodes.getNode(this->BindingID);
3151  if (const auto *ND = BN.get<NamedDecl>()) {
3152  if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3153  return true;
3154  return ND->getName() != MemberName;
3155  }
3156  return true;
3157  });
3158 }
3159 
3160 /// Matches C++ classes that are directly or indirectly derived from a class
3161 /// matching \c Base, or Objective-C classes that directly or indirectly
3162 /// subclass a class matching \c Base.
3163 ///
3164 /// Note that a class is not considered to be derived from itself.
3165 ///
3166 /// Example matches Y, Z, C (Base == hasName("X"))
3167 /// \code
3168 /// class X;
3169 /// class Y : public X {}; // directly derived
3170 /// class Z : public Y {}; // indirectly derived
3171 /// typedef X A;
3172 /// typedef A B;
3173 /// class C : public B {}; // derived from a typedef of X
3174 /// \endcode
3175 ///
3176 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
3177 /// \code
3178 /// class Foo;
3179 /// typedef Foo X;
3180 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
3181 /// \endcode
3182 ///
3183 /// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3184 /// \code
3185 /// @interface NSObject @end
3186 /// @interface Bar : NSObject @end
3187 /// \endcode
3188 ///
3189 /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3191  isDerivedFrom,
3193  internal::Matcher<NamedDecl>, Base) {
3194  // Check if the node is a C++ struct/union/class.
3195  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3196  return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3197 
3198  // The node must be an Objective-C class.
3199  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3200  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3201  /*Directly=*/false);
3202 }
3203 
3204 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3206  isDerivedFrom,
3208  std::string, BaseName, 1) {
3209  if (BaseName.empty())
3210  return false;
3211 
3212  const auto M = isDerivedFrom(hasName(BaseName));
3213 
3214  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3215  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3216 
3217  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3218  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3219 }
3220 
3221 /// Matches C++ classes that have a direct or indirect base matching \p
3222 /// BaseSpecMatcher.
3223 ///
3224 /// Example:
3225 /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3226 /// \code
3227 /// class Foo;
3228 /// class Bar : Foo {};
3229 /// class Baz : Bar {};
3230 /// class SpecialBase;
3231 /// class Proxy : SpecialBase {}; // matches Proxy
3232 /// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3233 /// \endcode
3234 ///
3235 // FIXME: Refactor this and isDerivedFrom to reuse implementation.
3236 AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3237  BaseSpecMatcher) {
3238  return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3239 }
3240 
3241 /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3242 ///
3243 /// Example:
3244 /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3245 /// \code
3246 /// class Foo;
3247 /// class Bar : Foo {};
3248 /// class Baz : Bar {};
3249 /// class SpecialBase;
3250 /// class Proxy : SpecialBase {}; // matches Proxy
3251 /// class IndirectlyDerived : Proxy {}; // doesn't match
3252 /// \endcode
3253 AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3254  BaseSpecMatcher) {
3255  return Node.hasDefinition() &&
3256  llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3257  return BaseSpecMatcher.matches(Base, Finder, Builder);
3258  });
3259 }
3260 
3261 /// Similar to \c isDerivedFrom(), but also matches classes that directly
3262 /// match \c Base.
3264  isSameOrDerivedFrom,
3266  internal::Matcher<NamedDecl>, Base, 0) {
3267  const auto M = anyOf(Base, isDerivedFrom(Base));
3268 
3269  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3270  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3271 
3272  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3273  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3274 }
3275 
3276 /// Overloaded method as shortcut for
3277 /// \c isSameOrDerivedFrom(hasName(...)).
3279  isSameOrDerivedFrom,
3281  std::string, BaseName, 1) {
3282  if (BaseName.empty())
3283  return false;
3284 
3285  const auto M = isSameOrDerivedFrom(hasName(BaseName));
3286 
3287  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3288  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3289 
3290  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3291  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3292 }
3293 
3294 /// Matches C++ or Objective-C classes that are directly derived from a class
3295 /// matching \c Base.
3296 ///
3297 /// Note that a class is not considered to be derived from itself.
3298 ///
3299 /// Example matches Y, C (Base == hasName("X"))
3300 /// \code
3301 /// class X;
3302 /// class Y : public X {}; // directly derived
3303 /// class Z : public Y {}; // indirectly derived
3304 /// typedef X A;
3305 /// typedef A B;
3306 /// class C : public B {}; // derived from a typedef of X
3307 /// \endcode
3308 ///
3309 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
3310 /// \code
3311 /// class Foo;
3312 /// typedef Foo X;
3313 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
3314 /// \endcode
3316  isDirectlyDerivedFrom,
3318  internal::Matcher<NamedDecl>, Base, 0) {
3319  // Check if the node is a C++ struct/union/class.
3320  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3321  return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3322 
3323  // The node must be an Objective-C class.
3324  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3325  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3326  /*Directly=*/true);
3327 }
3328 
3329 /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3331  isDirectlyDerivedFrom,
3333  std::string, BaseName, 1) {
3334  if (BaseName.empty())
3335  return false;
3336  const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3337 
3338  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3339  return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3340 
3341  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3342  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3343 }
3344 /// Matches the first method of a class or struct that satisfies \c
3345 /// InnerMatcher.
3346 ///
3347 /// Given:
3348 /// \code
3349 /// class A { void func(); };
3350 /// class B { void member(); };
3351 /// \endcode
3352 ///
3353 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3354 /// \c A but not \c B.
3355 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3356  InnerMatcher) {
3357  BoundNodesTreeBuilder Result(*Builder);
3358  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3359  Node.method_end(), Finder, &Result);
3360  if (MatchIt == Node.method_end())
3361  return false;
3362 
3363  if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3364  return false;
3365  *Builder = std::move(Result);
3366  return true;
3367 }
3368 
3369 /// Matches the generated class of lambda expressions.
3370 ///
3371 /// Given:
3372 /// \code
3373 /// auto x = []{};
3374 /// \endcode
3375 ///
3376 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3377 /// \c decltype(x)
3379  return Node.isLambda();
3380 }
3381 
3382 /// Matches AST nodes that have child AST nodes that match the
3383 /// provided matcher.
3384 ///
3385 /// Example matches X, Y
3386 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3387 /// \code
3388 /// class X {}; // Matches X, because X::X is a class of name X inside X.
3389 /// class Y { class X {}; };
3390 /// class Z { class Y { class X {}; }; }; // Does not match Z.
3391 /// \endcode
3392 ///
3393 /// ChildT must be an AST base type.
3394 ///
3395 /// Usable as: Any Matcher
3396 /// Note that has is direct matcher, so it also matches things like implicit
3397 /// casts and paren casts. If you are matching with expr then you should
3398 /// probably consider using ignoringParenImpCasts like:
3399 /// has(ignoringParenImpCasts(expr())).
3400 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3401 
3402 /// Matches AST nodes that have descendant AST nodes that match the
3403 /// provided matcher.
3404 ///
3405 /// Example matches X, Y, Z
3406 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3407 /// \code
3408 /// class X {}; // Matches X, because X::X is a class of name X inside X.
3409 /// class Y { class X {}; };
3410 /// class Z { class Y { class X {}; }; };
3411 /// \endcode
3412 ///
3413 /// DescendantT must be an AST base type.
3414 ///
3415 /// Usable as: Any Matcher
3416 extern const internal::ArgumentAdaptingMatcherFunc<
3417  internal::HasDescendantMatcher>
3418  hasDescendant;
3419 
3420 /// Matches AST nodes that have child AST nodes that match the
3421 /// provided matcher.
3422 ///
3423 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3424 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3425 /// \code
3426 /// class X {};
3427 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3428 /// // inside Y.
3429 /// class Z { class Y { class X {}; }; }; // Does not match Z.
3430 /// \endcode
3431 ///
3432 /// ChildT must be an AST base type.
3433 ///
3434 /// As opposed to 'has', 'forEach' will cause a match for each result that
3435 /// matches instead of only on the first one.
3436 ///
3437 /// Usable as: Any Matcher
3438 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3439  forEach;
3440 
3441 /// Matches AST nodes that have descendant AST nodes that match the
3442 /// provided matcher.
3443 ///
3444 /// Example matches X, A, A::X, B, B::C, B::C::X
3445 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3446 /// \code
3447 /// class X {};
3448 /// class A { class X {}; }; // Matches A, because A::X is a class of name
3449 /// // X inside A.
3450 /// class B { class C { class X {}; }; };
3451 /// \endcode
3452 ///
3453 /// DescendantT must be an AST base type.
3454 ///
3455 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3456 /// each result that matches instead of only on the first one.
3457 ///
3458 /// Note: Recursively combined ForEachDescendant can cause many matches:
3459 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3460 /// forEachDescendant(cxxRecordDecl())
3461 /// )))
3462 /// will match 10 times (plus injected class name matches) on:
3463 /// \code
3464 /// class A { class B { class C { class D { class E {}; }; }; }; };
3465 /// \endcode
3466 ///
3467 /// Usable as: Any Matcher
3468 extern const internal::ArgumentAdaptingMatcherFunc<
3469  internal::ForEachDescendantMatcher>
3471 
3472 /// Matches if the node or any descendant matches.
3473 ///
3474 /// Generates results for each match.
3475 ///
3476 /// For example, in:
3477 /// \code
3478 /// class A { class B {}; class C {}; };
3479 /// \endcode
3480 /// The matcher:
3481 /// \code
3482 /// cxxRecordDecl(hasName("::A"),
3483 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3484 /// \endcode
3485 /// will generate results for \c A, \c B and \c C.
3486 ///
3487 /// Usable as: Any Matcher
3488 template <typename T>
3489 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3490  return eachOf(Matcher, forEachDescendant(Matcher));
3491 }
3492 
3493 /// Matches AST nodes that have a parent that matches the provided
3494 /// matcher.
3495 ///
3496 /// Given
3497 /// \code
3498 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3499 /// \endcode
3500 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3501 ///
3502 /// Usable as: Any Matcher
3503 extern const internal::ArgumentAdaptingMatcherFunc<
3504  internal::HasParentMatcher,
3505  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3506  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3507  hasParent;
3508 
3509 /// Matches AST nodes that have an ancestor that matches the provided
3510 /// matcher.
3511 ///
3512 /// Given
3513 /// \code
3514 /// void f() { if (true) { int x = 42; } }
3515 /// void g() { for (;;) { int x = 43; } }
3516 /// \endcode
3517 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3518 ///
3519 /// Usable as: Any Matcher
3520 extern const internal::ArgumentAdaptingMatcherFunc<
3521  internal::HasAncestorMatcher,
3522  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3523  internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3524  hasAncestor;
3525 
3526 /// Matches if the provided matcher does not match.
3527 ///
3528 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3529 /// \code
3530 /// class X {};
3531 /// class Y {};
3532 /// \endcode
3533 ///
3534 /// Usable as: Any Matcher
3535 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3536 
3537 /// Matches a node if the declaration associated with that node
3538 /// matches the given matcher.
3539 ///
3540 /// The associated declaration is:
3541 /// - for type nodes, the declaration of the underlying type
3542 /// - for CallExpr, the declaration of the callee
3543 /// - for MemberExpr, the declaration of the referenced member
3544 /// - for CXXConstructExpr, the declaration of the constructor
3545 /// - for CXXNewExpr, the declaration of the operator new
3546 /// - for ObjCIvarExpr, the declaration of the ivar
3547 ///
3548 /// For type nodes, hasDeclaration will generally match the declaration of the
3549 /// sugared type. Given
3550 /// \code
3551 /// class X {};
3552 /// typedef X Y;
3553 /// Y y;
3554 /// \endcode
3555 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3556 /// typedefDecl. A common use case is to match the underlying, desugared type.
3557 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3558 /// \code
3559 /// varDecl(hasType(hasUnqualifiedDesugaredType(
3560 /// recordType(hasDeclaration(decl())))))
3561 /// \endcode
3562 /// In this matcher, the decl will match the CXXRecordDecl of class X.
3563 ///
3564 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3565 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3566 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3567 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3568 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3569 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3570 /// Matcher<UnresolvedUsingType>
3571 inline internal::PolymorphicMatcher<
3572  internal::HasDeclarationMatcher,
3573  void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3574 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3575  return internal::PolymorphicMatcher<
3576  internal::HasDeclarationMatcher,
3577  void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3578  InnerMatcher);
3579 }
3580 
3581 /// Matches a \c NamedDecl whose underlying declaration matches the given
3582 /// matcher.
3583 ///
3584 /// Given
3585 /// \code
3586 /// namespace N { template<class T> void f(T t); }
3587 /// template <class T> void g() { using N::f; f(T()); }
3588 /// \endcode
3589 /// \c unresolvedLookupExpr(hasAnyDeclaration(
3590 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3591 /// matches the use of \c f in \c g() .
3592 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3593  InnerMatcher) {
3594  const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3595 
3596  return UnderlyingDecl != nullptr &&
3597  InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3598 }
3599 
3600 /// Matches on the implicit object argument of a member call expression, after
3601 /// stripping off any parentheses or implicit casts.
3602 ///
3603 /// Given
3604 /// \code
3605 /// class Y { public: void m(); };
3606 /// Y g();
3607 /// class X : public Y {};
3608 /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3609 /// \endcode
3610 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3611 /// matches `y.m()` and `(g()).m()`.
3612 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3613 /// matches `x.m()`.
3614 /// cxxMemberCallExpr(on(callExpr()))
3615 /// matches `(g()).m()`.
3616 ///
3617 /// FIXME: Overload to allow directly matching types?
3618 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3619  InnerMatcher) {
3620  const Expr *ExprNode = Node.getImplicitObjectArgument()
3621  ->IgnoreParenImpCasts();
3622  return (ExprNode != nullptr &&
3623  InnerMatcher.matches(*ExprNode, Finder, Builder));
3624 }
3625 
3626 
3627 /// Matches on the receiver of an ObjectiveC Message expression.
3628 ///
3629 /// Example
3630 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3631 /// matches the [webView ...] message invocation.
3632 /// \code
3633 /// NSString *webViewJavaScript = ...
3634 /// UIWebView *webView = ...
3635 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3636 /// \endcode
3637 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3638  InnerMatcher) {
3639  const QualType TypeDecl = Node.getReceiverType();
3640  return InnerMatcher.matches(TypeDecl, Finder, Builder);
3641 }
3642 
3643 /// Returns true when the Objective-C method declaration is a class method.
3644 ///
3645 /// Example
3646 /// matcher = objcMethodDecl(isClassMethod())
3647 /// matches
3648 /// \code
3649 /// @interface I + (void)foo; @end
3650 /// \endcode
3651 /// but not
3652 /// \code
3653 /// @interface I - (void)bar; @end
3654 /// \endcode
3655 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
3656  return Node.isClassMethod();
3657 }
3658 
3659 /// Returns true when the Objective-C method declaration is an instance method.
3660 ///
3661 /// Example
3662 /// matcher = objcMethodDecl(isInstanceMethod())
3663 /// matches
3664 /// \code
3665 /// @interface I - (void)bar; @end
3666 /// \endcode
3667 /// but not
3668 /// \code
3669 /// @interface I + (void)foo; @end
3670 /// \endcode
3672  return Node.isInstanceMethod();
3673 }
3674 
3675 /// Returns true when the Objective-C message is sent to a class.
3676 ///
3677 /// Example
3678 /// matcher = objcMessageExpr(isClassMessage())
3679 /// matches
3680 /// \code
3681 /// [NSString stringWithFormat:@"format"];
3682 /// \endcode
3683 /// but not
3684 /// \code
3685 /// NSString *x = @"hello";
3686 /// [x containsString:@"h"];
3687 /// \endcode
3688 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
3689  return Node.isClassMessage();
3690 }
3691 
3692 /// Returns true when the Objective-C message is sent to an instance.
3693 ///
3694 /// Example
3695 /// matcher = objcMessageExpr(isInstanceMessage())
3696 /// matches
3697 /// \code
3698 /// NSString *x = @"hello";
3699 /// [x containsString:@"h"];
3700 /// \endcode
3701 /// but not
3702 /// \code
3703 /// [NSString stringWithFormat:@"format"];
3704 /// \endcode
3705 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3706  return Node.isInstanceMessage();
3707 }
3708 
3709 /// Matches if the Objective-C message is sent to an instance,
3710 /// and the inner matcher matches on that instance.
3711 ///
3712 /// For example the method call in
3713 /// \code
3714 /// NSString *x = @"hello";
3715 /// [x containsString:@"h"];
3716 /// \endcode
3717 /// is matched by
3718 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3719 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3720  InnerMatcher) {
3721  const Expr *ReceiverNode = Node.getInstanceReceiver();
3722  return (ReceiverNode != nullptr &&
3723  InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3724  Builder));
3725 }
3726 
3727 /// Matches when BaseName == Selector.getAsString()
3728 ///
3729 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3730 /// matches the outer message expr in the code below, but NOT the message
3731 /// invocation for self.bodyView.
3732 /// \code
3733 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3734 /// \endcode
3735 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3736  Selector Sel = Node.getSelector();
3737  return BaseName == Sel.getAsString();
3738 }
3739 
3740 /// Matches when at least one of the supplied string equals to the
3741 /// Selector.getAsString()
3742 ///
3743 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3744 /// matches both of the expressions below:
3745 /// \code
3746 /// [myObj methodA:argA];
3747 /// [myObj methodB:argB];
3748 /// \endcode
3749 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3750  StringRef,
3753 
3754 /// Matches ObjC selectors whose name contains
3755 /// a substring matched by the given RegExp.
3756 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3757 /// matches the outer message expr in the code below, but NOT the message
3758 /// invocation for self.bodyView.
3759 /// \code
3760 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3761 /// \endcode
3762 AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3763  std::string SelectorString = Node.getSelector().getAsString();
3764  return RegExp->match(SelectorString);
3765 }
3766 
3767 /// Matches when the selector is the empty selector
3768 ///
3769 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3770 /// represent an error condition in the tree!
3771 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3772  return Node.getSelector().isNull();
3773 }
3774 
3775 /// Matches when the selector is a Unary Selector
3776 ///
3777 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3778 /// matches self.bodyView in the code below, but NOT the outer message
3779 /// invocation of "loadHTMLString:baseURL:".
3780 /// \code
3781 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3782 /// \endcode
3783 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3784  return Node.getSelector().isUnarySelector();
3785 }
3786 
3787 /// Matches when the selector is a keyword selector
3788 ///
3789 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3790 /// message expression in
3791 ///
3792 /// \code
3793 /// UIWebView *webView = ...;
3794 /// CGRect bodyFrame = webView.frame;
3795 /// bodyFrame.size.height = self.bodyContentHeight;
3796 /// webView.frame = bodyFrame;
3797 /// // ^---- matches here
3798 /// \endcode
3799 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3800  return Node.getSelector().isKeywordSelector();
3801 }
3802 
3803 /// Matches when the selector has the specified number of arguments
3804 ///
3805 /// matcher = objCMessageExpr(numSelectorArgs(0));
3806 /// matches self.bodyView in the code below
3807 ///
3808 /// matcher = objCMessageExpr(numSelectorArgs(2));
3809 /// matches the invocation of "loadHTMLString:baseURL:" but not that
3810 /// of self.bodyView
3811 /// \code
3812 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3813 /// \endcode
3814 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3815  return Node.getSelector().getNumArgs() == N;
3816 }
3817 
3818 /// Matches if the call expression's callee expression matches.
3819 ///
3820 /// Given
3821 /// \code
3822 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3823 /// void f() { f(); }
3824 /// \endcode
3825 /// callExpr(callee(expr()))
3826 /// matches this->x(), x(), y.x(), f()
3827 /// with callee(...)
3828 /// matching this->x, x, y.x, f respectively
3829 ///
3830 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3831 /// because this introduces ambiguous overloads with calls to Callee taking a
3832 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3833 /// implemented in terms of implicit casts.
3834 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3835  InnerMatcher) {
3836  const Expr *ExprNode = Node.getCallee();
3837  return (ExprNode != nullptr &&
3838  InnerMatcher.matches(*ExprNode, Finder, Builder));
3839 }
3840 
3841 /// Matches 1) if the call expression's callee's declaration matches the
3842 /// given matcher; or 2) if the Obj-C message expression's callee's method
3843 /// declaration matches the given matcher.
3844 ///
3845 /// Example matches y.x() (matcher = callExpr(callee(
3846 /// cxxMethodDecl(hasName("x")))))
3847 /// \code
3848 /// class Y { public: void x(); };
3849 /// void z() { Y y; y.x(); }
3850 /// \endcode
3851 ///
3852 /// Example 2. Matches [I foo] with
3853 /// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3854 ///
3855 /// \code
3856 /// @interface I: NSObject
3857 /// +(void)foo;
3858 /// @end
3859 /// ...
3860 /// [I foo]
3861 /// \endcode
3864  internal::Matcher<Decl>, InnerMatcher, 1) {
3865  if (const auto *CallNode = dyn_cast<CallExpr>(&Node))
3866  return callExpr(hasDeclaration(InnerMatcher))
3867  .matches(Node, Finder, Builder);
3868  else {
3869  // The dynamic cast below is guaranteed to succeed as there are only 2
3870  // supported return types.
3871  const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
3872  const Decl *DeclNode = MsgNode->getMethodDecl();
3873  return (DeclNode != nullptr &&
3874  InnerMatcher.matches(*DeclNode, Finder, Builder));
3875  }
3876 }
3877 
3878 /// Matches if the expression's or declaration's type matches a type
3879 /// matcher.
3880 ///
3881 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3882 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3883 /// and U (matcher = typedefDecl(hasType(asString("int")))
3884 /// and friend class X (matcher = friendDecl(hasType("X"))
3885 /// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3886 /// asString("class X")))
3887 /// \code
3888 /// class X {};
3889 /// void y(X &x) { x; X z; }
3890 /// typedef int U;
3891 /// class Y { friend class X; };
3892 /// class Z : public virtual X {};
3893 /// \endcode
3895  hasType,
3898  internal::Matcher<QualType>, InnerMatcher, 0) {
3900  if (!QT.isNull())
3901  return InnerMatcher.matches(QT, Finder, Builder);
3902  return false;
3903 }
3904 
3905 /// Overloaded to match the declaration of the expression's or value
3906 /// declaration's type.
3907 ///
3908 /// In case of a value declaration (for example a variable declaration),
3909 /// this resolves one layer of indirection. For example, in the value
3910 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3911 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3912 /// declaration of x.
3913 ///
3914 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3915 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3916 /// and friend class X (matcher = friendDecl(hasType("X"))
3917 /// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3918 /// cxxRecordDecl(hasName("X"))))
3919 /// \code
3920 /// class X {};
3921 /// void y(X &x) { x; X z; }
3922 /// class Y { friend class X; };
3923 /// class Z : public virtual X {};
3924 /// \endcode
3925 ///
3926 /// Example matches class Derived
3927 /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
3928 /// \code
3929 /// class Base {};
3930 /// class Derived : Base {};
3931 /// \endcode
3932 ///
3933 /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
3934 /// Matcher<CXXBaseSpecifier>
3936  hasType,
3939  internal::Matcher<Decl>, InnerMatcher, 1) {
3941  if (!QT.isNull())
3942  return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3943  return false;
3944 }
3945 
3946 /// Matches if the type location of a node matches the inner matcher.
3947 ///
3948 /// Examples:
3949 /// \code
3950 /// int x;
3951 /// \endcode
3952 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3953 /// matches int x
3954 ///
3955 /// \code
3956 /// auto x = int(3);
3957 /// \code
3958 /// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
3959 /// matches int(3)
3960 ///
3961 /// \code
3962 /// struct Foo { Foo(int, int); };
3963 /// auto x = Foo(1, 2);
3964 /// \code
3965 /// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
3966 /// matches Foo(1, 2)
3967 ///
3968 /// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
3969 /// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
3970 /// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
3971 /// Matcher<CXXUnresolvedConstructExpr>,
3972 /// Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>,
3973 /// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
3974 /// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
3975 /// Matcher<TypedefNameDecl>
3977  hasTypeLoc,
3983  TypedefNameDecl),
3984  internal::Matcher<TypeLoc>, Inner) {
3985  TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
3986  if (source == nullptr) {
3987  // This happens for example for implicit destructors.
3988  return false;
3989  }
3990  return Inner.matches(source->getTypeLoc(), Finder, Builder);
3991 }
3992 
3993 /// Matches if the matched type is represented by the given string.
3994 ///
3995 /// Given
3996 /// \code
3997 /// class Y { public: void x(); };
3998 /// void z() { Y* y; y->x(); }
3999 /// \endcode
4000 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
4001 /// matches y->x()
4003  return Name == Node.getAsString();
4004 }
4005 
4006 /// Matches if the matched type is a pointer type and the pointee type
4007 /// matches the specified matcher.
4008 ///
4009 /// Example matches y->x()
4010 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
4011 /// cxxRecordDecl(hasName("Y")))))))
4012 /// \code
4013 /// class Y { public: void x(); };
4014 /// void z() { Y *y; y->x(); }
4015 /// \endcode
4017  QualType, pointsTo, internal::Matcher<QualType>,
4018  InnerMatcher) {
4019  return (!Node.isNull() && Node->isAnyPointerType() &&
4020  InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4021 }
4022 
4023 /// Overloaded to match the pointee type's declaration.
4024 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
4025  InnerMatcher, 1) {
4026  return pointsTo(qualType(hasDeclaration(InnerMatcher)))
4027  .matches(Node, Finder, Builder);
4028 }
4029 
4030 /// Matches if the matched type matches the unqualified desugared
4031 /// type of the matched node.
4032 ///
4033 /// For example, in:
4034 /// \code
4035 /// class A {};
4036 /// using B = A;
4037 /// \endcode
4038 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4039 /// both B and A.
4040 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4041  InnerMatcher) {
4042  return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4043  Builder);
4044 }
4045 
4046 /// Matches if the matched type is a reference type and the referenced
4047 /// type matches the specified matcher.
4048 ///
4049 /// Example matches X &x and const X &y
4050 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4051 /// \code
4052 /// class X {
4053 /// void a(X b) {
4054 /// X &x = b;
4055 /// const X &y = b;
4056 /// }
4057 /// };
4058 /// \endcode
4059 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4060  InnerMatcher) {
4061  return (!Node.isNull() && Node->isReferenceType() &&
4062  InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4063 }
4064 
4065 /// Matches QualTypes whose canonical type matches InnerMatcher.
4066 ///
4067 /// Given:
4068 /// \code
4069 /// typedef int &int_ref;
4070 /// int a;
4071 /// int_ref b = a;
4072 /// \endcode
4073 ///
4074 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4075 /// declaration of b but \c
4076 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4077 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4078  InnerMatcher) {
4079  if (Node.isNull())
4080  return false;
4081  return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4082 }
4083 
4084 /// Overloaded to match the referenced type's declaration.
4085 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4086  InnerMatcher, 1) {
4087  return references(qualType(hasDeclaration(InnerMatcher)))
4088  .matches(Node, Finder, Builder);
4089 }
4090 
4091 /// Matches on the implicit object argument of a member call expression. Unlike
4092 /// `on`, matches the argument directly without stripping away anything.
4093 ///
4094 /// Given
4095 /// \code
4096 /// class Y { public: void m(); };
4097 /// Y g();
4098 /// class X : public Y { void g(); };
4099 /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4100 /// \endcode
4101 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4102 /// cxxRecordDecl(hasName("Y")))))
4103 /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
4104 /// cxxMemberCallExpr(on(callExpr()))
4105 /// does not match `(g()).m()`, because the parens are not ignored.
4106 ///
4107 /// FIXME: Overload to allow directly matching types?
4108 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4109  internal::Matcher<Expr>, InnerMatcher) {
4110  const Expr *ExprNode = Node.getImplicitObjectArgument();
4111  return (ExprNode != nullptr &&
4112  InnerMatcher.matches(*ExprNode, Finder, Builder));
4113 }
4114 
4115 /// Matches if the type of the expression's implicit object argument either
4116 /// matches the InnerMatcher, or is a pointer to a type that matches the
4117 /// InnerMatcher.
4118 ///
4119 /// Given
4120 /// \code
4121 /// class Y { public: void m(); };
4122 /// class X : public Y { void g(); };
4123 /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4124 /// \endcode
4125 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4126 /// cxxRecordDecl(hasName("Y")))))
4127 /// matches `y.m()`, `p->m()` and `x.m()`.
4128 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4129 /// cxxRecordDecl(hasName("X")))))
4130 /// matches `x.g()`.
4132  internal::Matcher<QualType>, InnerMatcher, 0) {
4133  return onImplicitObjectArgument(
4134  anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4135  .matches(Node, Finder, Builder);
4136 }
4137 
4138 /// Overloaded to match the type's declaration.
4140  internal::Matcher<Decl>, InnerMatcher, 1) {
4141  return onImplicitObjectArgument(
4142  anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4143  .matches(Node, Finder, Builder);
4144 }
4145 
4146 /// Matches a DeclRefExpr that refers to a declaration that matches the
4147 /// specified matcher.
4148 ///
4149 /// Example matches x in if(x)
4150 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4151 /// \code
4152 /// bool x;
4153 /// if (x) {}
4154 /// \endcode
4155 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4156  InnerMatcher) {
4157  const Decl *DeclNode = Node.getDecl();
4158  return (DeclNode != nullptr &&
4159  InnerMatcher.matches(*DeclNode, Finder, Builder));
4160 }
4161 
4162 /// Matches if a node refers to a declaration through a specific
4163 /// using shadow declaration.
4164 ///
4165 /// Examples:
4166 /// \code
4167 /// namespace a { int f(); }
4168 /// using a::f;
4169 /// int x = f();
4170 /// \endcode
4171 /// declRefExpr(throughUsingDecl(anything()))
4172 /// matches \c f
4173 ///
4174 /// \code
4175 /// namespace a { class X{}; }
4176 /// using a::X;
4177 /// X x;
4178 /// \code
4179 /// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4180 /// matches \c X
4181 ///
4182 /// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4183 AST_POLYMORPHIC_MATCHER_P(throughUsingDecl,
4185  UsingType),
4186  internal::Matcher<UsingShadowDecl>, Inner) {
4187  const NamedDecl *FoundDecl = Node.getFoundDecl();
4188  if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4189  return Inner.matches(*UsingDecl, Finder, Builder);
4190  return false;
4191 }
4192 
4193 /// Matches an \c OverloadExpr if any of the declarations in the set of
4194 /// overloads matches the given matcher.
4195 ///
4196 /// Given
4197 /// \code
4198 /// template <typename T> void foo(T);
4199 /// template <typename T> void bar(T);
4200 /// template <typename T> void baz(T t) {
4201 /// foo(t);
4202 /// bar(t);
4203 /// }
4204 /// \endcode
4205 /// unresolvedLookupExpr(hasAnyDeclaration(
4206 /// functionTemplateDecl(hasName("foo"))))
4207 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4208 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4209  InnerMatcher) {
4210  return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4211  Node.decls_end(), Finder,
4212  Builder) != Node.decls_end();
4213 }
4214 
4215 /// Matches the Decl of a DeclStmt which has a single declaration.
4216 ///
4217 /// Given
4218 /// \code
4219 /// int a, b;
4220 /// int c;
4221 /// \endcode
4222 /// declStmt(hasSingleDecl(anything()))
4223 /// matches 'int c;' but not 'int a, b;'.
4224 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4225  if (Node.isSingleDecl()) {
4226  const Decl *FoundDecl = Node.getSingleDecl();
4227  return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4228  }
4229  return false;
4230 }
4231 
4232 /// Matches a variable declaration that has an initializer expression
4233 /// that matches the given matcher.
4234 ///
4235 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4236 /// \code
4237 /// bool y() { return true; }
4238 /// bool x = y();
4239 /// \endcode
4241  VarDecl, hasInitializer, internal::Matcher<Expr>,
4242  InnerMatcher) {
4243  const Expr *Initializer = Node.getAnyInitializer();
4244  return (Initializer != nullptr &&
4245  InnerMatcher.matches(*Initializer, Finder, Builder));
4246 }
4247 
4248 /// Matches a variable serving as the implicit variable for a lambda init-
4249 /// capture.
4250 ///
4251 /// Example matches x (matcher = varDecl(isInitCapture()))
4252 /// \code
4253 /// auto f = [x=3]() { return x; };
4254 /// \endcode
4255 AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4256 
4257 /// Matches each lambda capture in a lambda expression.
4258 ///
4259 /// Given
4260 /// \code
4261 /// int main() {
4262 /// int x, y;
4263 /// float z;
4264 /// auto f = [=]() { return x + y + z; };
4265 /// }
4266 /// \endcode
4267 /// lambdaExpr(forEachLambdaCapture(
4268 /// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4269 /// will trigger two matches, binding for 'x' and 'y' respectively.
4270 AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4271  internal::Matcher<LambdaCapture>, InnerMatcher) {
4272  BoundNodesTreeBuilder Result;
4273  bool Matched = false;
4274  for (const auto &Capture : Node.captures()) {
4275  if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4276  continue;
4277  BoundNodesTreeBuilder CaptureBuilder(*Builder);
4278  if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4279  Matched = true;
4280  Result.addMatch(CaptureBuilder);
4281  }
4282  }
4283  *Builder = std::move(Result);
4284  return Matched;
4285 }
4286 
4287 /// \brief Matches a static variable with local scope.
4288 ///
4289 /// Example matches y (matcher = varDecl(isStaticLocal()))
4290 /// \code
4291 /// void f() {
4292 /// int x;
4293 /// static int y;
4294 /// }
4295 /// static int z;
4296 /// \endcode
4297 AST_MATCHER(VarDecl, isStaticLocal) {
4298  return Node.isStaticLocal();
4299 }
4300 
4301 /// Matches a variable declaration that has function scope and is a
4302 /// non-static local variable.
4303 ///
4304 /// Example matches x (matcher = varDecl(hasLocalStorage())
4305 /// \code
4306 /// void f() {
4307 /// int x;
4308 /// static int y;
4309 /// }
4310 /// int z;
4311 /// \endcode
4312 AST_MATCHER(VarDecl, hasLocalStorage) {
4313  return Node.hasLocalStorage();
4314 }
4315 
4316 /// Matches a variable declaration that does not have local storage.
4317 ///
4318 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4319 /// \code
4320 /// void f() {
4321 /// int x;
4322 /// static int y;
4323 /// }
4324 /// int z;
4325 /// \endcode
4326 AST_MATCHER(VarDecl, hasGlobalStorage) {
4327  return Node.hasGlobalStorage();
4328 }
4329 
4330 /// Matches a variable declaration that has automatic storage duration.
4331 ///
4332 /// Example matches x, but not y, z, or a.
4333 /// (matcher = varDecl(hasAutomaticStorageDuration())
4334 /// \code
4335 /// void f() {
4336 /// int x;
4337 /// static int y;
4338 /// thread_local int z;
4339 /// }
4340 /// int a;
4341 /// \endcode
4342 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4343  return Node.getStorageDuration() == SD_Automatic;
4344 }
4345 
4346 /// Matches a variable declaration that has static storage duration.
4347 /// It includes the variable declared at namespace scope and those declared
4348 /// with "static" and "extern" storage class specifiers.
4349 ///
4350 /// \code
4351 /// void f() {
4352 /// int x;
4353 /// static int y;
4354 /// thread_local int z;
4355 /// }
4356 /// int a;
4357 /// static int b;
4358 /// extern int c;
4359 /// varDecl(hasStaticStorageDuration())
4360 /// matches the function declaration y, a, b and c.
4361 /// \endcode
4362 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4363  return Node.getStorageDuration() == SD_Static;
4364 }
4365 
4366 /// Matches a variable declaration that has thread storage duration.
4367 ///
4368 /// Example matches z, but not x, z, or a.
4369 /// (matcher = varDecl(hasThreadStorageDuration())
4370 /// \code
4371 /// void f() {
4372 /// int x;
4373 /// static int y;
4374 /// thread_local int z;
4375 /// }
4376 /// int a;
4377 /// \endcode
4378 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4379  return Node.getStorageDuration() == SD_Thread;
4380 }
4381 
4382 /// Matches a variable declaration that is an exception variable from
4383 /// a C++ catch block, or an Objective-C \@catch statement.
4384 ///
4385 /// Example matches x (matcher = varDecl(isExceptionVariable())
4386 /// \code
4387 /// void f(int y) {
4388 /// try {
4389 /// } catch (int x) {
4390 /// }
4391 /// }
4392 /// \endcode
4393 AST_MATCHER(VarDecl, isExceptionVariable) {
4394  return Node.isExceptionVariable();
4395 }
4396 
4397 /// Checks that a call expression or a constructor call expression has
4398 /// a specific number of arguments (including absent default arguments).
4399 ///
4400 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4401 /// \code
4402 /// void f(int x, int y);
4403 /// f(0, 0);
4404 /// \endcode
4409  unsigned, N) {
4410  unsigned NumArgs = Node.getNumArgs();
4411  if (!Finder->isTraversalIgnoringImplicitNodes())
4412  return NumArgs == N;
4413  while (NumArgs) {
4414  if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4415  break;
4416  --NumArgs;
4417  }
4418  return NumArgs == N;
4419 }
4420 
4421 /// Matches the n'th argument of a call expression or a constructor
4422 /// call expression.
4423 ///
4424 /// Example matches y in x(y)
4425 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
4426 /// \code
4427 /// void x(int) { int y; x(y); }
4428 /// \endcode
4433  unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4434  if (N >= Node.getNumArgs())
4435  return false;
4436  const Expr *Arg = Node.getArg(N);
4437  if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4438  return false;
4439  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4440 }
4441 
4442 /// Matches the n'th item of an initializer list expression.
4443 ///
4444 /// Example matches y.
4445 /// (matcher = initListExpr(hasInit(0, expr())))
4446 /// \code
4447 /// int x{y}.
4448 /// \endcode
4449 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
4450  ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
4451  return N < Node.getNumInits() &&
4452  InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4453 }
4454 
4455 /// Matches declaration statements that contain a specific number of
4456 /// declarations.
4457 ///
4458 /// Example: Given
4459 /// \code
4460 /// int a, b;
4461 /// int c;
4462 /// int d = 2, e;
4463 /// \endcode
4464 /// declCountIs(2)
4465 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4466 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4467  return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4468 }
4469 
4470 /// Matches the n'th declaration of a declaration statement.
4471 ///
4472 /// Note that this does not work for global declarations because the AST
4473 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4474 /// DeclStmt's.
4475 /// Example: Given non-global declarations
4476 /// \code
4477 /// int a, b = 0;
4478 /// int c;
4479 /// int d = 2, e;
4480 /// \endcode
4481 /// declStmt(containsDeclaration(
4482 /// 0, varDecl(hasInitializer(anything()))))
4483 /// matches only 'int d = 2, e;', and
4484 /// declStmt(containsDeclaration(1, varDecl()))
4485 /// \code
4486 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
4487 /// but 'int c;' is not matched.
4488 /// \endcode
4489 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4490  internal::Matcher<Decl>, InnerMatcher) {
4491  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4492  if (N >= NumDecls)
4493  return false;
4494  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4495  std::advance(Iterator, N);
4496  return InnerMatcher.matches(**Iterator, Finder, Builder);
4497 }
4498 
4499 /// Matches a C++ catch statement that has a catch-all handler.
4500 ///
4501 /// Given
4502 /// \code
4503 /// try {
4504 /// // ...
4505 /// } catch (int) {
4506 /// // ...
4507 /// } catch (...) {
4508 /// // ...
4509 /// }
4510 /// \endcode
4511 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4513  return Node.getExceptionDecl() == nullptr;
4514 }
4515 
4516 /// Matches a constructor initializer.
4517 ///
4518 /// Given
4519 /// \code
4520 /// struct Foo {
4521 /// Foo() : foo_(1) { }
4522 /// int foo_;
4523 /// };
4524 /// \endcode
4525 /// cxxRecordDecl(has(cxxConstructorDecl(
4526 /// hasAnyConstructorInitializer(anything())
4527 /// )))
4528 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4529 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4530  internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4531  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4532  Node.init_end(), Finder, Builder);
4533  if (MatchIt == Node.init_end())
4534  return false;
4535  return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4536 }
4537 
4538 /// Matches the field declaration of a constructor initializer.
4539 ///
4540 /// Given
4541 /// \code
4542 /// struct Foo {
4543 /// Foo() : foo_(1) { }
4544 /// int foo_;
4545 /// };
4546 /// \endcode
4547 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4548 /// forField(hasName("foo_"))))))
4549 /// matches Foo
4550 /// with forField matching foo_
4552  internal::Matcher<FieldDecl>, InnerMatcher) {
4553  const FieldDecl *NodeAsDecl = Node.getAnyMember();
4554  return (NodeAsDecl != nullptr &&
4555  InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4556 }
4557 
4558 /// Matches the initializer expression of a constructor initializer.
4559 ///
4560 /// Given
4561 /// \code
4562 /// struct Foo {
4563 /// Foo() : foo_(1) { }
4564 /// int foo_;
4565 /// };
4566 /// \endcode
4567 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4568 /// withInitializer(integerLiteral(equals(1)))))))
4569 /// matches Foo
4570 /// with withInitializer matching (1)
4572  internal::Matcher<Expr>, InnerMatcher) {
4573  const Expr* NodeAsExpr = Node.getInit();
4574  return (NodeAsExpr != nullptr &&
4575  InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4576 }
4577 
4578 /// Matches a constructor initializer if it is explicitly written in
4579 /// code (as opposed to implicitly added by the compiler).
4580 ///
4581 /// Given
4582 /// \code
4583 /// struct Foo {
4584 /// Foo() { }
4585 /// Foo(int) : foo_("A") { }
4586 /// string foo_;
4587 /// };
4588 /// \endcode
4589 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4590 /// will match Foo(int), but not Foo()
4592  return Node.isWritten();
4593 }
4594 
4595 /// Matches a constructor initializer if it is initializing a base, as
4596 /// opposed to a member.
4597 ///
4598 /// Given
4599 /// \code
4600 /// struct B {};
4601 /// struct D : B {
4602 /// int I;
4603 /// D(int i) : I(i) {}
4604 /// };
4605 /// struct E : B {
4606 /// E() : B() {}
4607 /// };
4608 /// \endcode
4609 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4610 /// will match E(), but not match D(int).
4611 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4612  return Node.isBaseInitializer();
4613 }
4614 
4615 /// Matches a constructor initializer if it is initializing a member, as
4616 /// opposed to a base.
4617 ///
4618 /// Given
4619 /// \code
4620 /// struct B {};
4621 /// struct D : B {
4622 /// int I;
4623 /// D(int i) : I(i) {}
4624 /// };
4625 /// struct E : B {
4626 /// E() : B() {}
4627 /// };
4628 /// \endcode
4629 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4630 /// will match D(int), but not match E().
4631 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4632  return Node.isMemberInitializer();
4633 }
4634 
4635 /// Matches any argument of a call expression or a constructor call
4636 /// expression, or an ObjC-message-send expression.
4637 ///
4638 /// Given
4639 /// \code
4640 /// void x(int, int, int) { int y; x(1, y, 42); }
4641 /// \endcode
4642 /// callExpr(hasAnyArgument(declRefExpr()))
4643 /// matches x(1, y, 42)
4644 /// with hasAnyArgument(...)
4645 /// matching y
4646 ///
4647 /// For ObjectiveC, given
4648 /// \code
4649 /// @interface I - (void) f:(int) y; @end
4650 /// void foo(I *i) { [i f:12]; }
4651 /// \endcode
4652 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4653 /// matches [i f:12]
4658  internal::Matcher<Expr>, InnerMatcher) {
4659  for (const Expr *Arg : Node.arguments()) {
4660  if (Finder->isTraversalIgnoringImplicitNodes() &&
4661  isa<CXXDefaultArgExpr>(Arg))
4662  break;
4663  BoundNodesTreeBuilder Result(*Builder);
4664  if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4665  *Builder = std::move(Result);
4666  return true;
4667  }
4668  }
4669  return false;
4670 }
4671 
4672 /// Matches lambda captures.
4673 ///
4674 /// Given
4675 /// \code
4676 /// int main() {
4677 /// int x;
4678 /// auto f = [x](){};
4679 /// auto g = [x = 1](){};
4680 /// }
4681 /// \endcode
4682 /// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4683 /// `lambdaCapture()` matches `x` and `x=1`.
4684 extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4685 
4686 /// Matches any capture in a lambda expression.
4687 ///
4688 /// Given
4689 /// \code
4690 /// void foo() {
4691 /// int t = 5;
4692 /// auto f = [=](){ return t; };
4693 /// }
4694 /// \endcode
4695 /// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4696 /// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4697 /// both match `[=](){ return t; }`.
4698 AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4699  InnerMatcher) {
4700  for (const LambdaCapture &Capture : Node.captures()) {
4701  clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4702  if (InnerMatcher.matches(Capture, Finder, &Result)) {
4703  *Builder = std::move(Result);
4704  return true;
4705  }
4706  }
4707  return false;
4708 }
4709 
4710 /// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4711 /// `VarDecl` can be a separate variable that is captured by value or
4712 /// reference, or a synthesized variable if the capture has an initializer.
4713 ///
4714 /// Given
4715 /// \code
4716 /// void foo() {
4717 /// int x;
4718 /// auto f = [x](){};
4719 /// auto g = [x = 1](){};
4720 /// }
4721 /// \endcode
4722 /// In the matcher
4723 /// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4724 /// capturesVar(hasName("x")) matches `x` and `x = 1`.
4725 AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
4726  InnerMatcher) {
4727  auto *capturedVar = Node.getCapturedVar();
4728  return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
4729 }
4730 
4731 /// Matches a `LambdaCapture` that refers to 'this'.
4732 ///
4733 /// Given
4734 /// \code
4735 /// class C {
4736 /// int cc;
4737 /// int f() {
4738 /// auto l = [this]() { return cc; };
4739 /// return l();
4740 /// }
4741 /// };
4742 /// \endcode
4743 /// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
4744 /// matches `[this]() { return cc; }`.
4745 AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
4746 
4747 /// Matches a constructor call expression which uses list initialization.
4748 AST_MATCHER(CXXConstructExpr, isListInitialization) {
4749  return Node.isListInitialization();
4750 }
4751 
4752 /// Matches a constructor call expression which requires
4753 /// zero initialization.
4754 ///
4755 /// Given
4756 /// \code
4757 /// void foo() {
4758 /// struct point { double x; double y; };
4759 /// point pt[2] = { { 1.0, 2.0 } };
4760 /// }
4761 /// \endcode
4762 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
4763 /// will match the implicit array filler for pt[1].
4764 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
4765  return Node.requiresZeroInitialization();
4766 }
4767 
4768 /// Matches the n'th parameter of a function or an ObjC method
4769 /// declaration or a block.
4770 ///
4771 /// Given
4772 /// \code
4773 /// class X { void f(int x) {} };
4774 /// \endcode
4775 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
4776 /// matches f(int x) {}
4777 /// with hasParameter(...)
4778 /// matching int x
4779 ///
4780 /// For ObjectiveC, given
4781 /// \code
4782 /// @interface I - (void) f:(int) y; @end
4783 /// \endcode
4784 //
4785 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
4786 /// matches the declaration of method f with hasParameter
4787 /// matching y.
4791  BlockDecl),
4792  unsigned, N, internal::Matcher<ParmVarDecl>,
4793  InnerMatcher) {
4794  return (N < Node.parameters().size()
4795  && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4796 }
4797 
4798 /// Matches all arguments and their respective ParmVarDecl.
4799 ///
4800 /// Given
4801 /// \code
4802 /// void f(int i);
4803 /// int y;
4804 /// f(y);
4805 /// \endcode
4806 /// callExpr(
4807 /// forEachArgumentWithParam(
4808 /// declRefExpr(to(varDecl(hasName("y")))),
4809 /// parmVarDecl(hasType(isInteger()))
4810 /// ))
4811 /// matches f(y);
4812 /// with declRefExpr(...)
4813 /// matching int y
4814 /// and parmVarDecl(...)
4815 /// matching int i
4816 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4819  internal::Matcher<Expr>, ArgMatcher,
4820  internal::Matcher<ParmVarDecl>, ParamMatcher) {
4821  BoundNodesTreeBuilder Result;
4822  // The first argument of an overloaded member operator is the implicit object
4823  // argument of the method which should not be matched against a parameter, so
4824  // we skip over it here.
4825  BoundNodesTreeBuilder Matches;
4826  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4827  .matches(Node, Finder, &Matches)
4828  ? 1
4829  : 0;
4830  int ParamIndex = 0;
4831  bool Matched = false;
4832  for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
4833  BoundNodesTreeBuilder ArgMatches(*Builder);
4834  if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4835  Finder, &ArgMatches)) {
4836  BoundNodesTreeBuilder ParamMatches(ArgMatches);
4838  hasParameter(ParamIndex, ParamMatcher)))),
4839  callExpr(callee(functionDecl(
4840  hasParameter(ParamIndex, ParamMatcher))))))
4841  .matches(Node, Finder, &ParamMatches)) {
4842  Result.addMatch(ParamMatches);
4843  Matched = true;
4844  }
4845  }
4846  ++ParamIndex;
4847  }
4848  *Builder = std::move(Result);
4849  return Matched;
4850 }
4851 
4852 /// Matches all arguments and their respective types for a \c CallExpr or
4853 /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
4854 /// it works on calls through function pointers as well.
4855 ///
4856 /// The difference is, that function pointers do not provide access to a
4857 /// \c ParmVarDecl, but only the \c QualType for each argument.
4858 ///
4859 /// Given
4860 /// \code
4861 /// void f(int i);
4862 /// int y;
4863 /// f(y);
4864 /// void (*f_ptr)(int) = f;
4865 /// f_ptr(y);
4866 /// \endcode
4867 /// callExpr(
4868 /// forEachArgumentWithParamType(
4869 /// declRefExpr(to(varDecl(hasName("y")))),
4870 /// qualType(isInteger()).bind("type)
4871 /// ))
4872 /// matches f(y) and f_ptr(y)
4873 /// with declRefExpr(...)
4874 /// matching int y
4875 /// and qualType(...)
4876 /// matching int
4877 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
4880  internal::Matcher<Expr>, ArgMatcher,
4881  internal::Matcher<QualType>, ParamMatcher) {
4882  BoundNodesTreeBuilder Result;
4883  // The first argument of an overloaded member operator is the implicit object
4884  // argument of the method which should not be matched against a parameter, so
4885  // we skip over it here.
4886  BoundNodesTreeBuilder Matches;
4887  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4888  .matches(Node, Finder, &Matches)
4889  ? 1
4890  : 0;
4891 
4892  const FunctionProtoType *FProto = nullptr;
4893 
4894  if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4895  if (const auto *Value =
4896  dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4897  QualType QT = Value->getType().getCanonicalType();
4898 
4899  // This does not necessarily lead to a `FunctionProtoType`,
4900  // e.g. K&R functions do not have a function prototype.
4901  if (QT->isFunctionPointerType())
4902  FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4903 
4904  if (QT->isMemberFunctionPointerType()) {
4905  const auto *MP = QT->getAs<MemberPointerType>();
4906  assert(MP && "Must be member-pointer if its a memberfunctionpointer");
4907  FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
4908  assert(FProto &&
4909  "The call must have happened through a member function "
4910  "pointer");
4911  }
4912  }
4913  }
4914 
4915  unsigned ParamIndex = 0;
4916  bool Matched = false;
4917  unsigned NumArgs = Node.getNumArgs();
4918  if (FProto && FProto->isVariadic())
4919  NumArgs = std::min(NumArgs, FProto->getNumParams());
4920 
4921  for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
4922  BoundNodesTreeBuilder ArgMatches(*Builder);
4923  if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
4924  &ArgMatches)) {
4925  BoundNodesTreeBuilder ParamMatches(ArgMatches);
4926 
4927  // This test is cheaper compared to the big matcher in the next if.
4928  // Therefore, please keep this order.
4929  if (FProto && FProto->getNumParams() > ParamIndex) {
4930  QualType ParamType = FProto->getParamType(ParamIndex);
4931  if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
4932  Result.addMatch(ParamMatches);
4933  Matched = true;
4934  continue;
4935  }
4936  }
4938  hasParameter(ParamIndex, hasType(ParamMatcher))))),
4939  callExpr(callee(functionDecl(
4940  hasParameter(ParamIndex, hasType(ParamMatcher)))))))
4941  .matches(Node, Finder, &ParamMatches)) {
4942  Result.addMatch(ParamMatches);
4943  Matched = true;
4944  continue;
4945  }
4946  }
4947  }
4948  *Builder = std::move(Result);
4949  return Matched;
4950 }
4951 
4952 /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
4953 /// list. The parameter list could be that of either a block, function, or
4954 /// objc-method.
4955 ///
4956 ///
4957 /// Given
4958 ///
4959 /// \code
4960 /// void f(int a, int b, int c) {
4961 /// }
4962 /// \endcode
4963 ///
4964 /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
4965 ///
4966 /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
4967 AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
4968  const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
4969 
4970  if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
4971  return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4972  if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
4973  return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4974  if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
4975  return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4976 
4977  return false;
4978 }
4979 
4980 /// Matches any parameter of a function or an ObjC method declaration or a
4981 /// block.
4982 ///
4983 /// Does not match the 'this' parameter of a method.
4984 ///
4985 /// Given
4986 /// \code
4987 /// class X { void f(int x, int y, int z) {} };
4988 /// \endcode
4989 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
4990 /// matches f(int x, int y, int z) {}
4991 /// with hasAnyParameter(...)
4992 /// matching int y
4993 ///
4994 /// For ObjectiveC, given
4995 /// \code
4996 /// @interface I - (void) f:(int) y; @end
4997 /// \endcode
4998 //
4999 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5000 /// matches the declaration of method f with hasParameter
5001 /// matching y.
5002 ///
5003 /// For blocks, given
5004 /// \code
5005 /// b = ^(int y) { printf("%d", y) };
5006 /// \endcode
5007 ///
5008 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
5009 /// matches the declaration of the block b with hasParameter
5010 /// matching y.
5014  BlockDecl),
5015  internal::Matcher<ParmVarDecl>,
5016  InnerMatcher) {
5017  return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5018  Node.param_end(), Finder,
5019  Builder) != Node.param_end();
5020 }
5021 
5022 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5023 /// specific parameter count.
5024 ///
5025 /// Given
5026 /// \code
5027 /// void f(int i) {}
5028 /// void g(int i, int j) {}
5029 /// void h(int i, int j);
5030 /// void j(int i);
5031 /// void k(int x, int y, int z, ...);
5032 /// \endcode
5033 /// functionDecl(parameterCountIs(2))
5034 /// matches \c g and \c h
5035 /// functionProtoType(parameterCountIs(2))
5036 /// matches \c g and \c h
5037 /// functionProtoType(parameterCountIs(3))
5038 /// matches \c k
5039 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
5042  unsigned, N) {
5043  return Node.getNumParams() == N;
5044 }
5045 
5046 /// Matches classTemplateSpecialization, templateSpecializationType and
5047 /// functionDecl nodes where the template argument matches the inner matcher.
5048 /// This matcher may produce multiple matches.
5049 ///
5050 /// Given
5051 /// \code
5052 /// template <typename T, unsigned N, unsigned M>
5053 /// struct Matrix {};
5054 ///
5055 /// constexpr unsigned R = 2;
5056 /// Matrix<int, R * 2, R * 4> M;
5057 ///
5058 /// template <typename T, typename U>
5059 /// void f(T&& t, U&& u) {}
5060 ///
5061 /// bool B = false;
5062 /// f(R, B);
5063 /// \endcode
5064 /// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5065 /// matches twice, with expr() matching 'R * 2' and 'R * 4'
5066 /// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5067 /// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5068 /// and 'bool'
5070  forEachTemplateArgument,
5073  clang::ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
5074  ArrayRef<TemplateArgument> TemplateArgs =
5075  clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5076  clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5077  bool Matched = false;
5078  for (const auto &Arg : TemplateArgs) {
5079  clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5080  if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5081  Matched = true;
5082  Result.addMatch(ArgBuilder);
5083  }
5084  }
5085  *Builder = std::move(Result);
5086  return Matched;
5087 }
5088 
5089 /// Matches \c FunctionDecls that have a noreturn attribute.
5090 ///
5091 /// Given
5092 /// \code
5093 /// void nope();
5094 /// [[noreturn]] void a();
5095 /// __attribute__((noreturn)) void b();
5096 /// struct c { [[noreturn]] c(); };
5097 /// \endcode
5098 /// functionDecl(isNoReturn())
5099 /// matches all of those except
5100 /// \code
5101 /// void nope();
5102 /// \endcode
5103 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5104 
5105 /// Matches the return type of a function declaration.
5106 ///
5107 /// Given:
5108 /// \code
5109 /// class X { int f() { return 1; } };
5110 /// \endcode
5111 /// cxxMethodDecl(returns(asString("int")))
5112 /// matches int f() { return 1; }
5114  internal::Matcher<QualType>, InnerMatcher) {
5115  return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5116 }
5117 
5118 /// Matches extern "C" function or variable declarations.
5119 ///
5120 /// Given:
5121 /// \code
5122 /// extern "C" void f() {}
5123 /// extern "C" { void g() {} }
5124 /// void h() {}
5125 /// extern "C" int x = 1;
5126 /// extern "C" int y = 2;
5127 /// int z = 3;
5128 /// \endcode
5129 /// functionDecl(isExternC())
5130 /// matches the declaration of f and g, but not the declaration of h.
5131 /// varDecl(isExternC())
5132 /// matches the declaration of x and y, but not the declaration of z.
5134  VarDecl)) {
5135  return Node.isExternC();
5136 }
5137 
5138 /// Matches variable/function declarations that have "static" storage
5139 /// class specifier ("static" keyword) written in the source.
5140 ///
5141 /// Given:
5142 /// \code
5143 /// static void f() {}
5144 /// static int i = 0;
5145 /// extern int j;
5146 /// int k;
5147 /// \endcode
5148 /// functionDecl(isStaticStorageClass())
5149 /// matches the function declaration f.
5150 /// varDecl(isStaticStorageClass())
5151 /// matches the variable declaration i.
5152 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5154  VarDecl)) {
5155  return Node.getStorageClass() == SC_Static;
5156 }
5157 
5158 /// Matches deleted function declarations.
5159 ///
5160 /// Given:
5161 /// \code
5162 /// void Func();
5163 /// void DeletedFunc() = delete;
5164 /// \endcode
5165 /// functionDecl(isDeleted())
5166 /// matches the declaration of DeletedFunc, but not Func.
5168  return Node.isDeleted();
5169 }
5170 
5171 /// Matches defaulted function declarations.
5172 ///
5173 /// Given:
5174 /// \code
5175 /// class A { ~A(); };
5176 /// class B { ~B() = default; };
5177 /// \endcode
5178 /// functionDecl(isDefaulted())
5179 /// matches the declaration of ~B, but not ~A.
5180 AST_MATCHER(FunctionDecl, isDefaulted) {
5181  return Node.isDefaulted();
5182 }
5183 
5184 /// Matches weak function declarations.
5185 ///
5186 /// Given:
5187 /// \code
5188 /// void foo() __attribute__((__weakref__("__foo")));
5189 /// void bar();
5190 /// \endcode
5191 /// functionDecl(isWeak())
5192 /// matches the weak declaration "foo", but not "bar".
5193 AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5194 
5195 /// Matches functions that have a dynamic exception specification.
5196 ///
5197 /// Given:
5198 /// \code
5199 /// void f();
5200 /// void g() noexcept;
5201 /// void h() noexcept(true);
5202 /// void i() noexcept(false);
5203 /// void j() throw();
5204 /// void k() throw(int);
5205 /// void l() throw(...);
5206 /// \endcode
5207 /// functionDecl(hasDynamicExceptionSpec()) and
5208 /// functionProtoType(hasDynamicExceptionSpec())
5209 /// match the declarations of j, k, and l, but not f, g, h, or i.
5210 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5212  FunctionProtoType)) {
5213  if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5214  return FnTy->hasDynamicExceptionSpec();
5215  return false;
5216 }
5217 
5218 /// Matches functions that have a non-throwing exception specification.
5219 ///
5220 /// Given:
5221 /// \code
5222 /// void f();
5223 /// void g() noexcept;
5224 /// void h() throw();
5225 /// void i() throw(int);
5226 /// void j() noexcept(false);
5227 /// \endcode
5228 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5229 /// match the declarations of g, and h, but not f, i or j.
5232  FunctionProtoType)) {
5233  const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5234 
5235  // If the function does not have a prototype, then it is assumed to be a
5236  // throwing function (as it would if the function did not have any exception
5237  // specification).
5238  if (!FnTy)
5239  return false;
5240 
5241  // Assume the best for any unresolved exception specification.
5243  return true;
5244 
5245  return FnTy->isNothrow();
5246 }
5247 
5248 /// Matches consteval function declarations and if consteval/if ! consteval
5249 /// statements.
5250 ///
5251 /// Given:
5252 /// \code
5253 /// consteval int a();
5254 /// void b() { if consteval {} }
5255 /// void c() { if ! consteval {} }
5256 /// void d() { if ! consteval {} else {} }
5257 /// \endcode
5258 /// functionDecl(isConsteval())
5259 /// matches the declaration of "int a()".
5260 /// ifStmt(isConsteval())
5261 /// matches the if statement in "void b()", "void c()", "void d()".
5264  return Node.isConsteval();
5265 }
5266 
5267 /// Matches constexpr variable and function declarations,
5268 /// and if constexpr.
5269 ///
5270 /// Given:
5271 /// \code
5272 /// constexpr int foo = 42;
5273 /// constexpr int bar();
5274 /// void baz() { if constexpr(1 > 0) {} }
5275 /// \endcode
5276 /// varDecl(isConstexpr())
5277 /// matches the declaration of foo.
5278 /// functionDecl(isConstexpr())
5279 /// matches the declaration of bar.
5280 /// ifStmt(isConstexpr())
5281 /// matches the if statement in baz.
5284  FunctionDecl,
5285  IfStmt)) {
5286  return Node.isConstexpr();
5287 }
5288 
5289 /// Matches constinit variable declarations.
5290 ///
5291 /// Given:
5292 /// \code
5293 /// constinit int foo = 42;
5294 /// constinit const char* bar = "bar";
5295 /// int baz = 42;
5296 /// [[clang::require_constant_initialization]] int xyz = 42;
5297 /// \endcode
5298 /// varDecl(isConstinit())
5299 /// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5300 AST_MATCHER(VarDecl, isConstinit) {
5301  if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5302  return CIA->isConstinit();
5303  return false;
5304 }
5305 
5306 /// Matches selection statements with initializer.
5307 ///
5308 /// Given:
5309 /// \code
5310 /// void foo() {
5311 /// if (int i = foobar(); i > 0) {}
5312 /// switch (int i = foobar(); i) {}
5313 /// for (auto& a = get_range(); auto& x : a) {}
5314 /// }
5315 /// void bar() {
5316 /// if (foobar() > 0) {}
5317 /// switch (foobar()) {}
5318 /// for (auto& x : get_range()) {}
5319 /// }
5320 /// \endcode
5321 /// ifStmt(hasInitStatement(anything()))
5322 /// matches the if statement in foo but not in bar.
5323 /// switchStmt(hasInitStatement(anything()))
5324 /// matches the switch statement in foo but not in bar.
5325 /// cxxForRangeStmt(hasInitStatement(anything()))
5326 /// matches the range for statement in foo but not in bar.
5327 AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
5329  CXXForRangeStmt),
5330  internal::Matcher<Stmt>, InnerMatcher) {
5331  const Stmt *Init = Node.getInit();
5332  return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5333 }
5334 
5335 /// Matches the condition expression of an if statement, for loop,
5336 /// switch statement or conditional operator.
5337 ///
5338 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5339 /// \code
5340 /// if (true) {}
5341 /// \endcode
5343  hasCondition,
5346  internal::Matcher<Expr>, InnerMatcher) {
5347  const Expr *const Condition = Node.getCond();
5348  return (Condition != nullptr &&
5349  InnerMatcher.matches(*Condition, Finder, Builder));
5350 }
5351 
5352 /// Matches the then-statement of an if statement.
5353 ///
5354 /// Examples matches the if statement
5355 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5356 /// \code
5357 /// if (false) true; else false;
5358 /// \endcode
5359 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5360  const Stmt *const Then = Node.getThen();
5361  return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5362 }
5363 
5364 /// Matches the else-statement of an if statement.
5365 ///
5366 /// Examples matches the if statement
5367 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5368 /// \code
5369 /// if (false) false; else true;
5370 /// \endcode
5371 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5372  const Stmt *const Else = Node.getElse();
5373  return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5374 }
5375 
5376 /// Matches if a node equals a previously bound node.
5377 ///
5378 /// Matches a node if it equals the node previously bound to \p ID.
5379 ///
5380 /// Given
5381 /// \code
5382 /// class X { int a; int b; };
5383 /// \endcode
5384 /// cxxRecordDecl(
5385 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5386 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5387 /// matches the class \c X, as \c a and \c b have the same type.
5388 ///
5389 /// Note that when multiple matches are involved via \c forEach* matchers,
5390 /// \c equalsBoundNodes acts as a filter.
5391 /// For example:
5392 /// compoundStmt(
5393 /// forEachDescendant(varDecl().bind("d")),
5394 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5395 /// will trigger a match for each combination of variable declaration
5396 /// and reference to that variable declaration within a compound statement.
5399  QualType),
5400  std::string, ID) {
5401  // FIXME: Figure out whether it makes sense to allow this
5402  // on any other node types.
5403  // For *Loc it probably does not make sense, as those seem
5404  // unique. For NestedNameSepcifier it might make sense, as
5405  // those also have pointer identity, but I'm not sure whether
5406  // they're ever reused.
5407  internal::NotEqualsBoundNodePredicate Predicate;
5408  Predicate.ID = ID;
5409  Predicate.Node = DynTypedNode::create(Node);
5410  return Builder->removeBindings(Predicate);
5411 }
5412 
5413 /// Matches the condition variable statement in an if statement.
5414 ///
5415 /// Given
5416 /// \code
5417 /// if (A* a = GetAPointer()) {}
5418 /// \endcode
5419 /// hasConditionVariableStatement(...)
5420 /// matches 'A* a = GetAPointer()'.
5421 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5422  internal::Matcher<DeclStmt>, InnerMatcher) {
5423  const DeclStmt* const DeclarationStatement =
5424  Node.getConditionVariableDeclStmt();
5425  return DeclarationStatement != nullptr &&
5426  InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5427 }
5428 
5429 /// Matches the index expression of an array subscript expression.
5430 ///
5431 /// Given
5432 /// \code
5433 /// int i[5];
5434 /// void f() { i[1] = 42; }
5435 /// \endcode
5436 /// arraySubscriptExpression(hasIndex(integerLiteral()))
5437 /// matches \c i[1] with the \c integerLiteral() matching \c 1
5439  internal::Matcher<Expr>, InnerMatcher) {
5440  if (const Expr* Expression = Node.getIdx())
5441  return InnerMatcher.matches(*Expression, Finder, Builder);
5442  return false;
5443 }
5444 
5445 /// Matches the base expression of an array subscript expression.
5446 ///
5447 /// Given
5448 /// \code
5449 /// int i[5];
5450 /// void f() { i[1] = 42; }
5451 /// \endcode
5452 /// arraySubscriptExpression(hasBase(implicitCastExpr(
5453 /// hasSourceExpression(declRefExpr()))))
5454 /// matches \c i[1] with the \c declRefExpr() matching \c i
5456  internal::Matcher<Expr>, InnerMatcher) {
5457  if (const Expr* Expression = Node.getBase())
5458  return InnerMatcher.matches(*Expression, Finder, Builder);
5459  return false;
5460 }
5461 
5462 /// Matches a 'for', 'while', 'do while' statement or a function
5463 /// definition that has a given body. Note that in case of functions
5464 /// this matcher only matches the definition itself and not the other
5465 /// declarations of the same function.
5466 ///
5467 /// Given
5468 /// \code
5469 /// for (;;) {}
5470 /// \endcode
5471 /// hasBody(compoundStmt())
5472 /// matches 'for (;;) {}'
5473 /// with compoundStmt()
5474 /// matching '{}'
5475 ///
5476 /// Given
5477 /// \code
5478 /// void f();
5479 /// void f() {}
5480 /// \endcode
5481 /// hasBody(functionDecl())
5482 /// matches 'void f() {}'
5483 /// with compoundStmt()
5484 /// matching '{}'
5485 /// but does not match 'void f();'
5486 
5489  WhileStmt,
5491  FunctionDecl),
5492  internal::Matcher<Stmt>, InnerMatcher) {
5493  if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5494  return false;
5495  const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5496  return (Statement != nullptr &&
5497  InnerMatcher.matches(*Statement, Finder, Builder));
5498 }
5499 
5500 /// Matches a function declaration that has a given body present in the AST.
5501 /// Note that this matcher matches all the declarations of a function whose
5502 /// body is present in the AST.
5503 ///
5504 /// Given
5505 /// \code
5506 /// void f();
5507 /// void f() {}
5508 /// void g();
5509 /// \endcode
5510 /// functionDecl(hasAnyBody(compoundStmt()))
5511 /// matches both 'void f();'
5512 /// and 'void f() {}'
5513 /// with compoundStmt()
5514 /// matching '{}'
5515 /// but does not match 'void g();'
5517  internal::Matcher<Stmt>, InnerMatcher) {
5518  const Stmt *const Statement = Node.getBody();
5519  return (Statement != nullptr &&
5520  InnerMatcher.matches(*Statement, Finder, Builder));
5521 }
5522 
5523 
5524 /// Matches compound statements where at least one substatement matches
5525 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5526 ///
5527 /// Given
5528 /// \code
5529 /// { {}; 1+2; }
5530 /// \endcode
5531 /// hasAnySubstatement(compoundStmt())
5532 /// matches '{ {}; 1+2; }'
5533 /// with compoundStmt()
5534 /// matching '{}'
5535 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5537  StmtExpr),
5538  internal::Matcher<Stmt>, InnerMatcher) {
5539  const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5540  return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5541  CS->body_end(), Finder,
5542  Builder) != CS->body_end();
5543 }
5544 
5545 /// Checks that a compound statement contains a specific number of
5546 /// child statements.
5547 ///
5548 /// Example: Given
5549 /// \code
5550 /// { for (;;) {} }
5551 /// \endcode
5552 /// compoundStmt(statementCountIs(0)))
5553 /// matches '{}'
5554 /// but does not match the outer compound statement.
5555 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5556  return Node.size() == N;
5557 }
5558 
5559 /// Matches literals that are equal to the given value of type ValueT.
5560 ///
5561 /// Given
5562 /// \code
5563 /// f('\0', false, 3.14, 42);
5564 /// \endcode
5565 /// characterLiteral(equals(0))
5566 /// matches '\0'
5567 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5568 /// match false
5569 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5570 /// match 3.14
5571 /// integerLiteral(equals(42))
5572 /// matches 42
5573 ///
5574 /// Note that you cannot directly match a negative numeric literal because the
5575 /// minus sign is not part of the literal: It is a unary operator whose operand
5576 /// is the positive numeric literal. Instead, you must use a unaryOperator()
5577 /// matcher to match the minus sign:
5578 ///
5579 /// unaryOperator(hasOperatorName("-"),
5580 /// hasUnaryOperand(integerLiteral(equals(13))))
5581 ///
5582 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5583 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5584 template <typename ValueT>
5585 internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5586  void(internal::AllNodeBaseTypes), ValueT>
5587 equals(const ValueT &Value) {
5588  return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5589  void(internal::AllNodeBaseTypes), ValueT>(
5590  Value);
5591 }
5592 
5596  IntegerLiteral),
5597  bool, Value, 0) {
5598  return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5599  .matchesNode(Node);
5600 }
5601 
5605  IntegerLiteral),
5606  unsigned, Value, 1) {
5607  return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5608  .matchesNode(Node);
5609 }
5610 
5615  IntegerLiteral),
5616  double, Value, 2) {
5617  return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5618  .matchesNode(Node);
5619 }
5620 
5621 /// Matches the operator Name of operator expressions (binary or
5622 /// unary).
5623 ///
5624 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5625 /// \code
5626 /// !(a || b)
5627 /// \endcode
5629  hasOperatorName,
5632  std::string, Name) {
5633  if (Optional<StringRef> OpName = internal::getOpName(Node))
5634  return *OpName == Name;
5635  return false;
5636 }
5637 
5638 /// Matches operator expressions (binary or unary) that have any of the
5639 /// specified names.
5640 ///
5641 /// hasAnyOperatorName("+", "-")
5642 /// Is equivalent to
5643 /// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5644 extern const internal::VariadicFunction<
5645  internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5649  std::vector<std::string>>,
5652 
5653 /// Matches all kinds of assignment operators.
5654 ///
5655 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5656 /// \code
5657 /// if (a == b)
5658 /// a += b;
5659 /// \endcode
5660 ///
5661 /// Example 2: matches s1 = s2
5662 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5663 /// \code
5664 /// struct S { S& operator=(const S&); };
5665 /// void x() { S s1, s2; s1 = s2; }
5666 /// \endcode
5668  isAssignmentOperator,
5671  return Node.isAssignmentOp();
5672 }
5673 
5674 /// Matches comparison operators.
5675 ///
5676 /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5677 /// \code
5678 /// if (a == b)
5679 /// a += b;
5680 /// \endcode
5681 ///
5682 /// Example 2: matches s1 < s2
5683 /// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5684 /// \code
5685 /// struct S { bool operator<(const S& other); };
5686 /// void x(S s1, S s2) { bool b1 = s1 < s2; }
5687 /// \endcode
5692  return Node.isComparisonOp();
5693 }
5694 
5695 /// Matches the left hand side of binary operator expressions.
5696 ///
5697 /// Example matches a (matcher = binaryOperator(hasLHS()))
5698 /// \code
5699 /// a || b
5700 /// \endcode
5705  internal::Matcher<Expr>, InnerMatcher) {
5706  const Expr *LeftHandSide = internal::getLHS(Node);
5707  return (LeftHandSide != nullptr &&
5708  InnerMatcher.matches(*LeftHandSide, Finder, Builder));
5709 }
5710 
5711 /// Matches the right hand side of binary operator expressions.
5712 ///
5713 /// Example matches b (matcher = binaryOperator(hasRHS()))
5714 /// \code
5715 /// a || b
5716 /// \endcode
5721  internal::Matcher<Expr>, InnerMatcher) {
5722  const Expr *RightHandSide = internal::getRHS(Node);
5723  return (RightHandSide != nullptr &&
5724  InnerMatcher.matches(*RightHandSide, Finder, Builder));
5725 }
5726 
5727 /// Matches if either the left hand side or the right hand side of a
5728 /// binary operator matches.
5730  hasEitherOperand,
5733  internal::Matcher<Expr>, InnerMatcher) {
5734  return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5735  anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
5736  .matches(Node, Finder, Builder);
5737 }
5738 
5739 /// Matches if both matchers match with opposite sides of the binary operator.
5740 ///
5741 /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
5742 /// integerLiteral(equals(2)))
5743 /// \code
5744 /// 1 + 2 // Match
5745 /// 2 + 1 // Match
5746 /// 1 + 1 // No match
5747 /// 2 + 2 // No match
5748 /// \endcode
5750  hasOperands,
5753  internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
5754  return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5755  anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
5756  allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
5757  .matches(Node, Finder, Builder);
5758 }
5759 
5760 /// Matches if the operand of a unary operator matches.
5761 ///
5762 /// Example matches true (matcher = hasUnaryOperand(
5763 /// cxxBoolLiteral(equals(true))))
5764 /// \code
5765 /// !true
5766 /// \endcode
5770  internal::Matcher<Expr>, InnerMatcher) {
5771  const Expr *const Operand = internal::getSubExpr(Node);
5772  return (Operand != nullptr &&
5773  InnerMatcher.matches(*Operand, Finder, Builder));
5774 }
5775 
5776 /// Matches if the cast's source expression
5777 /// or opaque value's source expression matches the given matcher.
5778 ///
5779 /// Example 1: matches "a string"
5780 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
5781 /// \code
5782 /// class URL { URL(string); };
5783 /// URL url = "a string";
5784 /// \endcode
5785 ///
5786 /// Example 2: matches 'b' (matcher =
5787 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
5788 /// \code
5789 /// int a = b ?: 1;
5790 /// \endcode
5791 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
5793  OpaqueValueExpr),
5794  internal::Matcher<Expr>, InnerMatcher) {
5795  const Expr *const SubExpression =
5796  internal::GetSourceExpressionMatcher<NodeType>::get(Node);
5797  return (SubExpression != nullptr &&
5798  InnerMatcher.matches(*SubExpression, Finder, Builder));
5799 }
5800 
5801 /// Matches casts that has a given cast kind.
5802 ///
5803 /// Example: matches the implicit cast around \c 0
5804 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
5805 /// \code
5806 /// int *p = 0;
5807 /// \endcode
5808 ///
5809 /// If the matcher is use from clang-query, CastKind parameter
5810 /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
5812  return Node.getCastKind() == Kind;
5813 }
5814 
5815 /// Matches casts whose destination type matches a given matcher.
5816 ///
5817 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
5818 /// actual casts "explicit" casts.)
5819 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
5820  internal::Matcher<QualType>, InnerMatcher) {
5821  const QualType NodeType = Node.getTypeAsWritten();
5822  return InnerMatcher.matches(NodeType, Finder, Builder);
5823 }
5824 
5825 /// Matches implicit casts whose destination type matches a given
5826 /// matcher.
5827 ///
5828 /// FIXME: Unit test this matcher
5829 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
5830  internal::Matcher<QualType>, InnerMatcher) {
5831  return InnerMatcher.matches(Node.getType(), Finder, Builder);
5832 }
5833 
5834 /// Matches TagDecl object that are spelled with "struct."
5835 ///
5836 /// Example matches S, but not C, U or E.
5837 /// \code
5838 /// struct S {};
5839 /// class C {};
5840 /// union U {};
5841 /// enum E {};
5842 /// \endcode
5843 AST_MATCHER(TagDecl, isStruct) {
5844  return Node.isStruct();
5845 }
5846 
5847 /// Matches TagDecl object that are spelled with "union."
5848 ///
5849 /// Example matches U, but not C, S or E.
5850 /// \code
5851 /// struct S {};
5852 /// class C {};
5853 /// union U {};
5854 /// enum E {};
5855 /// \endcode
5857  return Node.isUnion();
5858 }
5859 
5860 /// Matches TagDecl object that are spelled with "class."
5861 ///
5862 /// Example matches C, but not S, U or E.
5863 /// \code
5864 /// struct S {};
5865 /// class C {};
5866 /// union U {};
5867 /// enum E {};
5868 /// \endcode
5870  return Node.isClass();
5871 }
5872 
5873 /// Matches TagDecl object that are spelled with "enum."
5874 ///
5875 /// Example matches E, but not C, S or U.
5876 /// \code
5877 /// struct S {};
5878 /// class C {};
5879 /// union U {};
5880 /// enum E {};
5881 /// \endcode
5883  return Node.isEnum();
5884 }
5885 
5886 /// Matches the true branch expression of a conditional operator.
5887 ///
5888 /// Example 1 (conditional ternary operator): matches a
5889 /// \code
5890 /// condition ? a : b
5891 /// \endcode
5892 ///
5893 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
5894 /// \code
5895 /// condition ?: b
5896 /// \endcode
5898  internal::Matcher<Expr>, InnerMatcher) {
5899  const Expr *Expression = Node.getTrueExpr();
5900  return (Expression != nullptr &&
5901  InnerMatcher.matches(*Expression, Finder, Builder));
5902 }
5903 
5904 /// Matches the false branch expression of a conditional operator
5905 /// (binary or ternary).
5906 ///
5907 /// Example matches b
5908 /// \code
5909 /// condition ? a : b
5910 /// condition ?: b
5911 /// \endcode
5913  internal::Matcher<Expr>, InnerMatcher) {
5914  const Expr *Expression = Node.getFalseExpr();
5915  return (Expression != nullptr &&
5916  InnerMatcher.matches(*Expression, Finder, Builder));
5917 }
5918 
5919 /// Matches if a declaration has a body attached.
5920 ///
5921 /// Example matches A, va, fa
5922 /// \code
5923 /// class A {};
5924 /// class B; // Doesn't match, as it has no body.
5925 /// int va;
5926 /// extern int vb; // Doesn't match, as it doesn't define the variable.
5927 /// void fa() {}
5928 /// void fb(); // Doesn't match, as it has no body.
5929 /// @interface X
5930 /// - (void)ma; // Doesn't match, interface is declaration.
5931 /// @end
5932 /// @implementation X
5933 /// - (void)ma {}
5934 /// @end
5935 /// \endcode
5936 ///
5937 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
5938 /// Matcher<ObjCMethodDecl>
5942  FunctionDecl)) {
5943  return Node.isThisDeclarationADefinition();
5944 }
5945 
5946 /// Matches if a function declaration is variadic.
5947 ///
5948 /// Example matches f, but not g or h. The function i will not match, even when
5949 /// compiled in C mode.
5950 /// \code
5951 /// void f(...);
5952 /// void g(int);
5953 /// template <typename... Ts> void h(Ts...);
5954 /// void i();
5955 /// \endcode
5957  return Node.isVariadic();
5958 }
5959 
5960 /// Matches the class declaration that the given method declaration
5961 /// belongs to.
5962 ///
5963 /// FIXME: Generalize this for other kinds of declarations.
5964 /// FIXME: What other kind of declarations would we need to generalize
5965 /// this to?
5966 ///
5967 /// Example matches A() in the last line
5968 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
5969 /// ofClass(hasName("A"))))))
5970 /// \code
5971 /// class A {
5972 /// public:
5973 /// A();
5974 /// };
5975 /// A a = A();
5976 /// \endcode
5978  internal::Matcher<CXXRecordDecl>, InnerMatcher) {
5979 
5980  ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
5981 
5982  const CXXRecordDecl *Parent = Node.getParent();
5983  return (Parent != nullptr &&
5984  InnerMatcher.matches(*Parent, Finder, Builder));
5985 }
5986 
5987 /// Matches each method overridden by the given method. This matcher may
5988 /// produce multiple matches.
5989 ///
5990 /// Given
5991 /// \code
5992 /// class A { virtual void f(); };
5993 /// class B : public A { void f(); };
5994 /// class C : public B { void f(); };
5995 /// \endcode
5996 /// cxxMethodDecl(ofClass(hasName("C")),
5997 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5998 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
5999 /// that B::f is not overridden by C::f).
6000 ///
6001 /// The check can produce multiple matches in case of multiple inheritance, e.g.
6002 /// \code
6003 /// class A1 { virtual void f(); };
6004 /// class A2 { virtual void f(); };
6005 /// class C : public A1, public A2 { void f(); };
6006 /// \endcode
6007 /// cxxMethodDecl(ofClass(hasName("C")),
6008 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6009 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
6010 /// once with "b" binding "A2::f" and "d" binding "C::f".
6011 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
6012  internal::Matcher<CXXMethodDecl>, InnerMatcher) {
6013  BoundNodesTreeBuilder Result;
6014  bool Matched = false;
6015  for (const auto *Overridden : Node.overridden_methods()) {
6016  BoundNodesTreeBuilder OverriddenBuilder(*Builder);
6017  const bool OverriddenMatched =
6018  InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
6019  if (OverriddenMatched) {
6020  Matched = true;
6021  Result.addMatch(OverriddenBuilder);
6022  }
6023  }
6024  *Builder = std::move(Result);
6025  return Matched;
6026 }
6027 
6028 /// Matches declarations of virtual methods and C++ base specifers that specify
6029 /// virtual inheritance.
6030 ///
6031 /// Example:
6032 /// \code
6033 /// class A {
6034 /// public:
6035 /// virtual void x(); // matches x
6036 /// };
6037 /// \endcode
6038 ///
6039 /// Example:
6040 /// \code
6041 /// class Base {};
6042 /// class DirectlyDerived : virtual Base {}; // matches Base
6043 /// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
6044 /// \endcode
6045 ///
6046 /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
6049  CXXBaseSpecifier)) {
6050  return Node.isVirtual();
6051 }
6052 
6053 /// Matches if the given method declaration has an explicit "virtual".
6054 ///
6055 /// Given
6056 /// \code
6057 /// class A {
6058 /// public:
6059 /// virtual void x();
6060 /// };
6061 /// class B : public A {
6062 /// public:
6063 /// void x();
6064 /// };
6065 /// \endcode
6066 /// matches A::x but not B::x
6067 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
6068  return Node.isVirtualAsWritten();
6069 }
6070 
6071 AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
6072  return Node.isInheritingConstructor();
6073 }
6074 
6075 /// Matches if the given method or class declaration is final.
6076 ///
6077 /// Given:
6078 /// \code
6079 /// class A final {};
6080 ///
6081 /// struct B {
6082 /// virtual void f();
6083 /// };
6084 ///
6085 /// struct C : B {
6086 /// void f() final;
6087 /// };
6088 /// \endcode
6089 /// matches A and C::f, but not B, C, or B::f
6092  CXXMethodDecl)) {
6093  return Node.template hasAttr<FinalAttr>();
6094 }
6095 
6096 /// Matches if the given method declaration is pure.
6097 ///
6098 /// Given
6099 /// \code
6100 /// class A {
6101 /// public:
6102 /// virtual void x() = 0;
6103 /// };
6104 /// \endcode
6105 /// matches A::x
6107  return Node.isPure();
6108 }
6109 
6110 /// Matches if the given method declaration is const.
6111 ///
6112 /// Given
6113 /// \code
6114 /// struct A {
6115 /// void foo() const;
6116 /// void bar();
6117 /// };
6118 /// \endcode
6119 ///
6120 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
6122  return Node.isConst();
6123 }
6124 
6125 /// Matches if the given method declaration declares a copy assignment
6126 /// operator.
6127 ///
6128 /// Given
6129 /// \code
6130 /// struct A {
6131 /// A &operator=(const A &);
6132 /// A &operator=(A &&);
6133 /// };
6134 /// \endcode
6135 ///
6136 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
6137 /// the second one.
6138 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
6139  return Node.isCopyAssignmentOperator();
6140 }
6141 
6142 /// Matches if the given method declaration declares a move assignment
6143 /// operator.
6144 ///
6145 /// Given
6146 /// \code
6147 /// struct A {
6148 /// A &operator=(const A &);
6149 /// A &operator=(A &&);
6150 /// };
6151 /// \endcode
6152 ///
6153 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
6154 /// the first one.
6155 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
6156  return Node.isMoveAssignmentOperator();
6157 }
6158 
6159 /// Matches if the given method declaration overrides another method.
6160 ///
6161 /// Given
6162 /// \code
6163 /// class A {
6164 /// public:
6165 /// virtual void x();
6166 /// };
6167 /// class B : public A {
6168 /// public:
6169 /// virtual void x();
6170 /// };
6171 /// \endcode
6172 /// matches B::x
6174  return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
6175 }
6176 
6177 /// Matches method declarations that are user-provided.
6178 ///
6179 /// Given
6180 /// \code
6181 /// struct S {
6182 /// S(); // #1
6183 /// S(const S &) = default; // #2
6184 /// S(S &&) = delete; // #3
6185 /// };
6186 /// \endcode
6187 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
6188 AST_MATCHER(CXXMethodDecl, isUserProvided) {
6189  return Node.isUserProvided();
6190 }
6191 
6192 /// Matches member expressions that are called with '->' as opposed
6193 /// to '.'.
6194 ///
6195 /// Member calls on the implicit this pointer match as called with '->'.
6196 ///
6197 /// Given
6198 /// \code
6199 /// class Y {
6200 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
6201 /// template <class T> void f() { this->f<T>(); f<T>(); }
6202 /// int a;
6203 /// static int b;
6204 /// };
6205 /// template <class T>
6206 /// class Z {
6207 /// void x() { this->m; }
6208 /// };
6209 /// \endcode
6210 /// memberExpr(isArrow())
6211 /// matches this->x, x, y.x, a, this->b
6212 /// cxxDependentScopeMemberExpr(isArrow())
6213 /// matches this->m
6214 /// unresolvedMemberExpr(isArrow())
6215 /// matches this->f<T>, f<T>
6219  return Node.isArrow();
6220 }
6221 
6222 /// Matches QualType nodes that are of integer type.
6223 ///
6224 /// Given
6225 /// \code
6226 /// void a(int);
6227 /// void b(long);
6228 /// void c(double);
6229 /// \endcode
6230 /// functionDecl(hasAnyParameter(hasType(isInteger())))
6231 /// matches "a(int)", "b(long)", but not "c(double)".
6232 AST_MATCHER(QualType, isInteger) {
6233  return Node->isIntegerType();
6234 }
6235 
6236 /// Matches QualType nodes that are of unsigned integer type.
6237 ///
6238 /// Given
6239 /// \code
6240 /// void a(int);
6241 /// void b(unsigned long);
6242 /// void c(double);
6243 /// \endcode
6244 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6245 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
6246 AST_MATCHER(QualType, isUnsignedInteger) {
6247  return Node->isUnsignedIntegerType();
6248 }
6249 
6250 /// Matches QualType nodes that are of signed integer type.
6251 ///
6252 /// Given
6253 /// \code
6254 /// void a(int);
6255 /// void b(unsigned long);
6256 /// void c(double);
6257 /// \endcode
6258 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6259 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
6260 AST_MATCHER(QualType, isSignedInteger) {
6261  return Node->isSignedIntegerType();
6262 }
6263 
6264 /// Matches QualType nodes that are of character type.
6265 ///
6266 /// Given
6267 /// \code
6268 /// void a(char);
6269 /// void b(wchar_t);
6270 /// void c(double);
6271 /// \endcode
6272 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6273 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
6274 AST_MATCHER(QualType, isAnyCharacter) {
6275  return Node->isAnyCharacterType();
6276 }
6277 
6278 /// Matches QualType nodes that are of any pointer type; this includes
6279 /// the Objective-C object pointer type, which is different despite being
6280 /// syntactically similar.
6281 ///
6282 /// Given
6283 /// \code
6284 /// int *i = nullptr;
6285 ///
6286 /// @interface Foo
6287 /// @end
6288 /// Foo *f;
6289 ///
6290 /// int j;
6291 /// \endcode
6292 /// varDecl(hasType(isAnyPointer()))
6293 /// matches "int *i" and "Foo *f", but not "int j".
6294 AST_MATCHER(QualType, isAnyPointer) {
6295  return Node->isAnyPointerType();
6296 }
6297 
6298 /// Matches QualType nodes that are const-qualified, i.e., that
6299 /// include "top-level" const.
6300 ///
6301 /// Given
6302 /// \code
6303 /// void a(int);
6304 /// void b(int const);
6305 /// void c(const int);
6306 /// void d(const int*);
6307 /// void e(int const) {};
6308 /// \endcode
6309 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6310 /// matches "void b(int const)", "void c(const int)" and
6311 /// "void e(int const) {}". It does not match d as there
6312 /// is no top-level const on the parameter type "const int *".
6313 AST_MATCHER(QualType, isConstQualified) {
6314  return Node.isConstQualified();
6315 }
6316 
6317 /// Matches QualType nodes that are volatile-qualified, i.e., that
6318 /// include "top-level" volatile.
6319 ///
6320 /// Given
6321 /// \code
6322 /// void a(int);
6323 /// void b(int volatile);
6324 /// void c(volatile int);
6325 /// void d(volatile int*);
6326 /// void e(int volatile) {};
6327 /// \endcode
6328 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6329 /// matches "void b(int volatile)", "void c(volatile int)" and
6330 /// "void e(int volatile) {}". It does not match d as there
6331 /// is no top-level volatile on the parameter type "volatile int *".
6332 AST_MATCHER(QualType, isVolatileQualified) {
6333  return Node.isVolatileQualified();
6334 }
6335