1 //===--- ASTMatchers.h - Structural query framework -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements matchers to be used together with the MatchFinder to
13 // Matchers are created by generator functions, which can be combined in
14 // a functional in-language DSL to express queries over the C++ AST.
16 // For example, to match a class with a certain name, one would call:
17 // cxxRecordDecl(hasName("MyClass"))
18 // which returns a matcher that can be used to find all AST nodes that declare
19 // a class named 'MyClass'.
21 // For more complicated match expressions we're often interested in accessing
22 // multiple parts of the matched AST nodes once a match is found. In that case,
23 // use the id(...) matcher around the match expressions that match the nodes
24 // you want to access.
26 // For example, when we're interested in child classes of a certain class, we
28 // cxxRecordDecl(hasName("MyClass"), hasChild(id("child", recordDecl())))
29 // When the match is found via the MatchFinder, a user provided callback will
30 // be called with a BoundNodes instance that contains a mapping from the
31 // strings that we provided for the id(...) calls to the nodes that were
33 // In the given example, each time our matcher finds a match we get a callback
34 // where "child" is bound to the RecordDecl node of the matching child
37 // See ASTMatchersInternal.h for a more in-depth explanation of the
38 // implementation details of the matcher framework.
40 // See ASTMatchFinder.h for how to use the generated matchers to run over
43 //===----------------------------------------------------------------------===//
45 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
46 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/DeclFriend.h"
50 #include "clang/AST/DeclObjC.h"
51 #include "clang/AST/DeclTemplate.h"
52 #include "clang/ASTMatchers/ASTMatchersInternal.h"
53 #include "clang/ASTMatchers/ASTMatchersMacros.h"
54 #include "llvm/ADT/Twine.h"
55 #include "llvm/Support/Regex.h"
59 namespace ast_matchers {
61 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
63 /// The bound nodes are generated by calling \c bind("id") on the node matchers
64 /// of the nodes we want to access later.
66 /// The instances of BoundNodes are created by \c MatchFinder when the user's
67 /// callbacks are executed every time a match is found.
70 /// \brief Returns the AST node bound to \c ID.
72 /// Returns NULL if there was no node bound to \c ID or if there is a node but
73 /// it cannot be converted to the specified type.
75 const T *getNodeAs(StringRef ID) const {
76 return MyBoundNodes.getNodeAs<T>(ID);
79 /// \brief Deprecated. Please use \c getNodeAs instead.
82 const T *getDeclAs(StringRef ID) const {
83 return getNodeAs<T>(ID);
86 const T *getStmtAs(StringRef ID) const {
87 return getNodeAs<T>(ID);
91 /// \brief Type of mapping from binding identifiers to bound nodes. This type
92 /// is an associative container with a key type of \c std::string and a value
93 /// type of \c clang::ast_type_traits::DynTypedNode
94 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
96 /// \brief Retrieve mapping from binding identifiers to bound nodes.
97 const IDToNodeMap &getMap() const {
98 return MyBoundNodes.getMap();
102 /// \brief Create BoundNodes from a pre-filled map of bindings.
103 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
104 : MyBoundNodes(MyBoundNodes) {}
106 internal::BoundNodesMap MyBoundNodes;
108 friend class internal::BoundNodesTreeBuilder;
111 /// \brief If the provided matcher matches a node, binds the node to \c ID.
113 /// FIXME: Do we want to support this now that we have bind()?
114 template <typename T>
115 internal::Matcher<T> id(StringRef ID,
116 const internal::BindableMatcher<T> &InnerMatcher) {
117 return InnerMatcher.bind(ID);
120 /// \brief Types of matchers for the top-level classes in the AST class
123 typedef internal::Matcher<Decl> DeclarationMatcher;
124 typedef internal::Matcher<Stmt> StatementMatcher;
125 typedef internal::Matcher<QualType> TypeMatcher;
126 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
127 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
128 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
131 /// \brief Matches any node.
133 /// Useful when another matcher requires a child matcher, but there's no
134 /// additional constraint. This will often be used with an explicit conversion
135 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
137 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
139 /// "int* p" and "void f()" in
144 /// Usable as: Any Matcher
145 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
147 /// \brief Matches the top declaration context.
154 /// } // namespace NS
156 /// decl(hasDeclContext(translationUnitDecl()))
157 /// matches "int X", but not "int Y".
158 const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
161 /// \brief Matches typedef declarations.
169 /// matches "typedef int X", but not "using Y = int"
170 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
172 /// \brief Matches typedef name declarations.
179 /// typedefNameDecl()
180 /// matches "typedef int X" and "using Y = int"
181 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
184 /// \brief Matches type alias declarations.
192 /// matches "using Y = int", but not "typedef int X"
193 const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl> typeAliasDecl;
195 /// \brief Matches AST nodes that were expanded within the main-file.
197 /// Example matches X but not Y
198 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
208 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
209 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
210 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
211 auto &SourceManager = Finder->getASTContext().getSourceManager();
212 return SourceManager.isInMainFile(
213 SourceManager.getExpansionLoc(Node.getLocStart()));
216 /// \brief Matches AST nodes that were expanded within system-header-files.
218 /// Example matches Y but not X
219 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
221 /// #include <SystemHeader.h>
229 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
230 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
231 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
232 auto &SourceManager = Finder->getASTContext().getSourceManager();
233 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
234 if (ExpansionLoc.isInvalid()) {
237 return SourceManager.isInSystemHeader(ExpansionLoc);
240 /// \brief Matches AST nodes that were expanded within files whose name is
241 /// partially matching a given regex.
243 /// Example matches Y but not X
244 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
246 /// #include "ASTMatcher.h"
254 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
255 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
256 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
257 std::string, RegExp) {
258 auto &SourceManager = Finder->getASTContext().getSourceManager();
259 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
260 if (ExpansionLoc.isInvalid()) {
264 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
269 auto Filename = FileEntry->getName();
270 llvm::Regex RE(RegExp);
271 return RE.match(Filename);
274 /// \brief Matches declarations.
276 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
283 const internal::VariadicAllOfMatcher<Decl> decl;
285 /// \brief Matches a declaration of a linkage specification.
291 /// linkageSpecDecl()
292 /// matches "extern "C" {}"
293 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
296 /// \brief Matches a declaration of anything that could have a name.
298 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
307 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
309 /// \brief Matches a declaration of label.
318 const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
320 /// \brief Matches a declaration of a namespace.
325 /// namespace test {}
328 /// matches "namespace {}" and "namespace test {}"
329 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
331 /// \brief Matches a declaration of a namespace alias.
335 /// namespace test {}
336 /// namespace alias = ::test;
338 /// namespaceAliasDecl()
339 /// matches "namespace alias" but not "namespace test"
340 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
343 /// \brief Matches class, struct, and union declarations.
345 /// Example matches \c X, \c Z, \c U, and \c S
348 /// template<class T> class Z {};
352 const internal::VariadicDynCastAllOfMatcher<
354 RecordDecl> recordDecl;
356 /// \brief Matches C++ class declarations.
358 /// Example matches \c X, \c Z
361 /// template<class T> class Z {};
363 const internal::VariadicDynCastAllOfMatcher<
365 CXXRecordDecl> cxxRecordDecl;
367 /// \brief Matches C++ class template declarations.
369 /// Example matches \c Z
371 /// template<class T> class Z {};
373 const internal::VariadicDynCastAllOfMatcher<
375 ClassTemplateDecl> classTemplateDecl;
377 /// \brief Matches C++ class template specializations.
381 /// template<typename T> class A {};
382 /// template<> class A<double> {};
385 /// classTemplateSpecializationDecl()
386 /// matches the specializations \c A<int> and \c A<double>
387 const internal::VariadicDynCastAllOfMatcher<
389 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
391 /// \brief Matches declarator declarations (field, variable, function
392 /// and non-type template parameter declarations).
396 /// class X { int y; };
399 /// matches \c int y.
400 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
403 /// \brief Matches parameter variable declarations.
410 /// matches \c int x.
411 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
413 /// \brief Matches C++ access specifier declarations.
423 /// matches 'public:'
424 const internal::VariadicDynCastAllOfMatcher<
426 AccessSpecDecl> accessSpecDecl;
428 /// \brief Matches constructor initializers.
430 /// Examples matches \c i(42).
437 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
439 /// \brief Matches template arguments.
443 /// template <typename T> struct C {};
446 /// templateArgument()
447 /// matches 'int' in C<int>.
448 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
450 /// \brief Matches non-type template parameter declarations.
454 /// template <typename T, int N> struct C {};
456 /// nonTypeTemplateParmDecl()
457 /// matches 'N', but not 'T'.
458 const internal::VariadicDynCastAllOfMatcher<
460 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
462 /// \brief Matches template type parameter declarations.
466 /// template <typename T, int N> struct C {};
468 /// templateTypeParmDecl()
469 /// matches 'T', but not 'N'.
470 const internal::VariadicDynCastAllOfMatcher<
472 TemplateTypeParmDecl> templateTypeParmDecl;
474 /// \brief Matches public C++ declarations.
480 /// protected: int b;
484 /// fieldDecl(isPublic())
486 AST_MATCHER(Decl, isPublic) {
487 return Node.getAccess() == AS_public;
490 /// \brief Matches protected C++ declarations.
496 /// protected: int b;
500 /// fieldDecl(isProtected())
502 AST_MATCHER(Decl, isProtected) {
503 return Node.getAccess() == AS_protected;
506 /// \brief Matches private C++ declarations.
512 /// protected: int b;
516 /// fieldDecl(isPrivate())
518 AST_MATCHER(Decl, isPrivate) {
519 return Node.getAccess() == AS_private;
522 /// \brief Matches non-static data members that are bit-fields.
531 /// fieldDecl(isBitField())
532 /// matches 'int a;' but not 'int b;'.
533 AST_MATCHER(FieldDecl, isBitField) {
534 return Node.isBitField();
537 /// \brief Matches non-static data members that are bit-fields.
547 /// fieldDecl(isBitField())
548 /// matches 'int a;' and 'int c;' but not 'int b;'.
549 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
550 return Node.isBitField() &&
551 Node.getBitWidthValue(Finder->getASTContext()) == Width;
554 /// \brief Matches a declaration that has been implicitly added
555 /// by the compiler (eg. implicit default/copy constructors).
556 AST_MATCHER(Decl, isImplicit) {
557 return Node.isImplicit();
560 /// \brief Matches classTemplateSpecializations that have at least one
561 /// TemplateArgument matching the given InnerMatcher.
565 /// template<typename T> class A {};
566 /// template<> class A<double> {};
569 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
570 /// refersToType(asString("int"))))
571 /// matches the specialization \c A<int>
572 AST_POLYMORPHIC_MATCHER_P(
573 hasAnyTemplateArgument,
574 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
575 TemplateSpecializationType),
576 internal::Matcher<TemplateArgument>, InnerMatcher) {
577 ArrayRef<TemplateArgument> List =
578 internal::getTemplateSpecializationArgs(Node);
579 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
583 /// \brief Matches expressions that match InnerMatcher after any implicit AST
584 /// nodes are stripped off.
586 /// Parentheses and explicit casts are not discarded.
596 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
598 /// would match the declarations for a, b, and c.
601 /// varDecl(hasInitializer(cxxConstructExpr()))
603 /// only match the declarations for b and c.
604 AST_MATCHER_P(Expr, ignoringImplicit, ast_matchers::internal::Matcher<Expr>,
606 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
609 /// \brief Matches expressions that match InnerMatcher after any implicit casts
610 /// are stripped off.
612 /// Parentheses and explicit casts are not discarded.
620 /// long e = (long) 0l;
624 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
625 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
627 /// would match the declarations for a, b, c, and d, but not e.
630 /// varDecl(hasInitializer(integerLiteral()))
631 /// varDecl(hasInitializer(declRefExpr()))
633 /// only match the declarations for b, c, and d.
634 AST_MATCHER_P(Expr, ignoringImpCasts,
635 internal::Matcher<Expr>, InnerMatcher) {
636 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
639 /// \brief Matches expressions that match InnerMatcher after parentheses and
640 /// casts are stripped off.
642 /// Implicit and non-C Style casts are also discarded.
647 /// void* c = reinterpret_cast<char*>(0);
648 /// char d = char(0);
651 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
652 /// would match the declarations for a, b, c, and d.
654 /// varDecl(hasInitializer(integerLiteral()))
655 /// only match the declaration for a.
656 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
657 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
660 /// \brief Matches expressions that match InnerMatcher after implicit casts and
661 /// parentheses are stripped off.
663 /// Explicit casts are not discarded.
671 /// long e = ((long) 0l);
674 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
675 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
676 /// would match the declarations for a, b, c, and d, but not e.
678 /// varDecl(hasInitializer(integerLiteral()))
679 /// varDecl(hasInitializer(declRefExpr()))
680 /// would only match the declaration for a.
681 AST_MATCHER_P(Expr, ignoringParenImpCasts,
682 internal::Matcher<Expr>, InnerMatcher) {
683 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
686 /// \brief Matches types that match InnerMatcher after any parens are stripped.
690 /// void (*fp)(void);
694 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
696 /// would match the declaration for fp.
697 AST_MATCHER_P(QualType, ignoringParens,
698 internal::Matcher<QualType>, InnerMatcher) {
699 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
702 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
703 /// matches the given InnerMatcher.
707 /// template<typename T, typename U> class A {};
711 /// classTemplateSpecializationDecl(hasTemplateArgument(
712 /// 1, refersToType(asString("int"))))
713 /// matches the specialization \c A<bool, int>
714 AST_POLYMORPHIC_MATCHER_P2(
716 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
717 TemplateSpecializationType),
718 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
719 ArrayRef<TemplateArgument> List =
720 internal::getTemplateSpecializationArgs(Node);
721 if (List.size() <= N)
723 return InnerMatcher.matches(List[N], Finder, Builder);
726 /// \brief Matches if the number of template arguments equals \p N.
730 /// template<typename T> struct C {};
733 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
735 AST_POLYMORPHIC_MATCHER_P(
736 templateArgumentCountIs,
737 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
738 TemplateSpecializationType),
740 return internal::getTemplateSpecializationArgs(Node).size() == N;
743 /// \brief Matches a TemplateArgument that refers to a certain type.
748 /// template<typename T> struct A {};
751 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
752 /// refersToType(class(hasName("X")))))
753 /// matches the specialization \c A<X>
754 AST_MATCHER_P(TemplateArgument, refersToType,
755 internal::Matcher<QualType>, InnerMatcher) {
756 if (Node.getKind() != TemplateArgument::Type)
758 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
761 /// \brief Matches a canonical TemplateArgument that refers to a certain
766 /// template<typename T> struct A {};
767 /// struct B { B* next; };
770 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
771 /// refersToDeclaration(fieldDecl(hasName("next"))))
772 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
774 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
775 internal::Matcher<Decl>, InnerMatcher) {
776 if (Node.getKind() == TemplateArgument::Declaration)
777 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
781 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
785 /// template<typename T> struct A {};
786 /// struct B { B* next; };
789 /// templateSpecializationType(hasAnyTemplateArgument(
790 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
791 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
793 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
794 if (Node.getKind() == TemplateArgument::Expression)
795 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
799 /// \brief Matches a TemplateArgument that is an integral value.
803 /// template<int T> struct A {};
806 /// classTemplateSpecializationDecl(
807 /// hasAnyTemplateArgument(isIntegral()))
808 /// matches the implicit instantiation of C in C<42>
809 /// with isIntegral() matching 42.
810 AST_MATCHER(TemplateArgument, isIntegral) {
811 return Node.getKind() == TemplateArgument::Integral;
814 /// \brief Matches a TemplateArgument that referes to an integral type.
818 /// template<int T> struct A {};
821 /// classTemplateSpecializationDecl(
822 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
823 /// matches the implicit instantiation of C in C<42>.
824 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
825 internal::Matcher<QualType>, InnerMatcher) {
826 if (Node.getKind() != TemplateArgument::Integral)
828 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
831 /// \brief Matches a TemplateArgument of integral type with a given value.
833 /// Note that 'Value' is a string as the template argument's value is
834 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
835 /// representation of that integral value in base 10.
839 /// template<int T> struct A {};
842 /// classTemplateSpecializationDecl(
843 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
844 /// matches the implicit instantiation of C in C<42>.
845 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
846 std::string, Value) {
847 if (Node.getKind() != TemplateArgument::Integral)
849 return Node.getAsIntegral().toString(10) == Value;
852 /// \brief Matches any value declaration.
854 /// Example matches A, B, C and F
856 /// enum X { A, B, C };
859 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
861 /// \brief Matches C++ constructor declarations.
863 /// Example matches Foo::Foo() and Foo::Foo(int)
869 /// int DoSomething();
872 const internal::VariadicDynCastAllOfMatcher<
874 CXXConstructorDecl> cxxConstructorDecl;
876 /// \brief Matches explicit C++ destructor declarations.
878 /// Example matches Foo::~Foo()
885 const internal::VariadicDynCastAllOfMatcher<
887 CXXDestructorDecl> cxxDestructorDecl;
889 /// \brief Matches enum declarations.
891 /// Example matches X
897 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
899 /// \brief Matches enum constants.
901 /// Example matches A, B, C
907 const internal::VariadicDynCastAllOfMatcher<
909 EnumConstantDecl> enumConstantDecl;
911 /// \brief Matches method declarations.
913 /// Example matches y
915 /// class X { void y(); };
917 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
919 /// \brief Matches conversion operator declarations.
921 /// Example matches the operator.
923 /// class X { operator int() const; };
925 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
928 /// \brief Matches variable declarations.
930 /// Note: this does not match declarations of member variables, which are
931 /// "field" declarations in Clang parlance.
933 /// Example matches a
937 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
939 /// \brief Matches field declarations.
943 /// class X { int m; };
947 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
949 /// \brief Matches function declarations.
951 /// Example matches f
955 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
957 /// \brief Matches C++ function template declarations.
959 /// Example matches f
961 /// template<class T> void f(T t) {}
963 const internal::VariadicDynCastAllOfMatcher<
965 FunctionTemplateDecl> functionTemplateDecl;
967 /// \brief Matches friend declarations.
971 /// class X { friend void foo(); };
974 /// matches 'friend void foo()'.
975 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
977 /// \brief Matches statements.
984 /// matches both the compound statement '{ ++a; }' and '++a'.
985 const internal::VariadicAllOfMatcher<Stmt> stmt;
987 /// \brief Matches declaration statements.
995 const internal::VariadicDynCastAllOfMatcher<
999 /// \brief Matches member expressions.
1004 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1005 /// int a; static int b;
1009 /// matches this->x, x, y.x, a, this->b
1010 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1012 /// \brief Matches call expressions.
1014 /// Example matches x.y() and y()
1020 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1022 /// \brief Matches lambda expressions.
1024 /// Example matches [&](){return 5;}
1026 /// [&](){return 5;}
1028 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1030 /// \brief Matches member call expressions.
1032 /// Example matches x.y()
1037 const internal::VariadicDynCastAllOfMatcher<
1039 CXXMemberCallExpr> cxxMemberCallExpr;
1041 /// \brief Matches ObjectiveC Message invocation expressions.
1043 /// The innermost message send invokes the "alloc" class method on the
1044 /// NSString class, while the outermost message send invokes the
1045 /// "initWithString" instance method on the object returned from
1046 /// NSString's "alloc". This matcher should match both message sends.
1048 /// [[NSString alloc] initWithString:@"Hello"]
1050 const internal::VariadicDynCastAllOfMatcher<
1052 ObjCMessageExpr> objcMessageExpr;
1054 /// \brief Matches Objective-C interface declarations.
1056 /// Example matches Foo
1061 const internal::VariadicDynCastAllOfMatcher<
1063 ObjCInterfaceDecl> objcInterfaceDecl;
1065 /// \brief Matches expressions that introduce cleanups to be run at the end
1066 /// of the sub-expression's evaluation.
1068 /// Example matches std::string()
1070 /// const std::string str = std::string();
1072 const internal::VariadicDynCastAllOfMatcher<
1074 ExprWithCleanups> exprWithCleanups;
1076 /// \brief Matches init list expressions.
1080 /// int a[] = { 1, 2 };
1081 /// struct B { int x, y; };
1085 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1086 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
1088 /// \brief Matches the syntactic form of init list expressions
1089 /// (if expression have it).
1090 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1091 internal::Matcher<Expr>, InnerMatcher) {
1092 const Expr *SyntForm = Node.getSyntacticForm();
1093 return (SyntForm != nullptr &&
1094 InnerMatcher.matches(*SyntForm, Finder, Builder));
1097 /// \brief Matches implicit initializers of init list expressions.
1101 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1103 /// implicitValueInitExpr()
1104 /// matches "[0].y" (implicitly)
1105 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1106 implicitValueInitExpr;
1108 /// \brief Matches paren list expressions.
1109 /// ParenListExprs don't have a predefined type and are used for late parsing.
1110 /// In the final AST, they can be met in template declarations.
1114 /// template<typename T> class X {
1117 /// int a = 0, b = 1; int i = (a, b);
1121 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1122 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1123 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr;
1125 /// \brief Matches substitutions of non-type template parameters.
1129 /// template <int N>
1130 /// struct A { static const int n = N; };
1131 /// struct B : public A<42> {};
1133 /// substNonTypeTemplateParmExpr()
1134 /// matches "N" in the right-hand side of "static const int n = N;"
1135 const internal::VariadicDynCastAllOfMatcher<
1137 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
1139 /// \brief Matches using declarations.
1143 /// namespace X { int x; }
1147 /// matches \code using X::x \endcode
1148 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1150 /// \brief Matches using namespace declarations.
1154 /// namespace X { int x; }
1155 /// using namespace X;
1157 /// usingDirectiveDecl()
1158 /// matches \code using namespace X \endcode
1159 const internal::VariadicDynCastAllOfMatcher<
1161 UsingDirectiveDecl> usingDirectiveDecl;
1163 /// \brief Matches reference to a name that can be looked up during parsing
1164 /// but could not be resolved to a specific declaration.
1168 /// template<typename T>
1169 /// T foo() { T a; return a; }
1170 /// template<typename T>
1175 /// unresolvedLookupExpr()
1176 /// matches \code foo<T>() \endcode
1177 const internal::VariadicDynCastAllOfMatcher<
1179 UnresolvedLookupExpr> unresolvedLookupExpr;
1181 /// \brief Matches unresolved using value declarations.
1185 /// template<typename X>
1186 /// class C : private X {
1190 /// unresolvedUsingValueDecl()
1191 /// matches \code using X::x \endcode
1192 const internal::VariadicDynCastAllOfMatcher<
1194 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1196 /// \brief Matches unresolved using value declarations that involve the
1201 /// template <typename T>
1202 /// struct Base { typedef T Foo; };
1204 /// template<typename T>
1205 /// struct S : private Base<T> {
1206 /// using typename Base<T>::Foo;
1209 /// unresolvedUsingTypenameDecl()
1210 /// matches \code using Base<T>::Foo \endcode
1211 const internal::VariadicDynCastAllOfMatcher<
1213 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1215 /// \brief Matches parentheses used in expressions.
1217 /// Example matches (foo() + 1)
1219 /// int foo() { return 1; }
1220 /// int a = (foo() + 1);
1222 const internal::VariadicDynCastAllOfMatcher<
1224 ParenExpr> parenExpr;
1226 /// \brief Matches constructor call expressions (including implicit ones).
1228 /// Example matches string(ptr, n) and ptr within arguments of f
1229 /// (matcher = cxxConstructExpr())
1231 /// void f(const string &a, const string &b);
1234 /// f(string(ptr, n), ptr);
1236 const internal::VariadicDynCastAllOfMatcher<
1238 CXXConstructExpr> cxxConstructExpr;
1240 /// \brief Matches unresolved constructor call expressions.
1242 /// Example matches T(t) in return statement of f
1243 /// (matcher = cxxUnresolvedConstructExpr())
1245 /// template <typename T>
1246 /// void f(const T& t) { return T(t); }
1248 const internal::VariadicDynCastAllOfMatcher<
1250 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1252 /// \brief Matches implicit and explicit this expressions.
1254 /// Example matches the implicit this expression in "return i".
1255 /// (matcher = cxxThisExpr())
1259 /// int f() { return i; }
1262 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1264 /// \brief Matches nodes where temporaries are created.
1266 /// Example matches FunctionTakesString(GetStringByValue())
1267 /// (matcher = cxxBindTemporaryExpr())
1269 /// FunctionTakesString(GetStringByValue());
1270 /// FunctionTakesStringByPointer(GetStringPointer());
1272 const internal::VariadicDynCastAllOfMatcher<
1274 CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1276 /// \brief Matches nodes where temporaries are materialized.
1280 /// struct T {void func()};
1284 /// materializeTemporaryExpr() matches 'f()' in these statements
1289 /// but does not match
1294 const internal::VariadicDynCastAllOfMatcher<
1296 MaterializeTemporaryExpr> materializeTemporaryExpr;
1298 /// \brief Matches new expressions.
1305 /// matches 'new X'.
1306 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1308 /// \brief Matches delete expressions.
1315 /// matches 'delete X'.
1316 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1318 /// \brief Matches array subscript expressions.
1324 /// arraySubscriptExpr()
1326 const internal::VariadicDynCastAllOfMatcher<
1328 ArraySubscriptExpr> arraySubscriptExpr;
1330 /// \brief Matches the value of a default argument at the call site.
1332 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1333 /// default value of the second parameter in the call expression f(42)
1334 /// (matcher = cxxDefaultArgExpr())
1336 /// void f(int x, int y = 0);
1339 const internal::VariadicDynCastAllOfMatcher<
1341 CXXDefaultArgExpr> cxxDefaultArgExpr;
1343 /// \brief Matches overloaded operator calls.
1345 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1346 /// binaryOperator matcher.
1347 /// Currently it does not match operators such as new delete.
1348 /// FIXME: figure out why these do not match?
1350 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1351 /// (matcher = cxxOperatorCallExpr())
1353 /// ostream &operator<< (ostream &out, int i) { };
1354 /// ostream &o; int b = 1, c = 1;
1357 const internal::VariadicDynCastAllOfMatcher<
1359 CXXOperatorCallExpr> cxxOperatorCallExpr;
1361 /// \brief Matches expressions.
1363 /// Example matches x()
1365 /// void f() { x(); }
1367 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1369 /// \brief Matches expressions that refer to declarations.
1371 /// Example matches x in if (x)
1376 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1378 /// \brief Matches if statements.
1380 /// Example matches 'if (x) {}'
1384 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1386 /// \brief Matches for statements.
1388 /// Example matches 'for (;;) {}'
1391 /// int i[] = {1, 2, 3}; for (auto a : i);
1393 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1395 /// \brief Matches the increment statement of a for loop.
1398 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1399 /// matches '++x' in
1401 /// for (x; x < N; ++x) { }
1403 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1405 const Stmt *const Increment = Node.getInc();
1406 return (Increment != nullptr &&
1407 InnerMatcher.matches(*Increment, Finder, Builder));
1410 /// \brief Matches the initialization statement of a for loop.
1413 /// forStmt(hasLoopInit(declStmt()))
1414 /// matches 'int x = 0' in
1416 /// for (int x = 0; x < N; ++x) { }
1418 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1420 const Stmt *const Init = Node.getInit();
1421 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1424 /// \brief Matches range-based for statements.
1426 /// cxxForRangeStmt() matches 'for (auto a : i)'
1428 /// int i[] = {1, 2, 3}; for (auto a : i);
1429 /// for(int j = 0; j < 5; ++j);
1431 const internal::VariadicDynCastAllOfMatcher<
1433 CXXForRangeStmt> cxxForRangeStmt;
1435 /// \brief Matches the initialization statement of a for loop.
1438 /// forStmt(hasLoopVariable(anything()))
1439 /// matches 'int x' in
1441 /// for (int x : a) { }
1443 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1445 const VarDecl *const Var = Node.getLoopVariable();
1446 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1449 /// \brief Matches the range initialization statement of a for loop.
1452 /// forStmt(hasRangeInit(anything()))
1455 /// for (int x : a) { }
1457 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1459 const Expr *const Init = Node.getRangeInit();
1460 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1463 /// \brief Matches while statements.
1470 /// matches 'while (true) {}'.
1471 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1473 /// \brief Matches do statements.
1477 /// do {} while (true);
1480 /// matches 'do {} while(true)'
1481 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1483 /// \brief Matches break statements.
1487 /// while (true) { break; }
1491 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1493 /// \brief Matches continue statements.
1497 /// while (true) { continue; }
1500 /// matches 'continue'
1501 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1503 /// \brief Matches return statements.
1510 /// matches 'return 1'
1511 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1513 /// \brief Matches goto statements.
1521 /// matches 'goto FOO'
1522 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1524 /// \brief Matches label statements.
1533 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1535 /// \brief Matches address of label statements (GNU extension).
1540 /// void *ptr = &&FOO;
1545 const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr;
1547 /// \brief Matches switch statements.
1551 /// switch(a) { case 42: break; default: break; }
1554 /// matches 'switch(a)'.
1555 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1557 /// \brief Matches case and default statements inside switch statements.
1561 /// switch(a) { case 42: break; default: break; }
1564 /// matches 'case 42: break;' and 'default: break;'.
1565 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1567 /// \brief Matches case statements inside switch statements.
1571 /// switch(a) { case 42: break; default: break; }
1574 /// matches 'case 42: break;'.
1575 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1577 /// \brief Matches default statements inside switch statements.
1581 /// switch(a) { case 42: break; default: break; }
1584 /// matches 'default: break;'.
1585 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1587 /// \brief Matches compound statements.
1589 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1593 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1595 /// \brief Matches catch statements.
1598 /// try {} catch(int i) {}
1601 /// matches 'catch(int i)'
1602 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1604 /// \brief Matches try statements.
1607 /// try {} catch(int i) {}
1610 /// matches 'try {}'
1611 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1613 /// \brief Matches throw expressions.
1616 /// try { throw 5; } catch(int i) {}
1619 /// matches 'throw 5'
1620 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1622 /// \brief Matches null statements.
1628 /// matches the second ';'
1629 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1631 /// \brief Matches asm statements.
1635 /// __asm("mov al, 2");
1638 /// matches '__asm("mov al, 2")'
1639 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1641 /// \brief Matches bool literals.
1643 /// Example matches true
1647 const internal::VariadicDynCastAllOfMatcher<
1649 CXXBoolLiteralExpr> cxxBoolLiteral;
1651 /// \brief Matches string literals (also matches wide string literals).
1653 /// Example matches "abcd", L"abcd"
1655 /// char *s = "abcd";
1656 /// wchar_t *ws = L"abcd";
1658 const internal::VariadicDynCastAllOfMatcher<
1660 StringLiteral> stringLiteral;
1662 /// \brief Matches character literals (also matches wchar_t).
1664 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1667 /// Example matches 'a', L'a'
1670 /// wchar_t chw = L'a';
1672 const internal::VariadicDynCastAllOfMatcher<
1674 CharacterLiteral> characterLiteral;
1676 /// \brief Matches integer literals of all sizes / encodings, e.g.
1677 /// 1, 1L, 0x1 and 1U.
1679 /// Does not match character-encoded integers such as L'a'.
1680 const internal::VariadicDynCastAllOfMatcher<
1682 IntegerLiteral> integerLiteral;
1684 /// \brief Matches float literals of all sizes / encodings, e.g.
1685 /// 1.0, 1.0f, 1.0L and 1e10.
1687 /// Does not match implicit conversions such as
1691 const internal::VariadicDynCastAllOfMatcher<
1693 FloatingLiteral> floatLiteral;
1695 /// \brief Matches user defined literal operator call.
1697 /// Example match: "foo"_suffix
1698 const internal::VariadicDynCastAllOfMatcher<
1700 UserDefinedLiteral> userDefinedLiteral;
1702 /// \brief Matches compound (i.e. non-scalar) literals
1704 /// Example match: {1}, (1, 2)
1706 /// int array[4] = {1};
1707 /// vector int myvec = (vector int)(1, 2);
1709 const internal::VariadicDynCastAllOfMatcher<
1711 CompoundLiteralExpr> compoundLiteralExpr;
1713 /// \brief Matches nullptr literal.
1714 const internal::VariadicDynCastAllOfMatcher<
1716 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1718 /// \brief Matches GNU __null expression.
1719 const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr;
1721 /// \brief Matches atomic builtins.
1722 /// Example matches __atomic_load_n(ptr, 1)
1724 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
1726 const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
1728 /// \brief Matches statement expression (GNU extension).
1730 /// Example match: ({ int X = 4; X; })
1732 /// int C = ({ int X = 4; X; });
1734 const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
1736 /// \brief Matches binary operator expressions.
1738 /// Example matches a || b
1742 const internal::VariadicDynCastAllOfMatcher<
1744 BinaryOperator> binaryOperator;
1746 /// \brief Matches unary operator expressions.
1748 /// Example matches !a
1752 const internal::VariadicDynCastAllOfMatcher<
1754 UnaryOperator> unaryOperator;
1756 /// \brief Matches conditional operator expressions.
1758 /// Example matches a ? b : c
1760 /// (a ? b : c) + 42
1762 const internal::VariadicDynCastAllOfMatcher<
1764 ConditionalOperator> conditionalOperator;
1766 /// \brief Matches binary conditional operator expressions (GNU extension).
1768 /// Example matches a ?: b
1772 const internal::VariadicDynCastAllOfMatcher<
1774 BinaryConditionalOperator> binaryConditionalOperator;
1776 /// \brief Matches opaque value expressions. They are used as helpers
1777 /// to reference another expressions and can be met
1778 /// in BinaryConditionalOperators, for example.
1780 /// Example matches 'a'
1784 const internal::VariadicDynCastAllOfMatcher<
1786 OpaqueValueExpr> opaqueValueExpr;
1788 /// \brief Matches a C++ static_assert declaration.
1791 /// staticAssertExpr()
1793 /// static_assert(sizeof(S) == sizeof(int))
1799 /// static_assert(sizeof(S) == sizeof(int));
1801 const internal::VariadicDynCastAllOfMatcher<
1803 StaticAssertDecl> staticAssertDecl;
1805 /// \brief Matches a reinterpret_cast expression.
1807 /// Either the source expression or the destination type can be matched
1808 /// using has(), but hasDestinationType() is more specific and can be
1811 /// Example matches reinterpret_cast<char*>(&p) in
1813 /// void* p = reinterpret_cast<char*>(&p);
1815 const internal::VariadicDynCastAllOfMatcher<
1817 CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1819 /// \brief Matches a C++ static_cast expression.
1821 /// \see hasDestinationType
1822 /// \see reinterpretCast
1825 /// cxxStaticCastExpr()
1827 /// static_cast<long>(8)
1830 /// long eight(static_cast<long>(8));
1832 const internal::VariadicDynCastAllOfMatcher<
1834 CXXStaticCastExpr> cxxStaticCastExpr;
1836 /// \brief Matches a dynamic_cast expression.
1839 /// cxxDynamicCastExpr()
1841 /// dynamic_cast<D*>(&b);
1844 /// struct B { virtual ~B() {} }; struct D : B {};
1846 /// D* p = dynamic_cast<D*>(&b);
1848 const internal::VariadicDynCastAllOfMatcher<
1850 CXXDynamicCastExpr> cxxDynamicCastExpr;
1852 /// \brief Matches a const_cast expression.
1854 /// Example: Matches const_cast<int*>(&r) in
1857 /// const int &r(n);
1858 /// int* p = const_cast<int*>(&r);
1860 const internal::VariadicDynCastAllOfMatcher<
1862 CXXConstCastExpr> cxxConstCastExpr;
1864 /// \brief Matches a C-style cast expression.
1866 /// Example: Matches (int*) 2.2f in
1868 /// int i = (int) 2.2f;
1870 const internal::VariadicDynCastAllOfMatcher<
1872 CStyleCastExpr> cStyleCastExpr;
1874 /// \brief Matches explicit cast expressions.
1876 /// Matches any cast expression written in user code, whether it be a
1877 /// C-style cast, a functional-style cast, or a keyword cast.
1879 /// Does not match implicit conversions.
1881 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1882 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1883 /// actual cast expressions.
1885 /// \see hasDestinationType.
1887 /// Example: matches all five of the casts in
1889 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1891 /// but does not match the implicit conversion in
1895 const internal::VariadicDynCastAllOfMatcher<
1897 ExplicitCastExpr> explicitCastExpr;
1899 /// \brief Matches the implicit cast nodes of Clang's AST.
1901 /// This matches many different places, including function call return value
1902 /// eliding, as well as any type conversions.
1903 const internal::VariadicDynCastAllOfMatcher<
1905 ImplicitCastExpr> implicitCastExpr;
1907 /// \brief Matches any cast nodes of Clang's AST.
1909 /// Example: castExpr() matches each of the following:
1912 /// const_cast<Expr *>(SubExpr);
1915 /// but does not match
1920 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1922 /// \brief Matches functional cast expressions
1924 /// Example: Matches Foo(bar);
1927 /// Foo g = (Foo) bar;
1928 /// Foo h = Foo(bar);
1930 const internal::VariadicDynCastAllOfMatcher<
1932 CXXFunctionalCastExpr> cxxFunctionalCastExpr;
1934 /// \brief Matches functional cast expressions having N != 1 arguments
1936 /// Example: Matches Foo(bar, bar)
1938 /// Foo h = Foo(bar, bar);
1940 const internal::VariadicDynCastAllOfMatcher<
1942 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
1944 /// \brief Matches predefined identifier expressions [C99 6.4.2.2].
1946 /// Example: Matches __func__
1948 /// printf("%s", __func__);
1950 const internal::VariadicDynCastAllOfMatcher<
1952 PredefinedExpr> predefinedExpr;
1954 /// \brief Matches C99 designated initializer expressions [C99 6.7.8].
1956 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
1958 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
1960 const internal::VariadicDynCastAllOfMatcher<
1962 DesignatedInitExpr> designatedInitExpr;
1964 /// \brief Matches designated initializer expressions that contain
1965 /// a specific number of designators.
1969 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
1970 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
1972 /// designatorCountIs(2)
1973 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
1974 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
1975 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
1976 return Node.size() == N;
1979 /// \brief Matches \c QualTypes in the clang AST.
1980 const internal::VariadicAllOfMatcher<QualType> qualType;
1982 /// \brief Matches \c Types in the clang AST.
1983 const internal::VariadicAllOfMatcher<Type> type;
1985 /// \brief Matches \c TypeLocs in the clang AST.
1986 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1988 /// \brief Matches if any of the given matchers matches.
1990 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1991 /// matching submatcher.
1993 /// For example, in:
1995 /// class A { int a; int b; };
1999 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2000 /// has(fieldDecl(hasName("b")).bind("v"))))
2002 /// will generate two results binding "v", the first of which binds
2003 /// the field declaration of \c a, the second the field declaration of
2006 /// Usable as: Any Matcher
2007 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
2008 internal::DynTypedMatcher::VO_EachOf
2011 /// \brief Matches if any of the given matchers matches.
2013 /// Usable as: Any Matcher
2014 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
2015 internal::DynTypedMatcher::VO_AnyOf
2018 /// \brief Matches if all given matchers match.
2020 /// Usable as: Any Matcher
2021 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
2022 internal::DynTypedMatcher::VO_AllOf
2025 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2030 /// int y = sizeof(x) + alignof(x);
2032 /// unaryExprOrTypeTraitExpr()
2033 /// matches \c sizeof(x) and \c alignof(x)
2034 const internal::VariadicDynCastAllOfMatcher<
2036 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
2038 /// \brief Matches unary expressions that have a specific type of argument.
2042 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2044 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2045 /// matches \c sizeof(a) and \c alignof(c)
2046 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2047 internal::Matcher<QualType>, InnerMatcher) {
2048 const QualType ArgumentType = Node.getTypeOfArgument();
2049 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2052 /// \brief Matches unary expressions of a certain kind.
2057 /// int s = sizeof(x) + alignof(x)
2059 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2060 /// matches \c sizeof(x)
2061 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2062 return Node.getKind() == Kind;
2065 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2067 inline internal::Matcher<Stmt> alignOfExpr(
2068 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2069 return stmt(unaryExprOrTypeTraitExpr(allOf(
2070 ofKind(UETT_AlignOf), InnerMatcher)));
2073 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2075 inline internal::Matcher<Stmt> sizeOfExpr(
2076 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2077 return stmt(unaryExprOrTypeTraitExpr(
2078 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2081 /// \brief Matches NamedDecl nodes that have the specified name.
2083 /// Supports specifying enclosing namespaces or classes by prefixing the name
2084 /// with '<enclosing>::'.
2085 /// Does not match typedefs of an underlying type with the given name.
2087 /// Example matches X (Name == "X")
2092 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2094 /// namespace a { namespace b { class X; } }
2096 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2097 std::vector<std::string> Names;
2098 Names.push_back(Name);
2099 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
2102 /// \brief Matches NamedDecl nodes that have any of the specified names.
2104 /// This matcher is only provided as a performance optimization of hasName.
2106 /// hasAnyName(a, b, c)
2108 /// is equivalent to, but faster than
2110 /// anyOf(hasName(a), hasName(b), hasName(c))
2112 const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2113 internal::hasAnyNameFunc>
2116 /// \brief Matches NamedDecl nodes whose fully qualified names contain
2117 /// a substring matched by the given RegExp.
2119 /// Supports specifying enclosing namespaces or classes by
2120 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2121 /// of an underlying type with the given name.
2123 /// Example matches X (regexp == "::X")
2128 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2130 /// namespace foo { namespace bar { class X; } }
2132 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2133 assert(!RegExp.empty());
2134 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2135 llvm::Regex RE(RegExp);
2136 return RE.match(FullNameString);
2139 /// \brief Matches overloaded operator names.
2141 /// Matches overloaded operator names specified in strings without the
2142 /// "operator" prefix: e.g. "<<".
2146 /// class A { int operator*(); };
2147 /// const A &operator<<(const A &a, const A &b);
2149 /// a << a; // <-- This matches
2152 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2153 /// specified line and
2154 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2155 /// matches the declaration of \c A.
2157 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2158 inline internal::PolymorphicMatcherWithParam1<
2159 internal::HasOverloadedOperatorNameMatcher, StringRef,
2160 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2161 hasOverloadedOperatorName(StringRef Name) {
2162 return internal::PolymorphicMatcherWithParam1<
2163 internal::HasOverloadedOperatorNameMatcher, StringRef,
2164 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2167 /// \brief Matches C++ classes that are directly or indirectly derived from
2168 /// a class matching \c Base.
2170 /// Note that a class is not considered to be derived from itself.
2172 /// Example matches Y, Z, C (Base == hasName("X"))
2175 /// class Y : public X {}; // directly derived
2176 /// class Z : public Y {}; // indirectly derived
2179 /// class C : public B {}; // derived from a typedef of X
2182 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2186 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2188 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2189 internal::Matcher<NamedDecl>, Base) {
2190 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2193 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2194 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2195 assert(!BaseName.empty());
2196 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2199 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
2201 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2202 internal::Matcher<NamedDecl>, Base, 0) {
2203 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2204 .matches(Node, Finder, Builder);
2207 /// \brief Overloaded method as shortcut for
2208 /// \c isSameOrDerivedFrom(hasName(...)).
2209 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2211 assert(!BaseName.empty());
2212 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2215 /// \brief Matches the first method of a class or struct that satisfies \c
2220 /// class A { void func(); };
2221 /// class B { void member(); };
2224 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2225 /// \c A but not \c B.
2226 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2228 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2229 Node.method_end(), Finder, Builder);
2232 /// \brief Matches the generated class of lambda expressions.
2239 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2241 AST_MATCHER(CXXRecordDecl, isLambda) {
2242 return Node.isLambda();
2245 /// \brief Matches AST nodes that have child AST nodes that match the
2246 /// provided matcher.
2248 /// Example matches X, Y
2249 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2251 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2252 /// class Y { class X {}; };
2253 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2256 /// ChildT must be an AST base type.
2258 /// Usable as: Any Matcher
2259 /// Note that has is direct matcher, so it also matches things like implicit
2260 /// casts and paren casts. If you are matching with expr then you should
2261 /// probably consider using ignoringParenImpCasts like:
2262 /// has(ignoringParenImpCasts(expr())).
2263 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
2264 LLVM_ATTRIBUTE_UNUSED has = {};
2266 /// \brief Matches AST nodes that have descendant AST nodes that match the
2267 /// provided matcher.
2269 /// Example matches X, Y, Z
2270 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2272 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2273 /// class Y { class X {}; };
2274 /// class Z { class Y { class X {}; }; };
2277 /// DescendantT must be an AST base type.
2279 /// Usable as: Any Matcher
2280 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
2281 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
2283 /// \brief Matches AST nodes that have child AST nodes that match the
2284 /// provided matcher.
2286 /// Example matches X, Y
2287 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2289 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2290 /// class Y { class X {}; };
2291 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2294 /// ChildT must be an AST base type.
2296 /// As opposed to 'has', 'forEach' will cause a match for each result that
2297 /// matches instead of only on the first one.
2299 /// Usable as: Any Matcher
2300 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2301 LLVM_ATTRIBUTE_UNUSED forEach = {};
2303 /// \brief Matches AST nodes that have descendant AST nodes that match the
2304 /// provided matcher.
2306 /// Example matches X, A, B, C
2307 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2309 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2310 /// class A { class X {}; };
2311 /// class B { class C { class X {}; }; };
2314 /// DescendantT must be an AST base type.
2316 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2317 /// each result that matches instead of only on the first one.
2319 /// Note: Recursively combined ForEachDescendant can cause many matches:
2320 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2321 /// forEachDescendant(cxxRecordDecl())
2323 /// will match 10 times (plus injected class name matches) on:
2325 /// class A { class B { class C { class D { class E {}; }; }; }; };
2328 /// Usable as: Any Matcher
2329 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2330 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2332 /// \brief Matches if the node or any descendant matches.
2334 /// Generates results for each match.
2336 /// For example, in:
2338 /// class A { class B {}; class C {}; };
2342 /// cxxRecordDecl(hasName("::A"),
2343 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2345 /// will generate results for \c A, \c B and \c C.
2347 /// Usable as: Any Matcher
2348 template <typename T>
2349 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2350 return eachOf(Matcher, forEachDescendant(Matcher));
2353 /// \brief Matches AST nodes that have a parent that matches the provided
2358 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2360 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2362 /// Usable as: Any Matcher
2363 const internal::ArgumentAdaptingMatcherFunc<
2364 internal::HasParentMatcher,
2365 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2366 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2367 LLVM_ATTRIBUTE_UNUSED hasParent = {};
2369 /// \brief Matches AST nodes that have an ancestor that matches the provided
2374 /// void f() { if (true) { int x = 42; } }
2375 /// void g() { for (;;) { int x = 43; } }
2377 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2379 /// Usable as: Any Matcher
2380 const internal::ArgumentAdaptingMatcherFunc<
2381 internal::HasAncestorMatcher,
2382 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2383 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2384 LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2386 /// \brief Matches if the provided matcher does not match.
2388 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2394 /// Usable as: Any Matcher
2395 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2396 internal::DynTypedMatcher::VO_UnaryNot
2399 /// \brief Matches a node if the declaration associated with that node
2400 /// matches the given matcher.
2402 /// The associated declaration is:
2403 /// - for type nodes, the declaration of the underlying type
2404 /// - for CallExpr, the declaration of the callee
2405 /// - for MemberExpr, the declaration of the referenced member
2406 /// - for CXXConstructExpr, the declaration of the constructor
2408 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2409 /// function. e.g. various subtypes of clang::Type and various expressions.
2411 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
2412 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
2413 /// Matcher<LabelStmt>, Matcher<AddrLabelExpr>, Matcher<MemberExpr>,
2414 /// Matcher<QualType>, Matcher<RecordType>, Matcher<TagType>,
2415 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
2416 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
2417 inline internal::PolymorphicMatcherWithParam1<
2418 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2419 void(internal::HasDeclarationSupportedTypes)>
2420 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2421 return internal::PolymorphicMatcherWithParam1<
2422 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2423 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2426 /// \brief Matches on the implicit object argument of a member call expression.
2428 /// Example matches y.x()
2429 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2431 /// class Y { public: void x(); };
2432 /// void z() { Y y; y.x(); }",
2435 /// FIXME: Overload to allow directly matching types?
2436 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2438 const Expr *ExprNode = Node.getImplicitObjectArgument()
2439 ->IgnoreParenImpCasts();
2440 return (ExprNode != nullptr &&
2441 InnerMatcher.matches(*ExprNode, Finder, Builder));
2445 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2448 /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *")));
2449 /// matches the [webView ...] message invocation.
2451 /// NSString *webViewJavaScript = ...
2452 /// UIWebView *webView = ...
2453 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2455 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2457 const QualType TypeDecl = Node.getReceiverType();
2458 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2461 /// \brief Matches when BaseName == Selector.getAsString()
2463 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2464 /// matches the outer message expr in the code below, but NOT the message
2465 /// invocation for self.bodyView.
2467 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2469 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2470 Selector Sel = Node.getSelector();
2471 return BaseName.compare(Sel.getAsString()) == 0;
2475 /// \brief Matches ObjC selectors whose name contains
2476 /// a substring matched by the given RegExp.
2477 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2478 /// matches the outer message expr in the code below, but NOT the message
2479 /// invocation for self.bodyView.
2481 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2483 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2484 assert(!RegExp.empty());
2485 std::string SelectorString = Node.getSelector().getAsString();
2486 llvm::Regex RE(RegExp);
2487 return RE.match(SelectorString);
2490 /// \brief Matches when the selector is the empty selector
2492 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2493 /// represent an error condition in the tree!
2494 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2495 return Node.getSelector().isNull();
2498 /// \brief Matches when the selector is a Unary Selector
2500 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2501 /// matches self.bodyView in the code below, but NOT the outer message
2502 /// invocation of "loadHTMLString:baseURL:".
2504 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2506 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2507 return Node.getSelector().isUnarySelector();
2510 /// \brief Matches when the selector is a keyword selector
2512 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2513 /// message expression in
2516 /// UIWebView *webView = ...;
2517 /// CGRect bodyFrame = webView.frame;
2518 /// bodyFrame.size.height = self.bodyContentHeight;
2519 /// webView.frame = bodyFrame;
2520 /// // ^---- matches here
2522 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2523 return Node.getSelector().isKeywordSelector();
2526 /// \brief Matches when the selector has the specified number of arguments
2528 /// matcher = objCMessageExpr(numSelectorArgs(0));
2529 /// matches self.bodyView in the code below
2531 /// matcher = objCMessageExpr(numSelectorArgs(2));
2532 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2533 /// of self.bodyView
2535 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2537 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2538 return Node.getSelector().getNumArgs() == N;
2541 /// \brief Matches if the call expression's callee expression matches.
2545 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2546 /// void f() { f(); }
2548 /// callExpr(callee(expr()))
2549 /// matches this->x(), x(), y.x(), f()
2550 /// with callee(...)
2551 /// matching this->x, x, y.x, f respectively
2553 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2554 /// because this introduces ambiguous overloads with calls to Callee taking a
2555 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2556 /// implemented in terms of implicit casts.
2557 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2559 const Expr *ExprNode = Node.getCallee();
2560 return (ExprNode != nullptr &&
2561 InnerMatcher.matches(*ExprNode, Finder, Builder));
2564 /// \brief Matches if the call expression's callee's declaration matches the
2567 /// Example matches y.x() (matcher = callExpr(callee(
2568 /// cxxMethodDecl(hasName("x")))))
2570 /// class Y { public: void x(); };
2571 /// void z() { Y y; y.x(); }
2573 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2575 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2578 /// \brief Matches if the expression's or declaration's type matches a type
2581 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2582 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2583 /// and U (matcher = typedefDecl(hasType(asString("int")))
2586 /// void y(X &x) { x; X z; }
2589 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2590 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefNameDecl, ValueDecl),
2591 internal::Matcher<QualType>, InnerMatcher, 0) {
2592 return InnerMatcher.matches(internal::getUnderlyingType(Node),
2596 /// \brief Overloaded to match the declaration of the expression's or value
2597 /// declaration's type.
2599 /// In case of a value declaration (for example a variable declaration),
2600 /// this resolves one layer of indirection. For example, in the value
2601 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2602 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2603 /// declaration of x.
2605 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2606 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2609 /// void y(X &x) { x; X z; }
2612 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2613 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2614 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2616 internal::Matcher<Decl>, InnerMatcher, 1) {
2617 return qualType(hasDeclaration(InnerMatcher))
2618 .matches(Node.getType(), Finder, Builder);
2621 /// \brief Matches if the type location of the declarator decl's type matches
2622 /// the inner matcher.
2628 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2630 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2631 if (!Node.getTypeSourceInfo())
2632 // This happens for example for implicit destructors.
2634 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2637 /// \brief Matches if the matched type is represented by the given string.
2641 /// class Y { public: void x(); };
2642 /// void z() { Y* y; y->x(); }
2644 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2646 AST_MATCHER_P(QualType, asString, std::string, Name) {
2647 return Name == Node.getAsString();
2650 /// \brief Matches if the matched type is a pointer type and the pointee type
2651 /// matches the specified matcher.
2653 /// Example matches y->x()
2654 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2655 /// cxxRecordDecl(hasName("Y")))))))
2657 /// class Y { public: void x(); };
2658 /// void z() { Y *y; y->x(); }
2661 QualType, pointsTo, internal::Matcher<QualType>,
2663 return (!Node.isNull() && Node->isAnyPointerType() &&
2664 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2667 /// \brief Overloaded to match the pointee type's declaration.
2668 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2670 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2671 .matches(Node, Finder, Builder);
2674 /// \brief Matches if the matched type is a reference type and the referenced
2675 /// type matches the specified matcher.
2677 /// Example matches X &x and const X &y
2678 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2687 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2689 return (!Node.isNull() && Node->isReferenceType() &&
2690 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2693 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2697 /// typedef int &int_ref;
2702 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2703 /// declaration of b but \c
2704 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2705 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2709 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2712 /// \brief Overloaded to match the referenced type's declaration.
2713 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2715 return references(qualType(hasDeclaration(InnerMatcher)))
2716 .matches(Node, Finder, Builder);
2719 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2720 internal::Matcher<Expr>, InnerMatcher) {
2721 const Expr *ExprNode = Node.getImplicitObjectArgument();
2722 return (ExprNode != nullptr &&
2723 InnerMatcher.matches(*ExprNode, Finder, Builder));
2726 /// \brief Matches if the expression's type either matches the specified
2727 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2728 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2729 internal::Matcher<QualType>, InnerMatcher, 0) {
2730 return onImplicitObjectArgument(
2731 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2732 .matches(Node, Finder, Builder);
2735 /// \brief Overloaded to match the type's declaration.
2736 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2737 internal::Matcher<Decl>, InnerMatcher, 1) {
2738 return onImplicitObjectArgument(
2739 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2740 .matches(Node, Finder, Builder);
2743 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2744 /// specified matcher.
2746 /// Example matches x in if(x)
2747 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2752 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2754 const Decl *DeclNode = Node.getDecl();
2755 return (DeclNode != nullptr &&
2756 InnerMatcher.matches(*DeclNode, Finder, Builder));
2759 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2760 /// specific using shadow declaration.
2764 /// namespace a { void f() {} }
2767 /// f(); // Matches this ..
2768 /// a::f(); // .. but not this.
2771 /// declRefExpr(throughUsingDecl(anything()))
2773 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2774 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2775 const NamedDecl *FoundDecl = Node.getFoundDecl();
2776 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2777 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2781 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2788 /// declStmt(hasSingleDecl(anything()))
2789 /// matches 'int c;' but not 'int a, b;'.
2790 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2791 if (Node.isSingleDecl()) {
2792 const Decl *FoundDecl = Node.getSingleDecl();
2793 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2798 /// \brief Matches a variable declaration that has an initializer expression
2799 /// that matches the given matcher.
2801 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2803 /// bool y() { return true; }
2807 VarDecl, hasInitializer, internal::Matcher<Expr>,
2809 const Expr *Initializer = Node.getAnyInitializer();
2810 return (Initializer != nullptr &&
2811 InnerMatcher.matches(*Initializer, Finder, Builder));
2814 /// \brief Matches a variable declaration that has function scope and is a
2815 /// non-static local variable.
2817 /// Example matches x (matcher = varDecl(hasLocalStorage())
2825 AST_MATCHER(VarDecl, hasLocalStorage) {
2826 return Node.hasLocalStorage();
2829 /// \brief Matches a variable declaration that does not have local storage.
2831 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2839 AST_MATCHER(VarDecl, hasGlobalStorage) {
2840 return Node.hasGlobalStorage();
2843 /// \brief Matches a variable declaration that has automatic storage duration.
2845 /// Example matches x, but not y, z, or a.
2846 /// (matcher = varDecl(hasAutomaticStorageDuration())
2851 /// thread_local int z;
2855 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
2856 return Node.getStorageDuration() == SD_Automatic;
2859 /// \brief Matches a variable declaration that has static storage duration.
2861 /// Example matches y and a, but not x or z.
2862 /// (matcher = varDecl(hasStaticStorageDuration())
2867 /// thread_local int z;
2871 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
2872 return Node.getStorageDuration() == SD_Static;
2875 /// \brief Matches a variable declaration that has thread storage duration.
2877 /// Example matches z, but not x, z, or a.
2878 /// (matcher = varDecl(hasThreadStorageDuration())
2883 /// thread_local int z;
2887 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
2888 return Node.getStorageDuration() == SD_Thread;
2891 /// \brief Matches a variable declaration that is an exception variable from
2892 /// a C++ catch block, or an Objective-C \@catch statement.
2894 /// Example matches x (matcher = varDecl(isExceptionVariable())
2898 /// } catch (int x) {
2902 AST_MATCHER(VarDecl, isExceptionVariable) {
2903 return Node.isExceptionVariable();
2906 /// \brief Checks that a call expression or a constructor call expression has
2907 /// a specific number of arguments (including absent default arguments).
2909 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2911 /// void f(int x, int y);
2914 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
2915 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2919 return Node.getNumArgs() == N;
2922 /// \brief Matches the n'th argument of a call expression or a constructor
2923 /// call expression.
2925 /// Example matches y in x(y)
2926 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2928 /// void x(int) { int y; x(y); }
2930 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
2931 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2934 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2935 return (N < Node.getNumArgs() &&
2936 InnerMatcher.matches(
2937 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2940 /// \brief Matches declaration statements that contain a specific number of
2950 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2951 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2952 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2955 /// \brief Matches the n'th declaration of a declaration statement.
2957 /// Note that this does not work for global declarations because the AST
2958 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2960 /// Example: Given non-global declarations
2966 /// declStmt(containsDeclaration(
2967 /// 0, varDecl(hasInitializer(anything()))))
2968 /// matches only 'int d = 2, e;', and
2969 /// declStmt(containsDeclaration(1, varDecl()))
2971 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2972 /// but 'int c;' is not matched.
2974 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2975 internal::Matcher<Decl>, InnerMatcher) {
2976 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2979 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2980 std::advance(Iterator, N);
2981 return InnerMatcher.matches(**Iterator, Finder, Builder);
2984 /// \brief Matches a C++ catch statement that has a catch-all handler.
2996 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
2997 AST_MATCHER(CXXCatchStmt, isCatchAll) {
2998 return Node.getExceptionDecl() == nullptr;
3001 /// \brief Matches a constructor initializer.
3006 /// Foo() : foo_(1) { }
3010 /// cxxRecordDecl(has(cxxConstructorDecl(
3011 /// hasAnyConstructorInitializer(anything())
3013 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3014 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3015 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3016 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3017 Node.init_end(), Finder, Builder);
3020 /// \brief Matches the field declaration of a constructor initializer.
3025 /// Foo() : foo_(1) { }
3029 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3030 /// forField(hasName("foo_"))))))
3032 /// with forField matching foo_
3033 AST_MATCHER_P(CXXCtorInitializer, forField,
3034 internal::Matcher<FieldDecl>, InnerMatcher) {
3035 const FieldDecl *NodeAsDecl = Node.getMember();
3036 return (NodeAsDecl != nullptr &&
3037 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3040 /// \brief Matches the initializer expression of a constructor initializer.
3045 /// Foo() : foo_(1) { }
3049 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3050 /// withInitializer(integerLiteral(equals(1)))))))
3052 /// with withInitializer matching (1)
3053 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3054 internal::Matcher<Expr>, InnerMatcher) {
3055 const Expr* NodeAsExpr = Node.getInit();
3056 return (NodeAsExpr != nullptr &&
3057 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3060 /// \brief Matches a constructor initializer if it is explicitly written in
3061 /// code (as opposed to implicitly added by the compiler).
3067 /// Foo(int) : foo_("A") { }
3071 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3072 /// will match Foo(int), but not Foo()
3073 AST_MATCHER(CXXCtorInitializer, isWritten) {
3074 return Node.isWritten();
3077 /// \brief Matches a constructor initializer if it is initializing a base, as
3078 /// opposed to a member.
3085 /// D(int i) : I(i) {}
3091 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3092 /// will match E(), but not match D(int).
3093 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3094 return Node.isBaseInitializer();
3097 /// \brief Matches a constructor initializer if it is initializing a member, as
3098 /// opposed to a base.
3105 /// D(int i) : I(i) {}
3111 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3112 /// will match D(int), but not match E().
3113 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3114 return Node.isMemberInitializer();
3117 /// \brief Matches any argument of a call expression or a constructor call
3122 /// void x(int, int, int) { int y; x(1, y, 42); }
3124 /// callExpr(hasAnyArgument(declRefExpr()))
3125 /// matches x(1, y, 42)
3126 /// with hasAnyArgument(...)
3128 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3129 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3131 internal::Matcher<Expr>, InnerMatcher) {
3132 for (const Expr *Arg : Node.arguments()) {
3133 BoundNodesTreeBuilder Result(*Builder);
3134 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3135 *Builder = std::move(Result);
3142 /// \brief Matches a constructor call expression which uses list initialization.
3143 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3144 return Node.isListInitialization();
3147 /// \brief Matches a constructor call expression which requires
3148 /// zero initialization.
3153 /// struct point { double x; double y; };
3154 /// point pt[2] = { { 1.0, 2.0 } };
3157 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3158 /// will match the implicit array filler for pt[1].
3159 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3160 return Node.requiresZeroInitialization();
3163 /// \brief Matches the n'th parameter of a function declaration.
3167 /// class X { void f(int x) {} };
3169 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3170 /// matches f(int x) {}
3171 /// with hasParameter(...)
3173 AST_MATCHER_P2(FunctionDecl, hasParameter,
3174 unsigned, N, internal::Matcher<ParmVarDecl>,
3176 return (N < Node.getNumParams() &&
3177 InnerMatcher.matches(
3178 *Node.getParamDecl(N), Finder, Builder));
3181 /// \brief Matches all arguments and their respective ParmVarDecl.
3190 /// forEachArgumentWithParam(
3191 /// declRefExpr(to(varDecl(hasName("y")))),
3192 /// parmVarDecl(hasType(isInteger()))
3195 /// with declRefExpr(...)
3197 /// and parmVarDecl(...)
3199 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3200 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3202 internal::Matcher<Expr>, ArgMatcher,
3203 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3204 BoundNodesTreeBuilder Result;
3205 // The first argument of an overloaded member operator is the implicit object
3206 // argument of the method which should not be matched against a parameter, so
3207 // we skip over it here.
3208 BoundNodesTreeBuilder Matches;
3209 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3210 .matches(Node, Finder, &Matches)
3214 bool Matched = false;
3215 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3216 BoundNodesTreeBuilder ArgMatches(*Builder);
3217 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3218 Finder, &ArgMatches)) {
3219 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3220 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3221 hasParameter(ParamIndex, ParamMatcher)))),
3222 callExpr(callee(functionDecl(
3223 hasParameter(ParamIndex, ParamMatcher))))))
3224 .matches(Node, Finder, &ParamMatches)) {
3225 Result.addMatch(ParamMatches);
3231 *Builder = std::move(Result);
3235 /// \brief Matches any parameter of a function declaration.
3237 /// Does not match the 'this' parameter of a method.
3241 /// class X { void f(int x, int y, int z) {} };
3243 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3244 /// matches f(int x, int y, int z) {}
3245 /// with hasAnyParameter(...)
3247 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
3248 internal::Matcher<ParmVarDecl>, InnerMatcher) {
3249 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3250 Node.param_end(), Finder, Builder);
3253 /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3254 /// specific parameter count.
3258 /// void f(int i) {}
3259 /// void g(int i, int j) {}
3260 /// void h(int i, int j);
3262 /// void k(int x, int y, int z, ...);
3264 /// functionDecl(parameterCountIs(2))
3265 /// matches void g(int i, int j) {}
3266 /// functionProtoType(parameterCountIs(2))
3267 /// matches void h(int i, int j)
3268 /// functionProtoType(parameterCountIs(3))
3269 /// matches void k(int x, int y, int z, ...);
3270 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3271 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3274 return Node.getNumParams() == N;
3277 /// \brief Matches the return type of a function declaration.
3281 /// class X { int f() { return 1; } };
3283 /// cxxMethodDecl(returns(asString("int")))
3284 /// matches int f() { return 1; }
3285 AST_MATCHER_P(FunctionDecl, returns,
3286 internal::Matcher<QualType>, InnerMatcher) {
3287 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3290 /// \brief Matches extern "C" function declarations.
3294 /// extern "C" void f() {}
3295 /// extern "C" { void g() {} }
3298 /// functionDecl(isExternC())
3299 /// matches the declaration of f and g, but not the declaration h
3300 AST_MATCHER(FunctionDecl, isExternC) {
3301 return Node.isExternC();
3304 /// \brief Matches deleted function declarations.
3309 /// void DeletedFunc() = delete;
3311 /// functionDecl(isDeleted())
3312 /// matches the declaration of DeletedFunc, but not Func.
3313 AST_MATCHER(FunctionDecl, isDeleted) {
3314 return Node.isDeleted();
3317 /// \brief Matches defaulted function declarations.
3321 /// class A { ~A(); };
3322 /// class B { ~B() = default; };
3324 /// functionDecl(isDefaulted())
3325 /// matches the declaration of ~B, but not ~A.
3326 AST_MATCHER(FunctionDecl, isDefaulted) {
3327 return Node.isDefaulted();
3330 /// \brief Matches functions that have a dynamic exception specification.
3335 /// void g() noexcept;
3336 /// void h() noexcept(true);
3337 /// void i() noexcept(false);
3338 /// void j() throw();
3339 /// void k() throw(int);
3340 /// void l() throw(...);
3342 /// functionDecl(hasDynamicExceptionSpec()) and
3343 /// functionProtoType(hasDynamicExceptionSpec())
3344 /// match the declarations of j, k, and l, but not f, g, h, or i.
3345 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
3346 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3347 FunctionProtoType)) {
3348 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
3349 return FnTy->hasDynamicExceptionSpec();
3353 /// \brief Matches functions that have a non-throwing exception specification.
3358 /// void g() noexcept;
3359 /// void h() throw();
3360 /// void i() throw(int);
3361 /// void j() noexcept(false);
3363 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
3364 /// match the declarations of g, and h, but not f, i or j.
3365 AST_POLYMORPHIC_MATCHER(isNoThrow,
3366 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3367 FunctionProtoType)) {
3368 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
3370 // If the function does not have a prototype, then it is assumed to be a
3371 // throwing function (as it would if the function did not have any exception
3376 // Assume the best for any unresolved exception specification.
3377 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3380 return FnTy->isNothrow(Finder->getASTContext());
3383 /// \brief Matches constexpr variable and function declarations.
3387 /// constexpr int foo = 42;
3388 /// constexpr int bar();
3390 /// varDecl(isConstexpr())
3391 /// matches the declaration of foo.
3392 /// functionDecl(isConstexpr())
3393 /// matches the declaration of bar.
3394 AST_POLYMORPHIC_MATCHER(isConstexpr,
3395 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3397 return Node.isConstexpr();
3400 /// \brief Matches the condition expression of an if statement, for loop,
3401 /// switch statement or conditional operator.
3403 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3407 AST_POLYMORPHIC_MATCHER_P(
3409 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3410 SwitchStmt, AbstractConditionalOperator),
3411 internal::Matcher<Expr>, InnerMatcher) {
3412 const Expr *const Condition = Node.getCond();
3413 return (Condition != nullptr &&
3414 InnerMatcher.matches(*Condition, Finder, Builder));
3417 /// \brief Matches the then-statement of an if statement.
3419 /// Examples matches the if statement
3420 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3422 /// if (false) true; else false;
3424 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3425 const Stmt *const Then = Node.getThen();
3426 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3429 /// \brief Matches the else-statement of an if statement.
3431 /// Examples matches the if statement
3432 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3434 /// if (false) false; else true;
3436 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3437 const Stmt *const Else = Node.getElse();
3438 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3441 /// \brief Matches if a node equals a previously bound node.
3443 /// Matches a node if it equals the node previously bound to \p ID.
3447 /// class X { int a; int b; };
3450 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3451 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3452 /// matches the class \c X, as \c a and \c b have the same type.
3454 /// Note that when multiple matches are involved via \c forEach* matchers,
3455 /// \c equalsBoundNodes acts as a filter.
3458 /// forEachDescendant(varDecl().bind("d")),
3459 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3460 /// will trigger a match for each combination of variable declaration
3461 /// and reference to that variable declaration within a compound statement.
3462 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3463 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3466 // FIXME: Figure out whether it makes sense to allow this
3467 // on any other node types.
3468 // For *Loc it probably does not make sense, as those seem
3469 // unique. For NestedNameSepcifier it might make sense, as
3470 // those also have pointer identity, but I'm not sure whether
3471 // they're ever reused.
3472 internal::NotEqualsBoundNodePredicate Predicate;
3474 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3475 return Builder->removeBindings(Predicate);
3478 /// \brief Matches the condition variable statement in an if statement.
3482 /// if (A* a = GetAPointer()) {}
3484 /// hasConditionVariableStatement(...)
3485 /// matches 'A* a = GetAPointer()'.
3486 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3487 internal::Matcher<DeclStmt>, InnerMatcher) {
3488 const DeclStmt* const DeclarationStatement =
3489 Node.getConditionVariableDeclStmt();
3490 return DeclarationStatement != nullptr &&
3491 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3494 /// \brief Matches the index expression of an array subscript expression.
3499 /// void f() { i[1] = 42; }
3501 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3502 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3503 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3504 internal::Matcher<Expr>, InnerMatcher) {
3505 if (const Expr* Expression = Node.getIdx())
3506 return InnerMatcher.matches(*Expression, Finder, Builder);
3510 /// \brief Matches the base expression of an array subscript expression.
3515 /// void f() { i[1] = 42; }
3517 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3518 /// hasSourceExpression(declRefExpr()))))
3519 /// matches \c i[1] with the \c declRefExpr() matching \c i
3520 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3521 internal::Matcher<Expr>, InnerMatcher) {
3522 if (const Expr* Expression = Node.getBase())
3523 return InnerMatcher.matches(*Expression, Finder, Builder);
3527 /// \brief Matches a 'for', 'while', 'do while' statement or a function
3528 /// definition that has a given body.
3534 /// hasBody(compoundStmt())
3535 /// matches 'for (;;) {}'
3536 /// with compoundStmt()
3538 AST_POLYMORPHIC_MATCHER_P(hasBody,
3539 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3543 internal::Matcher<Stmt>, InnerMatcher) {
3544 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
3545 return (Statement != nullptr &&
3546 InnerMatcher.matches(*Statement, Finder, Builder));
3549 /// \brief Matches compound statements where at least one substatement matches
3550 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
3556 /// hasAnySubstatement(compoundStmt())
3557 /// matches '{ {}; 1+2; }'
3558 /// with compoundStmt()
3560 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
3561 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
3563 internal::Matcher<Stmt>, InnerMatcher) {
3564 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
3565 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
3566 CS->body_end(), Finder, Builder);
3569 /// \brief Checks that a compound statement contains a specific number of
3570 /// child statements.
3576 /// compoundStmt(statementCountIs(0)))
3578 /// but does not match the outer compound statement.
3579 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3580 return Node.size() == N;
3583 /// \brief Matches literals that are equal to the given value.
3585 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3590 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3591 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3592 template <typename ValueT>
3593 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3594 equals(const ValueT &Value) {
3595 return internal::PolymorphicMatcherWithParam1<
3596 internal::ValueEqualsMatcher,
3600 /// \brief Matches the operator Name of operator expressions (binary or
3603 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3607 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3608 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3610 std::string, Name) {
3611 return Name == Node.getOpcodeStr(Node.getOpcode());
3614 /// \brief Matches the left hand side of binary operator expressions.
3616 /// Example matches a (matcher = binaryOperator(hasLHS()))
3620 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3621 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3622 ArraySubscriptExpr),
3623 internal::Matcher<Expr>, InnerMatcher) {
3624 const Expr *LeftHandSide = Node.getLHS();
3625 return (LeftHandSide != nullptr &&
3626 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3629 /// \brief Matches the right hand side of binary operator expressions.
3631 /// Example matches b (matcher = binaryOperator(hasRHS()))
3635 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3636 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3637 ArraySubscriptExpr),
3638 internal::Matcher<Expr>, InnerMatcher) {
3639 const Expr *RightHandSide = Node.getRHS();
3640 return (RightHandSide != nullptr &&
3641 InnerMatcher.matches(*RightHandSide, Finder, Builder));
3644 /// \brief Matches if either the left hand side or the right hand side of a
3645 /// binary operator matches.
3646 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3647 const internal::Matcher<Expr> &InnerMatcher) {
3648 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3651 /// \brief Matches if the operand of a unary operator matches.
3653 /// Example matches true (matcher = hasUnaryOperand(
3654 /// cxxBoolLiteral(equals(true))))
3658 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3659 internal::Matcher<Expr>, InnerMatcher) {
3660 const Expr * const Operand = Node.getSubExpr();
3661 return (Operand != nullptr &&
3662 InnerMatcher.matches(*Operand, Finder, Builder));
3665 /// \brief Matches if the cast's source expression
3666 /// or opaque value's source expression matches the given matcher.
3668 /// Example 1: matches "a string"
3669 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
3671 /// class URL { URL(string); };
3672 /// URL url = "a string";
3675 /// Example 2: matches 'b' (matcher =
3676 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
3681 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
3682 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
3684 internal::Matcher<Expr>, InnerMatcher) {
3685 const Expr *const SubExpression =
3686 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
3687 return (SubExpression != nullptr &&
3688 InnerMatcher.matches(*SubExpression, Finder, Builder));
3691 /// \brief Matches casts that has a given cast kind.
3693 /// Example: matches the implicit cast around \c 0
3694 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
3698 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
3699 return Node.getCastKind() == Kind;
3702 /// \brief Matches casts whose destination type matches a given matcher.
3704 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3705 /// actual casts "explicit" casts.)
3706 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3707 internal::Matcher<QualType>, InnerMatcher) {
3708 const QualType NodeType = Node.getTypeAsWritten();
3709 return InnerMatcher.matches(NodeType, Finder, Builder);
3712 /// \brief Matches implicit casts whose destination type matches a given
3715 /// FIXME: Unit test this matcher
3716 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3717 internal::Matcher<QualType>, InnerMatcher) {
3718 return InnerMatcher.matches(Node.getType(), Finder, Builder);
3721 /// \brief Matches RecordDecl object that are spelled with "struct."
3723 /// Example matches S, but not C or U.
3729 AST_MATCHER(RecordDecl, isStruct) {
3730 return Node.isStruct();
3733 /// \brief Matches RecordDecl object that are spelled with "union."
3735 /// Example matches U, but not C or S.
3741 AST_MATCHER(RecordDecl, isUnion) {
3742 return Node.isUnion();
3745 /// \brief Matches RecordDecl object that are spelled with "class."
3747 /// Example matches C, but not S or U.
3753 AST_MATCHER(RecordDecl, isClass) {
3754 return Node.isClass();
3757 /// \brief Matches the true branch expression of a conditional operator.
3759 /// Example 1 (conditional ternary operator): matches a
3761 /// condition ? a : b
3764 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
3768 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
3769 internal::Matcher<Expr>, InnerMatcher) {
3770 const Expr *Expression = Node.getTrueExpr();
3771 return (Expression != nullptr &&
3772 InnerMatcher.matches(*Expression, Finder, Builder));
3775 /// \brief Matches the false branch expression of a conditional operator
3776 /// (binary or ternary).
3778 /// Example matches b
3780 /// condition ? a : b
3783 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
3784 internal::Matcher<Expr>, InnerMatcher) {
3785 const Expr *Expression = Node.getFalseExpr();
3786 return (Expression != nullptr &&
3787 InnerMatcher.matches(*Expression, Finder, Builder));
3790 /// \brief Matches if a declaration has a body attached.
3792 /// Example matches A, va, fa
3795 /// class B; // Doesn't match, as it has no body.
3797 /// extern int vb; // Doesn't match, as it doesn't define the variable.
3799 /// void fb(); // Doesn't match, as it has no body.
3802 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
3803 AST_POLYMORPHIC_MATCHER(isDefinition,
3804 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
3806 return Node.isThisDeclarationADefinition();
3809 /// \brief Matches if a function declaration is variadic.
3811 /// Example matches f, but not g or h. The function i will not match, even when
3812 /// compiled in C mode.
3816 /// template <typename... Ts> void h(Ts...);
3819 AST_MATCHER(FunctionDecl, isVariadic) {
3820 return Node.isVariadic();
3823 /// \brief Matches the class declaration that the given method declaration
3826 /// FIXME: Generalize this for other kinds of declarations.
3827 /// FIXME: What other kind of declarations would we need to generalize
3830 /// Example matches A() in the last line
3831 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
3832 /// ofClass(hasName("A"))))))
3840 AST_MATCHER_P(CXXMethodDecl, ofClass,
3841 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
3842 const CXXRecordDecl *Parent = Node.getParent();
3843 return (Parent != nullptr &&
3844 InnerMatcher.matches(*Parent, Finder, Builder));
3847 /// \brief Matches each method overriden by the given method. This matcher may
3848 /// produce multiple matches.
3852 /// class A { virtual void f(); };
3853 /// class B : public A { void f(); };
3854 /// class C : public B { void f(); };
3856 /// cxxMethodDecl(ofClass(hasName("C")),
3857 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
3858 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
3859 /// that B::f is not overridden by C::f).
3861 /// The check can produce multiple matches in case of multiple inheritance, e.g.
3863 /// class A1 { virtual void f(); };
3864 /// class A2 { virtual void f(); };
3865 /// class C : public A1, public A2 { void f(); };
3867 /// cxxMethodDecl(ofClass(hasName("C")),
3868 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
3869 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
3870 /// once with "b" binding "A2::f" and "d" binding "C::f".
3871 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
3872 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
3873 BoundNodesTreeBuilder Result;
3874 bool Matched = false;
3875 for (const auto *Overridden : Node.overridden_methods()) {
3876 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
3877 const bool OverriddenMatched =
3878 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
3879 if (OverriddenMatched) {
3881 Result.addMatch(OverriddenBuilder);
3884 *Builder = std::move(Result);
3888 /// \brief Matches if the given method declaration is virtual.
3894 /// virtual void x();
3898 AST_MATCHER(CXXMethodDecl, isVirtual) {
3899 return Node.isVirtual();
3902 /// \brief Matches if the given method declaration has an explicit "virtual".
3908 /// virtual void x();
3910 /// class B : public A {
3915 /// matches A::x but not B::x
3916 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
3917 return Node.isVirtualAsWritten();
3920 /// \brief Matches if the given method or class declaration is final.
3924 /// class A final {};
3927 /// virtual void f();
3934 /// matches A and C::f, but not B, C, or B::f
3935 AST_POLYMORPHIC_MATCHER(isFinal,
3936 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
3938 return Node.template hasAttr<FinalAttr>();
3941 /// \brief Matches if the given method declaration is pure.
3947 /// virtual void x() = 0;
3951 AST_MATCHER(CXXMethodDecl, isPure) {
3952 return Node.isPure();
3955 /// \brief Matches if the given method declaration is const.
3960 /// void foo() const;
3965 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
3966 AST_MATCHER(CXXMethodDecl, isConst) {
3967 return Node.isConst();
3970 /// \brief Matches if the given method declaration declares a copy assignment
3976 /// A &operator=(const A &);
3977 /// A &operator=(A &&);
3981 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
3983 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
3984 return Node.isCopyAssignmentOperator();
3987 /// \brief Matches if the given method declaration declares a move assignment
3993 /// A &operator=(const A &);
3994 /// A &operator=(A &&);
3998 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4000 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4001 return Node.isMoveAssignmentOperator();
4004 /// \brief Matches if the given method declaration overrides another method.
4010 /// virtual void x();
4012 /// class B : public A {
4014 /// virtual void x();
4018 AST_MATCHER(CXXMethodDecl, isOverride) {
4019 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4022 /// \brief Matches method declarations that are user-provided.
4028 /// S(const S &) = default; // #2
4029 /// S(S &&) = delete; // #3
4032 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4033 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4034 return Node.isUserProvided();
4037 /// \brief Matches member expressions that are called with '->' as opposed
4040 /// Member calls on the implicit this pointer match as called with '->'.
4045 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4050 /// memberExpr(isArrow())
4051 /// matches this->x, x, y.x, a, this->b
4052 AST_MATCHER(MemberExpr, isArrow) {
4053 return Node.isArrow();
4056 /// \brief Matches QualType nodes that are of integer type.
4064 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4065 /// matches "a(int)", "b(long)", but not "c(double)".
4066 AST_MATCHER(QualType, isInteger) {
4067 return Node->isIntegerType();
4070 /// \brief Matches QualType nodes that are of unsigned integer type.
4075 /// void b(unsigned long);
4078 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4079 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4080 AST_MATCHER(QualType, isUnsignedInteger) {
4081 return Node->isUnsignedIntegerType();
4084 /// \brief Matches QualType nodes that are of signed integer type.
4089 /// void b(unsigned long);
4092 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4093 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4094 AST_MATCHER(QualType, isSignedInteger) {
4095 return Node->isSignedIntegerType();
4098 /// \brief Matches QualType nodes that are of character type.
4103 /// void b(wchar_t);
4106 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4107 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4108 AST_MATCHER(QualType, isAnyCharacter) {
4109 return Node->isAnyCharacterType();
4112 /// \brief Matches QualType nodes that are of any pointer type; this includes
4113 /// the Objective-C object pointer type, which is different despite being
4114 /// syntactically similar.
4118 /// int *i = nullptr;
4126 /// varDecl(hasType(isAnyPointer()))
4127 /// matches "int *i" and "Foo *f", but not "int j".
4128 AST_MATCHER(QualType, isAnyPointer) {
4129 return Node->isAnyPointerType();
4132 /// \brief Matches QualType nodes that are const-qualified, i.e., that
4133 /// include "top-level" const.
4138 /// void b(int const);
4139 /// void c(const int);
4140 /// void d(const int*);
4141 /// void e(int const) {};
4143 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4144 /// matches "void b(int const)", "void c(const int)" and
4145 /// "void e(int const) {}". It does not match d as there
4146 /// is no top-level const on the parameter type "const int *".
4147 AST_MATCHER(QualType, isConstQualified) {
4148 return Node.isConstQualified();
4151 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
4152 /// include "top-level" volatile.
4157 /// void b(int volatile);
4158 /// void c(volatile int);
4159 /// void d(volatile int*);
4160 /// void e(int volatile) {};
4162 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4163 /// matches "void b(int volatile)", "void c(volatile int)" and
4164 /// "void e(int volatile) {}". It does not match d as there
4165 /// is no top-level volatile on the parameter type "volatile int *".
4166 AST_MATCHER(QualType, isVolatileQualified) {
4167 return Node.isVolatileQualified();
4170 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
4171 /// the node, not hidden within a typedef.
4175 /// typedef const int const_int;
4178 /// int *volatile k;
4181 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4182 /// \c i is const-qualified but the qualifier is not local.
4183 AST_MATCHER(QualType, hasLocalQualifiers) {
4184 return Node.hasLocalQualifiers();
4187 /// \brief Matches a member expression where the member is matched by a
4192 /// struct { int first, second; } first, second;
4193 /// int i(second.first);
4194 /// int j(first.second);
4196 /// memberExpr(member(hasName("first")))
4197 /// matches second.first
4198 /// but not first.second (because the member name there is "second").
4199 AST_MATCHER_P(MemberExpr, member,
4200 internal::Matcher<ValueDecl>, InnerMatcher) {
4201 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4204 /// \brief Matches a member expression where the object expression is
4205 /// matched by a given matcher.
4209 /// struct X { int m; };
4210 /// void f(X x) { x.m; m; }
4212 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4213 /// matches "x.m" and "m"
4214 /// with hasObjectExpression(...)
4215 /// matching "x" and the implicit object expression of "m" which has type X*.
4216 AST_MATCHER_P(MemberExpr, hasObjectExpression,
4217 internal::Matcher<Expr>, InnerMatcher) {
4218 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4221 /// \brief Matches any using shadow declaration.
4225 /// namespace X { void b(); }
4228 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
4229 /// matches \code using X::b \endcode
4230 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
4231 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4232 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
4233 Node.shadow_end(), Finder, Builder);
4236 /// \brief Matches a using shadow declaration where the target declaration is
4237 /// matched by the given matcher.
4241 /// namespace X { int a; void b(); }
4245 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
4246 /// matches \code using X::b \endcode
4247 /// but not \code using X::a \endcode
4248 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
4249 internal::Matcher<NamedDecl>, InnerMatcher) {
4250 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
4253 /// \brief Matches template instantiations of function, class, or static
4254 /// member variable template instantiations.
4258 /// template <typename T> class X {}; class A {}; X<A> x;
4262 /// template <typename T> class X {}; class A {}; template class X<A>;
4264 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4265 /// matches the template instantiation of X<A>.
4269 /// template <typename T> class X {}; class A {};
4270 /// template <> class X<A> {}; X<A> x;
4272 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4273 /// does not match, as X<A> is an explicit template specialization.
4275 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4276 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4277 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4279 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4280 Node.getTemplateSpecializationKind() ==
4281 TSK_ExplicitInstantiationDefinition);
4284 /// \brief Matches declarations that are template instantiations or are inside
4285 /// template instantiations.
4289 /// template<typename T> void A(T t) { T i; }
4293 /// functionDecl(isInstantiated())
4294 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
4295 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4296 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4297 functionDecl(isTemplateInstantiation())));
4298 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4301 /// \brief Matches statements inside of a template instantiation.
4306 /// template<typename T> void A(T t) { T i; j += 42;}
4310 /// declStmt(isInTemplateInstantiation())
4311 /// matches 'int i;' and 'unsigned i'.
4312 /// unless(stmt(isInTemplateInstantiation()))
4313 /// will NOT match j += 42; as it's shared between the template definition and
4315 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4317 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4318 functionDecl(isTemplateInstantiation())))));
4321 /// \brief Matches explicit template specializations of function, class, or
4322 /// static member variable template instantiations.
4326 /// template<typename T> void A(T t) { }
4327 /// template<> void A(int N) { }
4329 /// functionDecl(isExplicitTemplateSpecialization())
4330 /// matches the specialization A<int>().
4332 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4333 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4334 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4336 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4339 /// \brief Matches \c TypeLocs for which the given inner
4340 /// QualType-matcher matches.
4341 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4342 internal::Matcher<QualType>, InnerMatcher, 0) {
4343 return internal::BindableMatcher<TypeLoc>(
4344 new internal::TypeLocTypeMatcher(InnerMatcher));
4347 /// \brief Matches type \c bool.
4351 /// struct S { bool func(); };
4353 /// functionDecl(returns(booleanType()))
4354 /// matches "bool func();"
4355 AST_MATCHER(Type, booleanType) {
4356 return Node.isBooleanType();
4359 /// \brief Matches type \c void.
4363 /// struct S { void func(); };
4365 /// functionDecl(returns(voidType()))
4366 /// matches "void func();"
4367 AST_MATCHER(Type, voidType) {
4368 return Node.isVoidType();
4371 /// \brief Matches builtin Types.
4382 /// matches "int b", "float c" and "bool d"
4383 AST_TYPE_MATCHER(BuiltinType, builtinType);
4385 /// \brief Matches all kinds of arrays.
4389 /// int a[] = { 2, 3 };
4391 /// void f() { int c[a[0]]; }
4394 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4395 AST_TYPE_MATCHER(ArrayType, arrayType);
4397 /// \brief Matches C99 complex types.
4401 /// _Complex float f;
4404 /// matches "_Complex float f"
4405 AST_TYPE_MATCHER(ComplexType, complexType);
4407 /// \brief Matches any real floating-point type (float, double, long double).
4414 /// realFloatingPointType()
4415 /// matches "float f" but not "int i"
4416 AST_MATCHER(Type, realFloatingPointType) {
4417 return Node.isRealFloatingType();
4420 /// \brief Matches arrays and C99 complex types that have a specific element
4429 /// arrayType(hasElementType(builtinType()))
4430 /// matches "int b[7]"
4432 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
4433 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
4434 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
4437 /// \brief Matches C arrays with a specified constant size.
4443 /// int b[] = { 2, 3 };
4447 /// constantArrayType()
4448 /// matches "int a[2]"
4449 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
4451 /// \brief Matches nodes that have the specified size.
4457 /// int c[41], d[43];
4458 /// char *s = "abcd";
4459 /// wchar_t *ws = L"abcd";
4462 /// constantArrayType(hasSize(42))
4463 /// matches "int a[42]" and "int b[2 * 21]"
4464 /// stringLiteral(hasSize(4))
4465 /// matches "abcd", L"abcd"
4466 AST_POLYMORPHIC_MATCHER_P(hasSize,
4467 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
4470 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
4473 /// \brief Matches C++ arrays whose size is a value-dependent expression.
4477 /// template<typename T, int Size>
4482 /// dependentSizedArrayType
4483 /// matches "T data[Size]"
4484 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
4486 /// \brief Matches C arrays with unspecified size.
4490 /// int a[] = { 2, 3 };
4492 /// void f(int c[]) { int d[a[0]]; };
4494 /// incompleteArrayType()
4495 /// matches "int a[]" and "int c[]"
4496 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
4498 /// \brief Matches C arrays with a specified size that is not an
4499 /// integer-constant-expression.
4504 /// int a[] = { 2, 3 }
4509 /// variableArrayType()
4510 /// matches "int c[a[0]]"
4511 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
4513 /// \brief Matches \c VariableArrayType nodes that have a specific size
4522 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4523 /// varDecl(hasName("b")))))))
4524 /// matches "int a[b]"
4525 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
4526 internal::Matcher<Expr>, InnerMatcher) {
4527 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
4530 /// \brief Matches atomic types.
4537 /// matches "_Atomic(int) i"
4538 AST_TYPE_MATCHER(AtomicType, atomicType);
4540 /// \brief Matches atomic types with a specific value type.
4545 /// _Atomic(float) f;
4547 /// atomicType(hasValueType(isInteger()))
4548 /// matches "_Atomic(int) i"
4550 /// Usable as: Matcher<AtomicType>
4551 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
4552 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
4554 /// \brief Matches types nodes representing C++11 auto types.
4559 /// int v[] = { 2, 3 }
4560 /// for (auto i : v) { }
4563 /// matches "auto n" and "auto i"
4564 AST_TYPE_MATCHER(AutoType, autoType);
4566 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
4568 /// Note: There is no \c TypeLoc for the deduced type and thus no
4569 /// \c getDeducedLoc() matcher.
4576 /// autoType(hasDeducedType(isInteger()))
4577 /// matches "auto a"
4579 /// Usable as: Matcher<AutoType>
4580 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
4581 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
4583 /// \brief Matches \c FunctionType nodes.
4591 /// matches "int (*f)(int)" and the type of "g".
4592 AST_TYPE_MATCHER(FunctionType, functionType);
4594 /// \brief Matches \c FunctionProtoType nodes.
4601 /// functionProtoType()
4602 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
4603 /// In C mode, "g" is not matched because it does not contain a prototype.
4604 AST_TYPE_MATCHER(FunctionProtoType, functionProtoType);
4606 /// \brief Matches \c ParenType nodes.
4610 /// int (*ptr_to_array)[4];
4611 /// int *array_of_ptrs[4];
4614 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4615 /// \c array_of_ptrs.
4616 AST_TYPE_MATCHER(ParenType, parenType);
4618 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4622 /// int (*ptr_to_array)[4];
4623 /// int (*ptr_to_func)(int);
4626 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4627 /// \c ptr_to_func but not \c ptr_to_array.
4629 /// Usable as: Matcher<ParenType>
4630 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4631 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4633 /// \brief Matches block pointer types, i.e. types syntactically represented as
4634 /// "void (^)(int)".
4636 /// The \c pointee is always required to be a \c FunctionType.
4637 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4639 /// \brief Matches member pointer types.
4642 /// struct A { int i; }
4643 /// A::* ptr = A::i;
4645 /// memberPointerType()
4646 /// matches "A::* ptr"
4647 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4649 /// \brief Matches pointer types, but does not match Objective-C object pointer
4663 /// matches "int *a", but does not match "Foo *f".
4664 AST_TYPE_MATCHER(PointerType, pointerType);
4666 /// \brief Matches an Objective-C object pointer type, which is different from
4667 /// a pointer type, despite being syntactically similar.
4678 /// matches "Foo *f", but does not match "int *a".
4679 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4681 /// \brief Matches both lvalue and rvalue reference types.
4694 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4695 AST_TYPE_MATCHER(ReferenceType, referenceType);
4697 /// \brief Matches lvalue reference types.
4710 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4711 /// matched since the type is deduced as int& by reference collapsing rules.
4712 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4714 /// \brief Matches rvalue reference types.
4727 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4728 /// matched as it is deduced to int& by reference collapsing rules.
4729 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4731 /// \brief Narrows PointerType (and similar) matchers to those where the
4732 /// \c pointee matches a given matcher.
4740 /// pointerType(pointee(isConstQualified(), isInteger()))
4741 /// matches "int const *b"
4743 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4744 /// Matcher<PointerType>, Matcher<ReferenceType>
4745 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4746 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4751 /// \brief Matches typedef types.
4758 /// matches "typedef int X"
4759 AST_TYPE_MATCHER(TypedefType, typedefType);
4761 /// \brief Matches enum types.
4765 /// enum C { Green };
4766 /// enum class S { Red };
4772 /// \c enumType() matches the type of the variable declarations of both \c c and
4774 AST_TYPE_MATCHER(EnumType, enumType);
4776 /// \brief Matches template specialization types.
4780 /// template <typename T>
4783 /// template class C<int>; // A
4784 /// C<char> var; // B
4787 /// \c templateSpecializationType() matches the type of the explicit
4788 /// instantiation in \c A and the type of the variable declaration in \c B.
4789 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
4791 /// \brief Matches types nodes representing unary type transformations.
4795 /// typedef __underlying_type(T) type;
4797 /// unaryTransformType()
4798 /// matches "__underlying_type(T)"
4799 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
4801 /// \brief Matches record types (e.g. structs, classes).
4812 /// \c recordType() matches the type of the variable declarations of both \c c
4814 AST_TYPE_MATCHER(RecordType, recordType);
4816 /// \brief Matches types specified with an elaborated type keyword or with a
4832 /// \c elaboratedType() matches the type of the variable declarations of both
4834 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
4836 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
4837 /// matches \c InnerMatcher if the qualifier exists.
4849 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
4850 /// matches the type of the variable declaration of \c d.
4851 AST_MATCHER_P(ElaboratedType, hasQualifier,
4852 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
4853 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
4854 return InnerMatcher.matches(*Qualifier, Finder, Builder);
4859 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
4871 /// \c elaboratedType(namesType(recordType(
4872 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
4873 /// declaration of \c d.
4874 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
4876 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
4879 /// \brief Matches types that represent the result of substituting a type for a
4880 /// template type parameter.
4884 /// template <typename T>
4890 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
4891 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
4893 /// \brief Matches template type parameter types.
4895 /// Example matches T, but not int.
4896 /// (matcher = templateTypeParmType())
4898 /// template <typename T> void f(int i);
4900 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
4902 /// \brief Matches injected class name types.
4904 /// Example matches S s, but not S<T> s.
4905 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
4907 /// template <typename T> struct S {
4912 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
4914 /// \brief Matches decayed type
4915 /// Example matches i[] in declaration of f.
4916 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
4917 /// Example matches i[1].
4918 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
4920 /// void f(int i[]) {
4924 AST_TYPE_MATCHER(DecayedType, decayedType);
4926 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
4927 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
4929 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
4932 /// \brief Matches declarations whose declaration context, interpreted as a
4933 /// Decl, matches \c InnerMatcher.
4944 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
4945 /// declaration of \c class \c D.
4946 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
4947 const DeclContext *DC = Node.getDeclContext();
4948 if (!DC) return false;
4949 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
4952 /// \brief Matches nested name specifiers.
4957 /// struct A { static void f(); };
4959 /// void g() { A::f(); }
4963 /// nestedNameSpecifier()
4964 /// matches "ns::" and both "A::"
4965 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
4967 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
4968 const internal::VariadicAllOfMatcher<
4969 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
4971 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
4972 /// NestedNameSpecifier-matcher matches.
4973 AST_MATCHER_FUNCTION_P_OVERLOAD(
4974 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
4975 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
4976 return internal::BindableMatcher<NestedNameSpecifierLoc>(
4977 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
4981 /// \brief Matches nested name specifiers that specify a type matching the
4982 /// given \c QualType matcher without qualifiers.
4986 /// struct A { struct B { struct C {}; }; };
4989 /// nestedNameSpecifier(specifiesType(
4990 /// hasDeclaration(cxxRecordDecl(hasName("A")))
4993 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
4994 internal::Matcher<QualType>, InnerMatcher) {
4995 if (!Node.getAsType())
4997 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5000 /// \brief Matches nested name specifier locs that specify a type matching the
5001 /// given \c TypeLoc.
5005 /// struct A { struct B { struct C {}; }; };
5008 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5009 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5011 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5012 internal::Matcher<TypeLoc>, InnerMatcher) {
5013 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5016 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
5020 /// struct A { struct B { struct C {}; }; };
5023 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5025 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5026 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5028 const NestedNameSpecifier *NextNode = Node.getPrefix();
5031 return InnerMatcher.matches(*NextNode, Finder, Builder);
5034 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
5038 /// struct A { struct B { struct C {}; }; };
5041 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5043 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5044 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5046 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5049 return InnerMatcher.matches(NextNode, Finder, Builder);
5052 /// \brief Matches nested name specifiers that specify a namespace matching the
5053 /// given namespace matcher.
5057 /// namespace ns { struct A {}; }
5060 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5062 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5063 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5064 if (!Node.getAsNamespace())
5066 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5069 /// \brief Overloads for the \c equalsNode matcher.
5070 /// FIXME: Implement for other node types.
5073 /// \brief Matches if a node equals another node.
5075 /// \c Decl has pointer identity in the AST.
5076 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5077 return &Node == Other;
5079 /// \brief Matches if a node equals another node.
5081 /// \c Stmt has pointer identity in the AST.
5082 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5083 return &Node == Other;
5085 /// \brief Matches if a node equals another node.
5087 /// \c Type has pointer identity in the AST.
5088 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5089 return &Node == Other;
5094 /// \brief Matches each case or default statement belonging to the given switch
5095 /// statement. This matcher may produce multiple matches.
5099 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5101 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5102 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5103 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5104 /// "switch (1)", "switch (2)" and "switch (2)".
5105 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5107 BoundNodesTreeBuilder Result;
5108 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5109 // iteration order. We should use the more general iterating matchers once
5110 // they are capable of expressing this matcher (for example, it should ignore
5111 // case statements belonging to nested switch statements).
5112 bool Matched = false;
5113 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5114 SC = SC->getNextSwitchCase()) {
5115 BoundNodesTreeBuilder CaseBuilder(*Builder);
5116 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5119 Result.addMatch(CaseBuilder);
5122 *Builder = std::move(Result);
5126 /// \brief Matches each constructor initializer in a constructor definition.
5130 /// class A { A() : i(42), j(42) {} int i; int j; };
5132 /// cxxConstructorDecl(forEachConstructorInitializer(
5133 /// forField(decl().bind("x"))
5135 /// will trigger two matches, binding for 'i' and 'j' respectively.
5136 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5137 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5138 BoundNodesTreeBuilder Result;
5139 bool Matched = false;
5140 for (const auto *I : Node.inits()) {
5141 BoundNodesTreeBuilder InitBuilder(*Builder);
5142 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5144 Result.addMatch(InitBuilder);
5147 *Builder = std::move(Result);
5151 /// \brief Matches constructor declarations that are copy constructors.
5157 /// S(const S &); // #2
5161 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
5162 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
5163 return Node.isCopyConstructor();
5166 /// \brief Matches constructor declarations that are move constructors.
5172 /// S(const S &); // #2
5176 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
5177 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
5178 return Node.isMoveConstructor();
5181 /// \brief Matches constructor declarations that are default constructors.
5187 /// S(const S &); // #2
5191 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
5192 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
5193 return Node.isDefaultConstructor();
5196 /// \brief Matches constructors that delegate to another constructor.
5203 /// S(S &&) : S() {} // #3
5205 /// S::S() : S(0) {} // #4
5207 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
5209 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
5210 return Node.isDelegatingConstructor();
5213 /// \brief Matches constructor and conversion declarations that are marked with
5214 /// the explicit keyword.
5220 /// explicit S(double); // #2
5221 /// operator int(); // #3
5222 /// explicit operator bool(); // #4
5225 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
5226 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
5227 AST_POLYMORPHIC_MATCHER(isExplicit,
5228 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
5229 CXXConversionDecl)) {
5230 return Node.isExplicit();
5233 /// \brief Matches function and namespace declarations that are marked with
5234 /// the inline keyword.
5238 /// inline void f();
5241 /// inline namespace m {}
5244 /// functionDecl(isInline()) will match ::f().
5245 /// namespaceDecl(isInline()) will match n::m.
5246 AST_POLYMORPHIC_MATCHER(isInline,
5247 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
5249 // This is required because the spelling of the function used to determine
5250 // whether inline is specified or not differs between the polymorphic types.
5251 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
5252 return FD->isInlineSpecified();
5253 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
5254 return NSD->isInline();
5255 llvm_unreachable("Not a valid polymorphic type");
5258 /// \brief Matches anonymous namespace declarations.
5263 /// namespace {} // #1
5266 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
5267 AST_MATCHER(NamespaceDecl, isAnonymous) {
5268 return Node.isAnonymousNamespace();
5271 /// \brief If the given case statement does not use the GNU case range
5272 /// extension, matches the constant given in the statement.
5276 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
5278 /// caseStmt(hasCaseConstant(integerLiteral()))
5279 /// matches "case 1:"
5280 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
5285 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
5288 /// \brief Matches declaration that has a given attribute.
5292 /// __attribute__((device)) void f() { ... }
5294 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
5295 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
5296 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
5297 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
5298 for (const auto *Attr : Node.attrs()) {
5299 if (Attr->getKind() == AttrKind)
5305 /// \brief Matches the return value expression of a return statement
5311 /// hasReturnValue(binaryOperator())
5312 /// matches 'return a + b'
5313 /// with binaryOperator()
5314 /// matching 'a + b'
5315 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5317 if (const auto *RetValue = Node.getRetValue())
5318 return InnerMatcher.matches(*RetValue, Finder, Builder);
5323 /// \brief Matches CUDA kernel call expression.
5325 /// Example matches,
5327 /// kernel<<<i,j>>>();
5329 const internal::VariadicDynCastAllOfMatcher<
5331 CUDAKernelCallExpr> cudaKernelCallExpr;
5334 /// \brief Matches expressions that resolve to a null pointer constant, such as
5335 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5339 /// void *v1 = NULL;
5340 /// void *v2 = nullptr;
5341 /// void *v3 = __null; // GNU extension
5342 /// char *cp = (char *)0;
5346 /// expr(nullPointerConstant())
5347 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5348 /// initializer for i.
5349 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5351 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5352 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5355 /// \brief Matches declaration of the function the statemenet belongs to
5359 /// F& operator=(const F& o) {
5360 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
5364 /// returnStmt(forFunction(hasName("operator=")))
5365 /// matches 'return *this'
5366 /// but does match 'return > 0'
5367 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
5369 const auto &Parents = Finder->getASTContext().getParents(Node);
5371 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
5373 while(!Stack.empty()) {
5374 const auto &CurNode = Stack.back();
5376 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
5377 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
5380 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
5381 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
5386 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
5387 Stack.push_back(Parent);
5393 } // end namespace ast_matchers
5394 } // end namespace clang