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.
168 /// matches "typedef int X"
169 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
171 /// \brief Matches AST nodes that were expanded within the main-file.
173 /// Example matches X but not Y
174 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
184 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
185 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
186 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
187 auto &SourceManager = Finder->getASTContext().getSourceManager();
188 return SourceManager.isInMainFile(
189 SourceManager.getExpansionLoc(Node.getLocStart()));
192 /// \brief Matches AST nodes that were expanded within system-header-files.
194 /// Example matches Y but not X
195 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
197 /// #include <SystemHeader.h>
205 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
206 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
207 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
208 auto &SourceManager = Finder->getASTContext().getSourceManager();
209 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
210 if (ExpansionLoc.isInvalid()) {
213 return SourceManager.isInSystemHeader(ExpansionLoc);
216 /// \brief Matches AST nodes that were expanded within files whose name is
217 /// partially matching a given regex.
219 /// Example matches Y but not X
220 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
222 /// #include "ASTMatcher.h"
230 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
231 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
232 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
233 std::string, RegExp) {
234 auto &SourceManager = Finder->getASTContext().getSourceManager();
235 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
236 if (ExpansionLoc.isInvalid()) {
240 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
245 auto Filename = FileEntry->getName();
246 llvm::Regex RE(RegExp);
247 return RE.match(Filename);
250 /// \brief Matches declarations.
252 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
259 const internal::VariadicAllOfMatcher<Decl> decl;
261 /// \brief Matches a declaration of a linkage specification.
267 /// linkageSpecDecl()
268 /// matches "extern "C" {}"
269 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
272 /// \brief Matches a declaration of anything that could have a name.
274 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
283 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
285 /// \brief Matches a declaration of a namespace.
290 /// namespace test {}
293 /// matches "namespace {}" and "namespace test {}"
294 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
296 /// \brief Matches a declaration of a namespace alias.
300 /// namespace test {}
301 /// namespace alias = ::test;
303 /// namespaceAliasDecl()
304 /// matches "namespace alias" but not "namespace test"
305 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
308 /// \brief Matches class, struct, and union declarations.
310 /// Example matches \c X, \c Z, \c U, and \c S
313 /// template<class T> class Z {};
317 const internal::VariadicDynCastAllOfMatcher<
319 RecordDecl> recordDecl;
321 /// \brief Matches C++ class declarations.
323 /// Example matches \c X, \c Z
326 /// template<class T> class Z {};
328 const internal::VariadicDynCastAllOfMatcher<
330 CXXRecordDecl> cxxRecordDecl;
332 /// \brief Matches C++ class template declarations.
334 /// Example matches \c Z
336 /// template<class T> class Z {};
338 const internal::VariadicDynCastAllOfMatcher<
340 ClassTemplateDecl> classTemplateDecl;
342 /// \brief Matches C++ class template specializations.
346 /// template<typename T> class A {};
347 /// template<> class A<double> {};
350 /// classTemplateSpecializationDecl()
351 /// matches the specializations \c A<int> and \c A<double>
352 const internal::VariadicDynCastAllOfMatcher<
354 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
356 /// \brief Matches declarator declarations (field, variable, function
357 /// and non-type template parameter declarations).
361 /// class X { int y; };
364 /// matches \c int y.
365 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
368 /// \brief Matches parameter variable declarations.
375 /// matches \c int x.
376 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
378 /// \brief Matches C++ access specifier declarations.
388 /// matches 'public:'
389 const internal::VariadicDynCastAllOfMatcher<
391 AccessSpecDecl> accessSpecDecl;
393 /// \brief Matches constructor initializers.
395 /// Examples matches \c i(42).
402 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
404 /// \brief Matches template arguments.
408 /// template <typename T> struct C {};
411 /// templateArgument()
412 /// matches 'int' in C<int>.
413 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
415 /// \brief Matches non-type template parameter declarations.
419 /// template <typename T, int N> struct C {};
421 /// nonTypeTemplateParmDecl()
422 /// matches 'N', but not 'T'.
423 const internal::VariadicDynCastAllOfMatcher<
425 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
427 /// \brief Matches template type parameter declarations.
431 /// template <typename T, int N> struct C {};
433 /// templateTypeParmDecl()
434 /// matches 'T', but not 'N'.
435 const internal::VariadicDynCastAllOfMatcher<
437 TemplateTypeParmDecl> templateTypeParmDecl;
439 /// \brief Matches public C++ declarations.
445 /// protected: int b;
449 /// fieldDecl(isPublic())
451 AST_MATCHER(Decl, isPublic) {
452 return Node.getAccess() == AS_public;
455 /// \brief Matches protected C++ declarations.
461 /// protected: int b;
465 /// fieldDecl(isProtected())
467 AST_MATCHER(Decl, isProtected) {
468 return Node.getAccess() == AS_protected;
471 /// \brief Matches private C++ declarations.
477 /// protected: int b;
481 /// fieldDecl(isPrivate())
483 AST_MATCHER(Decl, isPrivate) {
484 return Node.getAccess() == AS_private;
487 /// \brief Matches a declaration that has been implicitly added
488 /// by the compiler (eg. implicit default/copy constructors).
489 AST_MATCHER(Decl, isImplicit) {
490 return Node.isImplicit();
493 /// \brief Matches classTemplateSpecializations that have at least one
494 /// TemplateArgument matching the given InnerMatcher.
498 /// template<typename T> class A {};
499 /// template<> class A<double> {};
502 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
503 /// refersToType(asString("int"))))
504 /// matches the specialization \c A<int>
505 AST_POLYMORPHIC_MATCHER_P(
506 hasAnyTemplateArgument,
507 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
508 TemplateSpecializationType),
509 internal::Matcher<TemplateArgument>, InnerMatcher) {
510 ArrayRef<TemplateArgument> List =
511 internal::getTemplateSpecializationArgs(Node);
512 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
516 /// \brief Matches expressions that match InnerMatcher after any implicit casts
517 /// are stripped off.
519 /// Parentheses and explicit casts are not discarded.
527 /// long e = (long) 0l;
531 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
532 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
534 /// would match the declarations for a, b, c, and d, but not e.
537 /// varDecl(hasInitializer(integerLiteral()))
538 /// varDecl(hasInitializer(declRefExpr()))
540 /// only match the declarations for b, c, and d.
541 AST_MATCHER_P(Expr, ignoringImpCasts,
542 internal::Matcher<Expr>, InnerMatcher) {
543 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
546 /// \brief Matches expressions that match InnerMatcher after parentheses and
547 /// casts are stripped off.
549 /// Implicit and non-C Style casts are also discarded.
554 /// void* c = reinterpret_cast<char*>(0);
555 /// char d = char(0);
558 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
559 /// would match the declarations for a, b, c, and d.
561 /// varDecl(hasInitializer(integerLiteral()))
562 /// only match the declaration for a.
563 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
564 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
567 /// \brief Matches expressions that match InnerMatcher after implicit casts and
568 /// parentheses are stripped off.
570 /// Explicit casts are not discarded.
578 /// long e = ((long) 0l);
581 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
582 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
583 /// would match the declarations for a, b, c, and d, but not e.
585 /// varDecl(hasInitializer(integerLiteral()))
586 /// varDecl(hasInitializer(declRefExpr()))
587 /// would only match the declaration for a.
588 AST_MATCHER_P(Expr, ignoringParenImpCasts,
589 internal::Matcher<Expr>, InnerMatcher) {
590 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
593 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
594 /// matches the given InnerMatcher.
598 /// template<typename T, typename U> class A {};
602 /// classTemplateSpecializationDecl(hasTemplateArgument(
603 /// 1, refersToType(asString("int"))))
604 /// matches the specialization \c A<bool, int>
605 AST_POLYMORPHIC_MATCHER_P2(
607 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
608 TemplateSpecializationType),
609 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
610 ArrayRef<TemplateArgument> List =
611 internal::getTemplateSpecializationArgs(Node);
612 if (List.size() <= N)
614 return InnerMatcher.matches(List[N], Finder, Builder);
617 /// \brief Matches if the number of template arguments equals \p N.
621 /// template<typename T> struct C {};
624 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
626 AST_POLYMORPHIC_MATCHER_P(
627 templateArgumentCountIs,
628 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
629 TemplateSpecializationType),
631 return internal::getTemplateSpecializationArgs(Node).size() == N;
634 /// \brief Matches a TemplateArgument that refers to a certain type.
639 /// template<typename T> struct A {};
642 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
643 /// refersToType(class(hasName("X")))))
644 /// matches the specialization \c A<X>
645 AST_MATCHER_P(TemplateArgument, refersToType,
646 internal::Matcher<QualType>, InnerMatcher) {
647 if (Node.getKind() != TemplateArgument::Type)
649 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
652 /// \brief Matches a canonical TemplateArgument that refers to a certain
657 /// template<typename T> struct A {};
658 /// struct B { B* next; };
661 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
662 /// refersToDeclaration(fieldDecl(hasName("next"))))
663 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
665 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
666 internal::Matcher<Decl>, InnerMatcher) {
667 if (Node.getKind() == TemplateArgument::Declaration)
668 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
672 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
676 /// template<typename T> struct A {};
677 /// struct B { B* next; };
680 /// templateSpecializationType(hasAnyTemplateArgument(
681 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
682 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
684 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
685 if (Node.getKind() == TemplateArgument::Expression)
686 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
690 /// \brief Matches a TemplateArgument that is an integral value.
694 /// template<int T> struct A {};
697 /// classTemplateSpecializationDecl(
698 /// hasAnyTemplateArgument(isIntegral()))
699 /// matches the implicit instantiation of C in C<42>
700 /// with isIntegral() matching 42.
701 AST_MATCHER(TemplateArgument, isIntegral) {
702 return Node.getKind() == TemplateArgument::Integral;
705 /// \brief Matches a TemplateArgument that referes to an integral type.
709 /// template<int T> struct A {};
712 /// classTemplateSpecializationDecl(
713 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
714 /// matches the implicit instantiation of C in C<42>.
715 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
716 internal::Matcher<QualType>, InnerMatcher) {
717 if (Node.getKind() != TemplateArgument::Integral)
719 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
722 /// \brief Matches a TemplateArgument of integral type with a given value.
724 /// Note that 'Value' is a string as the template argument's value is
725 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
726 /// representation of that integral value in base 10.
730 /// template<int T> struct A {};
733 /// classTemplateSpecializationDecl(
734 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
735 /// matches the implicit instantiation of C in C<42>.
736 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
737 std::string, Value) {
738 if (Node.getKind() != TemplateArgument::Integral)
740 return Node.getAsIntegral().toString(10) == Value;
743 /// \brief Matches any value declaration.
745 /// Example matches A, B, C and F
747 /// enum X { A, B, C };
750 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
752 /// \brief Matches C++ constructor declarations.
754 /// Example matches Foo::Foo() and Foo::Foo(int)
760 /// int DoSomething();
763 const internal::VariadicDynCastAllOfMatcher<
765 CXXConstructorDecl> cxxConstructorDecl;
767 /// \brief Matches explicit C++ destructor declarations.
769 /// Example matches Foo::~Foo()
776 const internal::VariadicDynCastAllOfMatcher<
778 CXXDestructorDecl> cxxDestructorDecl;
780 /// \brief Matches enum declarations.
782 /// Example matches X
788 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
790 /// \brief Matches enum constants.
792 /// Example matches A, B, C
798 const internal::VariadicDynCastAllOfMatcher<
800 EnumConstantDecl> enumConstantDecl;
802 /// \brief Matches method declarations.
804 /// Example matches y
806 /// class X { void y(); };
808 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
810 /// \brief Matches conversion operator declarations.
812 /// Example matches the operator.
814 /// class X { operator int() const; };
816 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
819 /// \brief Matches variable declarations.
821 /// Note: this does not match declarations of member variables, which are
822 /// "field" declarations in Clang parlance.
824 /// Example matches a
828 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
830 /// \brief Matches field declarations.
834 /// class X { int m; };
838 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
840 /// \brief Matches function declarations.
842 /// Example matches f
846 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
848 /// \brief Matches C++ function template declarations.
850 /// Example matches f
852 /// template<class T> void f(T t) {}
854 const internal::VariadicDynCastAllOfMatcher<
856 FunctionTemplateDecl> functionTemplateDecl;
858 /// \brief Matches friend declarations.
862 /// class X { friend void foo(); };
865 /// matches 'friend void foo()'.
866 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
868 /// \brief Matches statements.
875 /// matches both the compound statement '{ ++a; }' and '++a'.
876 const internal::VariadicAllOfMatcher<Stmt> stmt;
878 /// \brief Matches declaration statements.
886 const internal::VariadicDynCastAllOfMatcher<
890 /// \brief Matches member expressions.
895 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
896 /// int a; static int b;
900 /// matches this->x, x, y.x, a, this->b
901 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
903 /// \brief Matches call expressions.
905 /// Example matches x.y() and y()
911 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
913 /// \brief Matches lambda expressions.
915 /// Example matches [&](){return 5;}
919 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
921 /// \brief Matches member call expressions.
923 /// Example matches x.y()
928 const internal::VariadicDynCastAllOfMatcher<
930 CXXMemberCallExpr> cxxMemberCallExpr;
932 /// \brief Matches ObjectiveC Message invocation expressions.
934 /// The innermost message send invokes the "alloc" class method on the
935 /// NSString class, while the outermost message send invokes the
936 /// "initWithString" instance method on the object returned from
937 /// NSString's "alloc". This matcher should match both message sends.
939 /// [[NSString alloc] initWithString:@"Hello"]
941 const internal::VariadicDynCastAllOfMatcher<
943 ObjCMessageExpr> objcMessageExpr;
945 /// \brief Matches Objective-C interface declarations.
947 /// Example matches Foo
952 const internal::VariadicDynCastAllOfMatcher<
954 ObjCInterfaceDecl> objcInterfaceDecl;
956 /// \brief Matches expressions that introduce cleanups to be run at the end
957 /// of the sub-expression's evaluation.
959 /// Example matches std::string()
961 /// const std::string str = std::string();
963 const internal::VariadicDynCastAllOfMatcher<
965 ExprWithCleanups> exprWithCleanups;
967 /// \brief Matches init list expressions.
971 /// int a[] = { 1, 2 };
972 /// struct B { int x, y; };
976 /// matches "{ 1, 2 }" and "{ 5, 6 }"
977 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
979 /// \brief Matches substitutions of non-type template parameters.
984 /// struct A { static const int n = N; };
985 /// struct B : public A<42> {};
987 /// substNonTypeTemplateParmExpr()
988 /// matches "N" in the right-hand side of "static const int n = N;"
989 const internal::VariadicDynCastAllOfMatcher<
991 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
993 /// \brief Matches using declarations.
997 /// namespace X { int x; }
1001 /// matches \code using X::x \endcode
1002 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1004 /// \brief Matches using namespace declarations.
1008 /// namespace X { int x; }
1009 /// using namespace X;
1011 /// usingDirectiveDecl()
1012 /// matches \code using namespace X \endcode
1013 const internal::VariadicDynCastAllOfMatcher<
1015 UsingDirectiveDecl> usingDirectiveDecl;
1017 /// \brief Matches unresolved using value declarations.
1021 /// template<typename X>
1022 /// class C : private X {
1026 /// unresolvedUsingValueDecl()
1027 /// matches \code using X::x \endcode
1028 const internal::VariadicDynCastAllOfMatcher<
1030 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1032 /// \brief Matches unresolved using value declarations that involve the
1037 /// template <typename T>
1038 /// struct Base { typedef T Foo; };
1040 /// template<typename T>
1041 /// struct S : private Base<T> {
1042 /// using typename Base<T>::Foo;
1045 /// unresolvedUsingTypenameDecl()
1046 /// matches \code using Base<T>::Foo \endcode
1047 const internal::VariadicDynCastAllOfMatcher<
1049 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1051 /// \brief Matches constructor call expressions (including implicit ones).
1053 /// Example matches string(ptr, n) and ptr within arguments of f
1054 /// (matcher = cxxConstructExpr())
1056 /// void f(const string &a, const string &b);
1059 /// f(string(ptr, n), ptr);
1061 const internal::VariadicDynCastAllOfMatcher<
1063 CXXConstructExpr> cxxConstructExpr;
1065 /// \brief Matches unresolved constructor call expressions.
1067 /// Example matches T(t) in return statement of f
1068 /// (matcher = cxxUnresolvedConstructExpr())
1070 /// template <typename T>
1071 /// void f(const T& t) { return T(t); }
1073 const internal::VariadicDynCastAllOfMatcher<
1075 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1077 /// \brief Matches implicit and explicit this expressions.
1079 /// Example matches the implicit this expression in "return i".
1080 /// (matcher = cxxThisExpr())
1084 /// int f() { return i; }
1087 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1089 /// \brief Matches nodes where temporaries are created.
1091 /// Example matches FunctionTakesString(GetStringByValue())
1092 /// (matcher = cxxBindTemporaryExpr())
1094 /// FunctionTakesString(GetStringByValue());
1095 /// FunctionTakesStringByPointer(GetStringPointer());
1097 const internal::VariadicDynCastAllOfMatcher<
1099 CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1101 /// \brief Matches nodes where temporaries are materialized.
1105 /// struct T {void func()};
1109 /// materializeTemporaryExpr() matches 'f()' in these statements
1114 /// but does not match
1119 const internal::VariadicDynCastAllOfMatcher<
1121 MaterializeTemporaryExpr> materializeTemporaryExpr;
1123 /// \brief Matches new expressions.
1130 /// matches 'new X'.
1131 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1133 /// \brief Matches delete expressions.
1140 /// matches 'delete X'.
1141 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1143 /// \brief Matches array subscript expressions.
1149 /// arraySubscriptExpr()
1151 const internal::VariadicDynCastAllOfMatcher<
1153 ArraySubscriptExpr> arraySubscriptExpr;
1155 /// \brief Matches the value of a default argument at the call site.
1157 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1158 /// default value of the second parameter in the call expression f(42)
1159 /// (matcher = cxxDefaultArgExpr())
1161 /// void f(int x, int y = 0);
1164 const internal::VariadicDynCastAllOfMatcher<
1166 CXXDefaultArgExpr> cxxDefaultArgExpr;
1168 /// \brief Matches overloaded operator calls.
1170 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1171 /// binaryOperator matcher.
1172 /// Currently it does not match operators such as new delete.
1173 /// FIXME: figure out why these do not match?
1175 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1176 /// (matcher = cxxOperatorCallExpr())
1178 /// ostream &operator<< (ostream &out, int i) { };
1179 /// ostream &o; int b = 1, c = 1;
1182 const internal::VariadicDynCastAllOfMatcher<
1184 CXXOperatorCallExpr> cxxOperatorCallExpr;
1186 /// \brief Matches expressions.
1188 /// Example matches x()
1190 /// void f() { x(); }
1192 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1194 /// \brief Matches expressions that refer to declarations.
1196 /// Example matches x in if (x)
1201 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1203 /// \brief Matches if statements.
1205 /// Example matches 'if (x) {}'
1209 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1211 /// \brief Matches for statements.
1213 /// Example matches 'for (;;) {}'
1216 /// int i[] = {1, 2, 3}; for (auto a : i);
1218 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1220 /// \brief Matches the increment statement of a for loop.
1223 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1224 /// matches '++x' in
1226 /// for (x; x < N; ++x) { }
1228 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1230 const Stmt *const Increment = Node.getInc();
1231 return (Increment != nullptr &&
1232 InnerMatcher.matches(*Increment, Finder, Builder));
1235 /// \brief Matches the initialization statement of a for loop.
1238 /// forStmt(hasLoopInit(declStmt()))
1239 /// matches 'int x = 0' in
1241 /// for (int x = 0; x < N; ++x) { }
1243 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1245 const Stmt *const Init = Node.getInit();
1246 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1249 /// \brief Matches range-based for statements.
1251 /// cxxForRangeStmt() matches 'for (auto a : i)'
1253 /// int i[] = {1, 2, 3}; for (auto a : i);
1254 /// for(int j = 0; j < 5; ++j);
1256 const internal::VariadicDynCastAllOfMatcher<
1258 CXXForRangeStmt> cxxForRangeStmt;
1260 /// \brief Matches the initialization statement of a for loop.
1263 /// forStmt(hasLoopVariable(anything()))
1264 /// matches 'int x' in
1266 /// for (int x : a) { }
1268 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1270 const VarDecl *const Var = Node.getLoopVariable();
1271 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1274 /// \brief Matches the range initialization statement of a for loop.
1277 /// forStmt(hasRangeInit(anything()))
1280 /// for (int x : a) { }
1282 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1284 const Expr *const Init = Node.getRangeInit();
1285 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1288 /// \brief Matches while statements.
1295 /// matches 'while (true) {}'.
1296 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1298 /// \brief Matches do statements.
1302 /// do {} while (true);
1305 /// matches 'do {} while(true)'
1306 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1308 /// \brief Matches break statements.
1312 /// while (true) { break; }
1316 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1318 /// \brief Matches continue statements.
1322 /// while (true) { continue; }
1325 /// matches 'continue'
1326 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1328 /// \brief Matches return statements.
1335 /// matches 'return 1'
1336 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1338 /// \brief Matches goto statements.
1346 /// matches 'goto FOO'
1347 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1349 /// \brief Matches label statements.
1358 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1360 /// \brief Matches switch statements.
1364 /// switch(a) { case 42: break; default: break; }
1367 /// matches 'switch(a)'.
1368 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1370 /// \brief Matches case and default statements inside switch statements.
1374 /// switch(a) { case 42: break; default: break; }
1377 /// matches 'case 42: break;' and 'default: break;'.
1378 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1380 /// \brief Matches case statements inside switch statements.
1384 /// switch(a) { case 42: break; default: break; }
1387 /// matches 'case 42: break;'.
1388 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1390 /// \brief Matches default statements inside switch statements.
1394 /// switch(a) { case 42: break; default: break; }
1397 /// matches 'default: break;'.
1398 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1400 /// \brief Matches compound statements.
1402 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1406 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1408 /// \brief Matches catch statements.
1411 /// try {} catch(int i) {}
1414 /// matches 'catch(int i)'
1415 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1417 /// \brief Matches try statements.
1420 /// try {} catch(int i) {}
1423 /// matches 'try {}'
1424 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1426 /// \brief Matches throw expressions.
1429 /// try { throw 5; } catch(int i) {}
1432 /// matches 'throw 5'
1433 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1435 /// \brief Matches null statements.
1441 /// matches the second ';'
1442 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1444 /// \brief Matches asm statements.
1448 /// __asm("mov al, 2");
1451 /// matches '__asm("mov al, 2")'
1452 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1454 /// \brief Matches bool literals.
1456 /// Example matches true
1460 const internal::VariadicDynCastAllOfMatcher<
1462 CXXBoolLiteralExpr> cxxBoolLiteral;
1464 /// \brief Matches string literals (also matches wide string literals).
1466 /// Example matches "abcd", L"abcd"
1468 /// char *s = "abcd"; wchar_t *ws = L"abcd"
1470 const internal::VariadicDynCastAllOfMatcher<
1472 StringLiteral> stringLiteral;
1474 /// \brief Matches character literals (also matches wchar_t).
1476 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1479 /// Example matches 'a', L'a'
1481 /// char ch = 'a'; wchar_t chw = L'a';
1483 const internal::VariadicDynCastAllOfMatcher<
1485 CharacterLiteral> characterLiteral;
1487 /// \brief Matches integer literals of all sizes / encodings, e.g.
1488 /// 1, 1L, 0x1 and 1U.
1490 /// Does not match character-encoded integers such as L'a'.
1491 const internal::VariadicDynCastAllOfMatcher<
1493 IntegerLiteral> integerLiteral;
1495 /// \brief Matches float literals of all sizes / encodings, e.g.
1496 /// 1.0, 1.0f, 1.0L and 1e10.
1498 /// Does not match implicit conversions such as
1502 const internal::VariadicDynCastAllOfMatcher<
1504 FloatingLiteral> floatLiteral;
1506 /// \brief Matches user defined literal operator call.
1508 /// Example match: "foo"_suffix
1509 const internal::VariadicDynCastAllOfMatcher<
1511 UserDefinedLiteral> userDefinedLiteral;
1513 /// \brief Matches compound (i.e. non-scalar) literals
1515 /// Example match: {1}, (1, 2)
1517 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1519 const internal::VariadicDynCastAllOfMatcher<
1521 CompoundLiteralExpr> compoundLiteralExpr;
1523 /// \brief Matches nullptr literal.
1524 const internal::VariadicDynCastAllOfMatcher<
1526 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1528 /// \brief Matches GNU __null expression.
1529 const internal::VariadicDynCastAllOfMatcher<
1531 GNUNullExpr> gnuNullExpr;
1533 /// \brief Matches binary operator expressions.
1535 /// Example matches a || b
1539 const internal::VariadicDynCastAllOfMatcher<
1541 BinaryOperator> binaryOperator;
1543 /// \brief Matches unary operator expressions.
1545 /// Example matches !a
1549 const internal::VariadicDynCastAllOfMatcher<
1551 UnaryOperator> unaryOperator;
1553 /// \brief Matches conditional operator expressions.
1555 /// Example matches a ? b : c
1557 /// (a ? b : c) + 42
1559 const internal::VariadicDynCastAllOfMatcher<
1561 ConditionalOperator> conditionalOperator;
1563 /// \brief Matches a C++ static_assert declaration.
1566 /// staticAssertExpr()
1568 /// static_assert(sizeof(S) == sizeof(int))
1574 /// static_assert(sizeof(S) == sizeof(int));
1576 const internal::VariadicDynCastAllOfMatcher<
1578 StaticAssertDecl> staticAssertDecl;
1580 /// \brief Matches a reinterpret_cast expression.
1582 /// Either the source expression or the destination type can be matched
1583 /// using has(), but hasDestinationType() is more specific and can be
1586 /// Example matches reinterpret_cast<char*>(&p) in
1588 /// void* p = reinterpret_cast<char*>(&p);
1590 const internal::VariadicDynCastAllOfMatcher<
1592 CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1594 /// \brief Matches a C++ static_cast expression.
1596 /// \see hasDestinationType
1597 /// \see reinterpretCast
1600 /// cxxStaticCastExpr()
1602 /// static_cast<long>(8)
1605 /// long eight(static_cast<long>(8));
1607 const internal::VariadicDynCastAllOfMatcher<
1609 CXXStaticCastExpr> cxxStaticCastExpr;
1611 /// \brief Matches a dynamic_cast expression.
1614 /// cxxDynamicCastExpr()
1616 /// dynamic_cast<D*>(&b);
1619 /// struct B { virtual ~B() {} }; struct D : B {};
1621 /// D* p = dynamic_cast<D*>(&b);
1623 const internal::VariadicDynCastAllOfMatcher<
1625 CXXDynamicCastExpr> cxxDynamicCastExpr;
1627 /// \brief Matches a const_cast expression.
1629 /// Example: Matches const_cast<int*>(&r) in
1632 /// const int &r(n);
1633 /// int* p = const_cast<int*>(&r);
1635 const internal::VariadicDynCastAllOfMatcher<
1637 CXXConstCastExpr> cxxConstCastExpr;
1639 /// \brief Matches a C-style cast expression.
1641 /// Example: Matches (int*) 2.2f in
1643 /// int i = (int) 2.2f;
1645 const internal::VariadicDynCastAllOfMatcher<
1647 CStyleCastExpr> cStyleCastExpr;
1649 /// \brief Matches explicit cast expressions.
1651 /// Matches any cast expression written in user code, whether it be a
1652 /// C-style cast, a functional-style cast, or a keyword cast.
1654 /// Does not match implicit conversions.
1656 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1657 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1658 /// actual cast expressions.
1660 /// \see hasDestinationType.
1662 /// Example: matches all five of the casts in
1664 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1666 /// but does not match the implicit conversion in
1670 const internal::VariadicDynCastAllOfMatcher<
1672 ExplicitCastExpr> explicitCastExpr;
1674 /// \brief Matches the implicit cast nodes of Clang's AST.
1676 /// This matches many different places, including function call return value
1677 /// eliding, as well as any type conversions.
1678 const internal::VariadicDynCastAllOfMatcher<
1680 ImplicitCastExpr> implicitCastExpr;
1682 /// \brief Matches any cast nodes of Clang's AST.
1684 /// Example: castExpr() matches each of the following:
1687 /// const_cast<Expr *>(SubExpr);
1690 /// but does not match
1695 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1697 /// \brief Matches functional cast expressions
1699 /// Example: Matches Foo(bar);
1702 /// Foo g = (Foo) bar;
1703 /// Foo h = Foo(bar);
1705 const internal::VariadicDynCastAllOfMatcher<
1707 CXXFunctionalCastExpr> cxxFunctionalCastExpr;
1709 /// \brief Matches functional cast expressions having N != 1 arguments
1711 /// Example: Matches Foo(bar, bar)
1713 /// Foo h = Foo(bar, bar);
1715 const internal::VariadicDynCastAllOfMatcher<
1717 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
1719 /// \brief Matches \c QualTypes in the clang AST.
1720 const internal::VariadicAllOfMatcher<QualType> qualType;
1722 /// \brief Matches \c Types in the clang AST.
1723 const internal::VariadicAllOfMatcher<Type> type;
1725 /// \brief Matches \c TypeLocs in the clang AST.
1726 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1728 /// \brief Matches if any of the given matchers matches.
1730 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1731 /// matching submatcher.
1733 /// For example, in:
1735 /// class A { int a; int b; };
1739 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1740 /// has(fieldDecl(hasName("b")).bind("v"))))
1742 /// will generate two results binding "v", the first of which binds
1743 /// the field declaration of \c a, the second the field declaration of
1746 /// Usable as: Any Matcher
1747 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
1748 internal::DynTypedMatcher::VO_EachOf
1751 /// \brief Matches if any of the given matchers matches.
1753 /// Usable as: Any Matcher
1754 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
1755 internal::DynTypedMatcher::VO_AnyOf
1758 /// \brief Matches if all given matchers match.
1760 /// Usable as: Any Matcher
1761 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
1762 internal::DynTypedMatcher::VO_AllOf
1765 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1770 /// int y = sizeof(x) + alignof(x);
1772 /// unaryExprOrTypeTraitExpr()
1773 /// matches \c sizeof(x) and \c alignof(x)
1774 const internal::VariadicDynCastAllOfMatcher<
1776 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1778 /// \brief Matches unary expressions that have a specific type of argument.
1782 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1784 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1785 /// matches \c sizeof(a) and \c alignof(c)
1786 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1787 internal::Matcher<QualType>, InnerMatcher) {
1788 const QualType ArgumentType = Node.getTypeOfArgument();
1789 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1792 /// \brief Matches unary expressions of a certain kind.
1797 /// int s = sizeof(x) + alignof(x)
1799 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1800 /// matches \c sizeof(x)
1801 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1802 return Node.getKind() == Kind;
1805 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1807 inline internal::Matcher<Stmt> alignOfExpr(
1808 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1809 return stmt(unaryExprOrTypeTraitExpr(allOf(
1810 ofKind(UETT_AlignOf), InnerMatcher)));
1813 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1815 inline internal::Matcher<Stmt> sizeOfExpr(
1816 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1817 return stmt(unaryExprOrTypeTraitExpr(
1818 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1821 /// \brief Matches NamedDecl nodes that have the specified name.
1823 /// Supports specifying enclosing namespaces or classes by prefixing the name
1824 /// with '<enclosing>::'.
1825 /// Does not match typedefs of an underlying type with the given name.
1827 /// Example matches X (Name == "X")
1832 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1834 /// namespace a { namespace b { class X; } }
1836 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
1837 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Name));
1840 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1841 /// a substring matched by the given RegExp.
1843 /// Supports specifying enclosing namespaces or classes by
1844 /// prefixing the name with '<enclosing>::'. Does not match typedefs
1845 /// of an underlying type with the given name.
1847 /// Example matches X (regexp == "::X")
1852 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1854 /// namespace foo { namespace bar { class X; } }
1856 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1857 assert(!RegExp.empty());
1858 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1859 llvm::Regex RE(RegExp);
1860 return RE.match(FullNameString);
1863 /// \brief Matches overloaded operator names.
1865 /// Matches overloaded operator names specified in strings without the
1866 /// "operator" prefix: e.g. "<<".
1870 /// class A { int operator*(); };
1871 /// const A &operator<<(const A &a, const A &b);
1873 /// a << a; // <-- This matches
1876 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
1877 /// specified line and
1878 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
1879 /// matches the declaration of \c A.
1881 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
1882 inline internal::PolymorphicMatcherWithParam1<
1883 internal::HasOverloadedOperatorNameMatcher, StringRef,
1884 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
1885 hasOverloadedOperatorName(StringRef Name) {
1886 return internal::PolymorphicMatcherWithParam1<
1887 internal::HasOverloadedOperatorNameMatcher, StringRef,
1888 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
1891 /// \brief Matches C++ classes that are directly or indirectly derived from
1892 /// a class matching \c Base.
1894 /// Note that a class is not considered to be derived from itself.
1896 /// Example matches Y, Z, C (Base == hasName("X"))
1899 /// class Y : public X {}; // directly derived
1900 /// class Z : public Y {}; // indirectly derived
1903 /// class C : public B {}; // derived from a typedef of X
1906 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1910 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
1912 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1913 internal::Matcher<NamedDecl>, Base) {
1914 return Finder->classIsDerivedFrom(&Node, Base, Builder);
1917 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1918 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
1919 assert(!BaseName.empty());
1920 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1923 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1925 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
1926 internal::Matcher<NamedDecl>, Base, 0) {
1927 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
1928 .matches(Node, Finder, Builder);
1931 /// \brief Overloaded method as shortcut for
1932 /// \c isSameOrDerivedFrom(hasName(...)).
1933 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
1935 assert(!BaseName.empty());
1936 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1939 /// \brief Matches the first method of a class or struct that satisfies \c
1944 /// class A { void func(); };
1945 /// class B { void member(); };
1948 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
1949 /// \c A but not \c B.
1950 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1952 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
1953 Node.method_end(), Finder, Builder);
1956 /// \brief Matches AST nodes that have child AST nodes that match the
1957 /// provided matcher.
1959 /// Example matches X, Y
1960 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
1962 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1963 /// class Y { class X {}; };
1964 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1967 /// ChildT must be an AST base type.
1969 /// Usable as: Any Matcher
1970 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
1971 LLVM_ATTRIBUTE_UNUSED has = {};
1973 /// \brief Matches AST nodes that have descendant AST nodes that match the
1974 /// provided matcher.
1976 /// Example matches X, Y, Z
1977 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
1979 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1980 /// class Y { class X {}; };
1981 /// class Z { class Y { class X {}; }; };
1984 /// DescendantT must be an AST base type.
1986 /// Usable as: Any Matcher
1987 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
1988 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
1990 /// \brief Matches AST nodes that have child AST nodes that match the
1991 /// provided matcher.
1993 /// Example matches X, Y
1994 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
1996 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1997 /// class Y { class X {}; };
1998 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2001 /// ChildT must be an AST base type.
2003 /// As opposed to 'has', 'forEach' will cause a match for each result that
2004 /// matches instead of only on the first one.
2006 /// Usable as: Any Matcher
2007 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2008 LLVM_ATTRIBUTE_UNUSED forEach = {};
2010 /// \brief Matches AST nodes that have descendant AST nodes that match the
2011 /// provided matcher.
2013 /// Example matches X, A, B, C
2014 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2016 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2017 /// class A { class X {}; };
2018 /// class B { class C { class X {}; }; };
2021 /// DescendantT must be an AST base type.
2023 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2024 /// each result that matches instead of only on the first one.
2026 /// Note: Recursively combined ForEachDescendant can cause many matches:
2027 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2028 /// forEachDescendant(cxxRecordDecl())
2030 /// will match 10 times (plus injected class name matches) on:
2032 /// class A { class B { class C { class D { class E {}; }; }; }; };
2035 /// Usable as: Any Matcher
2036 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2037 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2039 /// \brief Matches if the node or any descendant matches.
2041 /// Generates results for each match.
2043 /// For example, in:
2045 /// class A { class B {}; class C {}; };
2049 /// cxxRecordDecl(hasName("::A"),
2050 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2052 /// will generate results for \c A, \c B and \c C.
2054 /// Usable as: Any Matcher
2055 template <typename T>
2056 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2057 return eachOf(Matcher, forEachDescendant(Matcher));
2060 /// \brief Matches AST nodes that have a parent that matches the provided
2065 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2067 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2069 /// Usable as: Any Matcher
2070 const internal::ArgumentAdaptingMatcherFunc<
2071 internal::HasParentMatcher,
2072 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2073 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2074 LLVM_ATTRIBUTE_UNUSED hasParent = {};
2076 /// \brief Matches AST nodes that have an ancestor that matches the provided
2081 /// void f() { if (true) { int x = 42; } }
2082 /// void g() { for (;;) { int x = 43; } }
2084 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2086 /// Usable as: Any Matcher
2087 const internal::ArgumentAdaptingMatcherFunc<
2088 internal::HasAncestorMatcher,
2089 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2090 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2091 LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2093 /// \brief Matches if the provided matcher does not match.
2095 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2101 /// Usable as: Any Matcher
2102 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2103 internal::DynTypedMatcher::VO_UnaryNot
2106 /// \brief Matches a node if the declaration associated with that node
2107 /// matches the given matcher.
2109 /// The associated declaration is:
2110 /// - for type nodes, the declaration of the underlying type
2111 /// - for CallExpr, the declaration of the callee
2112 /// - for MemberExpr, the declaration of the referenced member
2113 /// - for CXXConstructExpr, the declaration of the constructor
2115 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2116 /// function. e.g. various subtypes of clang::Type and various expressions.
2118 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
2119 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
2120 /// Matcher<LabelStmt>, Matcher<MemberExpr>, Matcher<QualType>,
2121 /// Matcher<RecordType>, Matcher<TagType>,
2122 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
2123 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
2124 inline internal::PolymorphicMatcherWithParam1<
2125 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2126 void(internal::HasDeclarationSupportedTypes)>
2127 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2128 return internal::PolymorphicMatcherWithParam1<
2129 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2130 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2133 /// \brief Matches on the implicit object argument of a member call expression.
2135 /// Example matches y.x()
2136 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2138 /// class Y { public: void x(); };
2139 /// void z() { Y y; y.x(); }",
2142 /// FIXME: Overload to allow directly matching types?
2143 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2145 const Expr *ExprNode = Node.getImplicitObjectArgument()
2146 ->IgnoreParenImpCasts();
2147 return (ExprNode != nullptr &&
2148 InnerMatcher.matches(*ExprNode, Finder, Builder));
2152 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2155 /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *")));
2156 /// matches the [webView ...] message invocation.
2158 /// NSString *webViewJavaScript = ...
2159 /// UIWebView *webView = ...
2160 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2162 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2164 const QualType TypeDecl = Node.getReceiverType();
2165 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2168 /// \brief Matches when BaseName == Selector.getAsString()
2170 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2171 /// matches the outer message expr in the code below, but NOT the message
2172 /// invocation for self.bodyView.
2174 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2176 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2177 Selector Sel = Node.getSelector();
2178 return BaseName.compare(Sel.getAsString()) == 0;
2182 /// \brief Matches ObjC selectors whose name contains
2183 /// a substring matched by the given RegExp.
2184 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2185 /// matches the outer message expr in the code below, but NOT the message
2186 /// invocation for self.bodyView.
2188 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2190 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2191 assert(!RegExp.empty());
2192 std::string SelectorString = Node.getSelector().getAsString();
2193 llvm::Regex RE(RegExp);
2194 return RE.match(SelectorString);
2197 /// \brief Matches when the selector is the empty selector
2199 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2200 /// represent an error condition in the tree!
2201 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2202 return Node.getSelector().isNull();
2205 /// \brief Matches when the selector is a Unary Selector
2207 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2208 /// matches self.bodyView in the code below, but NOT the outer message
2209 /// invocation of "loadHTMLString:baseURL:".
2211 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2213 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2214 return Node.getSelector().isUnarySelector();
2217 /// \brief Matches when the selector is a keyword selector
2219 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2220 /// message expression in
2223 /// UIWebView *webView = ...;
2224 /// CGRect bodyFrame = webView.frame;
2225 /// bodyFrame.size.height = self.bodyContentHeight;
2226 /// webView.frame = bodyFrame;
2227 /// // ^---- matches here
2229 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2230 return Node.getSelector().isKeywordSelector();
2233 /// \brief Matches when the selector has the specified number of arguments
2235 /// matcher = objCMessageExpr(numSelectorArgs(0));
2236 /// matches self.bodyView in the code below
2238 /// matcher = objCMessageExpr(numSelectorArgs(2));
2239 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2240 /// of self.bodyView
2242 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2244 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2245 return Node.getSelector().getNumArgs() == N;
2248 /// \brief Matches if the call expression's callee expression matches.
2252 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2253 /// void f() { f(); }
2255 /// callExpr(callee(expr()))
2256 /// matches this->x(), x(), y.x(), f()
2257 /// with callee(...)
2258 /// matching this->x, x, y.x, f respectively
2260 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2261 /// because this introduces ambiguous overloads with calls to Callee taking a
2262 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2263 /// implemented in terms of implicit casts.
2264 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2266 const Expr *ExprNode = Node.getCallee();
2267 return (ExprNode != nullptr &&
2268 InnerMatcher.matches(*ExprNode, Finder, Builder));
2271 /// \brief Matches if the call expression's callee's declaration matches the
2274 /// Example matches y.x() (matcher = callExpr(callee(
2275 /// cxxMethodDecl(hasName("x")))))
2277 /// class Y { public: void x(); };
2278 /// void z() { Y y; y.x(); }
2280 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2282 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2285 /// \brief Matches if the expression's or declaration's type matches a type
2288 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2289 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2292 /// void y(X &x) { x; X z; }
2294 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2295 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, ValueDecl),
2296 internal::Matcher<QualType>, InnerMatcher, 0) {
2297 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2300 /// \brief Overloaded to match the declaration of the expression's or value
2301 /// declaration's type.
2303 /// In case of a value declaration (for example a variable declaration),
2304 /// this resolves one layer of indirection. For example, in the value
2305 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2306 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2307 /// declaration of x.
2309 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2310 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2313 /// void y(X &x) { x; X z; }
2316 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2317 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2318 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2320 internal::Matcher<Decl>, InnerMatcher, 1) {
2321 return qualType(hasDeclaration(InnerMatcher))
2322 .matches(Node.getType(), Finder, Builder);
2325 /// \brief Matches if the type location of the declarator decl's type matches
2326 /// the inner matcher.
2332 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2334 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2335 if (!Node.getTypeSourceInfo())
2336 // This happens for example for implicit destructors.
2338 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2341 /// \brief Matches if the matched type is represented by the given string.
2345 /// class Y { public: void x(); };
2346 /// void z() { Y* y; y->x(); }
2348 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2350 AST_MATCHER_P(QualType, asString, std::string, Name) {
2351 return Name == Node.getAsString();
2354 /// \brief Matches if the matched type is a pointer type and the pointee type
2355 /// matches the specified matcher.
2357 /// Example matches y->x()
2358 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2359 /// cxxRecordDecl(hasName("Y")))))))
2361 /// class Y { public: void x(); };
2362 /// void z() { Y *y; y->x(); }
2365 QualType, pointsTo, internal::Matcher<QualType>,
2367 return (!Node.isNull() && Node->isAnyPointerType() &&
2368 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2371 /// \brief Overloaded to match the pointee type's declaration.
2372 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2374 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2375 .matches(Node, Finder, Builder);
2378 /// \brief Matches if the matched type is a reference type and the referenced
2379 /// type matches the specified matcher.
2381 /// Example matches X &x and const X &y
2382 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2391 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2393 return (!Node.isNull() && Node->isReferenceType() &&
2394 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2397 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2401 /// typedef int &int_ref;
2406 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2407 /// declaration of b but \c
2408 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2409 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2413 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2416 /// \brief Overloaded to match the referenced type's declaration.
2417 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2419 return references(qualType(hasDeclaration(InnerMatcher)))
2420 .matches(Node, Finder, Builder);
2423 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2424 internal::Matcher<Expr>, InnerMatcher) {
2425 const Expr *ExprNode = Node.getImplicitObjectArgument();
2426 return (ExprNode != nullptr &&
2427 InnerMatcher.matches(*ExprNode, Finder, Builder));
2430 /// \brief Matches if the expression's type either matches the specified
2431 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2432 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2433 internal::Matcher<QualType>, InnerMatcher, 0) {
2434 return onImplicitObjectArgument(
2435 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2436 .matches(Node, Finder, Builder);
2439 /// \brief Overloaded to match the type's declaration.
2440 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2441 internal::Matcher<Decl>, InnerMatcher, 1) {
2442 return onImplicitObjectArgument(
2443 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2444 .matches(Node, Finder, Builder);
2447 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2448 /// specified matcher.
2450 /// Example matches x in if(x)
2451 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2456 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2458 const Decl *DeclNode = Node.getDecl();
2459 return (DeclNode != nullptr &&
2460 InnerMatcher.matches(*DeclNode, Finder, Builder));
2463 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2464 /// specific using shadow declaration.
2468 /// namespace a { void f() {} }
2471 /// f(); // Matches this ..
2472 /// a::f(); // .. but not this.
2475 /// declRefExpr(throughUsingDecl(anything()))
2477 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2478 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2479 const NamedDecl *FoundDecl = Node.getFoundDecl();
2480 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2481 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2485 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2492 /// declStmt(hasSingleDecl(anything()))
2493 /// matches 'int c;' but not 'int a, b;'.
2494 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2495 if (Node.isSingleDecl()) {
2496 const Decl *FoundDecl = Node.getSingleDecl();
2497 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2502 /// \brief Matches a variable declaration that has an initializer expression
2503 /// that matches the given matcher.
2505 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2507 /// bool y() { return true; }
2511 VarDecl, hasInitializer, internal::Matcher<Expr>,
2513 const Expr *Initializer = Node.getAnyInitializer();
2514 return (Initializer != nullptr &&
2515 InnerMatcher.matches(*Initializer, Finder, Builder));
2518 /// \brief Matches a variable declaration that has function scope and is a
2519 /// non-static local variable.
2521 /// Example matches x (matcher = varDecl(hasLocalStorage())
2529 AST_MATCHER(VarDecl, hasLocalStorage) {
2530 return Node.hasLocalStorage();
2533 /// \brief Matches a variable declaration that does not have local storage.
2535 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2543 AST_MATCHER(VarDecl, hasGlobalStorage) {
2544 return Node.hasGlobalStorage();
2547 /// \brief Matches a variable declaration that has automatic storage duration.
2549 /// Example matches x, but not y, z, or a.
2550 /// (matcher = varDecl(hasAutomaticStorageDuration())
2555 /// thread_local int z;
2559 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
2560 return Node.getStorageDuration() == SD_Automatic;
2563 /// \brief Matches a variable declaration that has static storage duration.
2565 /// Example matches y and a, but not x or z.
2566 /// (matcher = varDecl(hasStaticStorageDuration())
2571 /// thread_local int z;
2575 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
2576 return Node.getStorageDuration() == SD_Static;
2579 /// \brief Matches a variable declaration that has thread storage duration.
2581 /// Example matches z, but not x, z, or a.
2582 /// (matcher = varDecl(hasThreadStorageDuration())
2587 /// thread_local int z;
2591 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
2592 return Node.getStorageDuration() == SD_Thread;
2595 /// \brief Matches a variable declaration that is an exception variable from
2596 /// a C++ catch block, or an Objective-C \@catch statement.
2598 /// Example matches x (matcher = varDecl(isExceptionVariable())
2602 /// } catch (int x) {
2606 AST_MATCHER(VarDecl, isExceptionVariable) {
2607 return Node.isExceptionVariable();
2610 /// \brief Checks that a call expression or a constructor call expression has
2611 /// a specific number of arguments (including absent default arguments).
2613 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2615 /// void f(int x, int y);
2618 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
2619 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2623 return Node.getNumArgs() == N;
2626 /// \brief Matches the n'th argument of a call expression or a constructor
2627 /// call expression.
2629 /// Example matches y in x(y)
2630 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2632 /// void x(int) { int y; x(y); }
2634 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
2635 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2638 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2639 return (N < Node.getNumArgs() &&
2640 InnerMatcher.matches(
2641 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2644 /// \brief Matches declaration statements that contain a specific number of
2654 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2655 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2656 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2659 /// \brief Matches the n'th declaration of a declaration statement.
2661 /// Note that this does not work for global declarations because the AST
2662 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2664 /// Example: Given non-global declarations
2670 /// declStmt(containsDeclaration(
2671 /// 0, varDecl(hasInitializer(anything()))))
2672 /// matches only 'int d = 2, e;', and
2673 /// declStmt(containsDeclaration(1, varDecl()))
2675 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2676 /// but 'int c;' is not matched.
2678 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2679 internal::Matcher<Decl>, InnerMatcher) {
2680 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2683 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2684 std::advance(Iterator, N);
2685 return InnerMatcher.matches(**Iterator, Finder, Builder);
2688 /// \brief Matches a C++ catch statement that has a catch-all handler.
2700 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
2701 AST_MATCHER(CXXCatchStmt, isCatchAll) {
2702 return Node.getExceptionDecl() == nullptr;
2705 /// \brief Matches a constructor initializer.
2710 /// Foo() : foo_(1) { }
2714 /// cxxRecordDecl(has(cxxConstructorDecl(
2715 /// hasAnyConstructorInitializer(anything())
2717 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2718 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2719 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2720 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2721 Node.init_end(), Finder, Builder);
2724 /// \brief Matches the field declaration of a constructor initializer.
2729 /// Foo() : foo_(1) { }
2733 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2734 /// forField(hasName("foo_"))))))
2736 /// with forField matching foo_
2737 AST_MATCHER_P(CXXCtorInitializer, forField,
2738 internal::Matcher<FieldDecl>, InnerMatcher) {
2739 const FieldDecl *NodeAsDecl = Node.getMember();
2740 return (NodeAsDecl != nullptr &&
2741 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2744 /// \brief Matches the initializer expression of a constructor initializer.
2749 /// Foo() : foo_(1) { }
2753 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2754 /// withInitializer(integerLiteral(equals(1)))))))
2756 /// with withInitializer matching (1)
2757 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2758 internal::Matcher<Expr>, InnerMatcher) {
2759 const Expr* NodeAsExpr = Node.getInit();
2760 return (NodeAsExpr != nullptr &&
2761 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2764 /// \brief Matches a constructor initializer if it is explicitly written in
2765 /// code (as opposed to implicitly added by the compiler).
2771 /// Foo(int) : foo_("A") { }
2775 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
2776 /// will match Foo(int), but not Foo()
2777 AST_MATCHER(CXXCtorInitializer, isWritten) {
2778 return Node.isWritten();
2781 /// \brief Matches a constructor initializer if it is initializing a base, as
2782 /// opposed to a member.
2789 /// D(int i) : I(i) {}
2795 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
2796 /// will match E(), but not match D(int).
2797 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
2798 return Node.isBaseInitializer();
2801 /// \brief Matches a constructor initializer if it is initializing a member, as
2802 /// opposed to a base.
2809 /// D(int i) : I(i) {}
2815 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
2816 /// will match D(int), but not match E().
2817 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
2818 return Node.isMemberInitializer();
2821 /// \brief Matches any argument of a call expression or a constructor call
2826 /// void x(int, int, int) { int y; x(1, y, 42); }
2828 /// callExpr(hasAnyArgument(declRefExpr()))
2829 /// matches x(1, y, 42)
2830 /// with hasAnyArgument(...)
2833 /// FIXME: Currently this will ignore parentheses and implicit casts on
2834 /// the argument before applying the inner matcher. We'll want to remove
2835 /// this to allow for greater control by the user once \c ignoreImplicit()
2836 /// has been implemented.
2837 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
2838 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2840 internal::Matcher<Expr>, InnerMatcher) {
2841 for (const Expr *Arg : Node.arguments()) {
2842 BoundNodesTreeBuilder Result(*Builder);
2843 if (InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, &Result)) {
2844 *Builder = std::move(Result);
2851 /// \brief Matches a constructor call expression which uses list initialization.
2852 AST_MATCHER(CXXConstructExpr, isListInitialization) {
2853 return Node.isListInitialization();
2856 /// \brief Matches the n'th parameter of a function declaration.
2860 /// class X { void f(int x) {} };
2862 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
2863 /// matches f(int x) {}
2864 /// with hasParameter(...)
2866 AST_MATCHER_P2(FunctionDecl, hasParameter,
2867 unsigned, N, internal::Matcher<ParmVarDecl>,
2869 return (N < Node.getNumParams() &&
2870 InnerMatcher.matches(
2871 *Node.getParamDecl(N), Finder, Builder));
2874 /// \brief Matches any parameter of a function declaration.
2876 /// Does not match the 'this' parameter of a method.
2880 /// class X { void f(int x, int y, int z) {} };
2882 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
2883 /// matches f(int x, int y, int z) {}
2884 /// with hasAnyParameter(...)
2886 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2887 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2888 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2889 Node.param_end(), Finder, Builder);
2892 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2896 /// void f(int i) {}
2897 /// void g(int i, int j) {}
2899 /// functionDecl(parameterCountIs(2))
2900 /// matches g(int i, int j) {}
2901 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2902 return Node.getNumParams() == N;
2905 /// \brief Matches the return type of a function declaration.
2909 /// class X { int f() { return 1; } };
2911 /// cxxMethodDecl(returns(asString("int")))
2912 /// matches int f() { return 1; }
2913 AST_MATCHER_P(FunctionDecl, returns,
2914 internal::Matcher<QualType>, InnerMatcher) {
2915 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
2918 /// \brief Matches extern "C" function declarations.
2922 /// extern "C" void f() {}
2923 /// extern "C" { void g() {} }
2926 /// functionDecl(isExternC())
2927 /// matches the declaration of f and g, but not the declaration h
2928 AST_MATCHER(FunctionDecl, isExternC) {
2929 return Node.isExternC();
2932 /// \brief Matches deleted function declarations.
2937 /// void DeletedFunc() = delete;
2939 /// functionDecl(isDeleted())
2940 /// matches the declaration of DeletedFunc, but not Func.
2941 AST_MATCHER(FunctionDecl, isDeleted) {
2942 return Node.isDeleted();
2945 /// \brief Matches functions that have a non-throwing exception specification.
2950 /// void g() noexcept;
2951 /// void h() throw();
2952 /// void i() throw(int);
2953 /// void j() noexcept(false);
2955 /// functionDecl(isNoThrow())
2956 /// matches the declarations of g, and h, but not f, i or j.
2957 AST_MATCHER(FunctionDecl, isNoThrow) {
2958 const auto *FnTy = Node.getType()->getAs<FunctionProtoType>();
2960 // If the function does not have a prototype, then it is assumed to be a
2961 // throwing function (as it would if the function did not have any exception
2966 // Assume the best for any unresolved exception specification.
2967 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
2970 return FnTy->isNothrow(Node.getASTContext());
2973 /// \brief Matches constexpr variable and function declarations.
2977 /// constexpr int foo = 42;
2978 /// constexpr int bar();
2980 /// varDecl(isConstexpr())
2981 /// matches the declaration of foo.
2982 /// functionDecl(isConstexpr())
2983 /// matches the declaration of bar.
2984 AST_POLYMORPHIC_MATCHER(isConstexpr,
2985 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
2987 return Node.isConstexpr();
2990 /// \brief Matches the condition expression of an if statement, for loop,
2991 /// or conditional operator.
2993 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
2997 AST_POLYMORPHIC_MATCHER_P(hasCondition,
2998 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt,
3000 ConditionalOperator),
3001 internal::Matcher<Expr>, InnerMatcher) {
3002 const Expr *const Condition = Node.getCond();
3003 return (Condition != nullptr &&
3004 InnerMatcher.matches(*Condition, Finder, Builder));
3007 /// \brief Matches the then-statement of an if statement.
3009 /// Examples matches the if statement
3010 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3012 /// if (false) true; else false;
3014 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3015 const Stmt *const Then = Node.getThen();
3016 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3019 /// \brief Matches the else-statement of an if statement.
3021 /// Examples matches the if statement
3022 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3024 /// if (false) false; else true;
3026 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3027 const Stmt *const Else = Node.getElse();
3028 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3031 /// \brief Matches if a node equals a previously bound node.
3033 /// Matches a node if it equals the node previously bound to \p ID.
3037 /// class X { int a; int b; };
3040 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3041 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3042 /// matches the class \c X, as \c a and \c b have the same type.
3044 /// Note that when multiple matches are involved via \c forEach* matchers,
3045 /// \c equalsBoundNodes acts as a filter.
3048 /// forEachDescendant(varDecl().bind("d")),
3049 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3050 /// will trigger a match for each combination of variable declaration
3051 /// and reference to that variable declaration within a compound statement.
3052 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3053 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3056 // FIXME: Figure out whether it makes sense to allow this
3057 // on any other node types.
3058 // For *Loc it probably does not make sense, as those seem
3059 // unique. For NestedNameSepcifier it might make sense, as
3060 // those also have pointer identity, but I'm not sure whether
3061 // they're ever reused.
3062 internal::NotEqualsBoundNodePredicate Predicate;
3064 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3065 return Builder->removeBindings(Predicate);
3068 /// \brief Matches the condition variable statement in an if statement.
3072 /// if (A* a = GetAPointer()) {}
3074 /// hasConditionVariableStatement(...)
3075 /// matches 'A* a = GetAPointer()'.
3076 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3077 internal::Matcher<DeclStmt>, InnerMatcher) {
3078 const DeclStmt* const DeclarationStatement =
3079 Node.getConditionVariableDeclStmt();
3080 return DeclarationStatement != nullptr &&
3081 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3084 /// \brief Matches the index expression of an array subscript expression.
3089 /// void f() { i[1] = 42; }
3091 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3092 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3093 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3094 internal::Matcher<Expr>, InnerMatcher) {
3095 if (const Expr* Expression = Node.getIdx())
3096 return InnerMatcher.matches(*Expression, Finder, Builder);
3100 /// \brief Matches the base expression of an array subscript expression.
3105 /// void f() { i[1] = 42; }
3107 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3108 /// hasSourceExpression(declRefExpr()))))
3109 /// matches \c i[1] with the \c declRefExpr() matching \c i
3110 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3111 internal::Matcher<Expr>, InnerMatcher) {
3112 if (const Expr* Expression = Node.getBase())
3113 return InnerMatcher.matches(*Expression, Finder, Builder);
3117 /// \brief Matches a 'for', 'while', or 'do while' statement that has
3124 /// hasBody(compoundStmt())
3125 /// matches 'for (;;) {}'
3126 /// with compoundStmt()
3128 AST_POLYMORPHIC_MATCHER_P(hasBody,
3129 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3132 internal::Matcher<Stmt>, InnerMatcher) {
3133 const Stmt *const Statement = Node.getBody();
3134 return (Statement != nullptr &&
3135 InnerMatcher.matches(*Statement, Finder, Builder));
3138 /// \brief Matches compound statements where at least one substatement matches
3139 /// a given matcher.
3145 /// hasAnySubstatement(compoundStmt())
3146 /// matches '{ {}; 1+2; }'
3147 /// with compoundStmt()
3149 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
3150 internal::Matcher<Stmt>, InnerMatcher) {
3151 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
3152 Node.body_end(), Finder, Builder);
3155 /// \brief Checks that a compound statement contains a specific number of
3156 /// child statements.
3162 /// compoundStmt(statementCountIs(0)))
3164 /// but does not match the outer compound statement.
3165 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3166 return Node.size() == N;
3169 /// \brief Matches literals that are equal to the given value.
3171 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3176 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3177 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3178 template <typename ValueT>
3179 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3180 equals(const ValueT &Value) {
3181 return internal::PolymorphicMatcherWithParam1<
3182 internal::ValueEqualsMatcher,
3186 /// \brief Matches the operator Name of operator expressions (binary or
3189 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3193 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3194 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3196 std::string, Name) {
3197 return Name == Node.getOpcodeStr(Node.getOpcode());
3200 /// \brief Matches the left hand side of binary operator expressions.
3202 /// Example matches a (matcher = binaryOperator(hasLHS()))
3206 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3207 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3208 ArraySubscriptExpr),
3209 internal::Matcher<Expr>, InnerMatcher) {
3210 const Expr *LeftHandSide = Node.getLHS();
3211 return (LeftHandSide != nullptr &&
3212 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3215 /// \brief Matches the right hand side of binary operator expressions.
3217 /// Example matches b (matcher = binaryOperator(hasRHS()))
3221 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3222 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3223 ArraySubscriptExpr),
3224 internal::Matcher<Expr>, InnerMatcher) {
3225 const Expr *RightHandSide = Node.getRHS();
3226 return (RightHandSide != nullptr &&
3227 InnerMatcher.matches(*RightHandSide, Finder, Builder));
3230 /// \brief Matches if either the left hand side or the right hand side of a
3231 /// binary operator matches.
3232 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3233 const internal::Matcher<Expr> &InnerMatcher) {
3234 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3237 /// \brief Matches if the operand of a unary operator matches.
3239 /// Example matches true (matcher = hasUnaryOperand(
3240 /// cxxBoolLiteral(equals(true))))
3244 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3245 internal::Matcher<Expr>, InnerMatcher) {
3246 const Expr * const Operand = Node.getSubExpr();
3247 return (Operand != nullptr &&
3248 InnerMatcher.matches(*Operand, Finder, Builder));
3251 /// \brief Matches if the cast's source expression matches the given matcher.
3253 /// Example: matches "a string" (matcher =
3254 /// hasSourceExpression(cxxConstructExpr()))
3256 /// class URL { URL(string); };
3257 /// URL url = "a string";
3259 AST_MATCHER_P(CastExpr, hasSourceExpression,
3260 internal::Matcher<Expr>, InnerMatcher) {
3261 const Expr* const SubExpression = Node.getSubExpr();
3262 return (SubExpression != nullptr &&
3263 InnerMatcher.matches(*SubExpression, Finder, Builder));
3266 /// \brief Matches casts whose destination type matches a given matcher.
3268 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3269 /// actual casts "explicit" casts.)
3270 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3271 internal::Matcher<QualType>, InnerMatcher) {
3272 const QualType NodeType = Node.getTypeAsWritten();
3273 return InnerMatcher.matches(NodeType, Finder, Builder);
3276 /// \brief Matches implicit casts whose destination type matches a given
3279 /// FIXME: Unit test this matcher
3280 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3281 internal::Matcher<QualType>, InnerMatcher) {
3282 return InnerMatcher.matches(Node.getType(), Finder, Builder);
3285 /// \brief Matches RecordDecl object that are spelled with "struct."
3287 /// Example matches S, but not C or U.
3293 AST_MATCHER(RecordDecl, isStruct) {
3294 return Node.isStruct();
3297 /// \brief Matches RecordDecl object that are spelled with "union."
3299 /// Example matches U, but not C or S.
3305 AST_MATCHER(RecordDecl, isUnion) {
3306 return Node.isUnion();
3309 /// \brief Matches RecordDecl object that are spelled with "class."
3311 /// Example matches C, but not S or U.
3317 AST_MATCHER(RecordDecl, isClass) {
3318 return Node.isClass();
3321 /// \brief Matches the true branch expression of a conditional operator.
3323 /// Example matches a
3325 /// condition ? a : b
3327 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
3328 internal::Matcher<Expr>, InnerMatcher) {
3329 const Expr *Expression = Node.getTrueExpr();
3330 return (Expression != nullptr &&
3331 InnerMatcher.matches(*Expression, Finder, Builder));
3334 /// \brief Matches the false branch expression of a conditional operator.
3336 /// Example matches b
3338 /// condition ? a : b
3340 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
3341 internal::Matcher<Expr>, InnerMatcher) {
3342 const Expr *Expression = Node.getFalseExpr();
3343 return (Expression != nullptr &&
3344 InnerMatcher.matches(*Expression, Finder, Builder));
3347 /// \brief Matches if a declaration has a body attached.
3349 /// Example matches A, va, fa
3352 /// class B; // Doesn't match, as it has no body.
3354 /// extern int vb; // Doesn't match, as it doesn't define the variable.
3356 /// void fb(); // Doesn't match, as it has no body.
3359 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
3360 AST_POLYMORPHIC_MATCHER(isDefinition,
3361 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
3363 return Node.isThisDeclarationADefinition();
3366 /// \brief Matches if a function declaration is variadic.
3368 /// Example matches f, but not g or h. The function i will not match, even when
3369 /// compiled in C mode.
3373 /// template <typename... Ts> void h(Ts...);
3376 AST_MATCHER(FunctionDecl, isVariadic) {
3377 return Node.isVariadic();
3380 /// \brief Matches the class declaration that the given method declaration
3383 /// FIXME: Generalize this for other kinds of declarations.
3384 /// FIXME: What other kind of declarations would we need to generalize
3387 /// Example matches A() in the last line
3388 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
3389 /// ofClass(hasName("A"))))))
3397 AST_MATCHER_P(CXXMethodDecl, ofClass,
3398 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
3399 const CXXRecordDecl *Parent = Node.getParent();
3400 return (Parent != nullptr &&
3401 InnerMatcher.matches(*Parent, Finder, Builder));
3404 /// \brief Matches if the given method declaration is virtual.
3410 /// virtual void x();
3414 AST_MATCHER(CXXMethodDecl, isVirtual) {
3415 return Node.isVirtual();
3418 /// \brief Matches if the given method or class declaration is final.
3422 /// class A final {};
3425 /// virtual void f();
3432 /// matches A and C::f, but not B, C, or B::f
3433 AST_POLYMORPHIC_MATCHER(isFinal,
3434 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
3436 return Node.template hasAttr<FinalAttr>();
3439 /// \brief Matches if the given method declaration is pure.
3445 /// virtual void x() = 0;
3449 AST_MATCHER(CXXMethodDecl, isPure) {
3450 return Node.isPure();
3453 /// \brief Matches if the given method declaration is const.
3458 /// void foo() const;
3463 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
3464 AST_MATCHER(CXXMethodDecl, isConst) {
3465 return Node.isConst();
3468 /// \brief Matches if the given method declaration declares a copy assignment
3474 /// A &operator=(const A &);
3475 /// A &operator=(A &&);
3479 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
3481 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
3482 return Node.isCopyAssignmentOperator();
3485 /// \brief Matches if the given method declaration overrides another method.
3491 /// virtual void x();
3493 /// class B : public A {
3495 /// virtual void x();
3499 AST_MATCHER(CXXMethodDecl, isOverride) {
3500 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
3503 /// \brief Matches member expressions that are called with '->' as opposed
3506 /// Member calls on the implicit this pointer match as called with '->'.
3511 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
3516 /// memberExpr(isArrow())
3517 /// matches this->x, x, y.x, a, this->b
3518 AST_MATCHER(MemberExpr, isArrow) {
3519 return Node.isArrow();
3522 /// \brief Matches QualType nodes that are of integer type.
3530 /// functionDecl(hasAnyParameter(hasType(isInteger())))
3531 /// matches "a(int)", "b(long)", but not "c(double)".
3532 AST_MATCHER(QualType, isInteger) {
3533 return Node->isIntegerType();
3536 /// \brief Matches QualType nodes that are of character type.
3541 /// void b(wchar_t);
3544 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
3545 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
3546 AST_MATCHER(QualType, isAnyCharacter) {
3547 return Node->isAnyCharacterType();
3550 /// \brief Matches QualType nodes that are const-qualified, i.e., that
3551 /// include "top-level" const.
3556 /// void b(int const);
3557 /// void c(const int);
3558 /// void d(const int*);
3559 /// void e(int const) {};
3561 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
3562 /// matches "void b(int const)", "void c(const int)" and
3563 /// "void e(int const) {}". It does not match d as there
3564 /// is no top-level const on the parameter type "const int *".
3565 AST_MATCHER(QualType, isConstQualified) {
3566 return Node.isConstQualified();
3569 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
3570 /// include "top-level" volatile.
3575 /// void b(int volatile);
3576 /// void c(volatile int);
3577 /// void d(volatile int*);
3578 /// void e(int volatile) {};
3580 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
3581 /// matches "void b(int volatile)", "void c(volatile int)" and
3582 /// "void e(int volatile) {}". It does not match d as there
3583 /// is no top-level volatile on the parameter type "volatile int *".
3584 AST_MATCHER(QualType, isVolatileQualified) {
3585 return Node.isVolatileQualified();
3588 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
3589 /// the node, not hidden within a typedef.
3593 /// typedef const int const_int;
3596 /// int *volatile k;
3599 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
3600 /// \c i is const-qualified but the qualifier is not local.
3601 AST_MATCHER(QualType, hasLocalQualifiers) {
3602 return Node.hasLocalQualifiers();
3605 /// \brief Matches a member expression where the member is matched by a
3610 /// struct { int first, second; } first, second;
3611 /// int i(second.first);
3612 /// int j(first.second);
3614 /// memberExpr(member(hasName("first")))
3615 /// matches second.first
3616 /// but not first.second (because the member name there is "second").
3617 AST_MATCHER_P(MemberExpr, member,
3618 internal::Matcher<ValueDecl>, InnerMatcher) {
3619 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
3622 /// \brief Matches a member expression where the object expression is
3623 /// matched by a given matcher.
3627 /// struct X { int m; };
3628 /// void f(X x) { x.m; m; }
3630 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
3631 /// matches "x.m" and "m"
3632 /// with hasObjectExpression(...)
3633 /// matching "x" and the implicit object expression of "m" which has type X*.
3634 AST_MATCHER_P(MemberExpr, hasObjectExpression,
3635 internal::Matcher<Expr>, InnerMatcher) {
3636 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
3639 /// \brief Matches any using shadow declaration.
3643 /// namespace X { void b(); }
3646 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
3647 /// matches \code using X::b \endcode
3648 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
3649 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3650 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
3651 Node.shadow_end(), Finder, Builder);
3654 /// \brief Matches a using shadow declaration where the target declaration is
3655 /// matched by the given matcher.
3659 /// namespace X { int a; void b(); }
3663 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
3664 /// matches \code using X::b \endcode
3665 /// but not \code using X::a \endcode
3666 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
3667 internal::Matcher<NamedDecl>, InnerMatcher) {
3668 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
3671 /// \brief Matches template instantiations of function, class, or static
3672 /// member variable template instantiations.
3676 /// template <typename T> class X {}; class A {}; X<A> x;
3680 /// template <typename T> class X {}; class A {}; template class X<A>;
3682 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
3683 /// matches the template instantiation of X<A>.
3687 /// template <typename T> class X {}; class A {};
3688 /// template <> class X<A> {}; X<A> x;
3690 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
3691 /// does not match, as X<A> is an explicit template specialization.
3693 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
3694 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
3695 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
3697 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
3698 Node.getTemplateSpecializationKind() ==
3699 TSK_ExplicitInstantiationDefinition);
3702 /// \brief Matches declarations that are template instantiations or are inside
3703 /// template instantiations.
3707 /// template<typename T> void A(T t) { T i; }
3711 /// functionDecl(isInstantiated())
3712 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
3713 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
3714 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
3715 functionDecl(isTemplateInstantiation())));
3716 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
3719 /// \brief Matches statements inside of a template instantiation.
3724 /// template<typename T> void A(T t) { T i; j += 42;}
3728 /// declStmt(isInTemplateInstantiation())
3729 /// matches 'int i;' and 'unsigned i'.
3730 /// unless(stmt(isInTemplateInstantiation()))
3731 /// will NOT match j += 42; as it's shared between the template definition and
3733 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
3735 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
3736 functionDecl(isTemplateInstantiation())))));
3739 /// \brief Matches explicit template specializations of function, class, or
3740 /// static member variable template instantiations.
3744 /// template<typename T> void A(T t) { }
3745 /// template<> void A(int N) { }
3747 /// functionDecl(isExplicitTemplateSpecialization())
3748 /// matches the specialization A<int>().
3750 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
3751 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
3752 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
3754 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
3757 /// \brief Matches \c TypeLocs for which the given inner
3758 /// QualType-matcher matches.
3759 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
3760 internal::Matcher<QualType>, InnerMatcher, 0) {
3761 return internal::BindableMatcher<TypeLoc>(
3762 new internal::TypeLocTypeMatcher(InnerMatcher));
3765 /// \brief Matches type \c bool.
3769 /// struct S { bool func(); };
3771 /// functionDecl(returns(booleanType()))
3772 /// matches "bool func();"
3773 AST_MATCHER(Type, booleanType) {
3774 return Node.isBooleanType();
3777 /// \brief Matches type \c void.
3781 /// struct S { void func(); };
3783 /// functionDecl(returns(voidType()))
3784 /// matches "void func();"
3785 AST_MATCHER(Type, voidType) {
3786 return Node.isVoidType();
3789 /// \brief Matches builtin Types.
3800 /// matches "int b", "float c" and "bool d"
3801 AST_TYPE_MATCHER(BuiltinType, builtinType);
3803 /// \brief Matches all kinds of arrays.
3807 /// int a[] = { 2, 3 };
3809 /// void f() { int c[a[0]]; }
3812 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
3813 AST_TYPE_MATCHER(ArrayType, arrayType);
3815 /// \brief Matches C99 complex types.
3819 /// _Complex float f;
3822 /// matches "_Complex float f"
3823 AST_TYPE_MATCHER(ComplexType, complexType);
3825 /// \brief Matches arrays and C99 complex types that have a specific element
3834 /// arrayType(hasElementType(builtinType()))
3835 /// matches "int b[7]"
3837 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
3838 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
3839 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
3842 /// \brief Matches C arrays with a specified constant size.
3848 /// int b[] = { 2, 3 };
3852 /// constantArrayType()
3853 /// matches "int a[2]"
3854 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
3856 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
3862 /// int c[41], d[43];
3864 /// constantArrayType(hasSize(42))
3865 /// matches "int a[42]" and "int b[2 * 21]"
3866 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
3867 return Node.getSize() == N;
3870 /// \brief Matches C++ arrays whose size is a value-dependent expression.
3874 /// template<typename T, int Size>
3879 /// dependentSizedArrayType
3880 /// matches "T data[Size]"
3881 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
3883 /// \brief Matches C arrays with unspecified size.
3887 /// int a[] = { 2, 3 };
3889 /// void f(int c[]) { int d[a[0]]; };
3891 /// incompleteArrayType()
3892 /// matches "int a[]" and "int c[]"
3893 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
3895 /// \brief Matches C arrays with a specified size that is not an
3896 /// integer-constant-expression.
3901 /// int a[] = { 2, 3 }
3906 /// variableArrayType()
3907 /// matches "int c[a[0]]"
3908 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
3910 /// \brief Matches \c VariableArrayType nodes that have a specific size
3919 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3920 /// varDecl(hasName("b")))))))
3921 /// matches "int a[b]"
3922 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
3923 internal::Matcher<Expr>, InnerMatcher) {
3924 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
3927 /// \brief Matches atomic types.
3934 /// matches "_Atomic(int) i"
3935 AST_TYPE_MATCHER(AtomicType, atomicType);
3937 /// \brief Matches atomic types with a specific value type.
3942 /// _Atomic(float) f;
3944 /// atomicType(hasValueType(isInteger()))
3945 /// matches "_Atomic(int) i"
3947 /// Usable as: Matcher<AtomicType>
3948 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
3949 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
3951 /// \brief Matches types nodes representing C++11 auto types.
3956 /// int v[] = { 2, 3 }
3957 /// for (auto i : v) { }
3960 /// matches "auto n" and "auto i"
3961 AST_TYPE_MATCHER(AutoType, autoType);
3963 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3965 /// Note: There is no \c TypeLoc for the deduced type and thus no
3966 /// \c getDeducedLoc() matcher.
3973 /// autoType(hasDeducedType(isInteger()))
3974 /// matches "auto a"
3976 /// Usable as: Matcher<AutoType>
3977 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3978 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
3980 /// \brief Matches \c FunctionType nodes.
3988 /// matches "int (*f)(int)" and the type of "g".
3989 AST_TYPE_MATCHER(FunctionType, functionType);
3991 /// \brief Matches \c ParenType nodes.
3995 /// int (*ptr_to_array)[4];
3996 /// int *array_of_ptrs[4];
3999 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4000 /// \c array_of_ptrs.
4001 AST_TYPE_MATCHER(ParenType, parenType);
4003 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4007 /// int (*ptr_to_array)[4];
4008 /// int (*ptr_to_func)(int);
4011 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4012 /// \c ptr_to_func but not \c ptr_to_array.
4014 /// Usable as: Matcher<ParenType>
4015 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4016 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4018 /// \brief Matches block pointer types, i.e. types syntactically represented as
4019 /// "void (^)(int)".
4021 /// The \c pointee is always required to be a \c FunctionType.
4022 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4024 /// \brief Matches member pointer types.
4027 /// struct A { int i; }
4028 /// A::* ptr = A::i;
4030 /// memberPointerType()
4031 /// matches "A::* ptr"
4032 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4034 /// \brief Matches pointer types, but does not match Objective-C object pointer
4048 /// matches "int *a", but does not match "Foo *f".
4049 AST_TYPE_MATCHER(PointerType, pointerType);
4051 /// \brief Matches an Objective-C object pointer type, which is different from
4052 /// a pointer type, despite being syntactically similar.
4063 /// matches "Foo *f", but does not match "int *a".
4064 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4066 /// \brief Matches both lvalue and rvalue reference types.
4079 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4080 AST_TYPE_MATCHER(ReferenceType, referenceType);
4082 /// \brief Matches lvalue reference types.
4095 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4096 /// matched since the type is deduced as int& by reference collapsing rules.
4097 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4099 /// \brief Matches rvalue reference types.
4112 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4113 /// matched as it is deduced to int& by reference collapsing rules.
4114 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4116 /// \brief Narrows PointerType (and similar) matchers to those where the
4117 /// \c pointee matches a given matcher.
4125 /// pointerType(pointee(isConstQualified(), isInteger()))
4126 /// matches "int const *b"
4128 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4129 /// Matcher<PointerType>, Matcher<ReferenceType>
4130 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4131 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4136 /// \brief Matches typedef types.
4143 /// matches "typedef int X"
4144 AST_TYPE_MATCHER(TypedefType, typedefType);
4146 /// \brief Matches template specialization types.
4150 /// template <typename T>
4153 /// template class C<int>; // A
4154 /// C<char> var; // B
4157 /// \c templateSpecializationType() matches the type of the explicit
4158 /// instantiation in \c A and the type of the variable declaration in \c B.
4159 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
4161 /// \brief Matches types nodes representing unary type transformations.
4165 /// typedef __underlying_type(T) type;
4167 /// unaryTransformType()
4168 /// matches "__underlying_type(T)"
4169 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
4171 /// \brief Matches record types (e.g. structs, classes).
4182 /// \c recordType() matches the type of the variable declarations of both \c c
4184 AST_TYPE_MATCHER(RecordType, recordType);
4186 /// \brief Matches types specified with an elaborated type keyword or with a
4202 /// \c elaboratedType() matches the type of the variable declarations of both
4204 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
4206 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
4207 /// matches \c InnerMatcher if the qualifier exists.
4219 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
4220 /// matches the type of the variable declaration of \c d.
4221 AST_MATCHER_P(ElaboratedType, hasQualifier,
4222 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
4223 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
4224 return InnerMatcher.matches(*Qualifier, Finder, Builder);
4229 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
4241 /// \c elaboratedType(namesType(recordType(
4242 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
4243 /// declaration of \c d.
4244 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
4246 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
4249 /// \brief Matches types that represent the result of substituting a type for a
4250 /// template type parameter.
4254 /// template <typename T>
4260 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
4261 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
4263 /// \brief Matches template type parameter types.
4265 /// Example matches T, but not int.
4266 /// (matcher = templateTypeParmType())
4268 /// template <typename T> void f(int i);
4270 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
4272 /// \brief Matches injected class name types.
4274 /// Example matches S s, but not S<T> s.
4275 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
4277 /// template <typename T> struct S {
4282 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
4284 /// \brief Matches decayed type
4285 /// Example matches i[] in declaration of f.
4286 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
4287 /// Example matches i[1].
4288 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
4290 /// void f(int i[]) {
4294 AST_TYPE_MATCHER(DecayedType, decayedType);
4296 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
4297 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
4299 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
4302 /// \brief Matches declarations whose declaration context, interpreted as a
4303 /// Decl, matches \c InnerMatcher.
4314 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
4315 /// declaration of \c class \c D.
4316 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
4317 const DeclContext *DC = Node.getDeclContext();
4318 if (!DC) return false;
4319 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
4322 /// \brief Matches nested name specifiers.
4327 /// struct A { static void f(); };
4329 /// void g() { A::f(); }
4333 /// nestedNameSpecifier()
4334 /// matches "ns::" and both "A::"
4335 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
4337 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
4338 const internal::VariadicAllOfMatcher<
4339 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
4341 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
4342 /// NestedNameSpecifier-matcher matches.
4343 AST_MATCHER_FUNCTION_P_OVERLOAD(
4344 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
4345 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
4346 return internal::BindableMatcher<NestedNameSpecifierLoc>(
4347 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
4351 /// \brief Matches nested name specifiers that specify a type matching the
4352 /// given \c QualType matcher without qualifiers.
4356 /// struct A { struct B { struct C {}; }; };
4359 /// nestedNameSpecifier(specifiesType(
4360 /// hasDeclaration(cxxRecordDecl(hasName("A")))
4363 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
4364 internal::Matcher<QualType>, InnerMatcher) {
4365 if (!Node.getAsType())
4367 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
4370 /// \brief Matches nested name specifier locs that specify a type matching the
4371 /// given \c TypeLoc.
4375 /// struct A { struct B { struct C {}; }; };
4378 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
4379 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
4381 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
4382 internal::Matcher<TypeLoc>, InnerMatcher) {
4383 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
4386 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
4390 /// struct A { struct B { struct C {}; }; };
4393 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
4395 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
4396 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
4398 const NestedNameSpecifier *NextNode = Node.getPrefix();
4401 return InnerMatcher.matches(*NextNode, Finder, Builder);
4404 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
4408 /// struct A { struct B { struct C {}; }; };
4411 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
4413 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
4414 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
4416 NestedNameSpecifierLoc NextNode = Node.getPrefix();
4419 return InnerMatcher.matches(NextNode, Finder, Builder);
4422 /// \brief Matches nested name specifiers that specify a namespace matching the
4423 /// given namespace matcher.
4427 /// namespace ns { struct A {}; }
4430 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
4432 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
4433 internal::Matcher<NamespaceDecl>, InnerMatcher) {
4434 if (!Node.getAsNamespace())
4436 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
4439 /// \brief Overloads for the \c equalsNode matcher.
4440 /// FIXME: Implement for other node types.
4443 /// \brief Matches if a node equals another node.
4445 /// \c Decl has pointer identity in the AST.
4446 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
4447 return &Node == Other;
4449 /// \brief Matches if a node equals another node.
4451 /// \c Stmt has pointer identity in the AST.
4452 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
4453 return &Node == Other;
4455 /// \brief Matches if a node equals another node.
4457 /// \c Type has pointer identity in the AST.
4458 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
4459 return &Node == Other;
4464 /// \brief Matches each case or default statement belonging to the given switch
4465 /// statement. This matcher may produce multiple matches.
4469 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
4471 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
4472 /// matches four times, with "c" binding each of "case 1:", "case 2:",
4473 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
4474 /// "switch (1)", "switch (2)" and "switch (2)".
4475 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
4477 BoundNodesTreeBuilder Result;
4478 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
4479 // iteration order. We should use the more general iterating matchers once
4480 // they are capable of expressing this matcher (for example, it should ignore
4481 // case statements belonging to nested switch statements).
4482 bool Matched = false;
4483 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
4484 SC = SC->getNextSwitchCase()) {
4485 BoundNodesTreeBuilder CaseBuilder(*Builder);
4486 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
4489 Result.addMatch(CaseBuilder);
4492 *Builder = std::move(Result);
4496 /// \brief Matches each constructor initializer in a constructor definition.
4500 /// class A { A() : i(42), j(42) {} int i; int j; };
4502 /// cxxConstructorDecl(forEachConstructorInitializer(
4503 /// forField(decl().bind("x"))
4505 /// will trigger two matches, binding for 'i' and 'j' respectively.
4506 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
4507 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4508 BoundNodesTreeBuilder Result;
4509 bool Matched = false;
4510 for (const auto *I : Node.inits()) {
4511 BoundNodesTreeBuilder InitBuilder(*Builder);
4512 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
4514 Result.addMatch(InitBuilder);
4517 *Builder = std::move(Result);
4521 /// \brief Matches constructor declarations that are copy constructors.
4527 /// S(const S &); // #2
4531 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
4532 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
4533 return Node.isCopyConstructor();
4536 /// \brief Matches constructor declarations that are move constructors.
4542 /// S(const S &); // #2
4546 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
4547 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
4548 return Node.isMoveConstructor();
4551 /// \brief Matches constructor declarations that are default constructors.
4557 /// S(const S &); // #2
4561 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
4562 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
4563 return Node.isDefaultConstructor();
4566 /// \brief Matches constructor and conversion declarations that are marked with
4567 /// the explicit keyword.
4573 /// explicit S(double); // #2
4574 /// operator int(); // #3
4575 /// explicit operator bool(); // #4
4578 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
4579 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
4580 AST_POLYMORPHIC_MATCHER(isExplicit,
4581 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
4582 CXXConversionDecl)) {
4583 return Node.isExplicit();
4586 /// \brief Matches function and namespace declarations that are marked with
4587 /// the inline keyword.
4591 /// inline void f();
4594 /// inline namespace m {}
4597 /// functionDecl(isInline()) will match ::f().
4598 /// namespaceDecl(isInline()) will match n::m.
4599 AST_POLYMORPHIC_MATCHER(isInline,
4600 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
4602 // This is required because the spelling of the function used to determine
4603 // whether inline is specified or not differs between the polymorphic types.
4604 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
4605 return FD->isInlineSpecified();
4606 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
4607 return NSD->isInline();
4608 llvm_unreachable("Not a valid polymorphic type");
4611 /// \brief Matches anonymous namespace declarations.
4616 /// namespace {} // #1
4619 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
4620 AST_MATCHER(NamespaceDecl, isAnonymous) {
4621 return Node.isAnonymousNamespace();
4624 /// \brief If the given case statement does not use the GNU case range
4625 /// extension, matches the constant given in the statement.
4629 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
4631 /// caseStmt(hasCaseConstant(integerLiteral()))
4632 /// matches "case 1:"
4633 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
4638 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
4641 /// \brief Matches declaration that has a given attribute.
4645 /// __attribute__((device)) void f() { ... }
4647 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
4648 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
4649 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
4650 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
4651 for (const auto *Attr : Node.attrs()) {
4652 if (Attr->getKind() == AttrKind)
4658 /// \brief Matches CUDA kernel call expression.
4660 /// Example matches,
4662 /// kernel<<<i,j>>>();
4664 const internal::VariadicDynCastAllOfMatcher<
4666 CUDAKernelCallExpr> cudaKernelCallExpr;
4668 } // end namespace ast_matchers
4669 } // end namespace clang