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/DeclTemplate.h"
49 #include "clang/ASTMatchers/ASTMatchersInternal.h"
50 #include "clang/ASTMatchers/ASTMatchersMacros.h"
51 #include "llvm/ADT/Twine.h"
52 #include "llvm/Support/Regex.h"
56 namespace ast_matchers {
58 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
60 /// The bound nodes are generated by calling \c bind("id") on the node matchers
61 /// of the nodes we want to access later.
63 /// The instances of BoundNodes are created by \c MatchFinder when the user's
64 /// callbacks are executed every time a match is found.
67 /// \brief Returns the AST node bound to \c ID.
69 /// Returns NULL if there was no node bound to \c ID or if there is a node but
70 /// it cannot be converted to the specified type.
72 const T *getNodeAs(StringRef ID) const {
73 return MyBoundNodes.getNodeAs<T>(ID);
76 /// \brief Deprecated. Please use \c getNodeAs instead.
79 const T *getDeclAs(StringRef ID) const {
80 return getNodeAs<T>(ID);
83 const T *getStmtAs(StringRef ID) const {
84 return getNodeAs<T>(ID);
89 /// \brief Create BoundNodes from a pre-filled map of bindings.
90 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
91 : MyBoundNodes(MyBoundNodes) {}
93 internal::BoundNodesMap MyBoundNodes;
95 friend class internal::BoundNodesTree;
98 /// \brief If the provided matcher matches a node, binds the node to \c ID.
100 /// FIXME: Do we want to support this now that we have bind()?
101 template <typename T>
102 internal::Matcher<T> id(const std::string &ID,
103 const internal::BindableMatcher<T> &InnerMatcher) {
104 return InnerMatcher.bind(ID);
107 /// \brief Types of matchers for the top-level classes in the AST class
110 typedef internal::Matcher<Decl> DeclarationMatcher;
111 typedef internal::Matcher<Stmt> StatementMatcher;
112 typedef internal::Matcher<QualType> TypeMatcher;
113 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
114 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
115 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
118 /// \brief Matches any node.
120 /// Useful when another matcher requires a child matcher, but there's no
121 /// additional constraint. This will often be used with an explicit conversion
122 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
124 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
126 /// "int* p" and "void f()" in
131 /// Usable as: Any Matcher
132 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>
134 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
137 /// \brief Matches declarations.
139 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
146 const internal::VariadicAllOfMatcher<Decl> decl;
148 /// \brief Matches a declaration of anything that could have a name.
150 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
159 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
161 /// \brief Matches a declaration of a namespace.
166 /// namespace test {}
169 /// matches "namespace {}" and "namespace test {}"
170 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
172 /// \brief Matches C++ class declarations.
174 /// Example matches \c X, \c Z
177 /// template<class T> class Z {};
179 const internal::VariadicDynCastAllOfMatcher<
181 CXXRecordDecl> recordDecl;
183 /// \brief Matches C++ class template declarations.
185 /// Example matches \c Z
187 /// template<class T> class Z {};
189 const internal::VariadicDynCastAllOfMatcher<
191 ClassTemplateDecl> classTemplateDecl;
193 /// \brief Matches C++ class template specializations.
197 /// template<typename T> class A {};
198 /// template<> class A<double> {};
201 /// classTemplateSpecializationDecl()
202 /// matches the specializations \c A<int> and \c A<double>
203 const internal::VariadicDynCastAllOfMatcher<
205 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
207 /// \brief Matches C++ access specifier declarations.
217 /// matches 'public:'
218 const internal::VariadicDynCastAllOfMatcher<
220 AccessSpecDecl> accessSpecDecl;
222 /// \brief Matches public C++ declarations.
228 /// protected: int b;
232 /// fieldDecl(isPublic())
234 AST_MATCHER(Decl, isPublic) {
235 return Node.getAccess() == AS_public;
238 /// \brief Matches protected C++ declarations.
244 /// protected: int b;
248 /// fieldDecl(isProtected())
250 AST_MATCHER(Decl, isProtected) {
251 return Node.getAccess() == AS_protected;
254 /// \brief Matches private C++ declarations.
260 /// protected: int b;
264 /// fieldDecl(isPrivate())
266 AST_MATCHER(Decl, isPrivate) {
267 return Node.getAccess() == AS_private;
270 /// \brief Matches classTemplateSpecializations that have at least one
271 /// TemplateArgument matching the given InnerMatcher.
275 /// template<typename T> class A {};
276 /// template<> class A<double> {};
279 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
280 /// refersToType(asString("int"))))
281 /// matches the specialization \c A<int>
282 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
283 internal::Matcher<TemplateArgument>, InnerMatcher) {
284 const TemplateArgumentList &List = Node.getTemplateArgs();
285 for (unsigned i = 0; i < List.size(); ++i) {
286 if (InnerMatcher.matches(List.get(i), Finder, Builder))
292 /// \brief Matches expressions that match InnerMatcher after any implicit casts
293 /// are stripped off.
295 /// Parentheses and explicit casts are not discarded.
303 /// long e = (long) 0l;
307 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
308 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
310 /// would match the declarations for a, b, c, and d, but not e.
313 /// varDecl(hasInitializer(integerLiteral()))
314 /// varDecl(hasInitializer(declRefExpr()))
316 /// only match the declarations for b, c, and d.
317 AST_MATCHER_P(Expr, ignoringImpCasts,
318 internal::Matcher<Expr>, InnerMatcher) {
319 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
322 /// \brief Matches expressions that match InnerMatcher after parentheses and
323 /// casts are stripped off.
325 /// Implicit and non-C Style casts are also discarded.
330 /// void* c = reinterpret_cast<char*>(0);
331 /// char d = char(0);
334 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
335 /// would match the declarations for a, b, c, and d.
337 /// varDecl(hasInitializer(integerLiteral()))
338 /// only match the declaration for a.
339 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
340 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
343 /// \brief Matches expressions that match InnerMatcher after implicit casts and
344 /// parentheses are stripped off.
346 /// Explicit casts are not discarded.
354 /// long e = ((long) 0l);
357 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
358 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
359 /// would match the declarations for a, b, c, and d, but not e.
361 /// varDecl(hasInitializer(integerLiteral()))
362 /// varDecl(hasInitializer(declRefExpr()))
363 /// would only match the declaration for a.
364 AST_MATCHER_P(Expr, ignoringParenImpCasts,
365 internal::Matcher<Expr>, InnerMatcher) {
366 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
369 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
370 /// matches the given InnerMatcher.
374 /// template<typename T, typename U> class A {};
378 /// classTemplateSpecializationDecl(hasTemplateArgument(
379 /// 1, refersToType(asString("int"))))
380 /// matches the specialization \c A<bool, int>
381 AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
382 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
383 const TemplateArgumentList &List = Node.getTemplateArgs();
384 if (List.size() <= N)
386 return InnerMatcher.matches(List.get(N), Finder, Builder);
389 /// \brief Matches a TemplateArgument that refers to a certain type.
394 /// template<typename T> struct A {};
397 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
398 /// refersToType(class(hasName("X")))))
399 /// matches the specialization \c A<X>
400 AST_MATCHER_P(TemplateArgument, refersToType,
401 internal::Matcher<QualType>, InnerMatcher) {
402 if (Node.getKind() != TemplateArgument::Type)
404 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
407 /// \brief Matches a TemplateArgument that refers to a certain declaration.
411 /// template<typename T> struct A {};
412 /// struct B { B* next; };
415 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
416 /// refersToDeclaration(fieldDecl(hasName("next"))))
417 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
419 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
420 internal::Matcher<Decl>, InnerMatcher) {
421 if (Node.getKind() == TemplateArgument::Declaration)
422 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
426 /// \brief Matches C++ constructor declarations.
428 /// Example matches Foo::Foo() and Foo::Foo(int)
434 /// int DoSomething();
437 const internal::VariadicDynCastAllOfMatcher<
439 CXXConstructorDecl> constructorDecl;
441 /// \brief Matches explicit C++ destructor declarations.
443 /// Example matches Foo::~Foo()
450 const internal::VariadicDynCastAllOfMatcher<
452 CXXDestructorDecl> destructorDecl;
454 /// \brief Matches enum declarations.
456 /// Example matches X
462 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
464 /// \brief Matches enum constants.
466 /// Example matches A, B, C
472 const internal::VariadicDynCastAllOfMatcher<
474 EnumConstantDecl> enumConstantDecl;
476 /// \brief Matches method declarations.
478 /// Example matches y
480 /// class X { void y() };
482 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
484 /// \brief Matches variable declarations.
486 /// Note: this does not match declarations of member variables, which are
487 /// "field" declarations in Clang parlance.
489 /// Example matches a
493 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
495 /// \brief Matches field declarations.
499 /// class X { int m; };
503 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
505 /// \brief Matches function declarations.
507 /// Example matches f
511 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
513 /// \brief Matches C++ function template declarations.
515 /// Example matches f
517 /// template<class T> void f(T t) {}
519 const internal::VariadicDynCastAllOfMatcher<
521 FunctionTemplateDecl> functionTemplateDecl;
523 /// \brief Matches statements.
530 /// matches both the compound statement '{ ++a; }' and '++a'.
531 const internal::VariadicAllOfMatcher<Stmt> stmt;
533 /// \brief Matches declaration statements.
541 const internal::VariadicDynCastAllOfMatcher<
545 /// \brief Matches member expressions.
550 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
551 /// int a; static int b;
555 /// matches this->x, x, y.x, a, this->b
556 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
558 /// \brief Matches call expressions.
560 /// Example matches x.y() and y()
566 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
568 /// \brief Matches lambda expressions.
570 /// Example matches [&](){return 5;}
574 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
576 /// \brief Matches member call expressions.
578 /// Example matches x.y()
583 const internal::VariadicDynCastAllOfMatcher<
585 CXXMemberCallExpr> memberCallExpr;
587 /// \brief Matches init list expressions.
591 /// int a[] = { 1, 2 };
592 /// struct B { int x, y; };
596 /// matches "{ 1, 2 }" and "{ 5, 6 }"
597 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
599 /// \brief Matches using declarations.
603 /// namespace X { int x; }
607 /// matches \code using X::x \endcode
608 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
610 /// \brief Matches constructor call expressions (including implicit ones).
612 /// Example matches string(ptr, n) and ptr within arguments of f
613 /// (matcher = constructExpr())
615 /// void f(const string &a, const string &b);
618 /// f(string(ptr, n), ptr);
620 const internal::VariadicDynCastAllOfMatcher<
622 CXXConstructExpr> constructExpr;
624 /// \brief Matches implicit and explicit this expressions.
626 /// Example matches the implicit this expression in "return i".
627 /// (matcher = thisExpr())
631 /// int f() { return i; }
634 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr;
636 /// \brief Matches nodes where temporaries are created.
638 /// Example matches FunctionTakesString(GetStringByValue())
639 /// (matcher = bindTemporaryExpr())
641 /// FunctionTakesString(GetStringByValue());
642 /// FunctionTakesStringByPointer(GetStringPointer());
644 const internal::VariadicDynCastAllOfMatcher<
646 CXXBindTemporaryExpr> bindTemporaryExpr;
648 /// \brief Matches nodes where temporaries are materialized.
652 /// struct T {void func()};
656 /// materializeTemporaryExpr() matches 'f()' in these statements
661 /// but does not match
666 const internal::VariadicDynCastAllOfMatcher<
668 MaterializeTemporaryExpr> materializeTemporaryExpr;
670 /// \brief Matches new expressions.
678 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr;
680 /// \brief Matches delete expressions.
687 /// matches 'delete X'.
688 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr;
690 /// \brief Matches array subscript expressions.
696 /// arraySubscriptExpr()
698 const internal::VariadicDynCastAllOfMatcher<
700 ArraySubscriptExpr> arraySubscriptExpr;
702 /// \brief Matches the value of a default argument at the call site.
704 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
705 /// default value of the second parameter in the call expression f(42)
706 /// (matcher = defaultArgExpr())
708 /// void f(int x, int y = 0);
711 const internal::VariadicDynCastAllOfMatcher<
713 CXXDefaultArgExpr> defaultArgExpr;
715 /// \brief Matches overloaded operator calls.
717 /// Note that if an operator isn't overloaded, it won't match. Instead, use
718 /// binaryOperator matcher.
719 /// Currently it does not match operators such as new delete.
720 /// FIXME: figure out why these do not match?
722 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
723 /// (matcher = operatorCallExpr())
725 /// ostream &operator<< (ostream &out, int i) { };
726 /// ostream &o; int b = 1, c = 1;
729 const internal::VariadicDynCastAllOfMatcher<
731 CXXOperatorCallExpr> operatorCallExpr;
733 /// \brief Matches expressions.
735 /// Example matches x()
737 /// void f() { x(); }
739 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
741 /// \brief Matches expressions that refer to declarations.
743 /// Example matches x in if (x)
748 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
750 /// \brief Matches if statements.
752 /// Example matches 'if (x) {}'
756 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
758 /// \brief Matches for statements.
760 /// Example matches 'for (;;) {}'
763 /// int i[] = {1, 2, 3}; for (auto a : i);
765 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
767 /// \brief Matches range-based for statements.
769 /// forRangeStmt() matches 'for (auto a : i)'
771 /// int i[] = {1, 2, 3}; for (auto a : i);
772 /// for(int j = 0; j < 5; ++j);
774 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt;
776 /// \brief Matches the increment statement of a for loop.
779 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
782 /// for (x; x < N; ++x) { }
784 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
786 const Stmt *const Increment = Node.getInc();
787 return (Increment != NULL &&
788 InnerMatcher.matches(*Increment, Finder, Builder));
791 /// \brief Matches the initialization statement of a for loop.
794 /// forStmt(hasLoopInit(declStmt()))
795 /// matches 'int x = 0' in
797 /// for (int x = 0; x < N; ++x) { }
799 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
801 const Stmt *const Init = Node.getInit();
802 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
805 /// \brief Matches while statements.
812 /// matches 'while (true) {}'.
813 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
815 /// \brief Matches do statements.
819 /// do {} while (true);
822 /// matches 'do {} while(true)'
823 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
825 /// \brief Matches break statements.
829 /// while (true) { break; }
833 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
835 /// \brief Matches continue statements.
839 /// while (true) { continue; }
842 /// matches 'continue'
843 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
845 /// \brief Matches return statements.
852 /// matches 'return 1'
853 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
855 /// \brief Matches goto statements.
863 /// matches 'goto FOO'
864 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
866 /// \brief Matches label statements.
875 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
877 /// \brief Matches switch statements.
881 /// switch(a) { case 42: break; default: break; }
884 /// matches 'switch(a)'.
885 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
887 /// \brief Matches case and default statements inside switch statements.
891 /// switch(a) { case 42: break; default: break; }
894 /// matches 'case 42: break;' and 'default: break;'.
895 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
897 /// \brief Matches compound statements.
899 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
903 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
905 /// \brief Matches catch statements.
908 /// try {} catch(int i) {}
911 /// matches 'catch(int i)'
912 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt;
914 /// \brief Matches try statements.
917 /// try {} catch(int i) {}
921 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt;
923 /// \brief Matches throw expressions.
926 /// try { throw 5; } catch(int i) {}
929 /// matches 'throw 5'
930 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr;
932 /// \brief Matches null statements.
938 /// matches the second ';'
939 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
941 /// \brief Matches asm statements.
945 /// __asm("mov al, 2");
948 /// matches '__asm("mov al, 2")'
949 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
951 /// \brief Matches bool literals.
953 /// Example matches true
957 const internal::VariadicDynCastAllOfMatcher<
959 CXXBoolLiteralExpr> boolLiteral;
961 /// \brief Matches string literals (also matches wide string literals).
963 /// Example matches "abcd", L"abcd"
965 /// char *s = "abcd"; wchar_t *ws = L"abcd"
967 const internal::VariadicDynCastAllOfMatcher<
969 StringLiteral> stringLiteral;
971 /// \brief Matches character literals (also matches wchar_t).
973 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
976 /// Example matches 'a', L'a'
978 /// char ch = 'a'; wchar_t chw = L'a';
980 const internal::VariadicDynCastAllOfMatcher<
982 CharacterLiteral> characterLiteral;
984 /// \brief Matches integer literals of all sizes / encodings.
986 /// Not matching character-encoded integers such as L'a'.
988 /// Example matches 1, 1L, 0x1, 1U
989 const internal::VariadicDynCastAllOfMatcher<
991 IntegerLiteral> integerLiteral;
993 /// \brief Matches user defined literal operator call.
995 /// Example match: "foo"_suffix
996 const internal::VariadicDynCastAllOfMatcher<
998 UserDefinedLiteral> userDefinedLiteral;
1000 /// \brief Matches compound (i.e. non-scalar) literals
1002 /// Example match: {1}, (1, 2)
1004 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1006 const internal::VariadicDynCastAllOfMatcher<
1008 CompoundLiteralExpr> compoundLiteralExpr;
1010 /// \brief Matches nullptr literal.
1011 const internal::VariadicDynCastAllOfMatcher<
1013 CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
1015 /// \brief Matches binary operator expressions.
1017 /// Example matches a || b
1021 const internal::VariadicDynCastAllOfMatcher<
1023 BinaryOperator> binaryOperator;
1025 /// \brief Matches unary operator expressions.
1027 /// Example matches !a
1031 const internal::VariadicDynCastAllOfMatcher<
1033 UnaryOperator> unaryOperator;
1035 /// \brief Matches conditional operator expressions.
1037 /// Example matches a ? b : c
1039 /// (a ? b : c) + 42
1041 const internal::VariadicDynCastAllOfMatcher<
1043 ConditionalOperator> conditionalOperator;
1045 /// \brief Matches a reinterpret_cast expression.
1047 /// Either the source expression or the destination type can be matched
1048 /// using has(), but hasDestinationType() is more specific and can be
1051 /// Example matches reinterpret_cast<char*>(&p) in
1053 /// void* p = reinterpret_cast<char*>(&p);
1055 const internal::VariadicDynCastAllOfMatcher<
1057 CXXReinterpretCastExpr> reinterpretCastExpr;
1059 /// \brief Matches a C++ static_cast expression.
1061 /// \see hasDestinationType
1062 /// \see reinterpretCast
1065 /// staticCastExpr()
1067 /// static_cast<long>(8)
1070 /// long eight(static_cast<long>(8));
1072 const internal::VariadicDynCastAllOfMatcher<
1074 CXXStaticCastExpr> staticCastExpr;
1076 /// \brief Matches a dynamic_cast expression.
1079 /// dynamicCastExpr()
1081 /// dynamic_cast<D*>(&b);
1084 /// struct B { virtual ~B() {} }; struct D : B {};
1086 /// D* p = dynamic_cast<D*>(&b);
1088 const internal::VariadicDynCastAllOfMatcher<
1090 CXXDynamicCastExpr> dynamicCastExpr;
1092 /// \brief Matches a const_cast expression.
1094 /// Example: Matches const_cast<int*>(&r) in
1097 /// const int &r(n);
1098 /// int* p = const_cast<int*>(&r);
1100 const internal::VariadicDynCastAllOfMatcher<
1102 CXXConstCastExpr> constCastExpr;
1104 /// \brief Matches a C-style cast expression.
1106 /// Example: Matches (int*) 2.2f in
1108 /// int i = (int) 2.2f;
1110 const internal::VariadicDynCastAllOfMatcher<
1112 CStyleCastExpr> cStyleCastExpr;
1114 /// \brief Matches explicit cast expressions.
1116 /// Matches any cast expression written in user code, whether it be a
1117 /// C-style cast, a functional-style cast, or a keyword cast.
1119 /// Does not match implicit conversions.
1121 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1122 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1123 /// actual cast expressions.
1125 /// \see hasDestinationType.
1127 /// Example: matches all five of the casts in
1129 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1131 /// but does not match the implicit conversion in
1135 const internal::VariadicDynCastAllOfMatcher<
1137 ExplicitCastExpr> explicitCastExpr;
1139 /// \brief Matches the implicit cast nodes of Clang's AST.
1141 /// This matches many different places, including function call return value
1142 /// eliding, as well as any type conversions.
1143 const internal::VariadicDynCastAllOfMatcher<
1145 ImplicitCastExpr> implicitCastExpr;
1147 /// \brief Matches any cast nodes of Clang's AST.
1149 /// Example: castExpr() matches each of the following:
1152 /// const_cast<Expr *>(SubExpr);
1155 /// but does not match
1160 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1162 /// \brief Matches functional cast expressions
1164 /// Example: Matches Foo(bar);
1167 /// Foo g = (Foo) bar;
1168 /// Foo h = Foo(bar);
1170 const internal::VariadicDynCastAllOfMatcher<
1172 CXXFunctionalCastExpr> functionalCastExpr;
1174 /// \brief Matches \c QualTypes in the clang AST.
1175 const internal::VariadicAllOfMatcher<QualType> qualType;
1177 /// \brief Matches \c Types in the clang AST.
1178 const internal::VariadicAllOfMatcher<Type> type;
1180 /// \brief Matches \c TypeLocs in the clang AST.
1181 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1183 /// \brief Matches if any of the given matchers matches.
1185 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1186 /// matching submatcher.
1188 /// For example, in:
1190 /// class A { int a; int b; };
1194 /// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1195 /// has(fieldDecl(hasName("b")).bind("v"))))
1197 /// will generate two results binding "v", the first of which binds
1198 /// the field declaration of \c a, the second the field declaration of
1201 /// Usable as: Any Matcher
1202 template <typename M1, typename M2>
1203 internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, M2>
1204 eachOf(const M1 &P1, const M2 &P2) {
1205 return internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1,
1209 /// \brief Various overloads for the anyOf matcher.
1212 /// \brief Matches if any of the given matchers matches.
1214 /// Usable as: Any Matcher
1215 template<typename M1, typename M2>
1216 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2>
1217 anyOf(const M1 &P1, const M2 &P2) {
1218 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1221 template<typename M1, typename M2, typename M3>
1222 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1223 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> >
1224 anyOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1225 return anyOf(P1, anyOf(P2, P3));
1227 template<typename M1, typename M2, typename M3, typename M4>
1228 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1229 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1230 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1232 anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1233 return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
1235 template<typename M1, typename M2, typename M3, typename M4, typename M5>
1236 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1237 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1238 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3,
1239 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1241 anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1242 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
1247 /// \brief Various overloads for the allOf matcher.
1250 /// \brief Matches if all given matchers match.
1252 /// Usable as: Any Matcher
1253 template <typename M1, typename M2>
1254 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>
1255 allOf(const M1 &P1, const M2 &P2) {
1256 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>(
1259 template <typename M1, typename M2, typename M3>
1260 internal::PolymorphicMatcherWithParam2<
1261 internal::AllOfMatcher, M1,
1262 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> >
1263 allOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1264 return allOf(P1, allOf(P2, P3));
1266 template <typename M1, typename M2, typename M3, typename M4>
1267 internal::PolymorphicMatcherWithParam2<
1268 internal::AllOfMatcher, M1,
1269 internal::PolymorphicMatcherWithParam2<
1270 internal::AllOfMatcher, M2, internal::PolymorphicMatcherWithParam2<
1271 internal::AllOfMatcher, M3, M4> > >
1272 allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1273 return allOf(P1, allOf(P2, P3, P4));
1275 template <typename M1, typename M2, typename M3, typename M4, typename M5>
1276 internal::PolymorphicMatcherWithParam2<
1277 internal::AllOfMatcher, M1,
1278 internal::PolymorphicMatcherWithParam2<
1279 internal::AllOfMatcher, M2,
1280 internal::PolymorphicMatcherWithParam2<
1281 internal::AllOfMatcher, M3,
1282 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M4,
1284 allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1285 return allOf(P1, allOf(P2, P3, P4, P5));
1290 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1295 /// int y = sizeof(x) + alignof(x);
1297 /// unaryExprOrTypeTraitExpr()
1298 /// matches \c sizeof(x) and \c alignof(x)
1299 const internal::VariadicDynCastAllOfMatcher<
1301 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1303 /// \brief Matches unary expressions that have a specific type of argument.
1307 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1309 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1310 /// matches \c sizeof(a) and \c alignof(c)
1311 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1312 internal::Matcher<QualType>, InnerMatcher) {
1313 const QualType ArgumentType = Node.getTypeOfArgument();
1314 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1317 /// \brief Matches unary expressions of a certain kind.
1322 /// int s = sizeof(x) + alignof(x)
1324 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1325 /// matches \c sizeof(x)
1326 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1327 return Node.getKind() == Kind;
1330 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1332 inline internal::Matcher<Stmt> alignOfExpr(
1333 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1334 return stmt(unaryExprOrTypeTraitExpr(allOf(
1335 ofKind(UETT_AlignOf), InnerMatcher)));
1338 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1340 inline internal::Matcher<Stmt> sizeOfExpr(
1341 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1342 return stmt(unaryExprOrTypeTraitExpr(
1343 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1346 /// \brief Matches NamedDecl nodes that have the specified name.
1348 /// Supports specifying enclosing namespaces or classes by prefixing the name
1349 /// with '<enclosing>::'.
1350 /// Does not match typedefs of an underlying type with the given name.
1352 /// Example matches X (Name == "X")
1357 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1359 /// namespace a { namespace b { class X; } }
1361 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1362 assert(!Name.empty());
1363 const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1364 const StringRef FullName = FullNameString;
1365 const StringRef Pattern = Name;
1366 if (Pattern.startswith("::")) {
1367 return FullName == Pattern;
1369 return FullName.endswith(("::" + Pattern).str());
1373 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1374 /// a substring matched by the given RegExp.
1376 /// Supports specifying enclosing namespaces or classes by
1377 /// prefixing the name with '<enclosing>::'. Does not match typedefs
1378 /// of an underlying type with the given name.
1380 /// Example matches X (regexp == "::X")
1385 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1387 /// namespace foo { namespace bar { class X; } }
1389 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1390 assert(!RegExp.empty());
1391 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1392 llvm::Regex RE(RegExp);
1393 return RE.match(FullNameString);
1396 /// \brief Matches overloaded operator names.
1398 /// Matches overloaded operator names specified in strings without the
1399 /// "operator" prefix: e.g. "<<".
1403 /// class A { int operator*(); };
1404 /// const A &operator<<(const A &a, const A &b);
1406 /// a << a; // <-- This matches
1409 /// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified
1410 /// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
1411 /// the declaration of \c A.
1413 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl>
1414 inline internal::PolymorphicMatcherWithParam1<
1415 internal::HasOverloadedOperatorNameMatcher, StringRef>
1416 hasOverloadedOperatorName(const StringRef Name) {
1417 return internal::PolymorphicMatcherWithParam1<
1418 internal::HasOverloadedOperatorNameMatcher, StringRef>(Name);
1421 /// \brief Matches C++ classes that are directly or indirectly derived from
1422 /// a class matching \c Base.
1424 /// Note that a class is not considered to be derived from itself.
1426 /// Example matches Y, Z, C (Base == hasName("X"))
1429 /// class Y : public X {}; // directly derived
1430 /// class Z : public Y {}; // indirectly derived
1433 /// class C : public B {}; // derived from a typedef of X
1436 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1440 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
1442 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1443 internal::Matcher<NamedDecl>, Base) {
1444 return Finder->classIsDerivedFrom(&Node, Base, Builder);
1447 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1448 inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
1449 assert(!BaseName.empty());
1450 return isDerivedFrom(hasName(BaseName));
1453 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1455 inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1456 internal::Matcher<NamedDecl> Base) {
1457 return anyOf(Base, isDerivedFrom(Base));
1460 /// \brief Overloaded method as shortcut for
1461 /// \c isSameOrDerivedFrom(hasName(...)).
1462 inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1463 StringRef BaseName) {
1464 assert(!BaseName.empty());
1465 return isSameOrDerivedFrom(hasName(BaseName));
1468 /// \brief Matches the first method of a class or struct that satisfies \c
1473 /// class A { void func(); };
1474 /// class B { void member(); };
1477 /// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A
1479 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1481 for (CXXRecordDecl::method_iterator I = Node.method_begin(),
1482 E = Node.method_end();
1484 if (InnerMatcher.matches(**I, Finder, Builder))
1489 /// \brief Matches AST nodes that have child AST nodes that match the
1490 /// provided matcher.
1492 /// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1494 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1495 /// class Y { class X {}; };
1496 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1499 /// ChildT must be an AST base type.
1501 /// Usable as: Any Matcher
1502 template <typename ChildT>
1503 internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
1504 const internal::Matcher<ChildT> &ChildMatcher) {
1505 return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
1506 ChildT>(ChildMatcher);
1509 /// \brief Matches AST nodes that have descendant AST nodes that match the
1510 /// provided matcher.
1512 /// Example matches X, Y, Z
1513 /// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1515 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1516 /// class Y { class X {}; };
1517 /// class Z { class Y { class X {}; }; };
1520 /// DescendantT must be an AST base type.
1522 /// Usable as: Any Matcher
1523 template <typename DescendantT>
1524 internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
1525 hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1526 return internal::ArgumentAdaptingMatcher<
1527 internal::HasDescendantMatcher,
1528 DescendantT>(DescendantMatcher);
1531 /// \brief Matches AST nodes that have child AST nodes that match the
1532 /// provided matcher.
1534 /// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1536 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1537 /// class Y { class X {}; };
1538 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1541 /// ChildT must be an AST base type.
1543 /// As opposed to 'has', 'forEach' will cause a match for each result that
1544 /// matches instead of only on the first one.
1546 /// Usable as: Any Matcher
1547 template <typename ChildT>
1548 internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1549 const internal::Matcher<ChildT> &ChildMatcher) {
1550 return internal::ArgumentAdaptingMatcher<
1551 internal::ForEachMatcher,
1552 ChildT>(ChildMatcher);
1555 /// \brief Matches AST nodes that have descendant AST nodes that match the
1556 /// provided matcher.
1558 /// Example matches X, A, B, C
1559 /// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1561 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1562 /// class A { class X {}; };
1563 /// class B { class C { class X {}; }; };
1566 /// DescendantT must be an AST base type.
1568 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1569 /// each result that matches instead of only on the first one.
1571 /// Note: Recursively combined ForEachDescendant can cause many matches:
1572 /// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1573 /// will match 10 times (plus injected class name matches) on:
1575 /// class A { class B { class C { class D { class E {}; }; }; }; };
1578 /// Usable as: Any Matcher
1579 template <typename DescendantT>
1580 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher,
1583 const internal::Matcher<DescendantT> &DescendantMatcher) {
1584 return internal::ArgumentAdaptingMatcher<
1585 internal::ForEachDescendantMatcher,
1586 DescendantT>(DescendantMatcher);
1589 /// \brief Matches if the node or any descendant matches.
1591 /// Generates results for each match.
1593 /// For example, in:
1595 /// class A { class B {}; class C {}; };
1599 /// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1601 /// will generate results for \c A, \c B and \c C.
1603 /// Usable as: Any Matcher
1604 template <typename T>
1605 internal::PolymorphicMatcherWithParam2<
1606 internal::EachOfMatcher, internal::Matcher<T>,
1607 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> >
1608 findAll(const internal::Matcher<T> &Matcher) {
1609 return eachOf(Matcher, forEachDescendant(Matcher));
1612 /// \brief Matches AST nodes that have a parent that matches the provided
1617 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1619 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1621 /// Usable as: Any Matcher
1622 template <typename ParentT>
1623 internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT>
1624 hasParent(const internal::Matcher<ParentT> &ParentMatcher) {
1625 return internal::ArgumentAdaptingMatcher<
1626 internal::HasParentMatcher,
1627 ParentT>(ParentMatcher);
1630 /// \brief Matches AST nodes that have an ancestor that matches the provided
1635 /// void f() { if (true) { int x = 42; } }
1636 /// void g() { for (;;) { int x = 43; } }
1638 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1640 /// Usable as: Any Matcher
1641 template <typename AncestorT>
1642 internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT>
1643 hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) {
1644 return internal::ArgumentAdaptingMatcher<
1645 internal::HasAncestorMatcher,
1646 AncestorT>(AncestorMatcher);
1649 /// \brief Matches if the provided matcher does not match.
1651 /// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1657 /// Usable as: Any Matcher
1658 template <typename M>
1659 internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M>
1660 unless(const M &InnerMatcher) {
1661 return internal::PolymorphicMatcherWithParam1<
1662 internal::NotMatcher, M>(InnerMatcher);
1665 /// \brief Matches a type if the declaration of the type matches the given
1668 /// In addition to being usable as Matcher<TypedefType>, also usable as
1669 /// Matcher<T> for any T supporting the getDecl() member function. e.g. various
1670 /// subtypes of clang::Type.
1672 /// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1673 /// Matcher<MemberExpr>, Matcher<TypedefType>,
1674 /// Matcher<TemplateSpecializationType>
1675 inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1676 internal::Matcher<Decl> >
1677 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1678 return internal::PolymorphicMatcherWithParam1<
1679 internal::HasDeclarationMatcher,
1680 internal::Matcher<Decl> >(InnerMatcher);
1683 /// \brief Matches on the implicit object argument of a member call expression.
1685 /// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1687 /// class Y { public: void x(); };
1688 /// void z() { Y y; y.x(); }",
1691 /// FIXME: Overload to allow directly matching types?
1692 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1694 const Expr *ExprNode = Node.getImplicitObjectArgument()
1695 ->IgnoreParenImpCasts();
1696 return (ExprNode != NULL &&
1697 InnerMatcher.matches(*ExprNode, Finder, Builder));
1700 /// \brief Matches if the call expression's callee expression matches.
1704 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
1705 /// void f() { f(); }
1707 /// callExpr(callee(expr()))
1708 /// matches this->x(), x(), y.x(), f()
1709 /// with callee(...)
1710 /// matching this->x, x, y.x, f respectively
1712 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1713 /// because this introduces ambiguous overloads with calls to Callee taking a
1714 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1715 /// implemented in terms of implicit casts.
1716 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1718 const Expr *ExprNode = Node.getCallee();
1719 return (ExprNode != NULL &&
1720 InnerMatcher.matches(*ExprNode, Finder, Builder));
1723 /// \brief Matches if the call expression's callee's declaration matches the
1726 /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1728 /// class Y { public: void x(); };
1729 /// void z() { Y y; y.x();
1731 inline internal::Matcher<CallExpr> callee(
1732 const internal::Matcher<Decl> &InnerMatcher) {
1733 return callExpr(hasDeclaration(InnerMatcher));
1736 /// \brief Matches if the expression's or declaration's type matches a type
1739 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1740 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1743 /// void y(X &x) { x; X z; }
1745 AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1747 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1748 llvm::is_base_of<ValueDecl, NodeType>::value),
1749 instantiated_with_wrong_types);
1750 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1753 /// \brief Overloaded to match the declaration of the expression's or value
1754 /// declaration's type.
1756 /// In case of a value declaration (for example a variable declaration),
1757 /// this resolves one layer of indirection. For example, in the value
1758 /// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1759 /// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1762 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1763 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1766 /// void y(X &x) { x; X z; }
1769 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1770 inline internal::PolymorphicMatcherWithParam1<
1771 internal::matcher_hasType0Matcher,
1772 internal::Matcher<QualType> >
1773 hasType(const internal::Matcher<Decl> &InnerMatcher) {
1774 return hasType(qualType(hasDeclaration(InnerMatcher)));
1777 /// \brief Matches if the matched type is represented by the given string.
1781 /// class Y { public: void x(); };
1782 /// void z() { Y* y; y->x(); }
1784 /// callExpr(on(hasType(asString("class Y *"))))
1786 AST_MATCHER_P(QualType, asString, std::string, Name) {
1787 return Name == Node.getAsString();
1790 /// \brief Matches if the matched type is a pointer type and the pointee type
1791 /// matches the specified matcher.
1793 /// Example matches y->x()
1794 /// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1796 /// class Y { public: void x(); };
1797 /// void z() { Y *y; y->x(); }
1800 QualType, pointsTo, internal::Matcher<QualType>,
1802 return (!Node.isNull() && Node->isPointerType() &&
1803 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1806 /// \brief Overloaded to match the pointee type's declaration.
1807 inline internal::Matcher<QualType> pointsTo(
1808 const internal::Matcher<Decl> &InnerMatcher) {
1809 return pointsTo(qualType(hasDeclaration(InnerMatcher)));
1812 /// \brief Matches if the matched type is a reference type and the referenced
1813 /// type matches the specified matcher.
1815 /// Example matches X &x and const X &y
1816 /// (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1824 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1826 return (!Node.isNull() && Node->isReferenceType() &&
1827 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1830 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1834 /// typedef int &int_ref;
1839 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1840 /// declaration of b but \c
1841 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1842 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1844 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1847 /// \brief Overloaded to match the referenced type's declaration.
1848 inline internal::Matcher<QualType> references(
1849 const internal::Matcher<Decl> &InnerMatcher) {
1850 return references(qualType(hasDeclaration(InnerMatcher)));
1853 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1854 internal::Matcher<Expr>, InnerMatcher) {
1855 const Expr *ExprNode = Node.getImplicitObjectArgument();
1856 return (ExprNode != NULL &&
1857 InnerMatcher.matches(*ExprNode, Finder, Builder));
1860 /// \brief Matches if the expression's type either matches the specified
1861 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1862 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1863 const internal::Matcher<QualType> &InnerMatcher) {
1864 return onImplicitObjectArgument(
1865 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1868 /// \brief Overloaded to match the type's declaration.
1869 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1870 const internal::Matcher<Decl> &InnerMatcher) {
1871 return onImplicitObjectArgument(
1872 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1875 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1876 /// specified matcher.
1878 /// Example matches x in if(x)
1879 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
1884 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1886 const Decl *DeclNode = Node.getDecl();
1887 return (DeclNode != NULL &&
1888 InnerMatcher.matches(*DeclNode, Finder, Builder));
1891 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1892 /// specific using shadow declaration.
1894 /// FIXME: This currently only works for functions. Fix.
1898 /// namespace a { void f() {} }
1901 /// f(); // Matches this ..
1902 /// a::f(); // .. but not this.
1905 /// declRefExpr(throughUsingDeclaration(anything()))
1907 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1908 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
1909 const NamedDecl *FoundDecl = Node.getFoundDecl();
1910 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
1911 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
1915 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
1922 /// declStmt(hasSingleDecl(anything()))
1923 /// matches 'int c;' but not 'int a, b;'.
1924 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1925 if (Node.isSingleDecl()) {
1926 const Decl *FoundDecl = Node.getSingleDecl();
1927 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1932 /// \brief Matches a variable declaration that has an initializer expression
1933 /// that matches the given matcher.
1935 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
1937 /// bool y() { return true; }
1941 VarDecl, hasInitializer, internal::Matcher<Expr>,
1943 const Expr *Initializer = Node.getAnyInitializer();
1944 return (Initializer != NULL &&
1945 InnerMatcher.matches(*Initializer, Finder, Builder));
1948 /// \brief Checks that a call expression or a constructor call expression has
1949 /// a specific number of arguments (including absent default arguments).
1951 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
1953 /// void f(int x, int y);
1956 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1957 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1958 llvm::is_base_of<CXXConstructExpr,
1960 instantiated_with_wrong_types);
1961 return Node.getNumArgs() == N;
1964 /// \brief Matches the n'th argument of a call expression or a constructor
1965 /// call expression.
1967 /// Example matches y in x(y)
1968 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
1970 /// void x(int) { int y; x(y); }
1972 AST_POLYMORPHIC_MATCHER_P2(
1973 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1974 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1975 llvm::is_base_of<CXXConstructExpr,
1977 instantiated_with_wrong_types);
1978 return (N < Node.getNumArgs() &&
1979 InnerMatcher.matches(
1980 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1983 /// \brief Matches declaration statements that contain a specific number of
1993 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
1994 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
1995 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
1998 /// \brief Matches the n'th declaration of a declaration statement.
2000 /// Note that this does not work for global declarations because the AST
2001 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2003 /// Example: Given non-global declarations
2009 /// declStmt(containsDeclaration(
2010 /// 0, varDecl(hasInitializer(anything()))))
2011 /// matches only 'int d = 2, e;', and
2012 /// declStmt(containsDeclaration(1, varDecl()))
2014 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2015 /// but 'int c;' is not matched.
2017 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2018 internal::Matcher<Decl>, InnerMatcher) {
2019 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2022 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2023 std::advance(Iterator, N);
2024 return InnerMatcher.matches(**Iterator, Finder, Builder);
2027 /// \brief Matches a constructor initializer.
2032 /// Foo() : foo_(1) { }
2036 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2037 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2038 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2039 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2040 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
2041 I != Node.init_end(); ++I) {
2042 if (InnerMatcher.matches(**I, Finder, Builder)) {
2049 /// \brief Matches the field declaration of a constructor initializer.
2054 /// Foo() : foo_(1) { }
2058 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2059 /// forField(hasName("foo_"))))))
2061 /// with forField matching foo_
2062 AST_MATCHER_P(CXXCtorInitializer, forField,
2063 internal::Matcher<FieldDecl>, InnerMatcher) {
2064 const FieldDecl *NodeAsDecl = Node.getMember();
2065 return (NodeAsDecl != NULL &&
2066 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2069 /// \brief Matches the initializer expression of a constructor initializer.
2074 /// Foo() : foo_(1) { }
2078 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2079 /// withInitializer(integerLiteral(equals(1)))))))
2081 /// with withInitializer matching (1)
2082 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2083 internal::Matcher<Expr>, InnerMatcher) {
2084 const Expr* NodeAsExpr = Node.getInit();
2085 return (NodeAsExpr != NULL &&
2086 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2089 /// \brief Matches a contructor initializer if it is explicitly written in
2090 /// code (as opposed to implicitly added by the compiler).
2096 /// Foo(int) : foo_("A") { }
2100 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2101 /// will match Foo(int), but not Foo()
2102 AST_MATCHER(CXXCtorInitializer, isWritten) {
2103 return Node.isWritten();
2106 /// \brief Matches a constructor declaration that has been implicitly added
2107 /// by the compiler (eg. implicit default/copy constructors).
2108 AST_MATCHER(CXXConstructorDecl, isImplicit) {
2109 return Node.isImplicit();
2112 /// \brief Matches any argument of a call expression or a constructor call
2117 /// void x(int, int, int) { int y; x(1, y, 42); }
2119 /// callExpr(hasAnyArgument(declRefExpr()))
2120 /// matches x(1, y, 42)
2121 /// with hasAnyArgument(...)
2123 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
2125 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
2126 llvm::is_base_of<CXXConstructExpr,
2128 instantiated_with_wrong_types);
2129 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2130 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
2138 /// \brief Matches the n'th parameter of a function declaration.
2142 /// class X { void f(int x) {} };
2144 /// methodDecl(hasParameter(0, hasType(varDecl())))
2145 /// matches f(int x) {}
2146 /// with hasParameter(...)
2148 AST_MATCHER_P2(FunctionDecl, hasParameter,
2149 unsigned, N, internal::Matcher<ParmVarDecl>,
2151 return (N < Node.getNumParams() &&
2152 InnerMatcher.matches(
2153 *Node.getParamDecl(N), Finder, Builder));
2156 /// \brief Matches any parameter of a function declaration.
2158 /// Does not match the 'this' parameter of a method.
2162 /// class X { void f(int x, int y, int z) {} };
2164 /// methodDecl(hasAnyParameter(hasName("y")))
2165 /// matches f(int x, int y, int z) {}
2166 /// with hasAnyParameter(...)
2168 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2169 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2170 for (unsigned I = 0; I < Node.getNumParams(); ++I) {
2171 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
2178 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2182 /// void f(int i) {}
2183 /// void g(int i, int j) {}
2185 /// functionDecl(parameterCountIs(2))
2186 /// matches g(int i, int j) {}
2187 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2188 return Node.getNumParams() == N;
2191 /// \brief Matches the return type of a function declaration.
2195 /// class X { int f() { return 1; } };
2197 /// methodDecl(returns(asString("int")))
2198 /// matches int f() { return 1; }
2199 AST_MATCHER_P(FunctionDecl, returns,
2200 internal::Matcher<QualType>, InnerMatcher) {
2201 return InnerMatcher.matches(Node.getResultType(), Finder, Builder);
2204 /// \brief Matches extern "C" function declarations.
2208 /// extern "C" void f() {}
2209 /// extern "C" { void g() {} }
2212 /// functionDecl(isExternC())
2213 /// matches the declaration of f and g, but not the declaration h
2214 AST_MATCHER(FunctionDecl, isExternC) {
2215 return Node.isExternC();
2218 /// \brief Matches the condition expression of an if statement, for loop,
2219 /// or conditional operator.
2221 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2225 AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
2227 TOOLING_COMPILE_ASSERT(
2228 (llvm::is_base_of<IfStmt, NodeType>::value) ||
2229 (llvm::is_base_of<ForStmt, NodeType>::value) ||
2230 (llvm::is_base_of<WhileStmt, NodeType>::value) ||
2231 (llvm::is_base_of<DoStmt, NodeType>::value) ||
2232 (llvm::is_base_of<ConditionalOperator, NodeType>::value),
2233 has_condition_requires_if_statement_conditional_operator_or_loop);
2234 const Expr *const Condition = Node.getCond();
2235 return (Condition != NULL &&
2236 InnerMatcher.matches(*Condition, Finder, Builder));
2239 /// \brief Matches the condition variable statement in an if statement.
2243 /// if (A* a = GetAPointer()) {}
2245 /// hasConditionVariableStatment(...)
2246 /// matches 'A* a = GetAPointer()'.
2247 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2248 internal::Matcher<DeclStmt>, InnerMatcher) {
2249 const DeclStmt* const DeclarationStatement =
2250 Node.getConditionVariableDeclStmt();
2251 return DeclarationStatement != NULL &&
2252 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2255 /// \brief Matches the index expression of an array subscript expression.
2260 /// void f() { i[1] = 42; }
2262 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2263 /// matches \c i[1] with the \c integerLiteral() matching \c 1
2264 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2265 internal::Matcher<Expr>, InnerMatcher) {
2266 if (const Expr* Expression = Node.getIdx())
2267 return InnerMatcher.matches(*Expression, Finder, Builder);
2271 /// \brief Matches the base expression of an array subscript expression.
2276 /// void f() { i[1] = 42; }
2278 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2279 /// hasSourceExpression(declRefExpr()))))
2280 /// matches \c i[1] with the \c declRefExpr() matching \c i
2281 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2282 internal::Matcher<Expr>, InnerMatcher) {
2283 if (const Expr* Expression = Node.getBase())
2284 return InnerMatcher.matches(*Expression, Finder, Builder);
2288 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2295 /// hasBody(compoundStmt())
2296 /// matches 'for (;;) {}'
2297 /// with compoundStmt()
2299 AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
2301 TOOLING_COMPILE_ASSERT(
2302 (llvm::is_base_of<DoStmt, NodeType>::value) ||
2303 (llvm::is_base_of<ForStmt, NodeType>::value) ||
2304 (llvm::is_base_of<WhileStmt, NodeType>::value),
2305 has_body_requires_for_while_or_do_statement);
2306 const Stmt *const Statement = Node.getBody();
2307 return (Statement != NULL &&
2308 InnerMatcher.matches(*Statement, Finder, Builder));
2311 /// \brief Matches compound statements where at least one substatement matches
2312 /// a given matcher.
2318 /// hasAnySubstatement(compoundStmt())
2319 /// matches '{ {}; 1+2; }'
2320 /// with compoundStmt()
2322 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2323 internal::Matcher<Stmt>, InnerMatcher) {
2324 for (CompoundStmt::const_body_iterator It = Node.body_begin();
2325 It != Node.body_end();
2327 if (InnerMatcher.matches(**It, Finder, Builder)) return true;
2332 /// \brief Checks that a compound statement contains a specific number of
2333 /// child statements.
2339 /// compoundStmt(statementCountIs(0)))
2341 /// but does not match the outer compound statement.
2342 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2343 return Node.size() == N;
2346 /// \brief Matches literals that are equal to the given value.
2348 /// Example matches true (matcher = boolLiteral(equals(true)))
2353 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2354 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2355 template <typename ValueT>
2356 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2357 equals(const ValueT &Value) {
2358 return internal::PolymorphicMatcherWithParam1<
2359 internal::ValueEqualsMatcher,
2363 /// \brief Matches the operator Name of operator expressions (binary or
2366 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2370 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
2371 TOOLING_COMPILE_ASSERT(
2372 (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
2373 (llvm::is_base_of<UnaryOperator, NodeType>::value),
2374 has_condition_requires_if_statement_or_conditional_operator);
2375 return Name == Node.getOpcodeStr(Node.getOpcode());
2378 /// \brief Matches the left hand side of binary operator expressions.
2380 /// Example matches a (matcher = binaryOperator(hasLHS()))
2384 AST_MATCHER_P(BinaryOperator, hasLHS,
2385 internal::Matcher<Expr>, InnerMatcher) {
2386 Expr *LeftHandSide = Node.getLHS();
2387 return (LeftHandSide != NULL &&
2388 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2391 /// \brief Matches the right hand side of binary operator expressions.
2393 /// Example matches b (matcher = binaryOperator(hasRHS()))
2397 AST_MATCHER_P(BinaryOperator, hasRHS,
2398 internal::Matcher<Expr>, InnerMatcher) {
2399 Expr *RightHandSide = Node.getRHS();
2400 return (RightHandSide != NULL &&
2401 InnerMatcher.matches(*RightHandSide, Finder, Builder));
2404 /// \brief Matches if either the left hand side or the right hand side of a
2405 /// binary operator matches.
2406 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2407 const internal::Matcher<Expr> &InnerMatcher) {
2408 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2411 /// \brief Matches if the operand of a unary operator matches.
2413 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2417 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2418 internal::Matcher<Expr>, InnerMatcher) {
2419 const Expr * const Operand = Node.getSubExpr();
2420 return (Operand != NULL &&
2421 InnerMatcher.matches(*Operand, Finder, Builder));
2424 /// \brief Matches if the cast's source expression matches the given matcher.
2426 /// Example: matches "a string" (matcher =
2427 /// hasSourceExpression(constructExpr()))
2429 /// class URL { URL(string); };
2430 /// URL url = "a string";
2431 AST_MATCHER_P(CastExpr, hasSourceExpression,
2432 internal::Matcher<Expr>, InnerMatcher) {
2433 const Expr* const SubExpression = Node.getSubExpr();
2434 return (SubExpression != NULL &&
2435 InnerMatcher.matches(*SubExpression, Finder, Builder));
2438 /// \brief Matches casts whose destination type matches a given matcher.
2440 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2441 /// actual casts "explicit" casts.)
2442 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2443 internal::Matcher<QualType>, InnerMatcher) {
2444 const QualType NodeType = Node.getTypeAsWritten();
2445 return InnerMatcher.matches(NodeType, Finder, Builder);
2448 /// \brief Matches implicit casts whose destination type matches a given
2451 /// FIXME: Unit test this matcher
2452 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2453 internal::Matcher<QualType>, InnerMatcher) {
2454 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2457 /// \brief Matches the true branch expression of a conditional operator.
2459 /// Example matches a
2461 /// condition ? a : b
2463 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2464 internal::Matcher<Expr>, InnerMatcher) {
2465 Expr *Expression = Node.getTrueExpr();
2466 return (Expression != NULL &&
2467 InnerMatcher.matches(*Expression, Finder, Builder));
2470 /// \brief Matches the false branch expression of a conditional operator.
2472 /// Example matches b
2474 /// condition ? a : b
2476 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2477 internal::Matcher<Expr>, InnerMatcher) {
2478 Expr *Expression = Node.getFalseExpr();
2479 return (Expression != NULL &&
2480 InnerMatcher.matches(*Expression, Finder, Builder));
2483 /// \brief Matches if a declaration has a body attached.
2485 /// Example matches A, va, fa
2488 /// class B; // Doesn't match, as it has no body.
2490 /// extern int vb; // Doesn't match, as it doesn't define the variable.
2492 /// void fb(); // Doesn't match, as it has no body.
2495 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2496 AST_POLYMORPHIC_MATCHER(isDefinition) {
2497 TOOLING_COMPILE_ASSERT(
2498 (llvm::is_base_of<TagDecl, NodeType>::value) ||
2499 (llvm::is_base_of<VarDecl, NodeType>::value) ||
2500 (llvm::is_base_of<FunctionDecl, NodeType>::value),
2501 is_definition_requires_isThisDeclarationADefinition_method);
2502 return Node.isThisDeclarationADefinition();
2505 /// \brief Matches the class declaration that the given method declaration
2508 /// FIXME: Generalize this for other kinds of declarations.
2509 /// FIXME: What other kind of declarations would we need to generalize
2512 /// Example matches A() in the last line
2513 /// (matcher = constructExpr(hasDeclaration(methodDecl(
2514 /// ofClass(hasName("A"))))))
2522 AST_MATCHER_P(CXXMethodDecl, ofClass,
2523 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2524 const CXXRecordDecl *Parent = Node.getParent();
2525 return (Parent != NULL &&
2526 InnerMatcher.matches(*Parent, Finder, Builder));
2529 /// \brief Matches if the given method declaration is virtual.
2535 /// virtual void x();
2539 AST_MATCHER(CXXMethodDecl, isVirtual) {
2540 return Node.isVirtual();
2543 /// \brief Matches if the given method declaration overrides another method.
2549 /// virtual void x();
2551 /// class B : public A {
2553 /// virtual void x();
2557 AST_MATCHER(CXXMethodDecl, isOverride) {
2558 return Node.size_overridden_methods() > 0;
2561 /// \brief Matches member expressions that are called with '->' as opposed
2564 /// Member calls on the implicit this pointer match as called with '->'.
2569 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2574 /// memberExpr(isArrow())
2575 /// matches this->x, x, y.x, a, this->b
2576 AST_MATCHER(MemberExpr, isArrow) {
2577 return Node.isArrow();
2580 /// \brief Matches QualType nodes that are of integer type.
2588 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2589 /// matches "a(int)", "b(long)", but not "c(double)".
2590 AST_MATCHER(QualType, isInteger) {
2591 return Node->isIntegerType();
2594 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2595 /// include "top-level" const.
2600 /// void b(int const);
2601 /// void c(const int);
2602 /// void d(const int*);
2603 /// void e(int const) {};
2605 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2606 /// matches "void b(int const)", "void c(const int)" and
2607 /// "void e(int const) {}". It does not match d as there
2608 /// is no top-level const on the parameter type "const int *".
2609 AST_MATCHER(QualType, isConstQualified) {
2610 return Node.isConstQualified();
2613 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2614 /// the node, not hidden within a typedef.
2618 /// typedef const int const_int;
2621 /// int *volatile k;
2624 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2625 /// \c i is const-qualified but the qualifier is not local.
2626 AST_MATCHER(QualType, hasLocalQualifiers) {
2627 return Node.hasLocalQualifiers();
2630 /// \brief Matches a member expression where the member is matched by a
2635 /// struct { int first, second; } first, second;
2636 /// int i(second.first);
2637 /// int j(first.second);
2639 /// memberExpr(member(hasName("first")))
2640 /// matches second.first
2641 /// but not first.second (because the member name there is "second").
2642 AST_MATCHER_P(MemberExpr, member,
2643 internal::Matcher<ValueDecl>, InnerMatcher) {
2644 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2647 /// \brief Matches a member expression where the object expression is
2648 /// matched by a given matcher.
2652 /// struct X { int m; };
2653 /// void f(X x) { x.m; m; }
2655 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2656 /// matches "x.m" and "m"
2657 /// with hasObjectExpression(...)
2658 /// matching "x" and the implicit object expression of "m" which has type X*.
2659 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2660 internal::Matcher<Expr>, InnerMatcher) {
2661 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2664 /// \brief Matches any using shadow declaration.
2668 /// namespace X { void b(); }
2671 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2672 /// matches \code using X::b \endcode
2673 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2674 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2675 for (UsingDecl::shadow_iterator II = Node.shadow_begin();
2676 II != Node.shadow_end(); ++II) {
2677 if (InnerMatcher.matches(**II, Finder, Builder))
2683 /// \brief Matches a using shadow declaration where the target declaration is
2684 /// matched by the given matcher.
2688 /// namespace X { int a; void b(); }
2692 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2693 /// matches \code using X::b \endcode
2694 /// but not \code using X::a \endcode
2695 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2696 internal::Matcher<NamedDecl>, InnerMatcher) {
2697 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2700 /// \brief Matches template instantiations of function, class, or static
2701 /// member variable template instantiations.
2705 /// template <typename T> class X {}; class A {}; X<A> x;
2709 /// template <typename T> class X {}; class A {}; template class X<A>;
2711 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2712 /// matches the template instantiation of X<A>.
2716 /// template <typename T> class X {}; class A {};
2717 /// template <> class X<A> {}; X<A> x;
2719 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2720 /// does not match, as X<A> is an explicit template specialization.
2722 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2723 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation) {
2724 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2725 (llvm::is_base_of<VarDecl, NodeType>::value) ||
2726 (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2727 requires_getTemplateSpecializationKind_method);
2728 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2729 Node.getTemplateSpecializationKind() ==
2730 TSK_ExplicitInstantiationDefinition);
2733 /// \brief Matches explicit template specializations of function, class, or
2734 /// static member variable template instantiations.
2738 /// template<typename T> void A(T t) { }
2739 /// template<> void A(int N) { }
2741 /// functionDecl(isExplicitTemplateSpecialization())
2742 /// matches the specialization A<int>().
2744 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2745 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization) {
2746 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2747 (llvm::is_base_of<VarDecl, NodeType>::value) ||
2748 (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2749 requires_getTemplateSpecializationKind_method);
2750 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2753 /// \brief Matches \c TypeLocs for which the given inner
2754 /// QualType-matcher matches.
2755 inline internal::BindableMatcher<TypeLoc> loc(
2756 const internal::Matcher<QualType> &InnerMatcher) {
2757 return internal::BindableMatcher<TypeLoc>(
2758 new internal::TypeLocTypeMatcher(InnerMatcher));
2761 /// \brief Matches builtin Types.
2772 /// matches "int b", "float c" and "bool d"
2773 AST_TYPE_MATCHER(BuiltinType, builtinType);
2775 /// \brief Matches all kinds of arrays.
2779 /// int a[] = { 2, 3 };
2781 /// void f() { int c[a[0]]; }
2784 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
2785 AST_TYPE_MATCHER(ArrayType, arrayType);
2787 /// \brief Matches C99 complex types.
2791 /// _Complex float f;
2794 /// matches "_Complex float f"
2795 AST_TYPE_MATCHER(ComplexType, complexType);
2797 /// \brief Matches arrays and C99 complex types that have a specific element
2806 /// arrayType(hasElementType(builtinType()))
2807 /// matches "int b[7]"
2809 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
2810 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement);
2812 /// \brief Matches C arrays with a specified constant size.
2818 /// int b[] = { 2, 3 };
2822 /// constantArrayType()
2823 /// matches "int a[2]"
2824 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
2826 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
2832 /// int c[41], d[43];
2834 /// constantArrayType(hasSize(42))
2835 /// matches "int a[42]" and "int b[2 * 21]"
2836 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
2837 return Node.getSize() == N;
2840 /// \brief Matches C++ arrays whose size is a value-dependent expression.
2844 /// template<typename T, int Size>
2849 /// dependentSizedArrayType
2850 /// matches "T data[Size]"
2851 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
2853 /// \brief Matches C arrays with unspecified size.
2857 /// int a[] = { 2, 3 };
2859 /// void f(int c[]) { int d[a[0]]; };
2861 /// incompleteArrayType()
2862 /// matches "int a[]" and "int c[]"
2863 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
2865 /// \brief Matches C arrays with a specified size that is not an
2866 /// integer-constant-expression.
2871 /// int a[] = { 2, 3 }
2875 /// variableArrayType()
2876 /// matches "int c[a[0]]"
2877 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
2879 /// \brief Matches \c VariableArrayType nodes that have a specific size
2888 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
2889 /// varDecl(hasName("b")))))))
2890 /// matches "int a[b]"
2891 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
2892 internal::Matcher<Expr>, InnerMatcher) {
2893 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
2896 /// \brief Matches atomic types.
2903 /// matches "_Atomic(int) i"
2904 AST_TYPE_MATCHER(AtomicType, atomicType);
2906 /// \brief Matches atomic types with a specific value type.
2911 /// _Atomic(float) f;
2913 /// atomicType(hasValueType(isInteger()))
2914 /// matches "_Atomic(int) i"
2916 /// Usable as: Matcher<AtomicType>
2917 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue);
2919 /// \brief Matches types nodes representing C++11 auto types.
2924 /// int v[] = { 2, 3 }
2925 /// for (auto i : v) { }
2928 /// matches "auto n" and "auto i"
2929 AST_TYPE_MATCHER(AutoType, autoType);
2931 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
2933 /// Note: There is no \c TypeLoc for the deduced type and thus no
2934 /// \c getDeducedLoc() matcher.
2941 /// autoType(hasDeducedType(isInteger()))
2942 /// matches "auto a"
2944 /// Usable as: Matcher<AutoType>
2945 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType);
2947 /// \brief Matches \c FunctionType nodes.
2955 /// matches "int (*f)(int)" and the type of "g".
2956 AST_TYPE_MATCHER(FunctionType, functionType);
2958 /// \brief Matches \c ParenType nodes.
2962 /// int (*ptr_to_array)[4];
2963 /// int *array_of_ptrs[4];
2966 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
2967 /// \c array_of_ptrs.
2968 AST_TYPE_MATCHER(ParenType, parenType);
2970 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
2974 /// int (*ptr_to_array)[4];
2975 /// int (*ptr_to_func)(int);
2978 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
2979 /// \c ptr_to_func but not \c ptr_to_array.
2981 /// Usable as: Matcher<ParenType>
2982 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType);
2984 /// \brief Matches block pointer types, i.e. types syntactically represented as
2985 /// "void (^)(int)".
2987 /// The \c pointee is always required to be a \c FunctionType.
2988 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
2990 /// \brief Matches member pointer types.
2993 /// struct A { int i; }
2994 /// A::* ptr = A::i;
2996 /// memberPointerType()
2997 /// matches "A::* ptr"
2998 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3000 /// \brief Matches pointer types.
3009 /// matches "int *a"
3010 AST_TYPE_MATCHER(PointerType, pointerType);
3012 /// \brief Matches both lvalue and rvalue reference types.
3025 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3026 AST_TYPE_MATCHER(ReferenceType, referenceType);
3028 /// \brief Matches lvalue reference types.
3041 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3042 /// matched since the type is deduced as int& by reference collapsing rules.
3043 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3045 /// \brief Matches rvalue reference types.
3058 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3059 /// matched as it is deduced to int& by reference collapsing rules.
3060 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3062 /// \brief Narrows PointerType (and similar) matchers to those where the
3063 /// \c pointee matches a given matcher.
3071 /// pointerType(pointee(isConstQualified(), isInteger()))
3072 /// matches "int const *b"
3074 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3075 /// Matcher<PointerType>, Matcher<ReferenceType>
3076 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee);
3078 /// \brief Matches typedef types.
3085 /// matches "typedef int X"
3086 AST_TYPE_MATCHER(TypedefType, typedefType);
3088 /// \brief Matches template specialization types.
3092 /// template <typename T>
3095 /// template class C<int>; // A
3096 /// C<char> var; // B
3099 /// \c templateSpecializationType() matches the type of the explicit
3100 /// instantiation in \c A and the type of the variable declaration in \c B.
3101 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3103 /// \brief Matches record types (e.g. structs, classes).
3114 /// \c recordType() matches the type of the variable declarations of both \c c
3116 AST_TYPE_MATCHER(RecordType, recordType);
3118 /// \brief Matches types specified with an elaborated type keyword or with a
3134 /// \c elaboratedType() matches the type of the variable declarations of both
3136 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3138 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3139 /// matches \c InnerMatcher if the qualifier exists.
3151 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3152 /// matches the type of the variable declaration of \c d.
3153 AST_MATCHER_P(ElaboratedType, hasQualifier,
3154 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3155 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3156 return InnerMatcher.matches(*Qualifier, Finder, Builder);
3161 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3173 /// \c elaboratedType(namesType(recordType(
3174 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3175 /// declaration of \c d.
3176 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3178 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3181 /// \brief Matches declarations whose declaration context, interpreted as a
3182 /// Decl, matches \c InnerMatcher.
3193 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3194 /// declaration of \c class \c D.
3195 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3196 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3200 /// \brief Matches nested name specifiers.
3205 /// struct A { static void f(); };
3207 /// void g() { A::f(); }
3211 /// nestedNameSpecifier()
3212 /// matches "ns::" and both "A::"
3213 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3215 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3216 const internal::VariadicAllOfMatcher<
3217 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3219 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3220 /// NestedNameSpecifier-matcher matches.
3221 inline internal::BindableMatcher<NestedNameSpecifierLoc> loc(
3222 const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
3223 return internal::BindableMatcher<NestedNameSpecifierLoc>(
3224 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3228 /// \brief Matches nested name specifiers that specify a type matching the
3229 /// given \c QualType matcher without qualifiers.
3233 /// struct A { struct B { struct C {}; }; };
3236 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3238 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3239 internal::Matcher<QualType>, InnerMatcher) {
3240 if (Node.getAsType() == NULL)
3242 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3245 /// \brief Matches nested name specifier locs that specify a type matching the
3246 /// given \c TypeLoc.
3250 /// struct A { struct B { struct C {}; }; };
3253 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3254 /// hasDeclaration(recordDecl(hasName("A")))))))
3256 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3257 internal::Matcher<TypeLoc>, InnerMatcher) {
3258 return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3261 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3265 /// struct A { struct B { struct C {}; }; };
3268 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3270 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3271 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3273 NestedNameSpecifier *NextNode = Node.getPrefix();
3274 if (NextNode == NULL)
3276 return InnerMatcher.matches(*NextNode, Finder, Builder);
3279 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3283 /// struct A { struct B { struct C {}; }; };
3286 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3288 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3289 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3291 NestedNameSpecifierLoc NextNode = Node.getPrefix();
3294 return InnerMatcher.matches(NextNode, Finder, Builder);
3297 /// \brief Matches nested name specifiers that specify a namespace matching the
3298 /// given namespace matcher.
3302 /// namespace ns { struct A {}; }
3305 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3307 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3308 internal::Matcher<NamespaceDecl>, InnerMatcher) {
3309 if (Node.getAsNamespace() == NULL)
3311 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3314 /// \brief Overloads for the \c equalsNode matcher.
3315 /// FIXME: Implement for other node types.
3318 /// \brief Matches if a node equals another node.
3320 /// \c Decl has pointer identity in the AST.
3321 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) {
3322 return &Node == Other;
3324 /// \brief Matches if a node equals another node.
3326 /// \c Stmt has pointer identity in the AST.
3328 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) {
3329 return &Node == Other;
3334 } // end namespace ast_matchers
3335 } // end namespace clang
3337 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H