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 label.
294 const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
296 /// \brief Matches a declaration of a namespace.
301 /// namespace test {}
304 /// matches "namespace {}" and "namespace test {}"
305 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
307 /// \brief Matches a declaration of a namespace alias.
311 /// namespace test {}
312 /// namespace alias = ::test;
314 /// namespaceAliasDecl()
315 /// matches "namespace alias" but not "namespace test"
316 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
319 /// \brief Matches class, struct, and union declarations.
321 /// Example matches \c X, \c Z, \c U, and \c S
324 /// template<class T> class Z {};
328 const internal::VariadicDynCastAllOfMatcher<
330 RecordDecl> recordDecl;
332 /// \brief Matches C++ class declarations.
334 /// Example matches \c X, \c Z
337 /// template<class T> class Z {};
339 const internal::VariadicDynCastAllOfMatcher<
341 CXXRecordDecl> cxxRecordDecl;
343 /// \brief Matches C++ class template declarations.
345 /// Example matches \c Z
347 /// template<class T> class Z {};
349 const internal::VariadicDynCastAllOfMatcher<
351 ClassTemplateDecl> classTemplateDecl;
353 /// \brief Matches C++ class template specializations.
357 /// template<typename T> class A {};
358 /// template<> class A<double> {};
361 /// classTemplateSpecializationDecl()
362 /// matches the specializations \c A<int> and \c A<double>
363 const internal::VariadicDynCastAllOfMatcher<
365 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
367 /// \brief Matches declarator declarations (field, variable, function
368 /// and non-type template parameter declarations).
372 /// class X { int y; };
375 /// matches \c int y.
376 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
379 /// \brief Matches parameter variable declarations.
386 /// matches \c int x.
387 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
389 /// \brief Matches C++ access specifier declarations.
399 /// matches 'public:'
400 const internal::VariadicDynCastAllOfMatcher<
402 AccessSpecDecl> accessSpecDecl;
404 /// \brief Matches constructor initializers.
406 /// Examples matches \c i(42).
413 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
415 /// \brief Matches template arguments.
419 /// template <typename T> struct C {};
422 /// templateArgument()
423 /// matches 'int' in C<int>.
424 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
426 /// \brief Matches non-type template parameter declarations.
430 /// template <typename T, int N> struct C {};
432 /// nonTypeTemplateParmDecl()
433 /// matches 'N', but not 'T'.
434 const internal::VariadicDynCastAllOfMatcher<
436 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
438 /// \brief Matches template type parameter declarations.
442 /// template <typename T, int N> struct C {};
444 /// templateTypeParmDecl()
445 /// matches 'T', but not 'N'.
446 const internal::VariadicDynCastAllOfMatcher<
448 TemplateTypeParmDecl> templateTypeParmDecl;
450 /// \brief Matches public C++ declarations.
456 /// protected: int b;
460 /// fieldDecl(isPublic())
462 AST_MATCHER(Decl, isPublic) {
463 return Node.getAccess() == AS_public;
466 /// \brief Matches protected C++ declarations.
472 /// protected: int b;
476 /// fieldDecl(isProtected())
478 AST_MATCHER(Decl, isProtected) {
479 return Node.getAccess() == AS_protected;
482 /// \brief Matches private C++ declarations.
488 /// protected: int b;
492 /// fieldDecl(isPrivate())
494 AST_MATCHER(Decl, isPrivate) {
495 return Node.getAccess() == AS_private;
498 /// \brief Matches a declaration that has been implicitly added
499 /// by the compiler (eg. implicit default/copy constructors).
500 AST_MATCHER(Decl, isImplicit) {
501 return Node.isImplicit();
504 /// \brief Matches classTemplateSpecializations that have at least one
505 /// TemplateArgument matching the given InnerMatcher.
509 /// template<typename T> class A {};
510 /// template<> class A<double> {};
513 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
514 /// refersToType(asString("int"))))
515 /// matches the specialization \c A<int>
516 AST_POLYMORPHIC_MATCHER_P(
517 hasAnyTemplateArgument,
518 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
519 TemplateSpecializationType),
520 internal::Matcher<TemplateArgument>, InnerMatcher) {
521 ArrayRef<TemplateArgument> List =
522 internal::getTemplateSpecializationArgs(Node);
523 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
527 /// \brief Matches expressions that match InnerMatcher after any implicit casts
528 /// are stripped off.
530 /// Parentheses and explicit casts are not discarded.
538 /// long e = (long) 0l;
542 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
543 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
545 /// would match the declarations for a, b, c, and d, but not e.
548 /// varDecl(hasInitializer(integerLiteral()))
549 /// varDecl(hasInitializer(declRefExpr()))
551 /// only match the declarations for b, c, and d.
552 AST_MATCHER_P(Expr, ignoringImpCasts,
553 internal::Matcher<Expr>, InnerMatcher) {
554 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
557 /// \brief Matches expressions that match InnerMatcher after parentheses and
558 /// casts are stripped off.
560 /// Implicit and non-C Style casts are also discarded.
565 /// void* c = reinterpret_cast<char*>(0);
566 /// char d = char(0);
569 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
570 /// would match the declarations for a, b, c, and d.
572 /// varDecl(hasInitializer(integerLiteral()))
573 /// only match the declaration for a.
574 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
575 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
578 /// \brief Matches expressions that match InnerMatcher after implicit casts and
579 /// parentheses are stripped off.
581 /// Explicit casts are not discarded.
589 /// long e = ((long) 0l);
592 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
593 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
594 /// would match the declarations for a, b, c, and d, but not e.
596 /// varDecl(hasInitializer(integerLiteral()))
597 /// varDecl(hasInitializer(declRefExpr()))
598 /// would only match the declaration for a.
599 AST_MATCHER_P(Expr, ignoringParenImpCasts,
600 internal::Matcher<Expr>, InnerMatcher) {
601 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
604 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
605 /// matches the given InnerMatcher.
609 /// template<typename T, typename U> class A {};
613 /// classTemplateSpecializationDecl(hasTemplateArgument(
614 /// 1, refersToType(asString("int"))))
615 /// matches the specialization \c A<bool, int>
616 AST_POLYMORPHIC_MATCHER_P2(
618 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
619 TemplateSpecializationType),
620 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
621 ArrayRef<TemplateArgument> List =
622 internal::getTemplateSpecializationArgs(Node);
623 if (List.size() <= N)
625 return InnerMatcher.matches(List[N], Finder, Builder);
628 /// \brief Matches if the number of template arguments equals \p N.
632 /// template<typename T> struct C {};
635 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
637 AST_POLYMORPHIC_MATCHER_P(
638 templateArgumentCountIs,
639 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
640 TemplateSpecializationType),
642 return internal::getTemplateSpecializationArgs(Node).size() == N;
645 /// \brief Matches a TemplateArgument that refers to a certain type.
650 /// template<typename T> struct A {};
653 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
654 /// refersToType(class(hasName("X")))))
655 /// matches the specialization \c A<X>
656 AST_MATCHER_P(TemplateArgument, refersToType,
657 internal::Matcher<QualType>, InnerMatcher) {
658 if (Node.getKind() != TemplateArgument::Type)
660 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
663 /// \brief Matches a canonical TemplateArgument that refers to a certain
668 /// template<typename T> struct A {};
669 /// struct B { B* next; };
672 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
673 /// refersToDeclaration(fieldDecl(hasName("next"))))
674 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
676 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
677 internal::Matcher<Decl>, InnerMatcher) {
678 if (Node.getKind() == TemplateArgument::Declaration)
679 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
683 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
687 /// template<typename T> struct A {};
688 /// struct B { B* next; };
691 /// templateSpecializationType(hasAnyTemplateArgument(
692 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
693 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
695 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
696 if (Node.getKind() == TemplateArgument::Expression)
697 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
701 /// \brief Matches a TemplateArgument that is an integral value.
705 /// template<int T> struct A {};
708 /// classTemplateSpecializationDecl(
709 /// hasAnyTemplateArgument(isIntegral()))
710 /// matches the implicit instantiation of C in C<42>
711 /// with isIntegral() matching 42.
712 AST_MATCHER(TemplateArgument, isIntegral) {
713 return Node.getKind() == TemplateArgument::Integral;
716 /// \brief Matches a TemplateArgument that referes to an integral type.
720 /// template<int T> struct A {};
723 /// classTemplateSpecializationDecl(
724 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
725 /// matches the implicit instantiation of C in C<42>.
726 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
727 internal::Matcher<QualType>, InnerMatcher) {
728 if (Node.getKind() != TemplateArgument::Integral)
730 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
733 /// \brief Matches a TemplateArgument of integral type with a given value.
735 /// Note that 'Value' is a string as the template argument's value is
736 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
737 /// representation of that integral value in base 10.
741 /// template<int T> struct A {};
744 /// classTemplateSpecializationDecl(
745 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
746 /// matches the implicit instantiation of C in C<42>.
747 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
748 std::string, Value) {
749 if (Node.getKind() != TemplateArgument::Integral)
751 return Node.getAsIntegral().toString(10) == Value;
754 /// \brief Matches any value declaration.
756 /// Example matches A, B, C and F
758 /// enum X { A, B, C };
761 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
763 /// \brief Matches C++ constructor declarations.
765 /// Example matches Foo::Foo() and Foo::Foo(int)
771 /// int DoSomething();
774 const internal::VariadicDynCastAllOfMatcher<
776 CXXConstructorDecl> cxxConstructorDecl;
778 /// \brief Matches explicit C++ destructor declarations.
780 /// Example matches Foo::~Foo()
787 const internal::VariadicDynCastAllOfMatcher<
789 CXXDestructorDecl> cxxDestructorDecl;
791 /// \brief Matches enum declarations.
793 /// Example matches X
799 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
801 /// \brief Matches enum constants.
803 /// Example matches A, B, C
809 const internal::VariadicDynCastAllOfMatcher<
811 EnumConstantDecl> enumConstantDecl;
813 /// \brief Matches method declarations.
815 /// Example matches y
817 /// class X { void y(); };
819 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
821 /// \brief Matches conversion operator declarations.
823 /// Example matches the operator.
825 /// class X { operator int() const; };
827 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
830 /// \brief Matches variable declarations.
832 /// Note: this does not match declarations of member variables, which are
833 /// "field" declarations in Clang parlance.
835 /// Example matches a
839 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
841 /// \brief Matches field declarations.
845 /// class X { int m; };
849 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
851 /// \brief Matches function declarations.
853 /// Example matches f
857 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
859 /// \brief Matches C++ function template declarations.
861 /// Example matches f
863 /// template<class T> void f(T t) {}
865 const internal::VariadicDynCastAllOfMatcher<
867 FunctionTemplateDecl> functionTemplateDecl;
869 /// \brief Matches friend declarations.
873 /// class X { friend void foo(); };
876 /// matches 'friend void foo()'.
877 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
879 /// \brief Matches statements.
886 /// matches both the compound statement '{ ++a; }' and '++a'.
887 const internal::VariadicAllOfMatcher<Stmt> stmt;
889 /// \brief Matches declaration statements.
897 const internal::VariadicDynCastAllOfMatcher<
901 /// \brief Matches member expressions.
906 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
907 /// int a; static int b;
911 /// matches this->x, x, y.x, a, this->b
912 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
914 /// \brief Matches call expressions.
916 /// Example matches x.y() and y()
922 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
924 /// \brief Matches lambda expressions.
926 /// Example matches [&](){return 5;}
930 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
932 /// \brief Matches member call expressions.
934 /// Example matches x.y()
939 const internal::VariadicDynCastAllOfMatcher<
941 CXXMemberCallExpr> cxxMemberCallExpr;
943 /// \brief Matches ObjectiveC Message invocation expressions.
945 /// The innermost message send invokes the "alloc" class method on the
946 /// NSString class, while the outermost message send invokes the
947 /// "initWithString" instance method on the object returned from
948 /// NSString's "alloc". This matcher should match both message sends.
950 /// [[NSString alloc] initWithString:@"Hello"]
952 const internal::VariadicDynCastAllOfMatcher<
954 ObjCMessageExpr> objcMessageExpr;
956 /// \brief Matches Objective-C interface declarations.
958 /// Example matches Foo
963 const internal::VariadicDynCastAllOfMatcher<
965 ObjCInterfaceDecl> objcInterfaceDecl;
967 /// \brief Matches expressions that introduce cleanups to be run at the end
968 /// of the sub-expression's evaluation.
970 /// Example matches std::string()
972 /// const std::string str = std::string();
974 const internal::VariadicDynCastAllOfMatcher<
976 ExprWithCleanups> exprWithCleanups;
978 /// \brief Matches init list expressions.
982 /// int a[] = { 1, 2 };
983 /// struct B { int x, y; };
987 /// matches "{ 1, 2 }" and "{ 5, 6 }"
988 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
990 /// \brief Matches the syntactic form of init list expressions
991 /// (if expression have it).
992 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
993 internal::Matcher<Expr>, InnerMatcher) {
994 const Expr *SyntForm = Node.getSyntacticForm();
995 return (SyntForm != nullptr &&
996 InnerMatcher.matches(*SyntForm, Finder, Builder));
999 /// \brief Matches implicit initializers of init list expressions.
1003 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1005 /// implicitValueInitExpr()
1006 /// matches "[0].y" (implicitly)
1007 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1008 implicitValueInitExpr;
1010 /// \brief Matches paren list expressions.
1011 /// ParenListExprs don't have a predefined type and are used for late parsing.
1012 /// In the final AST, they can be met in template declarations.
1016 /// template<typename T> class X {
1019 /// int a = 0, b = 1; int i = (a, b);
1023 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1024 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1025 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr;
1027 /// \brief Matches substitutions of non-type template parameters.
1031 /// template <int N>
1032 /// struct A { static const int n = N; };
1033 /// struct B : public A<42> {};
1035 /// substNonTypeTemplateParmExpr()
1036 /// matches "N" in the right-hand side of "static const int n = N;"
1037 const internal::VariadicDynCastAllOfMatcher<
1039 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
1041 /// \brief Matches using declarations.
1045 /// namespace X { int x; }
1049 /// matches \code using X::x \endcode
1050 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1052 /// \brief Matches using namespace declarations.
1056 /// namespace X { int x; }
1057 /// using namespace X;
1059 /// usingDirectiveDecl()
1060 /// matches \code using namespace X \endcode
1061 const internal::VariadicDynCastAllOfMatcher<
1063 UsingDirectiveDecl> usingDirectiveDecl;
1065 /// \brief Matches unresolved using value declarations.
1069 /// template<typename X>
1070 /// class C : private X {
1074 /// unresolvedUsingValueDecl()
1075 /// matches \code using X::x \endcode
1076 const internal::VariadicDynCastAllOfMatcher<
1078 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1080 /// \brief Matches unresolved using value declarations that involve the
1085 /// template <typename T>
1086 /// struct Base { typedef T Foo; };
1088 /// template<typename T>
1089 /// struct S : private Base<T> {
1090 /// using typename Base<T>::Foo;
1093 /// unresolvedUsingTypenameDecl()
1094 /// matches \code using Base<T>::Foo \endcode
1095 const internal::VariadicDynCastAllOfMatcher<
1097 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1099 /// \brief Matches parentheses used in expressions.
1101 /// Example matches (foo() + 1)
1103 /// int foo() { return 1; }
1104 /// int a = (foo() + 1);
1106 const internal::VariadicDynCastAllOfMatcher<
1108 ParenExpr> parenExpr;
1110 /// \brief Matches constructor call expressions (including implicit ones).
1112 /// Example matches string(ptr, n) and ptr within arguments of f
1113 /// (matcher = cxxConstructExpr())
1115 /// void f(const string &a, const string &b);
1118 /// f(string(ptr, n), ptr);
1120 const internal::VariadicDynCastAllOfMatcher<
1122 CXXConstructExpr> cxxConstructExpr;
1124 /// \brief Matches unresolved constructor call expressions.
1126 /// Example matches T(t) in return statement of f
1127 /// (matcher = cxxUnresolvedConstructExpr())
1129 /// template <typename T>
1130 /// void f(const T& t) { return T(t); }
1132 const internal::VariadicDynCastAllOfMatcher<
1134 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1136 /// \brief Matches implicit and explicit this expressions.
1138 /// Example matches the implicit this expression in "return i".
1139 /// (matcher = cxxThisExpr())
1143 /// int f() { return i; }
1146 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1148 /// \brief Matches nodes where temporaries are created.
1150 /// Example matches FunctionTakesString(GetStringByValue())
1151 /// (matcher = cxxBindTemporaryExpr())
1153 /// FunctionTakesString(GetStringByValue());
1154 /// FunctionTakesStringByPointer(GetStringPointer());
1156 const internal::VariadicDynCastAllOfMatcher<
1158 CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1160 /// \brief Matches nodes where temporaries are materialized.
1164 /// struct T {void func()};
1168 /// materializeTemporaryExpr() matches 'f()' in these statements
1173 /// but does not match
1178 const internal::VariadicDynCastAllOfMatcher<
1180 MaterializeTemporaryExpr> materializeTemporaryExpr;
1182 /// \brief Matches new expressions.
1189 /// matches 'new X'.
1190 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1192 /// \brief Matches delete expressions.
1199 /// matches 'delete X'.
1200 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1202 /// \brief Matches array subscript expressions.
1208 /// arraySubscriptExpr()
1210 const internal::VariadicDynCastAllOfMatcher<
1212 ArraySubscriptExpr> arraySubscriptExpr;
1214 /// \brief Matches the value of a default argument at the call site.
1216 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1217 /// default value of the second parameter in the call expression f(42)
1218 /// (matcher = cxxDefaultArgExpr())
1220 /// void f(int x, int y = 0);
1223 const internal::VariadicDynCastAllOfMatcher<
1225 CXXDefaultArgExpr> cxxDefaultArgExpr;
1227 /// \brief Matches overloaded operator calls.
1229 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1230 /// binaryOperator matcher.
1231 /// Currently it does not match operators such as new delete.
1232 /// FIXME: figure out why these do not match?
1234 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1235 /// (matcher = cxxOperatorCallExpr())
1237 /// ostream &operator<< (ostream &out, int i) { };
1238 /// ostream &o; int b = 1, c = 1;
1241 const internal::VariadicDynCastAllOfMatcher<
1243 CXXOperatorCallExpr> cxxOperatorCallExpr;
1245 /// \brief Matches expressions.
1247 /// Example matches x()
1249 /// void f() { x(); }
1251 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1253 /// \brief Matches expressions that refer to declarations.
1255 /// Example matches x in if (x)
1260 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1262 /// \brief Matches if statements.
1264 /// Example matches 'if (x) {}'
1268 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1270 /// \brief Matches for statements.
1272 /// Example matches 'for (;;) {}'
1275 /// int i[] = {1, 2, 3}; for (auto a : i);
1277 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1279 /// \brief Matches the increment statement of a for loop.
1282 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1283 /// matches '++x' in
1285 /// for (x; x < N; ++x) { }
1287 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1289 const Stmt *const Increment = Node.getInc();
1290 return (Increment != nullptr &&
1291 InnerMatcher.matches(*Increment, Finder, Builder));
1294 /// \brief Matches the initialization statement of a for loop.
1297 /// forStmt(hasLoopInit(declStmt()))
1298 /// matches 'int x = 0' in
1300 /// for (int x = 0; x < N; ++x) { }
1302 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1304 const Stmt *const Init = Node.getInit();
1305 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1308 /// \brief Matches range-based for statements.
1310 /// cxxForRangeStmt() matches 'for (auto a : i)'
1312 /// int i[] = {1, 2, 3}; for (auto a : i);
1313 /// for(int j = 0; j < 5; ++j);
1315 const internal::VariadicDynCastAllOfMatcher<
1317 CXXForRangeStmt> cxxForRangeStmt;
1319 /// \brief Matches the initialization statement of a for loop.
1322 /// forStmt(hasLoopVariable(anything()))
1323 /// matches 'int x' in
1325 /// for (int x : a) { }
1327 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1329 const VarDecl *const Var = Node.getLoopVariable();
1330 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1333 /// \brief Matches the range initialization statement of a for loop.
1336 /// forStmt(hasRangeInit(anything()))
1339 /// for (int x : a) { }
1341 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1343 const Expr *const Init = Node.getRangeInit();
1344 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1347 /// \brief Matches while statements.
1354 /// matches 'while (true) {}'.
1355 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1357 /// \brief Matches do statements.
1361 /// do {} while (true);
1364 /// matches 'do {} while(true)'
1365 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1367 /// \brief Matches break statements.
1371 /// while (true) { break; }
1375 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1377 /// \brief Matches continue statements.
1381 /// while (true) { continue; }
1384 /// matches 'continue'
1385 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1387 /// \brief Matches return statements.
1394 /// matches 'return 1'
1395 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1397 /// \brief Matches goto statements.
1405 /// matches 'goto FOO'
1406 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1408 /// \brief Matches label statements.
1417 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1419 /// \brief Matches address of label statements (GNU extension).
1424 /// void *ptr = &&FOO;
1429 const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr;
1431 /// \brief Matches switch statements.
1435 /// switch(a) { case 42: break; default: break; }
1438 /// matches 'switch(a)'.
1439 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1441 /// \brief Matches case and default statements inside switch statements.
1445 /// switch(a) { case 42: break; default: break; }
1448 /// matches 'case 42: break;' and 'default: break;'.
1449 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1451 /// \brief Matches case statements inside switch statements.
1455 /// switch(a) { case 42: break; default: break; }
1458 /// matches 'case 42: break;'.
1459 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1461 /// \brief Matches default statements inside switch statements.
1465 /// switch(a) { case 42: break; default: break; }
1468 /// matches 'default: break;'.
1469 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1471 /// \brief Matches compound statements.
1473 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1477 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1479 /// \brief Matches catch statements.
1482 /// try {} catch(int i) {}
1485 /// matches 'catch(int i)'
1486 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1488 /// \brief Matches try statements.
1491 /// try {} catch(int i) {}
1494 /// matches 'try {}'
1495 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1497 /// \brief Matches throw expressions.
1500 /// try { throw 5; } catch(int i) {}
1503 /// matches 'throw 5'
1504 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1506 /// \brief Matches null statements.
1512 /// matches the second ';'
1513 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1515 /// \brief Matches asm statements.
1519 /// __asm("mov al, 2");
1522 /// matches '__asm("mov al, 2")'
1523 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1525 /// \brief Matches bool literals.
1527 /// Example matches true
1531 const internal::VariadicDynCastAllOfMatcher<
1533 CXXBoolLiteralExpr> cxxBoolLiteral;
1535 /// \brief Matches string literals (also matches wide string literals).
1537 /// Example matches "abcd", L"abcd"
1539 /// char *s = "abcd"; wchar_t *ws = L"abcd"
1541 const internal::VariadicDynCastAllOfMatcher<
1543 StringLiteral> stringLiteral;
1545 /// \brief Matches character literals (also matches wchar_t).
1547 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1550 /// Example matches 'a', L'a'
1552 /// char ch = 'a'; wchar_t chw = L'a';
1554 const internal::VariadicDynCastAllOfMatcher<
1556 CharacterLiteral> characterLiteral;
1558 /// \brief Matches integer literals of all sizes / encodings, e.g.
1559 /// 1, 1L, 0x1 and 1U.
1561 /// Does not match character-encoded integers such as L'a'.
1562 const internal::VariadicDynCastAllOfMatcher<
1564 IntegerLiteral> integerLiteral;
1566 /// \brief Matches float literals of all sizes / encodings, e.g.
1567 /// 1.0, 1.0f, 1.0L and 1e10.
1569 /// Does not match implicit conversions such as
1573 const internal::VariadicDynCastAllOfMatcher<
1575 FloatingLiteral> floatLiteral;
1577 /// \brief Matches user defined literal operator call.
1579 /// Example match: "foo"_suffix
1580 const internal::VariadicDynCastAllOfMatcher<
1582 UserDefinedLiteral> userDefinedLiteral;
1584 /// \brief Matches compound (i.e. non-scalar) literals
1586 /// Example match: {1}, (1, 2)
1588 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1590 const internal::VariadicDynCastAllOfMatcher<
1592 CompoundLiteralExpr> compoundLiteralExpr;
1594 /// \brief Matches nullptr literal.
1595 const internal::VariadicDynCastAllOfMatcher<
1597 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1599 /// \brief Matches GNU __null expression.
1600 const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr;
1602 /// \brief Matches atomic builtins.
1603 /// Example matches __atomic_load_n(ptr, 1)
1605 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
1607 const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
1609 /// \brief Matches statement expression (GNU extension).
1611 /// Example match: ({ int X = 4; X; })
1613 /// int C = ({ int X = 4; X; });
1615 const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
1617 /// \brief Matches binary operator expressions.
1619 /// Example matches a || b
1623 const internal::VariadicDynCastAllOfMatcher<
1625 BinaryOperator> binaryOperator;
1627 /// \brief Matches unary operator expressions.
1629 /// Example matches !a
1633 const internal::VariadicDynCastAllOfMatcher<
1635 UnaryOperator> unaryOperator;
1637 /// \brief Matches conditional operator expressions.
1639 /// Example matches a ? b : c
1641 /// (a ? b : c) + 42
1643 const internal::VariadicDynCastAllOfMatcher<
1645 ConditionalOperator> conditionalOperator;
1647 /// \brief Matches binary conditional operator expressions (GNU extension).
1649 /// Example matches a ?: b
1653 const internal::VariadicDynCastAllOfMatcher<
1655 BinaryConditionalOperator> binaryConditionalOperator;
1657 /// \brief Matches opaque value expressions. They are used as helpers
1658 /// to reference another expressions and can be met
1659 /// in BinaryConditionalOperators, for example.
1661 /// Example matches 'a'
1665 const internal::VariadicDynCastAllOfMatcher<
1667 OpaqueValueExpr> opaqueValueExpr;
1669 /// \brief Matches a C++ static_assert declaration.
1672 /// staticAssertExpr()
1674 /// static_assert(sizeof(S) == sizeof(int))
1680 /// static_assert(sizeof(S) == sizeof(int));
1682 const internal::VariadicDynCastAllOfMatcher<
1684 StaticAssertDecl> staticAssertDecl;
1686 /// \brief Matches a reinterpret_cast expression.
1688 /// Either the source expression or the destination type can be matched
1689 /// using has(), but hasDestinationType() is more specific and can be
1692 /// Example matches reinterpret_cast<char*>(&p) in
1694 /// void* p = reinterpret_cast<char*>(&p);
1696 const internal::VariadicDynCastAllOfMatcher<
1698 CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1700 /// \brief Matches a C++ static_cast expression.
1702 /// \see hasDestinationType
1703 /// \see reinterpretCast
1706 /// cxxStaticCastExpr()
1708 /// static_cast<long>(8)
1711 /// long eight(static_cast<long>(8));
1713 const internal::VariadicDynCastAllOfMatcher<
1715 CXXStaticCastExpr> cxxStaticCastExpr;
1717 /// \brief Matches a dynamic_cast expression.
1720 /// cxxDynamicCastExpr()
1722 /// dynamic_cast<D*>(&b);
1725 /// struct B { virtual ~B() {} }; struct D : B {};
1727 /// D* p = dynamic_cast<D*>(&b);
1729 const internal::VariadicDynCastAllOfMatcher<
1731 CXXDynamicCastExpr> cxxDynamicCastExpr;
1733 /// \brief Matches a const_cast expression.
1735 /// Example: Matches const_cast<int*>(&r) in
1738 /// const int &r(n);
1739 /// int* p = const_cast<int*>(&r);
1741 const internal::VariadicDynCastAllOfMatcher<
1743 CXXConstCastExpr> cxxConstCastExpr;
1745 /// \brief Matches a C-style cast expression.
1747 /// Example: Matches (int*) 2.2f in
1749 /// int i = (int) 2.2f;
1751 const internal::VariadicDynCastAllOfMatcher<
1753 CStyleCastExpr> cStyleCastExpr;
1755 /// \brief Matches explicit cast expressions.
1757 /// Matches any cast expression written in user code, whether it be a
1758 /// C-style cast, a functional-style cast, or a keyword cast.
1760 /// Does not match implicit conversions.
1762 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1763 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1764 /// actual cast expressions.
1766 /// \see hasDestinationType.
1768 /// Example: matches all five of the casts in
1770 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1772 /// but does not match the implicit conversion in
1776 const internal::VariadicDynCastAllOfMatcher<
1778 ExplicitCastExpr> explicitCastExpr;
1780 /// \brief Matches the implicit cast nodes of Clang's AST.
1782 /// This matches many different places, including function call return value
1783 /// eliding, as well as any type conversions.
1784 const internal::VariadicDynCastAllOfMatcher<
1786 ImplicitCastExpr> implicitCastExpr;
1788 /// \brief Matches any cast nodes of Clang's AST.
1790 /// Example: castExpr() matches each of the following:
1793 /// const_cast<Expr *>(SubExpr);
1796 /// but does not match
1801 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1803 /// \brief Matches functional cast expressions
1805 /// Example: Matches Foo(bar);
1808 /// Foo g = (Foo) bar;
1809 /// Foo h = Foo(bar);
1811 const internal::VariadicDynCastAllOfMatcher<
1813 CXXFunctionalCastExpr> cxxFunctionalCastExpr;
1815 /// \brief Matches functional cast expressions having N != 1 arguments
1817 /// Example: Matches Foo(bar, bar)
1819 /// Foo h = Foo(bar, bar);
1821 const internal::VariadicDynCastAllOfMatcher<
1823 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
1825 /// \brief Matches predefined identifier expressions [C99 6.4.2.2].
1827 /// Example: Matches __func__
1829 /// printf("%s", __func__);
1831 const internal::VariadicDynCastAllOfMatcher<
1833 PredefinedExpr> predefinedExpr;
1835 /// \brief Matches C99 designated initializer expressions [C99 6.7.8].
1837 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
1839 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
1841 const internal::VariadicDynCastAllOfMatcher<
1843 DesignatedInitExpr> designatedInitExpr;
1845 /// \brief Matches designated initializer expressions that contain
1846 /// a specific number of designators.
1850 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
1851 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
1853 /// designatorCountIs(2)
1854 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
1855 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
1856 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
1857 return Node.size() == N;
1860 /// \brief Matches \c QualTypes in the clang AST.
1861 const internal::VariadicAllOfMatcher<QualType> qualType;
1863 /// \brief Matches \c Types in the clang AST.
1864 const internal::VariadicAllOfMatcher<Type> type;
1866 /// \brief Matches \c TypeLocs in the clang AST.
1867 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1869 /// \brief Matches if any of the given matchers matches.
1871 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1872 /// matching submatcher.
1874 /// For example, in:
1876 /// class A { int a; int b; };
1880 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1881 /// has(fieldDecl(hasName("b")).bind("v"))))
1883 /// will generate two results binding "v", the first of which binds
1884 /// the field declaration of \c a, the second the field declaration of
1887 /// Usable as: Any Matcher
1888 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
1889 internal::DynTypedMatcher::VO_EachOf
1892 /// \brief Matches if any of the given matchers matches.
1894 /// Usable as: Any Matcher
1895 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
1896 internal::DynTypedMatcher::VO_AnyOf
1899 /// \brief Matches if all given matchers match.
1901 /// Usable as: Any Matcher
1902 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
1903 internal::DynTypedMatcher::VO_AllOf
1906 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1911 /// int y = sizeof(x) + alignof(x);
1913 /// unaryExprOrTypeTraitExpr()
1914 /// matches \c sizeof(x) and \c alignof(x)
1915 const internal::VariadicDynCastAllOfMatcher<
1917 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1919 /// \brief Matches unary expressions that have a specific type of argument.
1923 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1925 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1926 /// matches \c sizeof(a) and \c alignof(c)
1927 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1928 internal::Matcher<QualType>, InnerMatcher) {
1929 const QualType ArgumentType = Node.getTypeOfArgument();
1930 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1933 /// \brief Matches unary expressions of a certain kind.
1938 /// int s = sizeof(x) + alignof(x)
1940 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1941 /// matches \c sizeof(x)
1942 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1943 return Node.getKind() == Kind;
1946 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1948 inline internal::Matcher<Stmt> alignOfExpr(
1949 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1950 return stmt(unaryExprOrTypeTraitExpr(allOf(
1951 ofKind(UETT_AlignOf), InnerMatcher)));
1954 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1956 inline internal::Matcher<Stmt> sizeOfExpr(
1957 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1958 return stmt(unaryExprOrTypeTraitExpr(
1959 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1962 /// \brief Matches NamedDecl nodes that have the specified name.
1964 /// Supports specifying enclosing namespaces or classes by prefixing the name
1965 /// with '<enclosing>::'.
1966 /// Does not match typedefs of an underlying type with the given name.
1968 /// Example matches X (Name == "X")
1973 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1975 /// namespace a { namespace b { class X; } }
1977 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
1978 std::vector<std::string> Names;
1979 Names.push_back(Name);
1980 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
1983 /// \brief Matches NamedDecl nodes that have any of the specified names.
1985 /// This matcher is only provided as a performance optimization of hasName.
1987 /// hasAnyName(a, b, c)
1989 /// is equivalent to, but faster than
1991 /// anyOf(hasName(a), hasName(b), hasName(c))
1993 const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
1994 internal::hasAnyNameFunc>
1997 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1998 /// a substring matched by the given RegExp.
2000 /// Supports specifying enclosing namespaces or classes by
2001 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2002 /// of an underlying type with the given name.
2004 /// Example matches X (regexp == "::X")
2009 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2011 /// namespace foo { namespace bar { class X; } }
2013 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2014 assert(!RegExp.empty());
2015 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2016 llvm::Regex RE(RegExp);
2017 return RE.match(FullNameString);
2020 /// \brief Matches overloaded operator names.
2022 /// Matches overloaded operator names specified in strings without the
2023 /// "operator" prefix: e.g. "<<".
2027 /// class A { int operator*(); };
2028 /// const A &operator<<(const A &a, const A &b);
2030 /// a << a; // <-- This matches
2033 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2034 /// specified line and
2035 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2036 /// matches the declaration of \c A.
2038 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2039 inline internal::PolymorphicMatcherWithParam1<
2040 internal::HasOverloadedOperatorNameMatcher, StringRef,
2041 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2042 hasOverloadedOperatorName(StringRef Name) {
2043 return internal::PolymorphicMatcherWithParam1<
2044 internal::HasOverloadedOperatorNameMatcher, StringRef,
2045 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2048 /// \brief Matches C++ classes that are directly or indirectly derived from
2049 /// a class matching \c Base.
2051 /// Note that a class is not considered to be derived from itself.
2053 /// Example matches Y, Z, C (Base == hasName("X"))
2056 /// class Y : public X {}; // directly derived
2057 /// class Z : public Y {}; // indirectly derived
2060 /// class C : public B {}; // derived from a typedef of X
2063 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2067 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2069 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2070 internal::Matcher<NamedDecl>, Base) {
2071 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2074 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2075 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2076 assert(!BaseName.empty());
2077 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2080 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
2082 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2083 internal::Matcher<NamedDecl>, Base, 0) {
2084 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2085 .matches(Node, Finder, Builder);
2088 /// \brief Overloaded method as shortcut for
2089 /// \c isSameOrDerivedFrom(hasName(...)).
2090 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2092 assert(!BaseName.empty());
2093 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2096 /// \brief Matches the first method of a class or struct that satisfies \c
2101 /// class A { void func(); };
2102 /// class B { void member(); };
2105 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2106 /// \c A but not \c B.
2107 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2109 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2110 Node.method_end(), Finder, Builder);
2113 /// \brief Matches AST nodes that have child AST nodes that match the
2114 /// provided matcher.
2116 /// Example matches X, Y
2117 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2119 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2120 /// class Y { class X {}; };
2121 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2124 /// ChildT must be an AST base type.
2126 /// Usable as: Any Matcher
2127 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
2128 LLVM_ATTRIBUTE_UNUSED has = {};
2130 /// \brief Matches AST nodes that have descendant AST nodes that match the
2131 /// provided matcher.
2133 /// Example matches X, Y, Z
2134 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2136 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2137 /// class Y { class X {}; };
2138 /// class Z { class Y { class X {}; }; };
2141 /// DescendantT must be an AST base type.
2143 /// Usable as: Any Matcher
2144 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
2145 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
2147 /// \brief Matches AST nodes that have child AST nodes that match the
2148 /// provided matcher.
2150 /// Example matches X, Y
2151 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2153 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2154 /// class Y { class X {}; };
2155 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2158 /// ChildT must be an AST base type.
2160 /// As opposed to 'has', 'forEach' will cause a match for each result that
2161 /// matches instead of only on the first one.
2163 /// Usable as: Any Matcher
2164 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2165 LLVM_ATTRIBUTE_UNUSED forEach = {};
2167 /// \brief Matches AST nodes that have descendant AST nodes that match the
2168 /// provided matcher.
2170 /// Example matches X, A, B, C
2171 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2173 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2174 /// class A { class X {}; };
2175 /// class B { class C { class X {}; }; };
2178 /// DescendantT must be an AST base type.
2180 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2181 /// each result that matches instead of only on the first one.
2183 /// Note: Recursively combined ForEachDescendant can cause many matches:
2184 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2185 /// forEachDescendant(cxxRecordDecl())
2187 /// will match 10 times (plus injected class name matches) on:
2189 /// class A { class B { class C { class D { class E {}; }; }; }; };
2192 /// Usable as: Any Matcher
2193 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2194 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2196 /// \brief Matches if the node or any descendant matches.
2198 /// Generates results for each match.
2200 /// For example, in:
2202 /// class A { class B {}; class C {}; };
2206 /// cxxRecordDecl(hasName("::A"),
2207 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2209 /// will generate results for \c A, \c B and \c C.
2211 /// Usable as: Any Matcher
2212 template <typename T>
2213 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2214 return eachOf(Matcher, forEachDescendant(Matcher));
2217 /// \brief Matches AST nodes that have a parent that matches the provided
2222 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2224 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2226 /// Usable as: Any Matcher
2227 const internal::ArgumentAdaptingMatcherFunc<
2228 internal::HasParentMatcher,
2229 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2230 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2231 LLVM_ATTRIBUTE_UNUSED hasParent = {};
2233 /// \brief Matches AST nodes that have an ancestor that matches the provided
2238 /// void f() { if (true) { int x = 42; } }
2239 /// void g() { for (;;) { int x = 43; } }
2241 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2243 /// Usable as: Any Matcher
2244 const internal::ArgumentAdaptingMatcherFunc<
2245 internal::HasAncestorMatcher,
2246 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2247 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2248 LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2250 /// \brief Matches if the provided matcher does not match.
2252 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2258 /// Usable as: Any Matcher
2259 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2260 internal::DynTypedMatcher::VO_UnaryNot
2263 /// \brief Matches a node if the declaration associated with that node
2264 /// matches the given matcher.
2266 /// The associated declaration is:
2267 /// - for type nodes, the declaration of the underlying type
2268 /// - for CallExpr, the declaration of the callee
2269 /// - for MemberExpr, the declaration of the referenced member
2270 /// - for CXXConstructExpr, the declaration of the constructor
2272 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2273 /// function. e.g. various subtypes of clang::Type and various expressions.
2275 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
2276 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
2277 /// Matcher<LabelStmt>, Matcher<AddrLabelExpr>, Matcher<MemberExpr>,
2278 /// Matcher<QualType>, Matcher<RecordType>, Matcher<TagType>,
2279 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
2280 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
2281 inline internal::PolymorphicMatcherWithParam1<
2282 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2283 void(internal::HasDeclarationSupportedTypes)>
2284 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2285 return internal::PolymorphicMatcherWithParam1<
2286 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2287 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2290 /// \brief Matches on the implicit object argument of a member call expression.
2292 /// Example matches y.x()
2293 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2295 /// class Y { public: void x(); };
2296 /// void z() { Y y; y.x(); }",
2299 /// FIXME: Overload to allow directly matching types?
2300 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2302 const Expr *ExprNode = Node.getImplicitObjectArgument()
2303 ->IgnoreParenImpCasts();
2304 return (ExprNode != nullptr &&
2305 InnerMatcher.matches(*ExprNode, Finder, Builder));
2309 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2312 /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *")));
2313 /// matches the [webView ...] message invocation.
2315 /// NSString *webViewJavaScript = ...
2316 /// UIWebView *webView = ...
2317 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2319 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2321 const QualType TypeDecl = Node.getReceiverType();
2322 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2325 /// \brief Matches when BaseName == Selector.getAsString()
2327 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2328 /// matches the outer message expr in the code below, but NOT the message
2329 /// invocation for self.bodyView.
2331 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2333 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2334 Selector Sel = Node.getSelector();
2335 return BaseName.compare(Sel.getAsString()) == 0;
2339 /// \brief Matches ObjC selectors whose name contains
2340 /// a substring matched by the given RegExp.
2341 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2342 /// matches the outer message expr in the code below, but NOT the message
2343 /// invocation for self.bodyView.
2345 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2347 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2348 assert(!RegExp.empty());
2349 std::string SelectorString = Node.getSelector().getAsString();
2350 llvm::Regex RE(RegExp);
2351 return RE.match(SelectorString);
2354 /// \brief Matches when the selector is the empty selector
2356 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2357 /// represent an error condition in the tree!
2358 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2359 return Node.getSelector().isNull();
2362 /// \brief Matches when the selector is a Unary Selector
2364 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2365 /// matches self.bodyView in the code below, but NOT the outer message
2366 /// invocation of "loadHTMLString:baseURL:".
2368 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2370 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2371 return Node.getSelector().isUnarySelector();
2374 /// \brief Matches when the selector is a keyword selector
2376 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2377 /// message expression in
2380 /// UIWebView *webView = ...;
2381 /// CGRect bodyFrame = webView.frame;
2382 /// bodyFrame.size.height = self.bodyContentHeight;
2383 /// webView.frame = bodyFrame;
2384 /// // ^---- matches here
2386 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2387 return Node.getSelector().isKeywordSelector();
2390 /// \brief Matches when the selector has the specified number of arguments
2392 /// matcher = objCMessageExpr(numSelectorArgs(0));
2393 /// matches self.bodyView in the code below
2395 /// matcher = objCMessageExpr(numSelectorArgs(2));
2396 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2397 /// of self.bodyView
2399 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2401 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2402 return Node.getSelector().getNumArgs() == N;
2405 /// \brief Matches if the call expression's callee expression matches.
2409 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2410 /// void f() { f(); }
2412 /// callExpr(callee(expr()))
2413 /// matches this->x(), x(), y.x(), f()
2414 /// with callee(...)
2415 /// matching this->x, x, y.x, f respectively
2417 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2418 /// because this introduces ambiguous overloads with calls to Callee taking a
2419 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2420 /// implemented in terms of implicit casts.
2421 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2423 const Expr *ExprNode = Node.getCallee();
2424 return (ExprNode != nullptr &&
2425 InnerMatcher.matches(*ExprNode, Finder, Builder));
2428 /// \brief Matches if the call expression's callee's declaration matches the
2431 /// Example matches y.x() (matcher = callExpr(callee(
2432 /// cxxMethodDecl(hasName("x")))))
2434 /// class Y { public: void x(); };
2435 /// void z() { Y y; y.x(); }
2437 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2439 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2442 /// \brief Matches if the expression's or declaration's type matches a type
2445 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2446 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2447 /// and U (matcher = typedefDecl(hasType(asString("int")))
2450 /// void y(X &x) { x; X z; }
2453 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2454 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefDecl, ValueDecl),
2455 internal::Matcher<QualType>, InnerMatcher, 0) {
2456 return InnerMatcher.matches(internal::getUnderlyingType<NodeType>(Node),
2460 /// \brief Overloaded to match the declaration of the expression's or value
2461 /// declaration's type.
2463 /// In case of a value declaration (for example a variable declaration),
2464 /// this resolves one layer of indirection. For example, in the value
2465 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2466 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2467 /// declaration of x.
2469 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2470 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2473 /// void y(X &x) { x; X z; }
2476 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2477 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2478 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2480 internal::Matcher<Decl>, InnerMatcher, 1) {
2481 return qualType(hasDeclaration(InnerMatcher))
2482 .matches(Node.getType(), Finder, Builder);
2485 /// \brief Matches if the type location of the declarator decl's type matches
2486 /// the inner matcher.
2492 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2494 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2495 if (!Node.getTypeSourceInfo())
2496 // This happens for example for implicit destructors.
2498 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2501 /// \brief Matches if the matched type is represented by the given string.
2505 /// class Y { public: void x(); };
2506 /// void z() { Y* y; y->x(); }
2508 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2510 AST_MATCHER_P(QualType, asString, std::string, Name) {
2511 return Name == Node.getAsString();
2514 /// \brief Matches if the matched type is a pointer type and the pointee type
2515 /// matches the specified matcher.
2517 /// Example matches y->x()
2518 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2519 /// cxxRecordDecl(hasName("Y")))))))
2521 /// class Y { public: void x(); };
2522 /// void z() { Y *y; y->x(); }
2525 QualType, pointsTo, internal::Matcher<QualType>,
2527 return (!Node.isNull() && Node->isAnyPointerType() &&
2528 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2531 /// \brief Overloaded to match the pointee type's declaration.
2532 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2534 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2535 .matches(Node, Finder, Builder);
2538 /// \brief Matches if the matched type is a reference type and the referenced
2539 /// type matches the specified matcher.
2541 /// Example matches X &x and const X &y
2542 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2551 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2553 return (!Node.isNull() && Node->isReferenceType() &&
2554 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2557 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2561 /// typedef int &int_ref;
2566 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2567 /// declaration of b but \c
2568 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2569 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2573 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2576 /// \brief Overloaded to match the referenced type's declaration.
2577 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2579 return references(qualType(hasDeclaration(InnerMatcher)))
2580 .matches(Node, Finder, Builder);
2583 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2584 internal::Matcher<Expr>, InnerMatcher) {
2585 const Expr *ExprNode = Node.getImplicitObjectArgument();
2586 return (ExprNode != nullptr &&
2587 InnerMatcher.matches(*ExprNode, Finder, Builder));
2590 /// \brief Matches if the expression's type either matches the specified
2591 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2592 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2593 internal::Matcher<QualType>, InnerMatcher, 0) {
2594 return onImplicitObjectArgument(
2595 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2596 .matches(Node, Finder, Builder);
2599 /// \brief Overloaded to match the type's declaration.
2600 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2601 internal::Matcher<Decl>, InnerMatcher, 1) {
2602 return onImplicitObjectArgument(
2603 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2604 .matches(Node, Finder, Builder);
2607 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2608 /// specified matcher.
2610 /// Example matches x in if(x)
2611 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2616 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2618 const Decl *DeclNode = Node.getDecl();
2619 return (DeclNode != nullptr &&
2620 InnerMatcher.matches(*DeclNode, Finder, Builder));
2623 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2624 /// specific using shadow declaration.
2628 /// namespace a { void f() {} }
2631 /// f(); // Matches this ..
2632 /// a::f(); // .. but not this.
2635 /// declRefExpr(throughUsingDecl(anything()))
2637 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2638 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2639 const NamedDecl *FoundDecl = Node.getFoundDecl();
2640 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2641 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2645 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2652 /// declStmt(hasSingleDecl(anything()))
2653 /// matches 'int c;' but not 'int a, b;'.
2654 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2655 if (Node.isSingleDecl()) {
2656 const Decl *FoundDecl = Node.getSingleDecl();
2657 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2662 /// \brief Matches a variable declaration that has an initializer expression
2663 /// that matches the given matcher.
2665 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2667 /// bool y() { return true; }
2671 VarDecl, hasInitializer, internal::Matcher<Expr>,
2673 const Expr *Initializer = Node.getAnyInitializer();
2674 return (Initializer != nullptr &&
2675 InnerMatcher.matches(*Initializer, Finder, Builder));
2678 /// \brief Matches a variable declaration that has function scope and is a
2679 /// non-static local variable.
2681 /// Example matches x (matcher = varDecl(hasLocalStorage())
2689 AST_MATCHER(VarDecl, hasLocalStorage) {
2690 return Node.hasLocalStorage();
2693 /// \brief Matches a variable declaration that does not have local storage.
2695 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2703 AST_MATCHER(VarDecl, hasGlobalStorage) {
2704 return Node.hasGlobalStorage();
2707 /// \brief Matches a variable declaration that has automatic storage duration.
2709 /// Example matches x, but not y, z, or a.
2710 /// (matcher = varDecl(hasAutomaticStorageDuration())
2715 /// thread_local int z;
2719 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
2720 return Node.getStorageDuration() == SD_Automatic;
2723 /// \brief Matches a variable declaration that has static storage duration.
2725 /// Example matches y and a, but not x or z.
2726 /// (matcher = varDecl(hasStaticStorageDuration())
2731 /// thread_local int z;
2735 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
2736 return Node.getStorageDuration() == SD_Static;
2739 /// \brief Matches a variable declaration that has thread storage duration.
2741 /// Example matches z, but not x, z, or a.
2742 /// (matcher = varDecl(hasThreadStorageDuration())
2747 /// thread_local int z;
2751 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
2752 return Node.getStorageDuration() == SD_Thread;
2755 /// \brief Matches a variable declaration that is an exception variable from
2756 /// a C++ catch block, or an Objective-C \@catch statement.
2758 /// Example matches x (matcher = varDecl(isExceptionVariable())
2762 /// } catch (int x) {
2766 AST_MATCHER(VarDecl, isExceptionVariable) {
2767 return Node.isExceptionVariable();
2770 /// \brief Checks that a call expression or a constructor call expression has
2771 /// a specific number of arguments (including absent default arguments).
2773 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2775 /// void f(int x, int y);
2778 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
2779 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2783 return Node.getNumArgs() == N;
2786 /// \brief Matches the n'th argument of a call expression or a constructor
2787 /// call expression.
2789 /// Example matches y in x(y)
2790 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2792 /// void x(int) { int y; x(y); }
2794 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
2795 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2798 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2799 return (N < Node.getNumArgs() &&
2800 InnerMatcher.matches(
2801 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2804 /// \brief Matches declaration statements that contain a specific number of
2814 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2815 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2816 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2819 /// \brief Matches the n'th declaration of a declaration statement.
2821 /// Note that this does not work for global declarations because the AST
2822 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2824 /// Example: Given non-global declarations
2830 /// declStmt(containsDeclaration(
2831 /// 0, varDecl(hasInitializer(anything()))))
2832 /// matches only 'int d = 2, e;', and
2833 /// declStmt(containsDeclaration(1, varDecl()))
2835 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2836 /// but 'int c;' is not matched.
2838 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2839 internal::Matcher<Decl>, InnerMatcher) {
2840 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2843 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2844 std::advance(Iterator, N);
2845 return InnerMatcher.matches(**Iterator, Finder, Builder);
2848 /// \brief Matches a C++ catch statement that has a catch-all handler.
2860 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
2861 AST_MATCHER(CXXCatchStmt, isCatchAll) {
2862 return Node.getExceptionDecl() == nullptr;
2865 /// \brief Matches a constructor initializer.
2870 /// Foo() : foo_(1) { }
2874 /// cxxRecordDecl(has(cxxConstructorDecl(
2875 /// hasAnyConstructorInitializer(anything())
2877 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2878 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2879 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2880 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2881 Node.init_end(), Finder, Builder);
2884 /// \brief Matches the field declaration of a constructor initializer.
2889 /// Foo() : foo_(1) { }
2893 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2894 /// forField(hasName("foo_"))))))
2896 /// with forField matching foo_
2897 AST_MATCHER_P(CXXCtorInitializer, forField,
2898 internal::Matcher<FieldDecl>, InnerMatcher) {
2899 const FieldDecl *NodeAsDecl = Node.getMember();
2900 return (NodeAsDecl != nullptr &&
2901 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2904 /// \brief Matches the initializer expression of a constructor initializer.
2909 /// Foo() : foo_(1) { }
2913 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2914 /// withInitializer(integerLiteral(equals(1)))))))
2916 /// with withInitializer matching (1)
2917 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2918 internal::Matcher<Expr>, InnerMatcher) {
2919 const Expr* NodeAsExpr = Node.getInit();
2920 return (NodeAsExpr != nullptr &&
2921 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2924 /// \brief Matches a constructor initializer if it is explicitly written in
2925 /// code (as opposed to implicitly added by the compiler).
2931 /// Foo(int) : foo_("A") { }
2935 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
2936 /// will match Foo(int), but not Foo()
2937 AST_MATCHER(CXXCtorInitializer, isWritten) {
2938 return Node.isWritten();
2941 /// \brief Matches a constructor initializer if it is initializing a base, as
2942 /// opposed to a member.
2949 /// D(int i) : I(i) {}
2955 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
2956 /// will match E(), but not match D(int).
2957 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
2958 return Node.isBaseInitializer();
2961 /// \brief Matches a constructor initializer if it is initializing a member, as
2962 /// opposed to a base.
2969 /// D(int i) : I(i) {}
2975 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
2976 /// will match D(int), but not match E().
2977 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
2978 return Node.isMemberInitializer();
2981 /// \brief Matches any argument of a call expression or a constructor call
2986 /// void x(int, int, int) { int y; x(1, y, 42); }
2988 /// callExpr(hasAnyArgument(declRefExpr()))
2989 /// matches x(1, y, 42)
2990 /// with hasAnyArgument(...)
2992 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
2993 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2995 internal::Matcher<Expr>, InnerMatcher) {
2996 for (const Expr *Arg : Node.arguments()) {
2997 BoundNodesTreeBuilder Result(*Builder);
2998 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
2999 *Builder = std::move(Result);
3006 /// \brief Matches a constructor call expression which uses list initialization.
3007 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3008 return Node.isListInitialization();
3011 /// \brief Matches a constructor call expression which requires
3012 /// zero initialization.
3017 /// struct point { double x; double y; };
3018 /// point pt[2] = { { 1.0, 2.0 } };
3021 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3022 /// will match the implicit array filler for pt[1].
3023 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3024 return Node.requiresZeroInitialization();
3027 /// \brief Matches the n'th parameter of a function declaration.
3031 /// class X { void f(int x) {} };
3033 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3034 /// matches f(int x) {}
3035 /// with hasParameter(...)
3037 AST_MATCHER_P2(FunctionDecl, hasParameter,
3038 unsigned, N, internal::Matcher<ParmVarDecl>,
3040 return (N < Node.getNumParams() &&
3041 InnerMatcher.matches(
3042 *Node.getParamDecl(N), Finder, Builder));
3045 /// \brief Matches all arguments and their respective ParmVarDecl.
3053 /// callExpr(declRefExpr(to(varDecl(hasName("y")))),
3054 /// parmVarDecl(hasType(isInteger())))
3056 /// with declRefExpr(...)
3058 /// and parmVarDecl(...)
3060 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3061 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3063 internal::Matcher<Expr>, ArgMatcher,
3064 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3065 BoundNodesTreeBuilder Result;
3066 // The first argument of an overloaded member operator is the implicit object
3067 // argument of the method which should not be matched against a parameter, so
3068 // we skip over it here.
3069 BoundNodesTreeBuilder Matches;
3070 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3071 .matches(Node, Finder, &Matches)
3075 bool Matched = false;
3076 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3077 BoundNodesTreeBuilder ArgMatches(*Builder);
3078 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3079 Finder, &ArgMatches)) {
3080 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3081 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3082 hasParameter(ParamIndex, ParamMatcher)))),
3083 callExpr(callee(functionDecl(
3084 hasParameter(ParamIndex, ParamMatcher))))))
3085 .matches(Node, Finder, &ParamMatches)) {
3086 Result.addMatch(ParamMatches);
3092 *Builder = std::move(Result);
3096 /// \brief Matches any parameter of a function declaration.
3098 /// Does not match the 'this' parameter of a method.
3102 /// class X { void f(int x, int y, int z) {} };
3104 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3105 /// matches f(int x, int y, int z) {}
3106 /// with hasAnyParameter(...)
3108 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
3109 internal::Matcher<ParmVarDecl>, InnerMatcher) {
3110 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3111 Node.param_end(), Finder, Builder);
3114 /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3115 /// specific parameter count.
3119 /// void f(int i) {}
3120 /// void g(int i, int j) {}
3121 /// void h(int i, int j);
3123 /// void k(int x, int y, int z, ...);
3125 /// functionDecl(parameterCountIs(2))
3126 /// matches void g(int i, int j) {}
3127 /// functionProtoType(parameterCountIs(2))
3128 /// matches void h(int i, int j)
3129 /// functionProtoType(parameterCountIs(3))
3130 /// matches void k(int x, int y, int z, ...);
3131 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3132 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3135 return Node.getNumParams() == N;
3138 /// \brief Matches the return type of a function declaration.
3142 /// class X { int f() { return 1; } };
3144 /// cxxMethodDecl(returns(asString("int")))
3145 /// matches int f() { return 1; }
3146 AST_MATCHER_P(FunctionDecl, returns,
3147 internal::Matcher<QualType>, InnerMatcher) {
3148 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3151 /// \brief Matches extern "C" function declarations.
3155 /// extern "C" void f() {}
3156 /// extern "C" { void g() {} }
3159 /// functionDecl(isExternC())
3160 /// matches the declaration of f and g, but not the declaration h
3161 AST_MATCHER(FunctionDecl, isExternC) {
3162 return Node.isExternC();
3165 /// \brief Matches deleted function declarations.
3170 /// void DeletedFunc() = delete;
3172 /// functionDecl(isDeleted())
3173 /// matches the declaration of DeletedFunc, but not Func.
3174 AST_MATCHER(FunctionDecl, isDeleted) {
3175 return Node.isDeleted();
3178 /// \brief Matches defaulted function declarations.
3182 /// class A { ~A(); };
3183 /// class B { ~B() = default; };
3185 /// functionDecl(isDefaulted())
3186 /// matches the declaration of ~B, but not ~A.
3187 AST_MATCHER(FunctionDecl, isDefaulted) {
3188 return Node.isDefaulted();
3191 /// \brief Matches functions that have a non-throwing exception specification.
3196 /// void g() noexcept;
3197 /// void h() throw();
3198 /// void i() throw(int);
3199 /// void j() noexcept(false);
3201 /// functionDecl(isNoThrow())
3202 /// matches the declarations of g, and h, but not f, i or j.
3203 AST_MATCHER(FunctionDecl, isNoThrow) {
3204 const auto *FnTy = Node.getType()->getAs<FunctionProtoType>();
3206 // If the function does not have a prototype, then it is assumed to be a
3207 // throwing function (as it would if the function did not have any exception
3212 // Assume the best for any unresolved exception specification.
3213 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3216 return FnTy->isNothrow(Node.getASTContext());
3219 /// \brief Matches constexpr variable and function declarations.
3223 /// constexpr int foo = 42;
3224 /// constexpr int bar();
3226 /// varDecl(isConstexpr())
3227 /// matches the declaration of foo.
3228 /// functionDecl(isConstexpr())
3229 /// matches the declaration of bar.
3230 AST_POLYMORPHIC_MATCHER(isConstexpr,
3231 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3233 return Node.isConstexpr();
3236 /// \brief Matches the condition expression of an if statement, for loop,
3237 /// or conditional operator.
3239 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3243 AST_POLYMORPHIC_MATCHER_P(
3245 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3246 AbstractConditionalOperator),
3247 internal::Matcher<Expr>, InnerMatcher) {
3248 const Expr *const Condition = Node.getCond();
3249 return (Condition != nullptr &&
3250 InnerMatcher.matches(*Condition, Finder, Builder));
3253 /// \brief Matches the then-statement of an if statement.
3255 /// Examples matches the if statement
3256 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3258 /// if (false) true; else false;
3260 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3261 const Stmt *const Then = Node.getThen();
3262 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3265 /// \brief Matches the else-statement of an if statement.
3267 /// Examples matches the if statement
3268 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3270 /// if (false) false; else true;
3272 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3273 const Stmt *const Else = Node.getElse();
3274 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3277 /// \brief Matches if a node equals a previously bound node.
3279 /// Matches a node if it equals the node previously bound to \p ID.
3283 /// class X { int a; int b; };
3286 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3287 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3288 /// matches the class \c X, as \c a and \c b have the same type.
3290 /// Note that when multiple matches are involved via \c forEach* matchers,
3291 /// \c equalsBoundNodes acts as a filter.
3294 /// forEachDescendant(varDecl().bind("d")),
3295 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3296 /// will trigger a match for each combination of variable declaration
3297 /// and reference to that variable declaration within a compound statement.
3298 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3299 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3302 // FIXME: Figure out whether it makes sense to allow this
3303 // on any other node types.
3304 // For *Loc it probably does not make sense, as those seem
3305 // unique. For NestedNameSepcifier it might make sense, as
3306 // those also have pointer identity, but I'm not sure whether
3307 // they're ever reused.
3308 internal::NotEqualsBoundNodePredicate Predicate;
3310 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3311 return Builder->removeBindings(Predicate);
3314 /// \brief Matches the condition variable statement in an if statement.
3318 /// if (A* a = GetAPointer()) {}
3320 /// hasConditionVariableStatement(...)
3321 /// matches 'A* a = GetAPointer()'.
3322 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3323 internal::Matcher<DeclStmt>, InnerMatcher) {
3324 const DeclStmt* const DeclarationStatement =
3325 Node.getConditionVariableDeclStmt();
3326 return DeclarationStatement != nullptr &&
3327 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3330 /// \brief Matches the index expression of an array subscript expression.
3335 /// void f() { i[1] = 42; }
3337 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3338 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3339 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3340 internal::Matcher<Expr>, InnerMatcher) {
3341 if (const Expr* Expression = Node.getIdx())
3342 return InnerMatcher.matches(*Expression, Finder, Builder);
3346 /// \brief Matches the base expression of an array subscript expression.
3351 /// void f() { i[1] = 42; }
3353 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3354 /// hasSourceExpression(declRefExpr()))))
3355 /// matches \c i[1] with the \c declRefExpr() matching \c i
3356 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3357 internal::Matcher<Expr>, InnerMatcher) {
3358 if (const Expr* Expression = Node.getBase())
3359 return InnerMatcher.matches(*Expression, Finder, Builder);
3363 /// \brief Matches a 'for', 'while', 'do while' statement or a function
3364 /// definition that has a given body.
3370 /// hasBody(compoundStmt())
3371 /// matches 'for (;;) {}'
3372 /// with compoundStmt()
3374 AST_POLYMORPHIC_MATCHER_P(hasBody,
3375 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3379 internal::Matcher<Stmt>, InnerMatcher) {
3380 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
3381 return (Statement != nullptr &&
3382 InnerMatcher.matches(*Statement, Finder, Builder));
3385 /// \brief Matches compound statements where at least one substatement matches
3386 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
3392 /// hasAnySubstatement(compoundStmt())
3393 /// matches '{ {}; 1+2; }'
3394 /// with compoundStmt()
3396 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
3397 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
3399 internal::Matcher<Stmt>, InnerMatcher) {
3400 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
3401 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
3402 CS->body_end(), Finder, Builder);
3405 /// \brief Checks that a compound statement contains a specific number of
3406 /// child statements.
3412 /// compoundStmt(statementCountIs(0)))
3414 /// but does not match the outer compound statement.
3415 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3416 return Node.size() == N;
3419 /// \brief Matches literals that are equal to the given value.
3421 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3426 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3427 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3428 template <typename ValueT>
3429 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3430 equals(const ValueT &Value) {
3431 return internal::PolymorphicMatcherWithParam1<
3432 internal::ValueEqualsMatcher,
3436 /// \brief Matches the operator Name of operator expressions (binary or
3439 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3443 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3444 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3446 std::string, Name) {
3447 return Name == Node.getOpcodeStr(Node.getOpcode());
3450 /// \brief Matches the left hand side of binary operator expressions.
3452 /// Example matches a (matcher = binaryOperator(hasLHS()))
3456 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3457 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3458 ArraySubscriptExpr),
3459 internal::Matcher<Expr>, InnerMatcher) {
3460 const Expr *LeftHandSide = Node.getLHS();
3461 return (LeftHandSide != nullptr &&
3462 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3465 /// \brief Matches the right hand side of binary operator expressions.
3467 /// Example matches b (matcher = binaryOperator(hasRHS()))
3471 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3472 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3473 ArraySubscriptExpr),
3474 internal::Matcher<Expr>, InnerMatcher) {
3475 const Expr *RightHandSide = Node.getRHS();
3476 return (RightHandSide != nullptr &&
3477 InnerMatcher.matches(*RightHandSide, Finder, Builder));
3480 /// \brief Matches if either the left hand side or the right hand side of a
3481 /// binary operator matches.
3482 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3483 const internal::Matcher<Expr> &InnerMatcher) {
3484 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3487 /// \brief Matches if the operand of a unary operator matches.
3489 /// Example matches true (matcher = hasUnaryOperand(
3490 /// cxxBoolLiteral(equals(true))))
3494 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3495 internal::Matcher<Expr>, InnerMatcher) {
3496 const Expr * const Operand = Node.getSubExpr();
3497 return (Operand != nullptr &&
3498 InnerMatcher.matches(*Operand, Finder, Builder));
3501 /// \brief Matches if the cast's source expression
3502 /// or opaque value's source expression matches the given matcher.
3504 /// Example 1: matches "a string"
3505 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
3507 /// class URL { URL(string); };
3508 /// URL url = "a string";
3511 /// Example 2: matches 'b' (matcher =
3512 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
3517 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
3518 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
3520 internal::Matcher<Expr>, InnerMatcher) {
3521 const Expr *const SubExpression =
3522 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
3523 return (SubExpression != nullptr &&
3524 InnerMatcher.matches(*SubExpression, Finder, Builder));
3527 /// \brief Matches casts whose destination type matches a given matcher.
3529 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3530 /// actual casts "explicit" casts.)
3531 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3532 internal::Matcher<QualType>, InnerMatcher) {
3533 const QualType NodeType = Node.getTypeAsWritten();
3534 return InnerMatcher.matches(NodeType, Finder, Builder);
3537 /// \brief Matches implicit casts whose destination type matches a given
3540 /// FIXME: Unit test this matcher
3541 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3542 internal::Matcher<QualType>, InnerMatcher) {
3543 return InnerMatcher.matches(Node.getType(), Finder, Builder);
3546 /// \brief Matches RecordDecl object that are spelled with "struct."
3548 /// Example matches S, but not C or U.
3554 AST_MATCHER(RecordDecl, isStruct) {
3555 return Node.isStruct();
3558 /// \brief Matches RecordDecl object that are spelled with "union."
3560 /// Example matches U, but not C or S.
3566 AST_MATCHER(RecordDecl, isUnion) {
3567 return Node.isUnion();
3570 /// \brief Matches RecordDecl object that are spelled with "class."
3572 /// Example matches C, but not S or U.
3578 AST_MATCHER(RecordDecl, isClass) {
3579 return Node.isClass();
3582 /// \brief Matches the true branch expression of a conditional operator.
3584 /// Example 1 (conditional ternary operator): matches a
3586 /// condition ? a : b
3589 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
3593 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
3594 internal::Matcher<Expr>, InnerMatcher) {
3595 const Expr *Expression = Node.getTrueExpr();
3596 return (Expression != nullptr &&
3597 InnerMatcher.matches(*Expression, Finder, Builder));
3600 /// \brief Matches the false branch expression of a conditional operator
3601 /// (binary or ternary).
3603 /// Example matches b
3605 /// condition ? a : b
3608 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
3609 internal::Matcher<Expr>, InnerMatcher) {
3610 const Expr *Expression = Node.getFalseExpr();
3611 return (Expression != nullptr &&
3612 InnerMatcher.matches(*Expression, Finder, Builder));
3615 /// \brief Matches if a declaration has a body attached.
3617 /// Example matches A, va, fa
3620 /// class B; // Doesn't match, as it has no body.
3622 /// extern int vb; // Doesn't match, as it doesn't define the variable.
3624 /// void fb(); // Doesn't match, as it has no body.
3627 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
3628 AST_POLYMORPHIC_MATCHER(isDefinition,
3629 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
3631 return Node.isThisDeclarationADefinition();
3634 /// \brief Matches if a function declaration is variadic.
3636 /// Example matches f, but not g or h. The function i will not match, even when
3637 /// compiled in C mode.
3641 /// template <typename... Ts> void h(Ts...);
3644 AST_MATCHER(FunctionDecl, isVariadic) {
3645 return Node.isVariadic();
3648 /// \brief Matches the class declaration that the given method declaration
3651 /// FIXME: Generalize this for other kinds of declarations.
3652 /// FIXME: What other kind of declarations would we need to generalize
3655 /// Example matches A() in the last line
3656 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
3657 /// ofClass(hasName("A"))))))
3665 AST_MATCHER_P(CXXMethodDecl, ofClass,
3666 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
3667 const CXXRecordDecl *Parent = Node.getParent();
3668 return (Parent != nullptr &&
3669 InnerMatcher.matches(*Parent, Finder, Builder));
3672 /// \brief Matches if the given method declaration is virtual.
3678 /// virtual void x();
3682 AST_MATCHER(CXXMethodDecl, isVirtual) {
3683 return Node.isVirtual();
3686 /// \brief Matches if the given method declaration has an explicit "virtual".
3692 /// virtual void x();
3694 /// class B : public A {
3699 /// matches A::x but not B::x
3700 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
3701 return Node.isVirtualAsWritten();
3704 /// \brief Matches if the given method or class declaration is final.
3708 /// class A final {};
3711 /// virtual void f();
3718 /// matches A and C::f, but not B, C, or B::f
3719 AST_POLYMORPHIC_MATCHER(isFinal,
3720 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
3722 return Node.template hasAttr<FinalAttr>();
3725 /// \brief Matches if the given method declaration is pure.
3731 /// virtual void x() = 0;
3735 AST_MATCHER(CXXMethodDecl, isPure) {
3736 return Node.isPure();
3739 /// \brief Matches if the given method declaration is const.
3744 /// void foo() const;
3749 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
3750 AST_MATCHER(CXXMethodDecl, isConst) {
3751 return Node.isConst();
3754 /// \brief Matches if the given method declaration declares a copy assignment
3760 /// A &operator=(const A &);
3761 /// A &operator=(A &&);
3765 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
3767 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
3768 return Node.isCopyAssignmentOperator();
3771 /// \brief Matches if the given method declaration declares a move assignment
3777 /// A &operator=(const A &);
3778 /// A &operator=(A &&);
3782 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
3784 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
3785 return Node.isMoveAssignmentOperator();
3788 /// \brief Matches if the given method declaration overrides another method.
3794 /// virtual void x();
3796 /// class B : public A {
3798 /// virtual void x();
3802 AST_MATCHER(CXXMethodDecl, isOverride) {
3803 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
3806 /// \brief Matches member expressions that are called with '->' as opposed
3809 /// Member calls on the implicit this pointer match as called with '->'.
3814 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
3819 /// memberExpr(isArrow())
3820 /// matches this->x, x, y.x, a, this->b
3821 AST_MATCHER(MemberExpr, isArrow) {
3822 return Node.isArrow();
3825 /// \brief Matches QualType nodes that are of integer type.
3833 /// functionDecl(hasAnyParameter(hasType(isInteger())))
3834 /// matches "a(int)", "b(long)", but not "c(double)".
3835 AST_MATCHER(QualType, isInteger) {
3836 return Node->isIntegerType();
3839 /// \brief Matches QualType nodes that are of character type.
3844 /// void b(wchar_t);
3847 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
3848 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
3849 AST_MATCHER(QualType, isAnyCharacter) {
3850 return Node->isAnyCharacterType();
3853 /// \brief Matches QualType nodes that are of any pointer type; this includes
3854 /// the Objective-C object pointer type, which is different despite being
3855 /// syntactically similar.
3859 /// int *i = nullptr;
3867 /// varDecl(hasType(isAnyPointer()))
3868 /// matches "int *i" and "Foo *f", but not "int j".
3869 AST_MATCHER(QualType, isAnyPointer) {
3870 return Node->isAnyPointerType();
3873 /// \brief Matches QualType nodes that are const-qualified, i.e., that
3874 /// include "top-level" const.
3879 /// void b(int const);
3880 /// void c(const int);
3881 /// void d(const int*);
3882 /// void e(int const) {};
3884 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
3885 /// matches "void b(int const)", "void c(const int)" and
3886 /// "void e(int const) {}". It does not match d as there
3887 /// is no top-level const on the parameter type "const int *".
3888 AST_MATCHER(QualType, isConstQualified) {
3889 return Node.isConstQualified();
3892 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
3893 /// include "top-level" volatile.
3898 /// void b(int volatile);
3899 /// void c(volatile int);
3900 /// void d(volatile int*);
3901 /// void e(int volatile) {};
3903 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
3904 /// matches "void b(int volatile)", "void c(volatile int)" and
3905 /// "void e(int volatile) {}". It does not match d as there
3906 /// is no top-level volatile on the parameter type "volatile int *".
3907 AST_MATCHER(QualType, isVolatileQualified) {
3908 return Node.isVolatileQualified();
3911 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
3912 /// the node, not hidden within a typedef.
3916 /// typedef const int const_int;
3919 /// int *volatile k;
3922 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
3923 /// \c i is const-qualified but the qualifier is not local.
3924 AST_MATCHER(QualType, hasLocalQualifiers) {
3925 return Node.hasLocalQualifiers();
3928 /// \brief Matches a member expression where the member is matched by a
3933 /// struct { int first, second; } first, second;
3934 /// int i(second.first);
3935 /// int j(first.second);
3937 /// memberExpr(member(hasName("first")))
3938 /// matches second.first
3939 /// but not first.second (because the member name there is "second").
3940 AST_MATCHER_P(MemberExpr, member,
3941 internal::Matcher<ValueDecl>, InnerMatcher) {
3942 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
3945 /// \brief Matches a member expression where the object expression is
3946 /// matched by a given matcher.
3950 /// struct X { int m; };
3951 /// void f(X x) { x.m; m; }
3953 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
3954 /// matches "x.m" and "m"
3955 /// with hasObjectExpression(...)
3956 /// matching "x" and the implicit object expression of "m" which has type X*.
3957 AST_MATCHER_P(MemberExpr, hasObjectExpression,
3958 internal::Matcher<Expr>, InnerMatcher) {
3959 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
3962 /// \brief Matches any using shadow declaration.
3966 /// namespace X { void b(); }
3969 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
3970 /// matches \code using X::b \endcode
3971 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
3972 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3973 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
3974 Node.shadow_end(), Finder, Builder);
3977 /// \brief Matches a using shadow declaration where the target declaration is
3978 /// matched by the given matcher.
3982 /// namespace X { int a; void b(); }
3986 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
3987 /// matches \code using X::b \endcode
3988 /// but not \code using X::a \endcode
3989 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
3990 internal::Matcher<NamedDecl>, InnerMatcher) {
3991 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
3994 /// \brief Matches template instantiations of function, class, or static
3995 /// member variable template instantiations.
3999 /// template <typename T> class X {}; class A {}; X<A> x;
4003 /// template <typename T> class X {}; class A {}; template class X<A>;
4005 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4006 /// matches the template instantiation of X<A>.
4010 /// template <typename T> class X {}; class A {};
4011 /// template <> class X<A> {}; X<A> x;
4013 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4014 /// does not match, as X<A> is an explicit template specialization.
4016 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4017 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4018 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4020 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4021 Node.getTemplateSpecializationKind() ==
4022 TSK_ExplicitInstantiationDefinition);
4025 /// \brief Matches declarations that are template instantiations or are inside
4026 /// template instantiations.
4030 /// template<typename T> void A(T t) { T i; }
4034 /// functionDecl(isInstantiated())
4035 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
4036 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4037 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4038 functionDecl(isTemplateInstantiation())));
4039 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4042 /// \brief Matches statements inside of a template instantiation.
4047 /// template<typename T> void A(T t) { T i; j += 42;}
4051 /// declStmt(isInTemplateInstantiation())
4052 /// matches 'int i;' and 'unsigned i'.
4053 /// unless(stmt(isInTemplateInstantiation()))
4054 /// will NOT match j += 42; as it's shared between the template definition and
4056 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4058 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4059 functionDecl(isTemplateInstantiation())))));
4062 /// \brief Matches explicit template specializations of function, class, or
4063 /// static member variable template instantiations.
4067 /// template<typename T> void A(T t) { }
4068 /// template<> void A(int N) { }
4070 /// functionDecl(isExplicitTemplateSpecialization())
4071 /// matches the specialization A<int>().
4073 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4074 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4075 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4077 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4080 /// \brief Matches \c TypeLocs for which the given inner
4081 /// QualType-matcher matches.
4082 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4083 internal::Matcher<QualType>, InnerMatcher, 0) {
4084 return internal::BindableMatcher<TypeLoc>(
4085 new internal::TypeLocTypeMatcher(InnerMatcher));
4088 /// \brief Matches type \c bool.
4092 /// struct S { bool func(); };
4094 /// functionDecl(returns(booleanType()))
4095 /// matches "bool func();"
4096 AST_MATCHER(Type, booleanType) {
4097 return Node.isBooleanType();
4100 /// \brief Matches type \c void.
4104 /// struct S { void func(); };
4106 /// functionDecl(returns(voidType()))
4107 /// matches "void func();"
4108 AST_MATCHER(Type, voidType) {
4109 return Node.isVoidType();
4112 /// \brief Matches builtin Types.
4123 /// matches "int b", "float c" and "bool d"
4124 AST_TYPE_MATCHER(BuiltinType, builtinType);
4126 /// \brief Matches all kinds of arrays.
4130 /// int a[] = { 2, 3 };
4132 /// void f() { int c[a[0]]; }
4135 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4136 AST_TYPE_MATCHER(ArrayType, arrayType);
4138 /// \brief Matches C99 complex types.
4142 /// _Complex float f;
4145 /// matches "_Complex float f"
4146 AST_TYPE_MATCHER(ComplexType, complexType);
4148 /// \brief Matches any real floating-point type (float, double, long double).
4155 /// realFloatingPointType()
4156 /// matches "float f" but not "int i"
4157 AST_MATCHER(Type, realFloatingPointType) {
4158 return Node.isRealFloatingType();
4161 /// \brief Matches arrays and C99 complex types that have a specific element
4170 /// arrayType(hasElementType(builtinType()))
4171 /// matches "int b[7]"
4173 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
4174 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
4175 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
4178 /// \brief Matches C arrays with a specified constant size.
4184 /// int b[] = { 2, 3 };
4188 /// constantArrayType()
4189 /// matches "int a[2]"
4190 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
4192 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
4198 /// int c[41], d[43];
4200 /// constantArrayType(hasSize(42))
4201 /// matches "int a[42]" and "int b[2 * 21]"
4202 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
4203 return Node.getSize() == N;
4206 /// \brief Matches C++ arrays whose size is a value-dependent expression.
4210 /// template<typename T, int Size>
4215 /// dependentSizedArrayType
4216 /// matches "T data[Size]"
4217 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
4219 /// \brief Matches C arrays with unspecified size.
4223 /// int a[] = { 2, 3 };
4225 /// void f(int c[]) { int d[a[0]]; };
4227 /// incompleteArrayType()
4228 /// matches "int a[]" and "int c[]"
4229 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
4231 /// \brief Matches C arrays with a specified size that is not an
4232 /// integer-constant-expression.
4237 /// int a[] = { 2, 3 }
4242 /// variableArrayType()
4243 /// matches "int c[a[0]]"
4244 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
4246 /// \brief Matches \c VariableArrayType nodes that have a specific size
4255 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4256 /// varDecl(hasName("b")))))))
4257 /// matches "int a[b]"
4258 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
4259 internal::Matcher<Expr>, InnerMatcher) {
4260 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
4263 /// \brief Matches atomic types.
4270 /// matches "_Atomic(int) i"
4271 AST_TYPE_MATCHER(AtomicType, atomicType);
4273 /// \brief Matches atomic types with a specific value type.
4278 /// _Atomic(float) f;
4280 /// atomicType(hasValueType(isInteger()))
4281 /// matches "_Atomic(int) i"
4283 /// Usable as: Matcher<AtomicType>
4284 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
4285 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
4287 /// \brief Matches types nodes representing C++11 auto types.
4292 /// int v[] = { 2, 3 }
4293 /// for (auto i : v) { }
4296 /// matches "auto n" and "auto i"
4297 AST_TYPE_MATCHER(AutoType, autoType);
4299 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
4301 /// Note: There is no \c TypeLoc for the deduced type and thus no
4302 /// \c getDeducedLoc() matcher.
4309 /// autoType(hasDeducedType(isInteger()))
4310 /// matches "auto a"
4312 /// Usable as: Matcher<AutoType>
4313 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
4314 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
4316 /// \brief Matches \c FunctionType nodes.
4324 /// matches "int (*f)(int)" and the type of "g".
4325 AST_TYPE_MATCHER(FunctionType, functionType);
4327 /// \brief Matches \c FunctionProtoType nodes.
4334 /// functionProtoType()
4335 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
4336 /// In C mode, "g" is not matched because it does not contain a prototype.
4337 AST_TYPE_MATCHER(FunctionProtoType, functionProtoType);
4339 /// \brief Matches \c ParenType nodes.
4343 /// int (*ptr_to_array)[4];
4344 /// int *array_of_ptrs[4];
4347 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4348 /// \c array_of_ptrs.
4349 AST_TYPE_MATCHER(ParenType, parenType);
4351 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4355 /// int (*ptr_to_array)[4];
4356 /// int (*ptr_to_func)(int);
4359 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4360 /// \c ptr_to_func but not \c ptr_to_array.
4362 /// Usable as: Matcher<ParenType>
4363 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4364 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4366 /// \brief Matches block pointer types, i.e. types syntactically represented as
4367 /// "void (^)(int)".
4369 /// The \c pointee is always required to be a \c FunctionType.
4370 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4372 /// \brief Matches member pointer types.
4375 /// struct A { int i; }
4376 /// A::* ptr = A::i;
4378 /// memberPointerType()
4379 /// matches "A::* ptr"
4380 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4382 /// \brief Matches pointer types, but does not match Objective-C object pointer
4396 /// matches "int *a", but does not match "Foo *f".
4397 AST_TYPE_MATCHER(PointerType, pointerType);
4399 /// \brief Matches an Objective-C object pointer type, which is different from
4400 /// a pointer type, despite being syntactically similar.
4411 /// matches "Foo *f", but does not match "int *a".
4412 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4414 /// \brief Matches both lvalue and rvalue reference types.
4427 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4428 AST_TYPE_MATCHER(ReferenceType, referenceType);
4430 /// \brief Matches lvalue reference types.
4443 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4444 /// matched since the type is deduced as int& by reference collapsing rules.
4445 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4447 /// \brief Matches rvalue reference types.
4460 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4461 /// matched as it is deduced to int& by reference collapsing rules.
4462 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4464 /// \brief Narrows PointerType (and similar) matchers to those where the
4465 /// \c pointee matches a given matcher.
4473 /// pointerType(pointee(isConstQualified(), isInteger()))
4474 /// matches "int const *b"
4476 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4477 /// Matcher<PointerType>, Matcher<ReferenceType>
4478 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4479 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4484 /// \brief Matches typedef types.
4491 /// matches "typedef int X"
4492 AST_TYPE_MATCHER(TypedefType, typedefType);
4494 /// \brief Matches template specialization types.
4498 /// template <typename T>
4501 /// template class C<int>; // A
4502 /// C<char> var; // B
4505 /// \c templateSpecializationType() matches the type of the explicit
4506 /// instantiation in \c A and the type of the variable declaration in \c B.
4507 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
4509 /// \brief Matches types nodes representing unary type transformations.
4513 /// typedef __underlying_type(T) type;
4515 /// unaryTransformType()
4516 /// matches "__underlying_type(T)"
4517 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
4519 /// \brief Matches record types (e.g. structs, classes).
4530 /// \c recordType() matches the type of the variable declarations of both \c c
4532 AST_TYPE_MATCHER(RecordType, recordType);
4534 /// \brief Matches types specified with an elaborated type keyword or with a
4550 /// \c elaboratedType() matches the type of the variable declarations of both
4552 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
4554 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
4555 /// matches \c InnerMatcher if the qualifier exists.
4567 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
4568 /// matches the type of the variable declaration of \c d.
4569 AST_MATCHER_P(ElaboratedType, hasQualifier,
4570 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
4571 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
4572 return InnerMatcher.matches(*Qualifier, Finder, Builder);
4577 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
4589 /// \c elaboratedType(namesType(recordType(
4590 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
4591 /// declaration of \c d.
4592 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
4594 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
4597 /// \brief Matches types that represent the result of substituting a type for a
4598 /// template type parameter.
4602 /// template <typename T>
4608 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
4609 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
4611 /// \brief Matches template type parameter types.
4613 /// Example matches T, but not int.
4614 /// (matcher = templateTypeParmType())
4616 /// template <typename T> void f(int i);
4618 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
4620 /// \brief Matches injected class name types.
4622 /// Example matches S s, but not S<T> s.
4623 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
4625 /// template <typename T> struct S {
4630 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
4632 /// \brief Matches decayed type
4633 /// Example matches i[] in declaration of f.
4634 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
4635 /// Example matches i[1].
4636 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
4638 /// void f(int i[]) {
4642 AST_TYPE_MATCHER(DecayedType, decayedType);
4644 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
4645 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
4647 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
4650 /// \brief Matches declarations whose declaration context, interpreted as a
4651 /// Decl, matches \c InnerMatcher.
4662 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
4663 /// declaration of \c class \c D.
4664 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
4665 const DeclContext *DC = Node.getDeclContext();
4666 if (!DC) return false;
4667 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
4670 /// \brief Matches nested name specifiers.
4675 /// struct A { static void f(); };
4677 /// void g() { A::f(); }
4681 /// nestedNameSpecifier()
4682 /// matches "ns::" and both "A::"
4683 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
4685 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
4686 const internal::VariadicAllOfMatcher<
4687 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
4689 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
4690 /// NestedNameSpecifier-matcher matches.
4691 AST_MATCHER_FUNCTION_P_OVERLOAD(
4692 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
4693 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
4694 return internal::BindableMatcher<NestedNameSpecifierLoc>(
4695 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
4699 /// \brief Matches nested name specifiers that specify a type matching the
4700 /// given \c QualType matcher without qualifiers.
4704 /// struct A { struct B { struct C {}; }; };
4707 /// nestedNameSpecifier(specifiesType(
4708 /// hasDeclaration(cxxRecordDecl(hasName("A")))
4711 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
4712 internal::Matcher<QualType>, InnerMatcher) {
4713 if (!Node.getAsType())
4715 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
4718 /// \brief Matches nested name specifier locs that specify a type matching the
4719 /// given \c TypeLoc.
4723 /// struct A { struct B { struct C {}; }; };
4726 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
4727 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
4729 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
4730 internal::Matcher<TypeLoc>, InnerMatcher) {
4731 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
4734 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
4738 /// struct A { struct B { struct C {}; }; };
4741 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
4743 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
4744 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
4746 const NestedNameSpecifier *NextNode = Node.getPrefix();
4749 return InnerMatcher.matches(*NextNode, Finder, Builder);
4752 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
4756 /// struct A { struct B { struct C {}; }; };
4759 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
4761 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
4762 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
4764 NestedNameSpecifierLoc NextNode = Node.getPrefix();
4767 return InnerMatcher.matches(NextNode, Finder, Builder);
4770 /// \brief Matches nested name specifiers that specify a namespace matching the
4771 /// given namespace matcher.
4775 /// namespace ns { struct A {}; }
4778 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
4780 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
4781 internal::Matcher<NamespaceDecl>, InnerMatcher) {
4782 if (!Node.getAsNamespace())
4784 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
4787 /// \brief Overloads for the \c equalsNode matcher.
4788 /// FIXME: Implement for other node types.
4791 /// \brief Matches if a node equals another node.
4793 /// \c Decl has pointer identity in the AST.
4794 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
4795 return &Node == Other;
4797 /// \brief Matches if a node equals another node.
4799 /// \c Stmt has pointer identity in the AST.
4800 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
4801 return &Node == Other;
4803 /// \brief Matches if a node equals another node.
4805 /// \c Type has pointer identity in the AST.
4806 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
4807 return &Node == Other;
4812 /// \brief Matches each case or default statement belonging to the given switch
4813 /// statement. This matcher may produce multiple matches.
4817 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
4819 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
4820 /// matches four times, with "c" binding each of "case 1:", "case 2:",
4821 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
4822 /// "switch (1)", "switch (2)" and "switch (2)".
4823 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
4825 BoundNodesTreeBuilder Result;
4826 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
4827 // iteration order. We should use the more general iterating matchers once
4828 // they are capable of expressing this matcher (for example, it should ignore
4829 // case statements belonging to nested switch statements).
4830 bool Matched = false;
4831 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
4832 SC = SC->getNextSwitchCase()) {
4833 BoundNodesTreeBuilder CaseBuilder(*Builder);
4834 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
4837 Result.addMatch(CaseBuilder);
4840 *Builder = std::move(Result);
4844 /// \brief Matches each constructor initializer in a constructor definition.
4848 /// class A { A() : i(42), j(42) {} int i; int j; };
4850 /// cxxConstructorDecl(forEachConstructorInitializer(
4851 /// forField(decl().bind("x"))
4853 /// will trigger two matches, binding for 'i' and 'j' respectively.
4854 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
4855 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4856 BoundNodesTreeBuilder Result;
4857 bool Matched = false;
4858 for (const auto *I : Node.inits()) {
4859 BoundNodesTreeBuilder InitBuilder(*Builder);
4860 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
4862 Result.addMatch(InitBuilder);
4865 *Builder = std::move(Result);
4869 /// \brief Matches constructor declarations that are copy constructors.
4875 /// S(const S &); // #2
4879 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
4880 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
4881 return Node.isCopyConstructor();
4884 /// \brief Matches constructor declarations that are move constructors.
4890 /// S(const S &); // #2
4894 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
4895 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
4896 return Node.isMoveConstructor();
4899 /// \brief Matches constructor declarations that are default constructors.
4905 /// S(const S &); // #2
4909 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
4910 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
4911 return Node.isDefaultConstructor();
4914 /// \brief Matches constructor and conversion declarations that are marked with
4915 /// the explicit keyword.
4921 /// explicit S(double); // #2
4922 /// operator int(); // #3
4923 /// explicit operator bool(); // #4
4926 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
4927 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
4928 AST_POLYMORPHIC_MATCHER(isExplicit,
4929 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
4930 CXXConversionDecl)) {
4931 return Node.isExplicit();
4934 /// \brief Matches function and namespace declarations that are marked with
4935 /// the inline keyword.
4939 /// inline void f();
4942 /// inline namespace m {}
4945 /// functionDecl(isInline()) will match ::f().
4946 /// namespaceDecl(isInline()) will match n::m.
4947 AST_POLYMORPHIC_MATCHER(isInline,
4948 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
4950 // This is required because the spelling of the function used to determine
4951 // whether inline is specified or not differs between the polymorphic types.
4952 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
4953 return FD->isInlineSpecified();
4954 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
4955 return NSD->isInline();
4956 llvm_unreachable("Not a valid polymorphic type");
4959 /// \brief Matches anonymous namespace declarations.
4964 /// namespace {} // #1
4967 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
4968 AST_MATCHER(NamespaceDecl, isAnonymous) {
4969 return Node.isAnonymousNamespace();
4972 /// \brief If the given case statement does not use the GNU case range
4973 /// extension, matches the constant given in the statement.
4977 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
4979 /// caseStmt(hasCaseConstant(integerLiteral()))
4980 /// matches "case 1:"
4981 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
4986 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
4989 /// \brief Matches declaration that has a given attribute.
4993 /// __attribute__((device)) void f() { ... }
4995 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
4996 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
4997 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
4998 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
4999 for (const auto *Attr : Node.attrs()) {
5000 if (Attr->getKind() == AttrKind)
5006 /// \brief Matches the return value expression of a return statement
5012 /// hasReturnValue(binaryOperator())
5013 /// matches 'return a + b'
5014 /// with binaryOperator()
5015 /// matching 'a + b'
5016 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5018 return InnerMatcher.matches(*Node.getRetValue(), Finder, Builder);
5022 /// \brief Matches CUDA kernel call expression.
5024 /// Example matches,
5026 /// kernel<<<i,j>>>();
5028 const internal::VariadicDynCastAllOfMatcher<
5030 CUDAKernelCallExpr> cudaKernelCallExpr;
5033 /// \brief Matches expressions that resolve to a null pointer constant, such as
5034 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5038 /// void *v1 = NULL;
5039 /// void *v2 = nullptr;
5040 /// void *v3 = __null; // GNU extension
5041 /// char *cp = (char *)0;
5045 /// expr(nullPointerConstant())
5046 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5047 /// initializer for i.
5048 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5050 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5051 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5053 } // end namespace ast_matchers
5054 } // end namespace clang