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 // recordDecl(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 // recordDecl(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 CXXRecordDecl 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_AST_MATCHERS_AST_MATCHERS_H
46 #define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
48 #include "clang/AST/DeclFriend.h"
49 #include "clang/AST/DeclTemplate.h"
50 #include "clang/ASTMatchers/ASTMatchersInternal.h"
51 #include "clang/ASTMatchers/ASTMatchersMacros.h"
52 #include "llvm/ADT/Twine.h"
53 #include "llvm/Support/Regex.h"
57 namespace ast_matchers {
59 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
61 /// The bound nodes are generated by calling \c bind("id") on the node matchers
62 /// of the nodes we want to access later.
64 /// The instances of BoundNodes are created by \c MatchFinder when the user's
65 /// callbacks are executed every time a match is found.
68 /// \brief Returns the AST node bound to \c ID.
70 /// Returns NULL if there was no node bound to \c ID or if there is a node but
71 /// it cannot be converted to the specified type.
73 const T *getNodeAs(StringRef ID) const {
74 return MyBoundNodes.getNodeAs<T>(ID);
77 /// \brief Deprecated. Please use \c getNodeAs instead.
80 const T *getDeclAs(StringRef ID) const {
81 return getNodeAs<T>(ID);
84 const T *getStmtAs(StringRef ID) const {
85 return getNodeAs<T>(ID);
89 /// \brief Type of mapping from binding identifiers to bound nodes. This type
90 /// is an associative container with a key type of \c std::string and a value
91 /// type of \c clang::ast_type_traits::DynTypedNode
92 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
94 /// \brief Retrieve mapping from binding identifiers to bound nodes.
95 const IDToNodeMap &getMap() const {
96 return MyBoundNodes.getMap();
100 /// \brief Create BoundNodes from a pre-filled map of bindings.
101 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
102 : MyBoundNodes(MyBoundNodes) {}
104 internal::BoundNodesMap MyBoundNodes;
106 friend class internal::BoundNodesTreeBuilder;
109 /// \brief If the provided matcher matches a node, binds the node to \c ID.
111 /// FIXME: Do we want to support this now that we have bind()?
112 template <typename T>
113 internal::Matcher<T> id(const std::string &ID,
114 const internal::BindableMatcher<T> &InnerMatcher) {
115 return InnerMatcher.bind(ID);
118 /// \brief Types of matchers for the top-level classes in the AST class
121 typedef internal::Matcher<Decl> DeclarationMatcher;
122 typedef internal::Matcher<Stmt> StatementMatcher;
123 typedef internal::Matcher<QualType> TypeMatcher;
124 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
125 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
126 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
129 /// \brief Matches any node.
131 /// Useful when another matcher requires a child matcher, but there's no
132 /// additional constraint. This will often be used with an explicit conversion
133 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
135 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
137 /// "int* p" and "void f()" in
142 /// Usable as: Any Matcher
143 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>
145 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
148 /// \brief Matches declarations.
150 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
157 const internal::VariadicAllOfMatcher<Decl> decl;
159 /// \brief Matches a declaration of anything that could have a name.
161 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
170 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
172 /// \brief Matches a declaration of a namespace.
177 /// namespace test {}
180 /// matches "namespace {}" and "namespace test {}"
181 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
183 /// \brief Matches C++ class declarations.
185 /// Example matches \c X, \c Z
188 /// template<class T> class Z {};
190 const internal::VariadicDynCastAllOfMatcher<
192 CXXRecordDecl> recordDecl;
194 /// \brief Matches C++ class template declarations.
196 /// Example matches \c Z
198 /// template<class T> class Z {};
200 const internal::VariadicDynCastAllOfMatcher<
202 ClassTemplateDecl> classTemplateDecl;
204 /// \brief Matches C++ class template specializations.
208 /// template<typename T> class A {};
209 /// template<> class A<double> {};
212 /// classTemplateSpecializationDecl()
213 /// matches the specializations \c A<int> and \c A<double>
214 const internal::VariadicDynCastAllOfMatcher<
216 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
218 /// \brief Matches declarator declarations (field, variable, function
219 /// and non-type template parameter declarations).
223 /// class X { int y; };
226 /// matches \c int y.
227 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
230 /// \brief Matches parameter variable declarations.
237 /// matches \c int x.
238 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
240 /// \brief Matches C++ access specifier declarations.
250 /// matches 'public:'
251 const internal::VariadicDynCastAllOfMatcher<
253 AccessSpecDecl> accessSpecDecl;
255 /// \brief Matches constructor initializers.
257 /// Examples matches \c i(42).
264 const internal::VariadicAllOfMatcher<CXXCtorInitializer> ctorInitializer;
266 /// \brief Matches public C++ declarations.
272 /// protected: int b;
276 /// fieldDecl(isPublic())
278 AST_MATCHER(Decl, isPublic) {
279 return Node.getAccess() == AS_public;
282 /// \brief Matches protected C++ declarations.
288 /// protected: int b;
292 /// fieldDecl(isProtected())
294 AST_MATCHER(Decl, isProtected) {
295 return Node.getAccess() == AS_protected;
298 /// \brief Matches private C++ declarations.
304 /// protected: int b;
308 /// fieldDecl(isPrivate())
310 AST_MATCHER(Decl, isPrivate) {
311 return Node.getAccess() == AS_private;
314 /// \brief Matches classTemplateSpecializations that have at least one
315 /// TemplateArgument matching the given InnerMatcher.
319 /// template<typename T> class A {};
320 /// template<> class A<double> {};
323 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
324 /// refersToType(asString("int"))))
325 /// matches the specialization \c A<int>
326 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
327 internal::Matcher<TemplateArgument>, InnerMatcher) {
328 llvm::ArrayRef<TemplateArgument> List = Node.getTemplateArgs().asArray();
329 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
333 /// \brief Matches expressions that match InnerMatcher after any implicit casts
334 /// are stripped off.
336 /// Parentheses and explicit casts are not discarded.
344 /// long e = (long) 0l;
348 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
349 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
351 /// would match the declarations for a, b, c, and d, but not e.
354 /// varDecl(hasInitializer(integerLiteral()))
355 /// varDecl(hasInitializer(declRefExpr()))
357 /// only match the declarations for b, c, and d.
358 AST_MATCHER_P(Expr, ignoringImpCasts,
359 internal::Matcher<Expr>, InnerMatcher) {
360 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
363 /// \brief Matches expressions that match InnerMatcher after parentheses and
364 /// casts are stripped off.
366 /// Implicit and non-C Style casts are also discarded.
371 /// void* c = reinterpret_cast<char*>(0);
372 /// char d = char(0);
375 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
376 /// would match the declarations for a, b, c, and d.
378 /// varDecl(hasInitializer(integerLiteral()))
379 /// only match the declaration for a.
380 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
381 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
384 /// \brief Matches expressions that match InnerMatcher after implicit casts and
385 /// parentheses are stripped off.
387 /// Explicit casts are not discarded.
395 /// long e = ((long) 0l);
398 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
399 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
400 /// would match the declarations for a, b, c, and d, but not e.
402 /// varDecl(hasInitializer(integerLiteral()))
403 /// varDecl(hasInitializer(declRefExpr()))
404 /// would only match the declaration for a.
405 AST_MATCHER_P(Expr, ignoringParenImpCasts,
406 internal::Matcher<Expr>, InnerMatcher) {
407 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
410 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
411 /// matches the given InnerMatcher.
415 /// template<typename T, typename U> class A {};
419 /// classTemplateSpecializationDecl(hasTemplateArgument(
420 /// 1, refersToType(asString("int"))))
421 /// matches the specialization \c A<bool, int>
422 AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
423 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
424 const TemplateArgumentList &List = Node.getTemplateArgs();
425 if (List.size() <= N)
427 return InnerMatcher.matches(List.get(N), Finder, Builder);
430 /// \brief Matches a TemplateArgument that refers to a certain type.
435 /// template<typename T> struct A {};
438 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
439 /// refersToType(class(hasName("X")))))
440 /// matches the specialization \c A<X>
441 AST_MATCHER_P(TemplateArgument, refersToType,
442 internal::Matcher<QualType>, InnerMatcher) {
443 if (Node.getKind() != TemplateArgument::Type)
445 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
448 /// \brief Matches a TemplateArgument that refers to a certain declaration.
452 /// template<typename T> struct A {};
453 /// struct B { B* next; };
456 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
457 /// refersToDeclaration(fieldDecl(hasName("next"))))
458 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
460 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
461 internal::Matcher<Decl>, InnerMatcher) {
462 if (Node.getKind() == TemplateArgument::Declaration)
463 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
467 /// \brief Matches C++ constructor declarations.
469 /// Example matches Foo::Foo() and Foo::Foo(int)
475 /// int DoSomething();
478 const internal::VariadicDynCastAllOfMatcher<
480 CXXConstructorDecl> constructorDecl;
482 /// \brief Matches explicit C++ destructor declarations.
484 /// Example matches Foo::~Foo()
491 const internal::VariadicDynCastAllOfMatcher<
493 CXXDestructorDecl> destructorDecl;
495 /// \brief Matches enum declarations.
497 /// Example matches X
503 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
505 /// \brief Matches enum constants.
507 /// Example matches A, B, C
513 const internal::VariadicDynCastAllOfMatcher<
515 EnumConstantDecl> enumConstantDecl;
517 /// \brief Matches method declarations.
519 /// Example matches y
521 /// class X { void y() };
523 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
525 /// \brief Matches variable declarations.
527 /// Note: this does not match declarations of member variables, which are
528 /// "field" declarations in Clang parlance.
530 /// Example matches a
534 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
536 /// \brief Matches field declarations.
540 /// class X { int m; };
544 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
546 /// \brief Matches function declarations.
548 /// Example matches f
552 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
554 /// \brief Matches C++ function template declarations.
556 /// Example matches f
558 /// template<class T> void f(T t) {}
560 const internal::VariadicDynCastAllOfMatcher<
562 FunctionTemplateDecl> functionTemplateDecl;
564 /// \brief Matches friend declarations.
568 /// class X { friend void foo(); };
571 /// matches 'friend void foo()'.
572 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
574 /// \brief Matches statements.
581 /// matches both the compound statement '{ ++a; }' and '++a'.
582 const internal::VariadicAllOfMatcher<Stmt> stmt;
584 /// \brief Matches declaration statements.
592 const internal::VariadicDynCastAllOfMatcher<
596 /// \brief Matches member expressions.
601 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
602 /// int a; static int b;
606 /// matches this->x, x, y.x, a, this->b
607 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
609 /// \brief Matches call expressions.
611 /// Example matches x.y() and y()
617 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
619 /// \brief Matches lambda expressions.
621 /// Example matches [&](){return 5;}
625 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
627 /// \brief Matches member call expressions.
629 /// Example matches x.y()
634 const internal::VariadicDynCastAllOfMatcher<
636 CXXMemberCallExpr> memberCallExpr;
638 /// \brief Matches init list expressions.
642 /// int a[] = { 1, 2 };
643 /// struct B { int x, y; };
647 /// matches "{ 1, 2 }" and "{ 5, 6 }"
648 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
650 /// \brief Matches using declarations.
654 /// namespace X { int x; }
658 /// matches \code using X::x \endcode
659 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
661 /// \brief Matches unresolved using value declarations.
665 /// template<typename X>
666 /// class C : private X {
670 /// unresolvedUsingValueDecl()
671 /// matches \code using X::x \endcode
672 const internal::VariadicDynCastAllOfMatcher<
674 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
676 /// \brief Matches constructor call expressions (including implicit ones).
678 /// Example matches string(ptr, n) and ptr within arguments of f
679 /// (matcher = constructExpr())
681 /// void f(const string &a, const string &b);
684 /// f(string(ptr, n), ptr);
686 const internal::VariadicDynCastAllOfMatcher<
688 CXXConstructExpr> constructExpr;
690 /// \brief Matches unresolved constructor call expressions.
692 /// Example matches T(t) in return statement of f
693 /// (matcher = unresolvedConstructExpr())
695 /// template <typename T>
696 /// void f(const T& t) { return T(t); }
698 const internal::VariadicDynCastAllOfMatcher<
700 CXXUnresolvedConstructExpr> unresolvedConstructExpr;
702 /// \brief Matches implicit and explicit this expressions.
704 /// Example matches the implicit this expression in "return i".
705 /// (matcher = thisExpr())
709 /// int f() { return i; }
712 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr;
714 /// \brief Matches nodes where temporaries are created.
716 /// Example matches FunctionTakesString(GetStringByValue())
717 /// (matcher = bindTemporaryExpr())
719 /// FunctionTakesString(GetStringByValue());
720 /// FunctionTakesStringByPointer(GetStringPointer());
722 const internal::VariadicDynCastAllOfMatcher<
724 CXXBindTemporaryExpr> bindTemporaryExpr;
726 /// \brief Matches nodes where temporaries are materialized.
730 /// struct T {void func()};
734 /// materializeTemporaryExpr() matches 'f()' in these statements
739 /// but does not match
744 const internal::VariadicDynCastAllOfMatcher<
746 MaterializeTemporaryExpr> materializeTemporaryExpr;
748 /// \brief Matches new expressions.
756 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr;
758 /// \brief Matches delete expressions.
765 /// matches 'delete X'.
766 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr;
768 /// \brief Matches array subscript expressions.
774 /// arraySubscriptExpr()
776 const internal::VariadicDynCastAllOfMatcher<
778 ArraySubscriptExpr> arraySubscriptExpr;
780 /// \brief Matches the value of a default argument at the call site.
782 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
783 /// default value of the second parameter in the call expression f(42)
784 /// (matcher = defaultArgExpr())
786 /// void f(int x, int y = 0);
789 const internal::VariadicDynCastAllOfMatcher<
791 CXXDefaultArgExpr> defaultArgExpr;
793 /// \brief Matches overloaded operator calls.
795 /// Note that if an operator isn't overloaded, it won't match. Instead, use
796 /// binaryOperator matcher.
797 /// Currently it does not match operators such as new delete.
798 /// FIXME: figure out why these do not match?
800 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
801 /// (matcher = operatorCallExpr())
803 /// ostream &operator<< (ostream &out, int i) { };
804 /// ostream &o; int b = 1, c = 1;
807 const internal::VariadicDynCastAllOfMatcher<
809 CXXOperatorCallExpr> operatorCallExpr;
811 /// \brief Matches expressions.
813 /// Example matches x()
815 /// void f() { x(); }
817 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
819 /// \brief Matches expressions that refer to declarations.
821 /// Example matches x in if (x)
826 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
828 /// \brief Matches if statements.
830 /// Example matches 'if (x) {}'
834 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
836 /// \brief Matches for statements.
838 /// Example matches 'for (;;) {}'
841 /// int i[] = {1, 2, 3}; for (auto a : i);
843 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
845 /// \brief Matches range-based for statements.
847 /// forRangeStmt() matches 'for (auto a : i)'
849 /// int i[] = {1, 2, 3}; for (auto a : i);
850 /// for(int j = 0; j < 5; ++j);
852 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt;
854 /// \brief Matches the increment statement of a for loop.
857 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
860 /// for (x; x < N; ++x) { }
862 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
864 const Stmt *const Increment = Node.getInc();
865 return (Increment != NULL &&
866 InnerMatcher.matches(*Increment, Finder, Builder));
869 /// \brief Matches the initialization statement of a for loop.
872 /// forStmt(hasLoopInit(declStmt()))
873 /// matches 'int x = 0' in
875 /// for (int x = 0; x < N; ++x) { }
877 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
879 const Stmt *const Init = Node.getInit();
880 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
883 /// \brief Matches while statements.
890 /// matches 'while (true) {}'.
891 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
893 /// \brief Matches do statements.
897 /// do {} while (true);
900 /// matches 'do {} while(true)'
901 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
903 /// \brief Matches break statements.
907 /// while (true) { break; }
911 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
913 /// \brief Matches continue statements.
917 /// while (true) { continue; }
920 /// matches 'continue'
921 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
923 /// \brief Matches return statements.
930 /// matches 'return 1'
931 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
933 /// \brief Matches goto statements.
941 /// matches 'goto FOO'
942 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
944 /// \brief Matches label statements.
953 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
955 /// \brief Matches switch statements.
959 /// switch(a) { case 42: break; default: break; }
962 /// matches 'switch(a)'.
963 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
965 /// \brief Matches case and default statements inside switch statements.
969 /// switch(a) { case 42: break; default: break; }
972 /// matches 'case 42: break;' and 'default: break;'.
973 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
975 /// \brief Matches case statements inside switch statements.
979 /// switch(a) { case 42: break; default: break; }
982 /// matches 'case 42: break;'.
983 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
985 /// \brief Matches default statements inside switch statements.
989 /// switch(a) { case 42: break; default: break; }
992 /// matches 'default: break;'.
993 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
995 /// \brief Matches compound statements.
997 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1001 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1003 /// \brief Matches catch statements.
1006 /// try {} catch(int i) {}
1009 /// matches 'catch(int i)'
1010 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt;
1012 /// \brief Matches try statements.
1015 /// try {} catch(int i) {}
1018 /// matches 'try {}'
1019 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt;
1021 /// \brief Matches throw expressions.
1024 /// try { throw 5; } catch(int i) {}
1027 /// matches 'throw 5'
1028 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr;
1030 /// \brief Matches null statements.
1036 /// matches the second ';'
1037 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1039 /// \brief Matches asm statements.
1043 /// __asm("mov al, 2");
1046 /// matches '__asm("mov al, 2")'
1047 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1049 /// \brief Matches bool literals.
1051 /// Example matches true
1055 const internal::VariadicDynCastAllOfMatcher<
1057 CXXBoolLiteralExpr> boolLiteral;
1059 /// \brief Matches string literals (also matches wide string literals).
1061 /// Example matches "abcd", L"abcd"
1063 /// char *s = "abcd"; wchar_t *ws = L"abcd"
1065 const internal::VariadicDynCastAllOfMatcher<
1067 StringLiteral> stringLiteral;
1069 /// \brief Matches character literals (also matches wchar_t).
1071 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1074 /// Example matches 'a', L'a'
1076 /// char ch = 'a'; wchar_t chw = L'a';
1078 const internal::VariadicDynCastAllOfMatcher<
1080 CharacterLiteral> characterLiteral;
1082 /// \brief Matches integer literals of all sizes / encodings, e.g.
1083 /// 1, 1L, 0x1 and 1U.
1085 /// Does not match character-encoded integers such as L'a'.
1086 const internal::VariadicDynCastAllOfMatcher<
1088 IntegerLiteral> integerLiteral;
1090 /// \brief Matches float literals of all sizes / encodings, e.g.
1091 /// 1.0, 1.0f, 1.0L and 1e10.
1093 /// Does not match implicit conversions such as
1097 const internal::VariadicDynCastAllOfMatcher<
1099 FloatingLiteral> floatLiteral;
1101 /// \brief Matches user defined literal operator call.
1103 /// Example match: "foo"_suffix
1104 const internal::VariadicDynCastAllOfMatcher<
1106 UserDefinedLiteral> userDefinedLiteral;
1108 /// \brief Matches compound (i.e. non-scalar) literals
1110 /// Example match: {1}, (1, 2)
1112 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1114 const internal::VariadicDynCastAllOfMatcher<
1116 CompoundLiteralExpr> compoundLiteralExpr;
1118 /// \brief Matches nullptr literal.
1119 const internal::VariadicDynCastAllOfMatcher<
1121 CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
1123 /// \brief Matches binary operator expressions.
1125 /// Example matches a || b
1129 const internal::VariadicDynCastAllOfMatcher<
1131 BinaryOperator> binaryOperator;
1133 /// \brief Matches unary operator expressions.
1135 /// Example matches !a
1139 const internal::VariadicDynCastAllOfMatcher<
1141 UnaryOperator> unaryOperator;
1143 /// \brief Matches conditional operator expressions.
1145 /// Example matches a ? b : c
1147 /// (a ? b : c) + 42
1149 const internal::VariadicDynCastAllOfMatcher<
1151 ConditionalOperator> conditionalOperator;
1153 /// \brief Matches a reinterpret_cast expression.
1155 /// Either the source expression or the destination type can be matched
1156 /// using has(), but hasDestinationType() is more specific and can be
1159 /// Example matches reinterpret_cast<char*>(&p) in
1161 /// void* p = reinterpret_cast<char*>(&p);
1163 const internal::VariadicDynCastAllOfMatcher<
1165 CXXReinterpretCastExpr> reinterpretCastExpr;
1167 /// \brief Matches a C++ static_cast expression.
1169 /// \see hasDestinationType
1170 /// \see reinterpretCast
1173 /// staticCastExpr()
1175 /// static_cast<long>(8)
1178 /// long eight(static_cast<long>(8));
1180 const internal::VariadicDynCastAllOfMatcher<
1182 CXXStaticCastExpr> staticCastExpr;
1184 /// \brief Matches a dynamic_cast expression.
1187 /// dynamicCastExpr()
1189 /// dynamic_cast<D*>(&b);
1192 /// struct B { virtual ~B() {} }; struct D : B {};
1194 /// D* p = dynamic_cast<D*>(&b);
1196 const internal::VariadicDynCastAllOfMatcher<
1198 CXXDynamicCastExpr> dynamicCastExpr;
1200 /// \brief Matches a const_cast expression.
1202 /// Example: Matches const_cast<int*>(&r) in
1205 /// const int &r(n);
1206 /// int* p = const_cast<int*>(&r);
1208 const internal::VariadicDynCastAllOfMatcher<
1210 CXXConstCastExpr> constCastExpr;
1212 /// \brief Matches a C-style cast expression.
1214 /// Example: Matches (int*) 2.2f in
1216 /// int i = (int) 2.2f;
1218 const internal::VariadicDynCastAllOfMatcher<
1220 CStyleCastExpr> cStyleCastExpr;
1222 /// \brief Matches explicit cast expressions.
1224 /// Matches any cast expression written in user code, whether it be a
1225 /// C-style cast, a functional-style cast, or a keyword cast.
1227 /// Does not match implicit conversions.
1229 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1230 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1231 /// actual cast expressions.
1233 /// \see hasDestinationType.
1235 /// Example: matches all five of the casts in
1237 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1239 /// but does not match the implicit conversion in
1243 const internal::VariadicDynCastAllOfMatcher<
1245 ExplicitCastExpr> explicitCastExpr;
1247 /// \brief Matches the implicit cast nodes of Clang's AST.
1249 /// This matches many different places, including function call return value
1250 /// eliding, as well as any type conversions.
1251 const internal::VariadicDynCastAllOfMatcher<
1253 ImplicitCastExpr> implicitCastExpr;
1255 /// \brief Matches any cast nodes of Clang's AST.
1257 /// Example: castExpr() matches each of the following:
1260 /// const_cast<Expr *>(SubExpr);
1263 /// but does not match
1268 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1270 /// \brief Matches functional cast expressions
1272 /// Example: Matches Foo(bar);
1275 /// Foo g = (Foo) bar;
1276 /// Foo h = Foo(bar);
1278 const internal::VariadicDynCastAllOfMatcher<
1280 CXXFunctionalCastExpr> functionalCastExpr;
1282 /// \brief Matches functional cast expressions having N != 1 arguments
1284 /// Example: Matches Foo(bar, bar)
1286 /// Foo h = Foo(bar, bar);
1288 const internal::VariadicDynCastAllOfMatcher<
1290 CXXTemporaryObjectExpr> temporaryObjectExpr;
1292 /// \brief Matches \c QualTypes in the clang AST.
1293 const internal::VariadicAllOfMatcher<QualType> qualType;
1295 /// \brief Matches \c Types in the clang AST.
1296 const internal::VariadicAllOfMatcher<Type> type;
1298 /// \brief Matches \c TypeLocs in the clang AST.
1299 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1301 /// \brief Matches if any of the given matchers matches.
1303 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1304 /// matching submatcher.
1306 /// For example, in:
1308 /// class A { int a; int b; };
1312 /// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1313 /// has(fieldDecl(hasName("b")).bind("v"))))
1315 /// will generate two results binding "v", the first of which binds
1316 /// the field declaration of \c a, the second the field declaration of
1319 /// Usable as: Any Matcher
1320 const internal::VariadicOperatorMatcherFunc eachOf = {
1321 internal::EachOfVariadicOperator
1324 /// \brief Matches if any of the given matchers matches.
1326 /// Usable as: Any Matcher
1327 const internal::VariadicOperatorMatcherFunc anyOf = {
1328 internal::AnyOfVariadicOperator
1331 /// \brief Matches if all given matchers match.
1333 /// Usable as: Any Matcher
1334 const internal::VariadicOperatorMatcherFunc allOf = {
1335 internal::AllOfVariadicOperator
1338 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1343 /// int y = sizeof(x) + alignof(x);
1345 /// unaryExprOrTypeTraitExpr()
1346 /// matches \c sizeof(x) and \c alignof(x)
1347 const internal::VariadicDynCastAllOfMatcher<
1349 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1351 /// \brief Matches unary expressions that have a specific type of argument.
1355 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1357 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1358 /// matches \c sizeof(a) and \c alignof(c)
1359 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1360 internal::Matcher<QualType>, InnerMatcher) {
1361 const QualType ArgumentType = Node.getTypeOfArgument();
1362 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1365 /// \brief Matches unary expressions of a certain kind.
1370 /// int s = sizeof(x) + alignof(x)
1372 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1373 /// matches \c sizeof(x)
1374 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1375 return Node.getKind() == Kind;
1378 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1380 inline internal::Matcher<Stmt> alignOfExpr(
1381 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1382 return stmt(unaryExprOrTypeTraitExpr(allOf(
1383 ofKind(UETT_AlignOf), InnerMatcher)));
1386 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1388 inline internal::Matcher<Stmt> sizeOfExpr(
1389 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1390 return stmt(unaryExprOrTypeTraitExpr(
1391 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1394 /// \brief Matches NamedDecl nodes that have the specified name.
1396 /// Supports specifying enclosing namespaces or classes by prefixing the name
1397 /// with '<enclosing>::'.
1398 /// Does not match typedefs of an underlying type with the given name.
1400 /// Example matches X (Name == "X")
1405 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1407 /// namespace a { namespace b { class X; } }
1409 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1410 assert(!Name.empty());
1411 const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1412 const StringRef FullName = FullNameString;
1413 const StringRef Pattern = Name;
1414 if (Pattern.startswith("::")) {
1415 return FullName == Pattern;
1417 return FullName.endswith(("::" + Pattern).str());
1421 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1422 /// a substring matched by the given RegExp.
1424 /// Supports specifying enclosing namespaces or classes by
1425 /// prefixing the name with '<enclosing>::'. Does not match typedefs
1426 /// of an underlying type with the given name.
1428 /// Example matches X (regexp == "::X")
1433 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1435 /// namespace foo { namespace bar { class X; } }
1437 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1438 assert(!RegExp.empty());
1439 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1440 llvm::Regex RE(RegExp);
1441 return RE.match(FullNameString);
1444 /// \brief Matches overloaded operator names.
1446 /// Matches overloaded operator names specified in strings without the
1447 /// "operator" prefix: e.g. "<<".
1451 /// class A { int operator*(); };
1452 /// const A &operator<<(const A &a, const A &b);
1454 /// a << a; // <-- This matches
1457 /// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified
1458 /// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
1459 /// the declaration of \c A.
1461 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl>
1462 inline internal::PolymorphicMatcherWithParam1<
1463 internal::HasOverloadedOperatorNameMatcher, StringRef,
1464 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>
1465 hasOverloadedOperatorName(const StringRef Name) {
1466 return internal::PolymorphicMatcherWithParam1<
1467 internal::HasOverloadedOperatorNameMatcher, StringRef,
1468 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>(
1472 /// \brief Matches C++ classes that are directly or indirectly derived from
1473 /// a class matching \c Base.
1475 /// Note that a class is not considered to be derived from itself.
1477 /// Example matches Y, Z, C (Base == hasName("X"))
1480 /// class Y : public X {}; // directly derived
1481 /// class Z : public Y {}; // indirectly derived
1484 /// class C : public B {}; // derived from a typedef of X
1487 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1491 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
1493 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1494 internal::Matcher<NamedDecl>, Base) {
1495 return Finder->classIsDerivedFrom(&Node, Base, Builder);
1498 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1499 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, StringRef, BaseName, 1) {
1500 assert(!BaseName.empty());
1501 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1504 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1506 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
1507 internal::Matcher<NamedDecl>, Base, 0) {
1508 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
1509 .matches(Node, Finder, Builder);
1512 /// \brief Overloaded method as shortcut for
1513 /// \c isSameOrDerivedFrom(hasName(...)).
1514 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, StringRef, BaseName,
1516 assert(!BaseName.empty());
1517 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1520 /// \brief Matches the first method of a class or struct that satisfies \c
1525 /// class A { void func(); };
1526 /// class B { void member(); };
1529 /// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A
1531 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1533 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
1534 Node.method_end(), Finder, Builder);
1537 /// \brief Matches AST nodes that have child AST nodes that match the
1538 /// provided matcher.
1540 /// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1542 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1543 /// class Y { class X {}; };
1544 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1547 /// ChildT must be an AST base type.
1549 /// Usable as: Any Matcher
1550 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
1551 LLVM_ATTRIBUTE_UNUSED has = {};
1553 /// \brief Matches AST nodes that have descendant AST nodes that match the
1554 /// provided matcher.
1556 /// Example matches X, Y, Z
1557 /// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1559 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1560 /// class Y { class X {}; };
1561 /// class Z { class Y { class X {}; }; };
1564 /// DescendantT must be an AST base type.
1566 /// Usable as: Any Matcher
1567 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
1568 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
1570 /// \brief Matches AST nodes that have child AST nodes that match the
1571 /// provided matcher.
1573 /// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1575 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1576 /// class Y { class X {}; };
1577 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1580 /// ChildT must be an AST base type.
1582 /// As opposed to 'has', 'forEach' will cause a match for each result that
1583 /// matches instead of only on the first one.
1585 /// Usable as: Any Matcher
1586 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
1587 LLVM_ATTRIBUTE_UNUSED forEach = {};
1589 /// \brief Matches AST nodes that have descendant AST nodes that match the
1590 /// provided matcher.
1592 /// Example matches X, A, B, C
1593 /// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1595 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1596 /// class A { class X {}; };
1597 /// class B { class C { class X {}; }; };
1600 /// DescendantT must be an AST base type.
1602 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1603 /// each result that matches instead of only on the first one.
1605 /// Note: Recursively combined ForEachDescendant can cause many matches:
1606 /// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1607 /// will match 10 times (plus injected class name matches) on:
1609 /// class A { class B { class C { class D { class E {}; }; }; }; };
1612 /// Usable as: Any Matcher
1613 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
1614 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
1616 /// \brief Matches if the node or any descendant matches.
1618 /// Generates results for each match.
1620 /// For example, in:
1622 /// class A { class B {}; class C {}; };
1626 /// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1628 /// will generate results for \c A, \c B and \c C.
1630 /// Usable as: Any Matcher
1631 template <typename T>
1632 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
1633 return eachOf(Matcher, forEachDescendant(Matcher));
1636 /// \brief Matches AST nodes that have a parent that matches the provided
1641 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1643 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1645 /// Usable as: Any Matcher
1646 const internal::ArgumentAdaptingMatcherFunc<
1647 internal::HasParentMatcher, internal::TypeList<Decl, Stmt>,
1648 internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasParent = {};
1650 /// \brief Matches AST nodes that have an ancestor that matches the provided
1655 /// void f() { if (true) { int x = 42; } }
1656 /// void g() { for (;;) { int x = 43; } }
1658 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1660 /// Usable as: Any Matcher
1661 const internal::ArgumentAdaptingMatcherFunc<
1662 internal::HasAncestorMatcher, internal::TypeList<Decl, Stmt>,
1663 internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
1665 /// \brief Matches if the provided matcher does not match.
1667 /// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1673 /// Usable as: Any Matcher
1674 template <typename M>
1675 internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M>
1676 unless(const M &InnerMatcher) {
1677 return internal::PolymorphicMatcherWithParam1<
1678 internal::NotMatcher, M>(InnerMatcher);
1681 /// \brief Matches a node if the declaration associated with that node
1682 /// matches the given matcher.
1684 /// The associated declaration is:
1685 /// - for type nodes, the declaration of the underlying type
1686 /// - for CallExpr, the declaration of the callee
1687 /// - for MemberExpr, the declaration of the referenced member
1688 /// - for CXXConstructExpr, the declaration of the constructor
1690 /// Also usable as Matcher<T> for any T supporting the getDecl() member
1691 /// function. e.g. various subtypes of clang::Type and various expressions.
1693 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1694 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
1695 /// Matcher<LabelStmt>, Matcher<MemberExpr>, Matcher<QualType>,
1696 /// Matcher<RecordType>, Matcher<TagType>,
1697 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
1698 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
1699 inline internal::PolymorphicMatcherWithParam1<
1700 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
1701 void(internal::HasDeclarationSupportedTypes)>
1702 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1703 return internal::PolymorphicMatcherWithParam1<
1704 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
1705 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
1708 /// \brief Matches on the implicit object argument of a member call expression.
1710 /// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1712 /// class Y { public: void x(); };
1713 /// void z() { Y y; y.x(); }",
1716 /// FIXME: Overload to allow directly matching types?
1717 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1719 const Expr *ExprNode = Node.getImplicitObjectArgument()
1720 ->IgnoreParenImpCasts();
1721 return (ExprNode != NULL &&
1722 InnerMatcher.matches(*ExprNode, Finder, Builder));
1725 /// \brief Matches if the call expression's callee expression matches.
1729 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
1730 /// void f() { f(); }
1732 /// callExpr(callee(expr()))
1733 /// matches this->x(), x(), y.x(), f()
1734 /// with callee(...)
1735 /// matching this->x, x, y.x, f respectively
1737 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1738 /// because this introduces ambiguous overloads with calls to Callee taking a
1739 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1740 /// implemented in terms of implicit casts.
1741 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1743 const Expr *ExprNode = Node.getCallee();
1744 return (ExprNode != NULL &&
1745 InnerMatcher.matches(*ExprNode, Finder, Builder));
1748 /// \brief Matches if the call expression's callee's declaration matches the
1751 /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1753 /// class Y { public: void x(); };
1754 /// void z() { Y y; y.x();
1756 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
1758 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
1761 /// \brief Matches if the expression's or declaration's type matches a type
1764 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1765 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1768 /// void y(X &x) { x; X z; }
1770 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
1771 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl),
1772 internal::Matcher<QualType>, InnerMatcher, 0) {
1773 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1776 /// \brief Overloaded to match the declaration of the expression's or value
1777 /// declaration's type.
1779 /// In case of a value declaration (for example a variable declaration),
1780 /// this resolves one layer of indirection. For example, in the value
1781 /// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1782 /// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1785 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1786 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1789 /// void y(X &x) { x; X z; }
1792 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1793 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
1794 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl),
1795 internal::Matcher<Decl>, InnerMatcher, 1) {
1796 return qualType(hasDeclaration(InnerMatcher))
1797 .matches(Node.getType(), Finder, Builder);
1800 /// \brief Matches if the type location of the declarator decl's type matches
1801 /// the inner matcher.
1807 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
1809 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
1810 if (!Node.getTypeSourceInfo())
1811 // This happens for example for implicit destructors.
1813 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
1816 /// \brief Matches if the matched type is represented by the given string.
1820 /// class Y { public: void x(); };
1821 /// void z() { Y* y; y->x(); }
1823 /// callExpr(on(hasType(asString("class Y *"))))
1825 AST_MATCHER_P(QualType, asString, std::string, Name) {
1826 return Name == Node.getAsString();
1829 /// \brief Matches if the matched type is a pointer type and the pointee type
1830 /// matches the specified matcher.
1832 /// Example matches y->x()
1833 /// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1835 /// class Y { public: void x(); };
1836 /// void z() { Y *y; y->x(); }
1839 QualType, pointsTo, internal::Matcher<QualType>,
1841 return (!Node.isNull() && Node->isPointerType() &&
1842 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1845 /// \brief Overloaded to match the pointee type's declaration.
1846 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
1848 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
1849 .matches(Node, Finder, Builder);
1852 /// \brief Matches if the matched type is a reference type and the referenced
1853 /// type matches the specified matcher.
1855 /// Example matches X &x and const X &y
1856 /// (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1864 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1866 return (!Node.isNull() && Node->isReferenceType() &&
1867 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1870 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1874 /// typedef int &int_ref;
1879 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1880 /// declaration of b but \c
1881 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1882 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1886 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1889 /// \brief Overloaded to match the referenced type's declaration.
1890 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
1892 return references(qualType(hasDeclaration(InnerMatcher)))
1893 .matches(Node, Finder, Builder);
1896 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1897 internal::Matcher<Expr>, InnerMatcher) {
1898 const Expr *ExprNode = Node.getImplicitObjectArgument();
1899 return (ExprNode != NULL &&
1900 InnerMatcher.matches(*ExprNode, Finder, Builder));
1903 /// \brief Matches if the expression's type either matches the specified
1904 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1905 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
1906 internal::Matcher<QualType>, InnerMatcher, 0) {
1907 return onImplicitObjectArgument(
1908 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
1909 .matches(Node, Finder, Builder);
1912 /// \brief Overloaded to match the type's declaration.
1913 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
1914 internal::Matcher<Decl>, InnerMatcher, 1) {
1915 return onImplicitObjectArgument(
1916 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
1917 .matches(Node, Finder, Builder);
1920 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1921 /// specified matcher.
1923 /// Example matches x in if(x)
1924 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
1929 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1931 const Decl *DeclNode = Node.getDecl();
1932 return (DeclNode != NULL &&
1933 InnerMatcher.matches(*DeclNode, Finder, Builder));
1936 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1937 /// specific using shadow declaration.
1939 /// FIXME: This currently only works for functions. Fix.
1943 /// namespace a { void f() {} }
1946 /// f(); // Matches this ..
1947 /// a::f(); // .. but not this.
1950 /// declRefExpr(throughUsingDeclaration(anything()))
1952 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1953 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
1954 const NamedDecl *FoundDecl = Node.getFoundDecl();
1955 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
1956 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
1960 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
1967 /// declStmt(hasSingleDecl(anything()))
1968 /// matches 'int c;' but not 'int a, b;'.
1969 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1970 if (Node.isSingleDecl()) {
1971 const Decl *FoundDecl = Node.getSingleDecl();
1972 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1977 /// \brief Matches a variable declaration that has an initializer expression
1978 /// that matches the given matcher.
1980 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
1982 /// bool y() { return true; }
1986 VarDecl, hasInitializer, internal::Matcher<Expr>,
1988 const Expr *Initializer = Node.getAnyInitializer();
1989 return (Initializer != NULL &&
1990 InnerMatcher.matches(*Initializer, Finder, Builder));
1993 /// \brief Checks that a call expression or a constructor call expression has
1994 /// a specific number of arguments (including absent default arguments).
1996 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
1998 /// void f(int x, int y);
2001 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2002 CallExpr, CXXConstructExpr),
2004 return Node.getNumArgs() == N;
2007 /// \brief Matches the n'th argument of a call expression or a constructor
2008 /// call expression.
2010 /// Example matches y in x(y)
2011 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2013 /// void x(int) { int y; x(y); }
2015 AST_POLYMORPHIC_MATCHER_P2(
2017 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr),
2018 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2019 return (N < Node.getNumArgs() &&
2020 InnerMatcher.matches(
2021 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2024 /// \brief Matches declaration statements that contain a specific number of
2034 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2035 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2036 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2039 /// \brief Matches the n'th declaration of a declaration statement.
2041 /// Note that this does not work for global declarations because the AST
2042 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2044 /// Example: Given non-global declarations
2050 /// declStmt(containsDeclaration(
2051 /// 0, varDecl(hasInitializer(anything()))))
2052 /// matches only 'int d = 2, e;', and
2053 /// declStmt(containsDeclaration(1, varDecl()))
2055 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2056 /// but 'int c;' is not matched.
2058 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2059 internal::Matcher<Decl>, InnerMatcher) {
2060 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2063 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2064 std::advance(Iterator, N);
2065 return InnerMatcher.matches(**Iterator, Finder, Builder);
2068 /// \brief Matches a constructor initializer.
2073 /// Foo() : foo_(1) { }
2077 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2078 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2079 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2080 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2081 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2082 Node.init_end(), Finder, Builder);
2085 /// \brief Matches the field declaration of a constructor initializer.
2090 /// Foo() : foo_(1) { }
2094 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2095 /// forField(hasName("foo_"))))))
2097 /// with forField matching foo_
2098 AST_MATCHER_P(CXXCtorInitializer, forField,
2099 internal::Matcher<FieldDecl>, InnerMatcher) {
2100 const FieldDecl *NodeAsDecl = Node.getMember();
2101 return (NodeAsDecl != NULL &&
2102 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2105 /// \brief Matches the initializer expression of a constructor initializer.
2110 /// Foo() : foo_(1) { }
2114 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2115 /// withInitializer(integerLiteral(equals(1)))))))
2117 /// with withInitializer matching (1)
2118 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2119 internal::Matcher<Expr>, InnerMatcher) {
2120 const Expr* NodeAsExpr = Node.getInit();
2121 return (NodeAsExpr != NULL &&
2122 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2125 /// \brief Matches a constructor initializer if it is explicitly written in
2126 /// code (as opposed to implicitly added by the compiler).
2132 /// Foo(int) : foo_("A") { }
2136 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2137 /// will match Foo(int), but not Foo()
2138 AST_MATCHER(CXXCtorInitializer, isWritten) {
2139 return Node.isWritten();
2142 /// \brief Matches a constructor declaration that has been implicitly added
2143 /// by the compiler (eg. implicit default/copy constructors).
2144 AST_MATCHER(CXXConstructorDecl, isImplicit) {
2145 return Node.isImplicit();
2148 /// \brief Matches any argument of a call expression or a constructor call
2153 /// void x(int, int, int) { int y; x(1, y, 42); }
2155 /// callExpr(hasAnyArgument(declRefExpr()))
2156 /// matches x(1, y, 42)
2157 /// with hasAnyArgument(...)
2160 /// FIXME: Currently this will ignore parentheses and implicit casts on
2161 /// the argument before applying the inner matcher. We'll want to remove
2162 /// this to allow for greater control by the user once \c ignoreImplicit()
2163 /// has been implemented.
2164 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2165 CallExpr, CXXConstructExpr),
2166 internal::Matcher<Expr>, InnerMatcher) {
2167 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2168 BoundNodesTreeBuilder Result(*Builder);
2169 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
2178 /// \brief Matches the n'th parameter of a function declaration.
2182 /// class X { void f(int x) {} };
2184 /// methodDecl(hasParameter(0, hasType(varDecl())))
2185 /// matches f(int x) {}
2186 /// with hasParameter(...)
2188 AST_MATCHER_P2(FunctionDecl, hasParameter,
2189 unsigned, N, internal::Matcher<ParmVarDecl>,
2191 return (N < Node.getNumParams() &&
2192 InnerMatcher.matches(
2193 *Node.getParamDecl(N), Finder, Builder));
2196 /// \brief Matches any parameter of a function declaration.
2198 /// Does not match the 'this' parameter of a method.
2202 /// class X { void f(int x, int y, int z) {} };
2204 /// methodDecl(hasAnyParameter(hasName("y")))
2205 /// matches f(int x, int y, int z) {}
2206 /// with hasAnyParameter(...)
2208 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2209 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2210 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2211 Node.param_end(), Finder, Builder);
2214 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2218 /// void f(int i) {}
2219 /// void g(int i, int j) {}
2221 /// functionDecl(parameterCountIs(2))
2222 /// matches g(int i, int j) {}
2223 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2224 return Node.getNumParams() == N;
2227 /// \brief Matches the return type of a function declaration.
2231 /// class X { int f() { return 1; } };
2233 /// methodDecl(returns(asString("int")))
2234 /// matches int f() { return 1; }
2235 AST_MATCHER_P(FunctionDecl, returns,
2236 internal::Matcher<QualType>, InnerMatcher) {
2237 return InnerMatcher.matches(Node.getResultType(), Finder, Builder);
2240 /// \brief Matches extern "C" function declarations.
2244 /// extern "C" void f() {}
2245 /// extern "C" { void g() {} }
2248 /// functionDecl(isExternC())
2249 /// matches the declaration of f and g, but not the declaration h
2250 AST_MATCHER(FunctionDecl, isExternC) {
2251 return Node.isExternC();
2254 /// \brief Matches the condition expression of an if statement, for loop,
2255 /// or conditional operator.
2257 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2261 AST_POLYMORPHIC_MATCHER_P(
2262 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5(
2263 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator),
2264 internal::Matcher<Expr>, InnerMatcher) {
2265 const Expr *const Condition = Node.getCond();
2266 return (Condition != NULL &&
2267 InnerMatcher.matches(*Condition, Finder, Builder));
2270 namespace internal {
2271 struct NotEqualsBoundNodePredicate {
2272 bool operator()(const internal::BoundNodesMap &Nodes) const {
2273 return Nodes.getNode(ID) != Node;
2276 ast_type_traits::DynTypedNode Node;
2278 } // namespace internal
2280 /// \brief Matches if a node equals a previously bound node.
2282 /// Matches a node if it equals the node previously bound to \p ID.
2286 /// class X { int a; int b; };
2289 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2290 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
2291 /// matches the class \c X, as \c a and \c b have the same type.
2293 /// Note that when multiple matches are involved via \c forEach* matchers,
2294 /// \c equalsBoundNodes acts as a filter.
2297 /// forEachDescendant(varDecl().bind("d")),
2298 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
2299 /// will trigger a match for each combination of variable declaration
2300 /// and reference to that variable declaration within a compound statement.
2301 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4(
2302 Stmt, Decl, Type, QualType),
2304 // FIXME: Figure out whether it makes sense to allow this
2305 // on any other node types.
2306 // For *Loc it probably does not make sense, as those seem
2307 // unique. For NestedNameSepcifier it might make sense, as
2308 // those also have pointer identity, but I'm not sure whether
2309 // they're ever reused.
2310 internal::NotEqualsBoundNodePredicate Predicate;
2312 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
2313 return Builder->removeBindings(Predicate);
2316 /// \brief Matches the condition variable statement in an if statement.
2320 /// if (A* a = GetAPointer()) {}
2322 /// hasConditionVariableStatement(...)
2323 /// matches 'A* a = GetAPointer()'.
2324 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2325 internal::Matcher<DeclStmt>, InnerMatcher) {
2326 const DeclStmt* const DeclarationStatement =
2327 Node.getConditionVariableDeclStmt();
2328 return DeclarationStatement != NULL &&
2329 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2332 /// \brief Matches the index expression of an array subscript expression.
2337 /// void f() { i[1] = 42; }
2339 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2340 /// matches \c i[1] with the \c integerLiteral() matching \c 1
2341 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2342 internal::Matcher<Expr>, InnerMatcher) {
2343 if (const Expr* Expression = Node.getIdx())
2344 return InnerMatcher.matches(*Expression, Finder, Builder);
2348 /// \brief Matches the base expression of an array subscript expression.
2353 /// void f() { i[1] = 42; }
2355 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2356 /// hasSourceExpression(declRefExpr()))))
2357 /// matches \c i[1] with the \c declRefExpr() matching \c i
2358 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2359 internal::Matcher<Expr>, InnerMatcher) {
2360 if (const Expr* Expression = Node.getBase())
2361 return InnerMatcher.matches(*Expression, Finder, Builder);
2365 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2372 /// hasBody(compoundStmt())
2373 /// matches 'for (;;) {}'
2374 /// with compoundStmt()
2376 AST_POLYMORPHIC_MATCHER_P(
2377 hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES_3(DoStmt, ForStmt, WhileStmt),
2378 internal::Matcher<Stmt>, InnerMatcher) {
2379 const Stmt *const Statement = Node.getBody();
2380 return (Statement != NULL &&
2381 InnerMatcher.matches(*Statement, Finder, Builder));
2384 /// \brief Matches compound statements where at least one substatement matches
2385 /// a given matcher.
2391 /// hasAnySubstatement(compoundStmt())
2392 /// matches '{ {}; 1+2; }'
2393 /// with compoundStmt()
2395 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2396 internal::Matcher<Stmt>, InnerMatcher) {
2397 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
2398 Node.body_end(), Finder, Builder);
2401 /// \brief Checks that a compound statement contains a specific number of
2402 /// child statements.
2408 /// compoundStmt(statementCountIs(0)))
2410 /// but does not match the outer compound statement.
2411 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2412 return Node.size() == N;
2415 /// \brief Matches literals that are equal to the given value.
2417 /// Example matches true (matcher = boolLiteral(equals(true)))
2422 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2423 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2424 template <typename ValueT>
2425 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2426 equals(const ValueT &Value) {
2427 return internal::PolymorphicMatcherWithParam1<
2428 internal::ValueEqualsMatcher,
2432 /// \brief Matches the operator Name of operator expressions (binary or
2435 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2439 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2440 BinaryOperator, UnaryOperator),
2441 std::string, Name) {
2442 return Name == Node.getOpcodeStr(Node.getOpcode());
2445 /// \brief Matches the left hand side of binary operator expressions.
2447 /// Example matches a (matcher = binaryOperator(hasLHS()))
2451 AST_MATCHER_P(BinaryOperator, hasLHS,
2452 internal::Matcher<Expr>, InnerMatcher) {
2453 Expr *LeftHandSide = Node.getLHS();
2454 return (LeftHandSide != NULL &&
2455 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2458 /// \brief Matches the right hand side of binary operator expressions.
2460 /// Example matches b (matcher = binaryOperator(hasRHS()))
2464 AST_MATCHER_P(BinaryOperator, hasRHS,
2465 internal::Matcher<Expr>, InnerMatcher) {
2466 Expr *RightHandSide = Node.getRHS();
2467 return (RightHandSide != NULL &&
2468 InnerMatcher.matches(*RightHandSide, Finder, Builder));
2471 /// \brief Matches if either the left hand side or the right hand side of a
2472 /// binary operator matches.
2473 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2474 const internal::Matcher<Expr> &InnerMatcher) {
2475 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2478 /// \brief Matches if the operand of a unary operator matches.
2480 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2484 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2485 internal::Matcher<Expr>, InnerMatcher) {
2486 const Expr * const Operand = Node.getSubExpr();
2487 return (Operand != NULL &&
2488 InnerMatcher.matches(*Operand, Finder, Builder));
2491 /// \brief Matches if the cast's source expression matches the given matcher.
2493 /// Example: matches "a string" (matcher =
2494 /// hasSourceExpression(constructExpr()))
2496 /// class URL { URL(string); };
2497 /// URL url = "a string";
2498 AST_MATCHER_P(CastExpr, hasSourceExpression,
2499 internal::Matcher<Expr>, InnerMatcher) {
2500 const Expr* const SubExpression = Node.getSubExpr();
2501 return (SubExpression != NULL &&
2502 InnerMatcher.matches(*SubExpression, Finder, Builder));
2505 /// \brief Matches casts whose destination type matches a given matcher.
2507 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2508 /// actual casts "explicit" casts.)
2509 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2510 internal::Matcher<QualType>, InnerMatcher) {
2511 const QualType NodeType = Node.getTypeAsWritten();
2512 return InnerMatcher.matches(NodeType, Finder, Builder);
2515 /// \brief Matches implicit casts whose destination type matches a given
2518 /// FIXME: Unit test this matcher
2519 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2520 internal::Matcher<QualType>, InnerMatcher) {
2521 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2524 /// \brief Matches the true branch expression of a conditional operator.
2526 /// Example matches a
2528 /// condition ? a : b
2530 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2531 internal::Matcher<Expr>, InnerMatcher) {
2532 Expr *Expression = Node.getTrueExpr();
2533 return (Expression != NULL &&
2534 InnerMatcher.matches(*Expression, Finder, Builder));
2537 /// \brief Matches the false branch expression of a conditional operator.
2539 /// Example matches b
2541 /// condition ? a : b
2543 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2544 internal::Matcher<Expr>, InnerMatcher) {
2545 Expr *Expression = Node.getFalseExpr();
2546 return (Expression != NULL &&
2547 InnerMatcher.matches(*Expression, Finder, Builder));
2550 /// \brief Matches if a declaration has a body attached.
2552 /// Example matches A, va, fa
2555 /// class B; // Doesn't match, as it has no body.
2557 /// extern int vb; // Doesn't match, as it doesn't define the variable.
2559 /// void fb(); // Doesn't match, as it has no body.
2562 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2563 AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3(
2564 TagDecl, VarDecl, FunctionDecl)) {
2565 return Node.isThisDeclarationADefinition();
2568 /// \brief Matches the class declaration that the given method declaration
2571 /// FIXME: Generalize this for other kinds of declarations.
2572 /// FIXME: What other kind of declarations would we need to generalize
2575 /// Example matches A() in the last line
2576 /// (matcher = constructExpr(hasDeclaration(methodDecl(
2577 /// ofClass(hasName("A"))))))
2585 AST_MATCHER_P(CXXMethodDecl, ofClass,
2586 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2587 const CXXRecordDecl *Parent = Node.getParent();
2588 return (Parent != NULL &&
2589 InnerMatcher.matches(*Parent, Finder, Builder));
2592 /// \brief Matches if the given method declaration is virtual.
2598 /// virtual void x();
2602 AST_MATCHER(CXXMethodDecl, isVirtual) {
2603 return Node.isVirtual();
2606 /// \brief Matches if the given method declaration is const.
2611 /// void foo() const;
2616 /// methodDecl(isConst()) matches A::foo() but not A::bar()
2617 AST_MATCHER(CXXMethodDecl, isConst) {
2618 return Node.isConst();
2621 /// \brief Matches if the given method declaration overrides another method.
2627 /// virtual void x();
2629 /// class B : public A {
2631 /// virtual void x();
2635 AST_MATCHER(CXXMethodDecl, isOverride) {
2636 return Node.size_overridden_methods() > 0;
2639 /// \brief Matches member expressions that are called with '->' as opposed
2642 /// Member calls on the implicit this pointer match as called with '->'.
2647 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2652 /// memberExpr(isArrow())
2653 /// matches this->x, x, y.x, a, this->b
2654 AST_MATCHER(MemberExpr, isArrow) {
2655 return Node.isArrow();
2658 /// \brief Matches QualType nodes that are of integer type.
2666 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2667 /// matches "a(int)", "b(long)", but not "c(double)".
2668 AST_MATCHER(QualType, isInteger) {
2669 return Node->isIntegerType();
2672 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2673 /// include "top-level" const.
2678 /// void b(int const);
2679 /// void c(const int);
2680 /// void d(const int*);
2681 /// void e(int const) {};
2683 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2684 /// matches "void b(int const)", "void c(const int)" and
2685 /// "void e(int const) {}". It does not match d as there
2686 /// is no top-level const on the parameter type "const int *".
2687 AST_MATCHER(QualType, isConstQualified) {
2688 return Node.isConstQualified();
2691 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2692 /// the node, not hidden within a typedef.
2696 /// typedef const int const_int;
2699 /// int *volatile k;
2702 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2703 /// \c i is const-qualified but the qualifier is not local.
2704 AST_MATCHER(QualType, hasLocalQualifiers) {
2705 return Node.hasLocalQualifiers();
2708 /// \brief Matches a member expression where the member is matched by a
2713 /// struct { int first, second; } first, second;
2714 /// int i(second.first);
2715 /// int j(first.second);
2717 /// memberExpr(member(hasName("first")))
2718 /// matches second.first
2719 /// but not first.second (because the member name there is "second").
2720 AST_MATCHER_P(MemberExpr, member,
2721 internal::Matcher<ValueDecl>, InnerMatcher) {
2722 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2725 /// \brief Matches a member expression where the object expression is
2726 /// matched by a given matcher.
2730 /// struct X { int m; };
2731 /// void f(X x) { x.m; m; }
2733 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2734 /// matches "x.m" and "m"
2735 /// with hasObjectExpression(...)
2736 /// matching "x" and the implicit object expression of "m" which has type X*.
2737 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2738 internal::Matcher<Expr>, InnerMatcher) {
2739 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2742 /// \brief Matches any using shadow declaration.
2746 /// namespace X { void b(); }
2749 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2750 /// matches \code using X::b \endcode
2751 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2752 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2753 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
2754 Node.shadow_end(), Finder, Builder);
2757 /// \brief Matches a using shadow declaration where the target declaration is
2758 /// matched by the given matcher.
2762 /// namespace X { int a; void b(); }
2766 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2767 /// matches \code using X::b \endcode
2768 /// but not \code using X::a \endcode
2769 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2770 internal::Matcher<NamedDecl>, InnerMatcher) {
2771 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2774 /// \brief Matches template instantiations of function, class, or static
2775 /// member variable template instantiations.
2779 /// template <typename T> class X {}; class A {}; X<A> x;
2783 /// template <typename T> class X {}; class A {}; template class X<A>;
2785 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2786 /// matches the template instantiation of X<A>.
2790 /// template <typename T> class X {}; class A {};
2791 /// template <> class X<A> {}; X<A> x;
2793 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2794 /// does not match, as X<A> is an explicit template specialization.
2796 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2797 AST_POLYMORPHIC_MATCHER(
2798 isTemplateInstantiation,
2799 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2800 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2801 Node.getTemplateSpecializationKind() ==
2802 TSK_ExplicitInstantiationDefinition);
2805 /// \brief Matches explicit template specializations of function, class, or
2806 /// static member variable template instantiations.
2810 /// template<typename T> void A(T t) { }
2811 /// template<> void A(int N) { }
2813 /// functionDecl(isExplicitTemplateSpecialization())
2814 /// matches the specialization A<int>().
2816 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2817 AST_POLYMORPHIC_MATCHER(
2818 isExplicitTemplateSpecialization,
2819 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2820 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2823 /// \brief Matches \c TypeLocs for which the given inner
2824 /// QualType-matcher matches.
2825 inline internal::BindableMatcher<TypeLoc> loc(
2826 const internal::Matcher<QualType> &InnerMatcher) {
2827 return internal::BindableMatcher<TypeLoc>(
2828 new internal::TypeLocTypeMatcher(InnerMatcher));
2831 /// \brief Matches builtin Types.
2842 /// matches "int b", "float c" and "bool d"
2843 AST_TYPE_MATCHER(BuiltinType, builtinType);
2845 /// \brief Matches all kinds of arrays.
2849 /// int a[] = { 2, 3 };
2851 /// void f() { int c[a[0]]; }
2854 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
2855 AST_TYPE_MATCHER(ArrayType, arrayType);
2857 /// \brief Matches C99 complex types.
2861 /// _Complex float f;
2864 /// matches "_Complex float f"
2865 AST_TYPE_MATCHER(ComplexType, complexType);
2867 /// \brief Matches arrays and C99 complex types that have a specific element
2876 /// arrayType(hasElementType(builtinType()))
2877 /// matches "int b[7]"
2879 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
2880 AST_TYPELOC_TRAVERSE_MATCHER(
2881 hasElementType, getElement,
2882 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType));
2884 /// \brief Matches C arrays with a specified constant size.
2890 /// int b[] = { 2, 3 };
2894 /// constantArrayType()
2895 /// matches "int a[2]"
2896 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
2898 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
2904 /// int c[41], d[43];
2906 /// constantArrayType(hasSize(42))
2907 /// matches "int a[42]" and "int b[2 * 21]"
2908 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
2909 return Node.getSize() == N;
2912 /// \brief Matches C++ arrays whose size is a value-dependent expression.
2916 /// template<typename T, int Size>
2921 /// dependentSizedArrayType
2922 /// matches "T data[Size]"
2923 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
2925 /// \brief Matches C arrays with unspecified size.
2929 /// int a[] = { 2, 3 };
2931 /// void f(int c[]) { int d[a[0]]; };
2933 /// incompleteArrayType()
2934 /// matches "int a[]" and "int c[]"
2935 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
2937 /// \brief Matches C arrays with a specified size that is not an
2938 /// integer-constant-expression.
2943 /// int a[] = { 2, 3 }
2947 /// variableArrayType()
2948 /// matches "int c[a[0]]"
2949 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
2951 /// \brief Matches \c VariableArrayType nodes that have a specific size
2960 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
2961 /// varDecl(hasName("b")))))))
2962 /// matches "int a[b]"
2963 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
2964 internal::Matcher<Expr>, InnerMatcher) {
2965 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
2968 /// \brief Matches atomic types.
2975 /// matches "_Atomic(int) i"
2976 AST_TYPE_MATCHER(AtomicType, atomicType);
2978 /// \brief Matches atomic types with a specific value type.
2983 /// _Atomic(float) f;
2985 /// atomicType(hasValueType(isInteger()))
2986 /// matches "_Atomic(int) i"
2988 /// Usable as: Matcher<AtomicType>
2989 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
2990 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType));
2992 /// \brief Matches types nodes representing C++11 auto types.
2997 /// int v[] = { 2, 3 }
2998 /// for (auto i : v) { }
3001 /// matches "auto n" and "auto i"
3002 AST_TYPE_MATCHER(AutoType, autoType);
3004 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3006 /// Note: There is no \c TypeLoc for the deduced type and thus no
3007 /// \c getDeducedLoc() matcher.
3014 /// autoType(hasDeducedType(isInteger()))
3015 /// matches "auto a"
3017 /// Usable as: Matcher<AutoType>
3018 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3019 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType));
3021 /// \brief Matches \c FunctionType nodes.
3029 /// matches "int (*f)(int)" and the type of "g".
3030 AST_TYPE_MATCHER(FunctionType, functionType);
3032 /// \brief Matches \c ParenType nodes.
3036 /// int (*ptr_to_array)[4];
3037 /// int *array_of_ptrs[4];
3040 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3041 /// \c array_of_ptrs.
3042 AST_TYPE_MATCHER(ParenType, parenType);
3044 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
3048 /// int (*ptr_to_array)[4];
3049 /// int (*ptr_to_func)(int);
3052 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
3053 /// \c ptr_to_func but not \c ptr_to_array.
3055 /// Usable as: Matcher<ParenType>
3056 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
3057 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType));
3059 /// \brief Matches block pointer types, i.e. types syntactically represented as
3060 /// "void (^)(int)".
3062 /// The \c pointee is always required to be a \c FunctionType.
3063 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
3065 /// \brief Matches member pointer types.
3068 /// struct A { int i; }
3069 /// A::* ptr = A::i;
3071 /// memberPointerType()
3072 /// matches "A::* ptr"
3073 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3075 /// \brief Matches pointer types.
3084 /// matches "int *a"
3085 AST_TYPE_MATCHER(PointerType, pointerType);
3087 /// \brief Matches both lvalue and rvalue reference types.
3100 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3101 AST_TYPE_MATCHER(ReferenceType, referenceType);
3103 /// \brief Matches lvalue reference types.
3116 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3117 /// matched since the type is deduced as int& by reference collapsing rules.
3118 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3120 /// \brief Matches rvalue reference types.
3133 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3134 /// matched as it is deduced to int& by reference collapsing rules.
3135 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3137 /// \brief Narrows PointerType (and similar) matchers to those where the
3138 /// \c pointee matches a given matcher.
3146 /// pointerType(pointee(isConstQualified(), isInteger()))
3147 /// matches "int const *b"
3149 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3150 /// Matcher<PointerType>, Matcher<ReferenceType>
3151 AST_TYPELOC_TRAVERSE_MATCHER(
3152 pointee, getPointee,
3153 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType,
3154 PointerType, ReferenceType));
3156 /// \brief Matches typedef types.
3163 /// matches "typedef int X"
3164 AST_TYPE_MATCHER(TypedefType, typedefType);
3166 /// \brief Matches template specialization types.
3170 /// template <typename T>
3173 /// template class C<int>; // A
3174 /// C<char> var; // B
3177 /// \c templateSpecializationType() matches the type of the explicit
3178 /// instantiation in \c A and the type of the variable declaration in \c B.
3179 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3181 /// \brief Matches types nodes representing unary type transformations.
3185 /// typedef __underlying_type(T) type;
3187 /// unaryTransformType()
3188 /// matches "__underlying_type(T)"
3189 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
3191 /// \brief Matches record types (e.g. structs, classes).
3202 /// \c recordType() matches the type of the variable declarations of both \c c
3204 AST_TYPE_MATCHER(RecordType, recordType);
3206 /// \brief Matches types specified with an elaborated type keyword or with a
3222 /// \c elaboratedType() matches the type of the variable declarations of both
3224 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3226 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3227 /// matches \c InnerMatcher if the qualifier exists.
3239 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3240 /// matches the type of the variable declaration of \c d.
3241 AST_MATCHER_P(ElaboratedType, hasQualifier,
3242 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3243 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3244 return InnerMatcher.matches(*Qualifier, Finder, Builder);
3249 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3261 /// \c elaboratedType(namesType(recordType(
3262 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3263 /// declaration of \c d.
3264 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3266 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3269 /// \brief Matches declarations whose declaration context, interpreted as a
3270 /// Decl, matches \c InnerMatcher.
3281 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3282 /// declaration of \c class \c D.
3283 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3284 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3288 /// \brief Matches nested name specifiers.
3293 /// struct A { static void f(); };
3295 /// void g() { A::f(); }
3299 /// nestedNameSpecifier()
3300 /// matches "ns::" and both "A::"
3301 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3303 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3304 const internal::VariadicAllOfMatcher<
3305 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3307 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3308 /// NestedNameSpecifier-matcher matches.
3309 inline internal::BindableMatcher<NestedNameSpecifierLoc> loc(
3310 const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
3311 return internal::BindableMatcher<NestedNameSpecifierLoc>(
3312 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3316 /// \brief Matches nested name specifiers that specify a type matching the
3317 /// given \c QualType matcher without qualifiers.
3321 /// struct A { struct B { struct C {}; }; };
3324 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3326 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3327 internal::Matcher<QualType>, InnerMatcher) {
3328 if (Node.getAsType() == NULL)
3330 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3333 /// \brief Matches nested name specifier locs that specify a type matching the
3334 /// given \c TypeLoc.
3338 /// struct A { struct B { struct C {}; }; };
3341 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3342 /// hasDeclaration(recordDecl(hasName("A")))))))
3344 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3345 internal::Matcher<TypeLoc>, InnerMatcher) {
3346 return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3349 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3353 /// struct A { struct B { struct C {}; }; };
3356 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3358 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3359 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3361 NestedNameSpecifier *NextNode = Node.getPrefix();
3362 if (NextNode == NULL)
3364 return InnerMatcher.matches(*NextNode, Finder, Builder);
3367 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3371 /// struct A { struct B { struct C {}; }; };
3374 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3376 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3377 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3379 NestedNameSpecifierLoc NextNode = Node.getPrefix();
3382 return InnerMatcher.matches(NextNode, Finder, Builder);
3385 /// \brief Matches nested name specifiers that specify a namespace matching the
3386 /// given namespace matcher.
3390 /// namespace ns { struct A {}; }
3393 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3395 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3396 internal::Matcher<NamespaceDecl>, InnerMatcher) {
3397 if (Node.getAsNamespace() == NULL)
3399 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3402 /// \brief Overloads for the \c equalsNode matcher.
3403 /// FIXME: Implement for other node types.
3406 /// \brief Matches if a node equals another node.
3408 /// \c Decl has pointer identity in the AST.
3409 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) {
3410 return &Node == Other;
3412 /// \brief Matches if a node equals another node.
3414 /// \c Stmt has pointer identity in the AST.
3416 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) {
3417 return &Node == Other;
3422 /// \brief Matches each case or default statement belonging to the given switch
3423 /// statement. This matcher may produce multiple matches.
3427 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
3429 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
3430 /// matches four times, with "c" binding each of "case 1:", "case 2:",
3431 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
3432 /// "switch (1)", "switch (2)" and "switch (2)".
3433 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
3435 BoundNodesTreeBuilder Result;
3436 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
3437 // iteration order. We should use the more general iterating matchers once
3438 // they are capable of expressing this matcher (for example, it should ignore
3439 // case statements belonging to nested switch statements).
3440 bool Matched = false;
3441 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
3442 SC = SC->getNextSwitchCase()) {
3443 BoundNodesTreeBuilder CaseBuilder(*Builder);
3444 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
3447 Result.addMatch(CaseBuilder);
3454 /// \brief Matches each constructor initializer in a constructor definition.
3458 /// class A { A() : i(42), j(42) {} int i; int j; };
3460 /// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x"))))
3461 /// will trigger two matches, binding for 'i' and 'j' respectively.
3462 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
3463 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3464 BoundNodesTreeBuilder Result;
3465 bool Matched = false;
3466 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(),
3467 E = Node.init_end();
3469 BoundNodesTreeBuilder InitBuilder(*Builder);
3470 if (InnerMatcher.matches(**I, Finder, &InitBuilder)) {
3472 Result.addMatch(InitBuilder);
3479 /// \brief If the given case statement does not use the GNU case range
3480 /// extension, matches the constant given in the statement.
3484 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
3486 /// caseStmt(hasCaseConstant(integerLiteral()))
3487 /// matches "case 1:"
3488 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
3493 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
3496 } // end namespace ast_matchers
3497 } // end namespace clang
3499 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H