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 // record(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 // record(hasName("MyClass"), hasChild(id("child", record())))
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 adding id(...) matchers into the
61 /// match expression around the matchers for the nodes we want to access later.
63 /// The instances of BoundNodes are created by MatchFinder when the user's
64 /// callbacks are executed every time a match is found.
67 /// \brief Returns the AST node bound to 'ID'.
68 /// Returns NULL if there was no node bound to 'ID' or if there is a node but
69 /// it cannot be converted to the specified type.
70 /// FIXME: We'll need one of those for every base type.
73 const T *getDeclAs(StringRef ID) const {
74 return getNodeAs<T>(DeclBindings, ID);
77 const T *getStmtAs(StringRef ID) const {
78 return getNodeAs<T>(StmtBindings, ID);
83 /// \brief Create BoundNodes from a pre-filled map of bindings.
84 BoundNodes(const std::map<std::string, const Decl*> &DeclBindings,
85 const std::map<std::string, const Stmt*> &StmtBindings)
86 : DeclBindings(DeclBindings), StmtBindings(StmtBindings) {}
88 template <typename T, typename MapT>
89 const T *getNodeAs(const MapT &Bindings, StringRef ID) const {
90 typename MapT::const_iterator It = Bindings.find(ID);
91 if (It == Bindings.end()) {
94 return llvm::dyn_cast<T>(It->second);
97 std::map<std::string, const Decl*> DeclBindings;
98 std::map<std::string, const Stmt*> StmtBindings;
100 friend class internal::BoundNodesTree;
103 /// \brief If the provided matcher matches a node, binds the node to 'ID'.
105 /// FIXME: Add example for accessing it.
106 template <typename T>
107 internal::Matcher<T> id(const std::string &ID,
108 const internal::BindableMatcher<T> &InnerMatcher) {
109 return InnerMatcher.bind(ID);
112 /// \brief Types of matchers for the top-level classes in the AST class
115 typedef internal::Matcher<Decl> DeclarationMatcher;
116 typedef internal::Matcher<QualType> TypeMatcher;
117 typedef internal::Matcher<Stmt> StatementMatcher;
120 /// \brief Matches any node.
122 /// Useful when another matcher requires a child matcher, but there's no
123 /// additional constraint. This will often be used with an explicit conversion
124 /// to a internal::Matcher<> type such as TypeMatcher.
126 /// Example: DeclarationMatcher(anything()) matches all declarations, e.g.,
127 /// "int* p" and "void f()" in
130 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() {
131 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
134 /// \brief Matches declarations.
136 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
143 const internal::VariadicDynCastAllOfMatcher<Decl, Decl> decl;
145 /// \brief Matches a declaration of anything that could have a name.
147 /// Example matches X, S, the anonymous union type, i, and U;
154 const internal::VariadicDynCastAllOfMatcher<
156 NamedDecl> nameableDeclaration;
158 /// \brief Matches C++ class declarations.
160 /// Example matches X, Z
162 /// template<class T> class Z {};
163 const internal::VariadicDynCastAllOfMatcher<
165 CXXRecordDecl> record;
167 /// \brief Matches C++ class template specializations.
170 /// template<typename T> class A {};
171 /// template<> class A<double> {};
173 /// classTemplateSpecialization()
174 /// matches the specializations \c A<int> and \c A<double>
175 const internal::VariadicDynCastAllOfMatcher<
177 ClassTemplateSpecializationDecl> classTemplateSpecialization;
179 /// \brief Matches classTemplateSpecializations that have at least one
180 /// TemplateArgument matching the given Matcher.
183 /// template<typename T> class A {};
184 /// template<> class A<double> {};
186 /// classTemplateSpecialization(hasAnyTemplateArgument(
187 /// refersToType(asString("int"))))
188 /// matches the specialization \c A<int>
189 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
190 internal::Matcher<TemplateArgument>, Matcher) {
191 const TemplateArgumentList &List = Node.getTemplateArgs();
192 for (unsigned i = 0; i < List.size(); ++i) {
193 if (Matcher.matches(List.get(i), Finder, Builder))
199 /// \brief Matches expressions that match InnerMatcher after any implicit casts
200 /// are stripped off.
202 /// Parentheses and explicit casts are not discarded.
209 /// long e = (long) 0l;
211 /// variable(hasInitializer(ignoringImpCasts(integerLiteral())))
212 /// variable(hasInitializer(ignoringImpCasts(declarationReference())))
213 /// would match the declarations for a, b, c, and d, but not e.
215 /// variable(hasInitializer(integerLiteral()))
216 /// variable(hasInitializer(declarationReference()))
217 /// only match the declarations for b, c, and d.
218 AST_MATCHER_P(Expr, ignoringImpCasts,
219 internal::Matcher<Expr>, InnerMatcher) {
220 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
223 /// \brief Matches expressions that match InnerMatcher after parentheses and
224 /// casts are stripped off.
226 /// Implicit and non-C Style casts are also discarded.
230 /// void* c = reinterpret_cast<char*>(0);
231 /// char d = char(0);
233 /// variable(hasInitializer(ignoringParenCasts(integerLiteral())))
234 /// would match the declarations for a, b, c, and d.
236 /// variable(hasInitializer(integerLiteral()))
237 /// only match the declaration for a.
238 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
239 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
242 /// \brief Matches expressions that match InnerMatcher after implicit casts and
243 /// parentheses are stripped off.
245 /// Explicit casts are not discarded.
252 /// long e = ((long) 0l);
254 /// variable(hasInitializer(ignoringParenImpCasts(
255 /// integerLiteral())))
256 /// variable(hasInitializer(ignoringParenImpCasts(
257 /// declarationReference())))
258 /// would match the declarations for a, b, c, and d, but not e.
260 /// variable(hasInitializer(integerLiteral()))
261 /// variable(hasInitializer(declarationReference()))
262 /// would only match the declaration for a.
263 AST_MATCHER_P(Expr, ignoringParenImpCasts,
264 internal::Matcher<Expr>, InnerMatcher) {
265 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
268 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
269 /// matches the given Matcher.
272 /// template<typename T, typename U> class A {};
275 /// classTemplateSpecialization(hasTemplateArgument(
276 /// 1, refersToType(asString("int"))))
277 /// matches the specialization \c A<bool, int>
278 AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
279 unsigned, N, internal::Matcher<TemplateArgument>, Matcher) {
280 const TemplateArgumentList &List = Node.getTemplateArgs();
281 if (List.size() <= N)
283 return Matcher.matches(List.get(N), Finder, Builder);
286 /// \brief Matches a TemplateArgument that refers to a certain type.
290 /// template<typename T> struct A {};
292 /// classTemplateSpecialization(hasAnyTemplateArgument(
293 /// refersToType(class(hasName("X")))))
294 /// matches the specialization \c A<X>
295 AST_MATCHER_P(TemplateArgument, refersToType,
296 internal::Matcher<QualType>, Matcher) {
297 if (Node.getKind() != TemplateArgument::Type)
299 return Matcher.matches(Node.getAsType(), Finder, Builder);
302 /// \brief Matches a TemplateArgument that refers to a certain declaration.
305 /// template<typename T> struct A {};
306 /// struct B { B* next; };
308 /// classTemplateSpecialization(hasAnyTemplateArgument(
309 /// refersToDeclaration(field(hasName("next"))))
310 /// matches the specialization \c A<&B::next> with \c field(...) matching
312 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
313 internal::Matcher<Decl>, Matcher) {
314 if (const Decl *Declaration = Node.getAsDecl())
315 return Matcher.matches(*Declaration, Finder, Builder);
319 /// \brief Matches C++ constructor declarations.
321 /// Example matches Foo::Foo() and Foo::Foo(int)
326 /// int DoSomething();
328 const internal::VariadicDynCastAllOfMatcher<
330 CXXConstructorDecl> constructor;
332 /// \brief Matches explicit C++ destructor declarations.
334 /// Example matches Foo::~Foo()
339 const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> destructor;
341 /// \brief Matches enum declarations.
343 /// Example matches X
347 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
349 /// \brief Matches enum constants.
351 /// Example matches A, B, C
355 const internal::VariadicDynCastAllOfMatcher<
357 EnumConstantDecl> enumConstant;
359 /// \brief Matches method declarations.
361 /// Example matches y
362 /// class X { void y() };
363 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> method;
365 /// \brief Matches variable declarations.
367 /// Note: this does not match declarations of member variables, which are
368 /// "field" declarations in Clang parlance.
370 /// Example matches a
372 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> variable;
374 /// \brief Matches field declarations.
377 /// class X { int m; };
380 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> field;
382 /// \brief Matches function declarations.
384 /// Example matches f
386 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> function;
389 /// \brief Matches statements.
394 /// matches both the compound statement '{ ++a; }' and '++a'.
395 const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> statement;
397 /// \brief Matches declaration statements.
401 /// declarationStatement()
403 const internal::VariadicDynCastAllOfMatcher<
405 DeclStmt> declarationStatement;
407 /// \brief Matches member expressions.
411 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
412 /// int a; static int b;
414 /// memberExpression()
415 /// matches this->x, x, y.x, a, this->b
416 const internal::VariadicDynCastAllOfMatcher<
418 MemberExpr> memberExpression;
420 /// \brief Matches call expressions.
422 /// Example matches x.y() and y()
426 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> call;
428 /// \brief Matches member call expressions.
430 /// Example matches x.y()
433 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr> memberCall;
435 /// \brief Matches init list expressions.
438 /// int a[] = { 1, 2 };
439 /// struct B { int x, y; };
442 /// matches "{ 1, 2 }" and "{ 5, 6 }"
443 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
445 /// \brief Matches using declarations.
448 /// namespace X { int x; }
451 /// matches \code using X::x \endcode
452 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
454 /// \brief Matches constructor call expressions (including implicit ones).
456 /// Example matches string(ptr, n) and ptr within arguments of f
457 /// (matcher = constructorCall())
458 /// void f(const string &a, const string &b);
461 /// f(string(ptr, n), ptr);
462 const internal::VariadicDynCastAllOfMatcher<
464 CXXConstructExpr> constructorCall;
466 /// \brief Matches nodes where temporaries are created.
468 /// Example matches FunctionTakesString(GetStringByValue())
469 /// (matcher = bindTemporaryExpression())
470 /// FunctionTakesString(GetStringByValue());
471 /// FunctionTakesStringByPointer(GetStringPointer());
472 const internal::VariadicDynCastAllOfMatcher<
474 CXXBindTemporaryExpr> bindTemporaryExpression;
476 /// \brief Matches new expressions.
482 const internal::VariadicDynCastAllOfMatcher<
484 CXXNewExpr> newExpression;
486 /// \brief Matches delete expressions.
490 /// deleteExpression()
491 /// matches 'delete X'.
492 const internal::VariadicDynCastAllOfMatcher<
494 CXXDeleteExpr> deleteExpression;
496 /// \brief Matches array subscript expressions.
500 /// arraySubscriptExpr()
502 const internal::VariadicDynCastAllOfMatcher<
504 ArraySubscriptExpr> arraySubscriptExpr;
506 /// \brief Matches the value of a default argument at the call site.
508 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
509 /// default value of the second parameter in the call expression f(42)
510 /// (matcher = defaultArgument())
511 /// void f(int x, int y = 0);
513 const internal::VariadicDynCastAllOfMatcher<
515 CXXDefaultArgExpr> defaultArgument;
517 /// \brief Matches overloaded operator calls.
519 /// Note that if an operator isn't overloaded, it won't match. Instead, use
520 /// binaryOperator matcher.
521 /// Currently it does not match operators such as new delete.
522 /// FIXME: figure out why these do not match?
524 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
525 /// (matcher = overloadedOperatorCall())
526 /// ostream &operator<< (ostream &out, int i) { };
527 /// ostream &o; int b = 1, c = 1;
529 const internal::VariadicDynCastAllOfMatcher<
531 CXXOperatorCallExpr> overloadedOperatorCall;
533 /// \brief Matches expressions.
535 /// Example matches x()
536 /// void f() { x(); }
537 const internal::VariadicDynCastAllOfMatcher<
541 /// \brief Matches expressions that refer to declarations.
543 /// Example matches x in if (x)
546 const internal::VariadicDynCastAllOfMatcher<
548 DeclRefExpr> declarationReference;
550 /// \brief Matches if statements.
552 /// Example matches 'if (x) {}'
554 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
556 /// \brief Matches for statements.
558 /// Example matches 'for (;;) {}'
560 const internal::VariadicDynCastAllOfMatcher<
561 Stmt, ForStmt> forStmt;
563 /// \brief Matches the increment statement of a for loop.
566 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
568 /// for (x; x < N; ++x) { }
569 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
571 const Stmt *const Increment = Node.getInc();
572 return (Increment != NULL &&
573 InnerMatcher.matches(*Increment, Finder, Builder));
576 /// \brief Matches the initialization statement of a for loop.
579 /// forStmt(hasLoopInit(declarationStatement()))
580 /// matches 'int x = 0' in
581 /// for (int x = 0; x < N; ++x) { }
582 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
584 const Stmt *const Init = Node.getInit();
585 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
588 /// \brief Matches while statements.
593 /// matches 'while (true) {}'.
594 const internal::VariadicDynCastAllOfMatcher<
596 WhileStmt> whileStmt;
598 /// \brief Matches do statements.
601 /// do {} while (true);
603 /// matches 'do {} while(true)'
604 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
606 /// \brief Matches case and default statements inside switch statements.
609 /// switch(a) { case 42: break; default: break; }
611 /// matches 'case 42: break;' and 'default: break;'.
612 const internal::VariadicDynCastAllOfMatcher<
614 SwitchCase> switchCase;
616 /// \brief Matches compound statements.
618 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
620 const internal::VariadicDynCastAllOfMatcher<
622 CompoundStmt> compoundStatement;
624 /// \brief Matches bool literals.
626 /// Example matches true
628 const internal::VariadicDynCastAllOfMatcher<
630 CXXBoolLiteralExpr> boolLiteral;
632 /// \brief Matches string literals (also matches wide string literals).
634 /// Example matches "abcd", L"abcd"
635 /// char *s = "abcd"; wchar_t *ws = L"abcd"
636 const internal::VariadicDynCastAllOfMatcher<
638 StringLiteral> stringLiteral;
640 /// \brief Matches character literals (also matches wchar_t).
642 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
645 /// Example matches 'a', L'a'
646 /// char ch = 'a'; wchar_t chw = L'a';
647 const internal::VariadicDynCastAllOfMatcher<
649 CharacterLiteral> characterLiteral;
651 /// \brief Matches integer literals of all sizes / encodings.
653 /// Not matching character-encoded integers such as L'a'.
655 /// Example matches 1, 1L, 0x1, 1U
656 const internal::VariadicDynCastAllOfMatcher<
658 IntegerLiteral> integerLiteral;
660 /// \brief Matches binary operator expressions.
662 /// Example matches a || b
664 const internal::VariadicDynCastAllOfMatcher<
666 BinaryOperator> binaryOperator;
668 /// \brief Matches unary operator expressions.
670 /// Example matches !a
672 const internal::VariadicDynCastAllOfMatcher<
674 UnaryOperator> unaryOperator;
676 /// \brief Matches conditional operator expressions.
678 /// Example matches a ? b : c
680 const internal::VariadicDynCastAllOfMatcher<
682 ConditionalOperator> conditionalOperator;
684 /// \brief Matches a reinterpret_cast expression.
686 /// Either the source expression or the destination type can be matched
687 /// using has(), but hasDestinationType() is more specific and can be
690 /// Example matches reinterpret_cast<char*>(&p) in
691 /// void* p = reinterpret_cast<char*>(&p);
692 const internal::VariadicDynCastAllOfMatcher<
694 CXXReinterpretCastExpr> reinterpretCast;
696 /// \brief Matches a C++ static_cast expression.
698 /// \see hasDestinationType
699 /// \see reinterpretCast
704 /// static_cast<long>(8)
706 /// long eight(static_cast<long>(8));
707 const internal::VariadicDynCastAllOfMatcher<
709 CXXStaticCastExpr> staticCast;
711 /// \brief Matches a dynamic_cast expression.
716 /// dynamic_cast<D*>(&b);
718 /// struct B { virtual ~B() {} }; struct D : B {};
720 /// D* p = dynamic_cast<D*>(&b);
721 const internal::VariadicDynCastAllOfMatcher<
723 CXXDynamicCastExpr> dynamicCast;
725 /// \brief Matches a const_cast expression.
727 /// Example: Matches const_cast<int*>(&r) in
730 /// int* p = const_cast<int*>(&r);
731 const internal::VariadicDynCastAllOfMatcher<
733 CXXConstCastExpr> constCast;
735 /// \brief Matches explicit cast expressions.
737 /// Matches any cast expression written in user code, whether it be a
738 /// C-style cast, a functional-style cast, or a keyword cast.
740 /// Does not match implicit conversions.
742 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
743 /// Clang uses the term "cast" to apply to implicit conversions as well as to
744 /// actual cast expressions.
746 /// \see hasDestinationType.
748 /// Example: matches all five of the casts in
749 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
750 /// but does not match the implicit conversion in
752 const internal::VariadicDynCastAllOfMatcher<
754 ExplicitCastExpr> explicitCast;
756 /// \brief Matches the implicit cast nodes of Clang's AST.
758 /// This matches many different places, including function call return value
759 /// eliding, as well as any type conversions.
760 const internal::VariadicDynCastAllOfMatcher<
762 ImplicitCastExpr> implicitCast;
764 /// \brief Matches any cast nodes of Clang's AST.
766 /// Example: castExpr() matches each of the following:
768 /// const_cast<Expr *>(SubExpr);
770 /// but does not match
773 const internal::VariadicDynCastAllOfMatcher<
777 /// \brief Matches functional cast expressions
779 /// Example: Matches Foo(bar);
781 /// Foo g = (Foo) bar;
782 /// Foo h = Foo(bar);
783 const internal::VariadicDynCastAllOfMatcher<
785 CXXFunctionalCastExpr> functionalCast;
787 /// \brief Various overloads for the anyOf matcher.
789 template<typename C1, typename C2>
790 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, C2>
791 anyOf(const C1 &P1, const C2 &P2) {
792 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
795 template<typename C1, typename C2, typename C3>
796 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
797 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, C3> >
798 anyOf(const C1 &P1, const C2 &P2, const C3 &P3) {
799 return anyOf(P1, anyOf(P2, P3));
801 template<typename C1, typename C2, typename C3, typename C4>
802 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
803 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2,
804 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
806 anyOf(const C1 &P1, const C2 &P2, const C3 &P3, const C4 &P4) {
807 return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
809 template<typename C1, typename C2, typename C3, typename C4, typename C5>
810 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
811 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2,
812 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C3,
813 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
815 anyOf(const C1& P1, const C2& P2, const C3& P3, const C4& P4, const C5& P5) {
816 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
820 /// \brief Various overloads for the allOf matcher.
822 template<typename C1, typename C2>
823 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, C2>
824 allOf(const C1 &P1, const C2 &P2) {
825 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher,
828 template<typename C1, typename C2, typename C3>
829 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1,
830 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C2, C3> >
831 allOf(const C1& P1, const C2& P2, const C3& P3) {
832 return allOf(P1, allOf(P2, P3));
836 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
840 /// int y = sizeof(x) + alignof(x);
841 /// unaryExprOrTypeTraitExpr()
842 /// matches \c sizeof(x) and \c alignof(x)
843 const internal::VariadicDynCastAllOfMatcher<
845 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
847 /// \brief Matches unary expressions that have a specific type of argument.
850 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
851 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
852 /// matches \c sizeof(a) and \c alignof(c)
853 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
854 internal::Matcher<QualType>, Matcher) {
855 const QualType ArgumentType = Node.getTypeOfArgument();
856 return Matcher.matches(ArgumentType, Finder, Builder);
859 /// \brief Matches unary expressions of a certain kind.
863 /// int s = sizeof(x) + alignof(x)
864 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
865 /// matches \c sizeof(x)
866 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
867 return Node.getKind() == Kind;
870 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
872 inline internal::Matcher<Stmt> alignOfExpr(
873 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) {
874 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
875 ofKind(UETT_AlignOf), Matcher)));
878 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
880 inline internal::Matcher<Stmt> sizeOfExpr(
881 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) {
882 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
883 ofKind(UETT_SizeOf), Matcher)));
886 /// \brief Matches NamedDecl nodes that have the specified name.
888 /// Supports specifying enclosing namespaces or classes by prefixing the name
889 /// with '<enclosing>::'.
890 /// Does not match typedefs of an underlying type with the given name.
892 /// Example matches X (Name == "X")
895 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
896 /// namespace a { namespace b { class X; } }
897 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
898 assert(!Name.empty());
899 const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
900 const llvm::StringRef FullName = FullNameString;
901 const llvm::StringRef Pattern = Name;
902 if (Pattern.startswith("::")) {
903 return FullName == Pattern;
905 return FullName.endswith(("::" + Pattern).str());
909 /// \brief Matches NamedDecl nodes whose full names partially match the
912 /// Supports specifying enclosing namespaces or classes by
913 /// prefixing the name with '<enclosing>::'. Does not match typedefs
914 /// of an underlying type with the given name.
916 /// Example matches X (regexp == "::X")
919 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
920 /// namespace foo { namespace bar { class X; } }
921 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
922 assert(!RegExp.empty());
923 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
924 llvm::Regex RE(RegExp);
925 return RE.match(FullNameString);
928 /// \brief Matches overloaded operator names.
930 /// Matches overloaded operator names specified in strings without the
931 /// "operator" prefix, such as "<<", for OverloadedOperatorCall's.
933 /// Example matches a << b
934 /// (matcher == overloadedOperatorCall(hasOverloadedOperatorName("<<")))
936 /// c && d; // assuming both operator<<
937 /// // and operator&& are overloaded somewhere.
938 AST_MATCHER_P(CXXOperatorCallExpr,
939 hasOverloadedOperatorName, std::string, Name) {
940 return getOperatorSpelling(Node.getOperator()) == Name;
943 /// \brief Matches C++ classes that are directly or indirectly derived from
944 /// a class matching \c Base.
946 /// Note that a class is considered to be also derived from itself.
948 /// Example matches X, Y, Z, C (Base == hasName("X"))
949 /// class X; // A class is considered to be derived from itself
950 /// class Y : public X {}; // directly derived
951 /// class Z : public Y {}; // indirectly derived
954 /// class C : public B {}; // derived from a typedef of X
956 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
959 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
960 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
961 internal::Matcher<NamedDecl>, Base) {
962 return Finder->classIsDerivedFrom(&Node, Base, Builder);
965 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
966 inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
967 assert(!BaseName.empty());
968 return isDerivedFrom(hasName(BaseName));
971 /// \brief Matches AST nodes that have child AST nodes that match the
972 /// provided matcher.
974 /// Example matches X, Y (matcher = record(has(record(hasName("X")))
975 /// class X {}; // Matches X, because X::X is a class of name X inside X.
976 /// class Y { class X {}; };
977 /// class Z { class Y { class X {}; }; }; // Does not match Z.
979 /// ChildT must be an AST base type.
980 template <typename ChildT>
981 internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
982 const internal::Matcher<ChildT> &ChildMatcher) {
983 return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
984 ChildT>(ChildMatcher);
987 /// \brief Matches AST nodes that have descendant AST nodes that match the
988 /// provided matcher.
990 /// Example matches X, Y, Z
991 /// (matcher = record(hasDescendant(record(hasName("X")))))
992 /// class X {}; // Matches X, because X::X is a class of name X inside X.
993 /// class Y { class X {}; };
994 /// class Z { class Y { class X {}; }; };
996 /// DescendantT must be an AST base type.
997 template <typename DescendantT>
998 internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
999 hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1000 return internal::ArgumentAdaptingMatcher<
1001 internal::HasDescendantMatcher,
1002 DescendantT>(DescendantMatcher);
1006 /// \brief Matches AST nodes that have child AST nodes that match the
1007 /// provided matcher.
1009 /// Example matches X, Y (matcher = record(forEach(record(hasName("X")))
1010 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1011 /// class Y { class X {}; };
1012 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1014 /// ChildT must be an AST base type.
1016 /// As opposed to 'has', 'forEach' will cause a match for each result that
1017 /// matches instead of only on the first one.
1018 template <typename ChildT>
1019 internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1020 const internal::Matcher<ChildT>& ChildMatcher) {
1021 return internal::ArgumentAdaptingMatcher<
1022 internal::ForEachMatcher,
1023 ChildT>(ChildMatcher);
1026 /// \brief Matches AST nodes that have descendant AST nodes that match the
1027 /// provided matcher.
1029 /// Example matches X, A, B, C
1030 /// (matcher = record(forEachDescendant(record(hasName("X")))))
1031 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1032 /// class A { class X {}; };
1033 /// class B { class C { class X {}; }; };
1035 /// DescendantT must be an AST base type.
1037 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1038 /// each result that matches instead of only on the first one.
1040 /// Note: Recursively combined ForEachDescendant can cause many matches:
1041 /// record(forEachDescendant(record(forEachDescendant(record()))))
1042 /// will match 10 times (plus injected class name matches) on:
1043 /// class A { class B { class C { class D { class E {}; }; }; }; };
1044 template <typename DescendantT>
1045 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT>
1047 const internal::Matcher<DescendantT>& DescendantMatcher) {
1048 return internal::ArgumentAdaptingMatcher<
1049 internal::ForEachDescendantMatcher,
1050 DescendantT>(DescendantMatcher);
1053 /// \brief Matches if the provided matcher does not match.
1055 /// Example matches Y (matcher = record(unless(hasName("X"))))
1058 template <typename M>
1059 internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> unless(const M &InnerMatcher) {
1060 return internal::PolymorphicMatcherWithParam1<
1061 internal::NotMatcher, M>(InnerMatcher);
1064 /// \brief Matches a type if the declaration of the type matches the given
1067 /// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>
1068 inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1069 internal::Matcher<Decl> >
1070 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1071 return internal::PolymorphicMatcherWithParam1<
1072 internal::HasDeclarationMatcher,
1073 internal::Matcher<Decl> >(InnerMatcher);
1076 /// \brief Matches on the implicit object argument of a member call expression.
1078 /// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y"))))))
1079 /// class Y { public: void x(); };
1080 /// void z() { Y y; y.x(); }",
1082 /// FIXME: Overload to allow directly matching types?
1083 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1085 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node)
1086 .getImplicitObjectArgument()
1087 ->IgnoreParenImpCasts();
1088 return (ExprNode != NULL &&
1089 InnerMatcher.matches(*ExprNode, Finder, Builder));
1092 /// \brief Matches if the call expression's callee expression matches.
1095 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
1096 /// void f() { f(); }
1097 /// call(callee(expression()))
1098 /// matches this->x(), x(), y.x(), f()
1099 /// with callee(...)
1100 /// matching this->x, x, y.x, f respectively
1102 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1103 /// because this introduces ambiguous overloads with calls to Callee taking a
1104 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1105 /// implemented in terms of implicit casts.
1106 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1108 const Expr *ExprNode = Node.getCallee();
1109 return (ExprNode != NULL &&
1110 InnerMatcher.matches(*ExprNode, Finder, Builder));
1113 /// \brief Matches if the call expression's callee's declaration matches the
1116 /// Example matches y.x() (matcher = call(callee(method(hasName("x")))))
1117 /// class Y { public: void x(); };
1118 /// void z() { Y y; y.x();
1119 inline internal::Matcher<CallExpr> callee(
1120 const internal::Matcher<Decl> &InnerMatcher) {
1121 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher));
1124 /// \brief Matches if the expression's or declaration's type matches a type
1127 /// Example matches x (matcher = expression(hasType(
1128 /// hasDeclaration(record(hasName("X"))))))
1129 /// and z (matcher = variable(hasType(
1130 /// hasDeclaration(record(hasName("X"))))))
1132 /// void y(X &x) { x; X z; }
1133 AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1135 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1136 llvm::is_base_of<ValueDecl, NodeType>::value),
1137 instantiated_with_wrong_types);
1138 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1141 /// \brief Overloaded to match the declaration of the expression's or value
1142 /// declaration's type.
1144 /// In case of a value declaration (for example a variable declaration),
1145 /// this resolves one layer of indirection. For example, in the value
1146 /// declaration "X x;", record(hasName("X")) matches the declaration of X,
1147 /// while variable(hasType(record(hasName("X")))) matches the declaration
1150 /// Example matches x (matcher = expression(hasType(record(hasName("X")))))
1151 /// and z (matcher = variable(hasType(record(hasName("X")))))
1153 /// void y(X &x) { x; X z; }
1155 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1156 inline internal::PolymorphicMatcherWithParam1<
1157 internal::matcher_hasTypeMatcher,
1158 internal::Matcher<QualType> >
1159 hasType(const internal::Matcher<Decl> &InnerMatcher) {
1160 return hasType(internal::Matcher<QualType>(
1161 hasDeclaration(InnerMatcher)));
1164 /// \brief Matches if the matched type is represented by the given string.
1167 /// class Y { public: void x(); };
1168 /// void z() { Y* y; y->x(); }
1169 /// call(on(hasType(asString("class Y *"))))
1171 AST_MATCHER_P(QualType, asString, std::string, Name) {
1172 return Name == Node.getAsString();
1175 /// \brief Matches if the matched type is a pointer type and the pointee type
1176 /// matches the specified matcher.
1178 /// Example matches y->x()
1179 /// (matcher = call(on(hasType(pointsTo(record(hasName("Y")))))))
1180 /// class Y { public: void x(); };
1181 /// void z() { Y *y; y->x(); }
1183 QualType, pointsTo, internal::Matcher<QualType>,
1185 return (!Node.isNull() && Node->isPointerType() &&
1186 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1189 /// \brief Overloaded to match the pointee type's declaration.
1190 inline internal::Matcher<QualType> pointsTo(
1191 const internal::Matcher<Decl> &InnerMatcher) {
1192 return pointsTo(internal::Matcher<QualType>(
1193 hasDeclaration(InnerMatcher)));
1196 /// \brief Matches if the matched type is a reference type and the referenced
1197 /// type matches the specified matcher.
1199 /// Example matches X &x and const X &y
1200 /// (matcher = variable(hasType(references(record(hasName("X"))))))
1206 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1208 return (!Node.isNull() && Node->isReferenceType() &&
1209 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1212 /// \brief Overloaded to match the referenced type's declaration.
1213 inline internal::Matcher<QualType> references(
1214 const internal::Matcher<Decl> &InnerMatcher) {
1215 return references(internal::Matcher<QualType>(
1216 hasDeclaration(InnerMatcher)));
1219 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1220 internal::Matcher<Expr>, InnerMatcher) {
1221 const Expr *ExprNode =
1222 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument();
1223 return (ExprNode != NULL &&
1224 InnerMatcher.matches(*ExprNode, Finder, Builder));
1227 /// \brief Matches if the expression's type either matches the specified
1228 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1229 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1230 const internal::Matcher<QualType> &InnerMatcher) {
1231 return onImplicitObjectArgument(
1232 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1235 /// \brief Overloaded to match the type's declaration.
1236 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1237 const internal::Matcher<Decl> &InnerMatcher) {
1238 return onImplicitObjectArgument(
1239 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1242 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1243 /// specified matcher.
1245 /// Example matches x in if(x)
1246 /// (matcher = declarationReference(to(variable(hasName("x")))))
1249 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1251 const Decl *DeclNode = Node.getDecl();
1252 return (DeclNode != NULL &&
1253 InnerMatcher.matches(*DeclNode, Finder, Builder));
1256 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1257 /// specific using shadow declaration.
1259 /// FIXME: This currently only works for functions. Fix.
1262 /// namespace a { void f() {} }
1265 /// f(); // Matches this ..
1266 /// a::f(); // .. but not this.
1268 /// declarationReference(throughUsingDeclaration(anything()))
1270 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1271 internal::Matcher<UsingShadowDecl>, Matcher) {
1272 const NamedDecl *FoundDecl = Node.getFoundDecl();
1273 if (const UsingShadowDecl *UsingDecl =
1274 llvm::dyn_cast<UsingShadowDecl>(FoundDecl))
1275 return Matcher.matches(*UsingDecl, Finder, Builder);
1279 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
1284 /// declarationStatement(hasSingleDecl(anything()))
1285 /// matches 'int c;' but not 'int a, b;'.
1286 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1287 if (Node.isSingleDecl()) {
1288 const Decl *FoundDecl = Node.getSingleDecl();
1289 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1294 /// \brief Matches a variable declaration that has an initializer expression
1295 /// that matches the given matcher.
1297 /// Example matches x (matcher = variable(hasInitializer(call())))
1298 /// bool y() { return true; }
1301 VarDecl, hasInitializer, internal::Matcher<Expr>,
1303 const Expr *Initializer = Node.getAnyInitializer();
1304 return (Initializer != NULL &&
1305 InnerMatcher.matches(*Initializer, Finder, Builder));
1308 /// \brief Checks that a call expression or a constructor call expression has
1309 /// a specific number of arguments (including absent default arguments).
1311 /// Example matches f(0, 0) (matcher = call(argumentCountIs(2)))
1312 /// void f(int x, int y);
1314 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1315 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1316 llvm::is_base_of<CXXConstructExpr,
1318 instantiated_with_wrong_types);
1319 return Node.getNumArgs() == N;
1322 /// \brief Matches the n'th argument of a call expression or a constructor
1323 /// call expression.
1325 /// Example matches y in x(y)
1326 /// (matcher = call(hasArgument(0, declarationReference())))
1327 /// void x(int) { int y; x(y); }
1328 AST_POLYMORPHIC_MATCHER_P2(
1329 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1330 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1331 llvm::is_base_of<CXXConstructExpr,
1333 instantiated_with_wrong_types);
1334 return (N < Node.getNumArgs() &&
1335 InnerMatcher.matches(
1336 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1339 /// \brief Matches declaration statements that contain a specific number of
1347 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
1348 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
1349 return std::distance(Node.decl_begin(), Node.decl_end()) == N;
1352 /// \brief Matches the n'th declaration of a declaration statement.
1354 /// Note that this does not work for global declarations because the AST
1355 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
1357 /// Example: Given non-global declarations
1361 /// declarationStatement(containsDeclaration(
1362 /// 0, variable(hasInitializer(anything()))))
1363 /// matches only 'int d = 2, e;', and
1364 /// declarationStatement(containsDeclaration(1, variable()))
1365 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
1366 /// but 'int c;' is not matched.
1367 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
1368 internal::Matcher<Decl>, InnerMatcher) {
1369 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
1372 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
1373 std::advance(Iterator, N);
1374 return InnerMatcher.matches(**Iterator, Finder, Builder);
1377 /// \brief Matches a constructor initializer.
1381 /// Foo() : foo_(1) { }
1384 /// record(has(constructor(hasAnyConstructorInitializer(anything()))))
1385 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
1386 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
1387 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
1388 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
1389 I != Node.init_end(); ++I) {
1390 if (InnerMatcher.matches(**I, Finder, Builder)) {
1397 /// \brief Matches the field declaration of a constructor initializer.
1401 /// Foo() : foo_(1) { }
1404 /// record(has(constructor(hasAnyConstructorInitializer(
1405 /// forField(hasName("foo_"))))))
1407 /// with forField matching foo_
1408 AST_MATCHER_P(CXXCtorInitializer, forField,
1409 internal::Matcher<FieldDecl>, InnerMatcher) {
1410 const FieldDecl *NodeAsDecl = Node.getMember();
1411 return (NodeAsDecl != NULL &&
1412 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
1415 /// \brief Matches the initializer expression of a constructor initializer.
1419 /// Foo() : foo_(1) { }
1422 /// record(has(constructor(hasAnyConstructorInitializer(
1423 /// withInitializer(integerLiteral(equals(1)))))))
1425 /// with withInitializer matching (1)
1426 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
1427 internal::Matcher<Expr>, InnerMatcher) {
1428 const Expr* NodeAsExpr = Node.getInit();
1429 return (NodeAsExpr != NULL &&
1430 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
1433 /// \brief Matches a contructor initializer if it is explicitly written in
1434 /// code (as opposed to implicitly added by the compiler).
1439 /// Foo(int) : foo_("A") { }
1442 /// constructor(hasAnyConstructorInitializer(isWritten()))
1443 /// will match Foo(int), but not Foo()
1444 AST_MATCHER(CXXCtorInitializer, isWritten) {
1445 return Node.isWritten();
1448 /// \brief Matches a constructor declaration that has been implicitly added
1449 /// by the compiler (eg. implicit default/copy constructors).
1450 AST_MATCHER(CXXConstructorDecl, isImplicit) {
1451 return Node.isImplicit();
1454 /// \brief Matches any argument of a call expression or a constructor call
1458 /// void x(int, int, int) { int y; x(1, y, 42); }
1459 /// call(hasAnyArgument(declarationReference()))
1460 /// matches x(1, y, 42)
1461 /// with hasAnyArgument(...)
1463 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
1465 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1466 llvm::is_base_of<CXXConstructExpr,
1468 instantiated_with_wrong_types);
1469 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
1470 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
1478 /// \brief Matches the n'th parameter of a function declaration.
1481 /// class X { void f(int x) {} };
1482 /// method(hasParameter(0, hasType(variable())))
1483 /// matches f(int x) {}
1484 /// with hasParameter(...)
1486 AST_MATCHER_P2(FunctionDecl, hasParameter,
1487 unsigned, N, internal::Matcher<ParmVarDecl>,
1489 return (N < Node.getNumParams() &&
1490 InnerMatcher.matches(
1491 *Node.getParamDecl(N), Finder, Builder));
1494 /// \brief Matches any parameter of a function declaration.
1496 /// Does not match the 'this' parameter of a method.
1499 /// class X { void f(int x, int y, int z) {} };
1500 /// method(hasAnyParameter(hasName("y")))
1501 /// matches f(int x, int y, int z) {}
1502 /// with hasAnyParameter(...)
1504 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
1505 internal::Matcher<ParmVarDecl>, InnerMatcher) {
1506 for (unsigned I = 0; I < Node.getNumParams(); ++I) {
1507 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
1514 /// \brief Matches the return type of a function declaration.
1517 /// class X { int f() { return 1; } };
1518 /// method(returns(asString("int")))
1519 /// matches int f() { return 1; }
1520 AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, Matcher) {
1521 return Matcher.matches(Node.getResultType(), Finder, Builder);
1524 /// \brief Matches extern "C" function declarations.
1527 /// extern "C" void f() {}
1528 /// extern "C" { void g() {} }
1530 /// function(isExternC())
1531 /// matches the declaration of f and g, but not the declaration h
1532 AST_MATCHER(FunctionDecl, isExternC) {
1533 return Node.isExternC();
1536 /// \brief Matches the condition expression of an if statement, for loop,
1537 /// or conditional operator.
1539 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
1541 AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
1543 TOOLING_COMPILE_ASSERT(
1544 (llvm::is_base_of<IfStmt, NodeType>::value) ||
1545 (llvm::is_base_of<ForStmt, NodeType>::value) ||
1546 (llvm::is_base_of<WhileStmt, NodeType>::value) ||
1547 (llvm::is_base_of<DoStmt, NodeType>::value) ||
1548 (llvm::is_base_of<ConditionalOperator, NodeType>::value),
1549 has_condition_requires_if_statement_conditional_operator_or_loop);
1550 const Expr *const Condition = Node.getCond();
1551 return (Condition != NULL &&
1552 InnerMatcher.matches(*Condition, Finder, Builder));
1555 /// \brief Matches the condition variable statement in an if statement.
1558 /// if (A* a = GetAPointer()) {}
1559 /// hasConditionVariableStatment(...)
1560 /// matches 'A* a = GetAPointer()'.
1561 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
1562 internal::Matcher<DeclStmt>, InnerMatcher) {
1563 const DeclStmt* const DeclarationStatement =
1564 Node.getConditionVariableDeclStmt();
1565 return DeclarationStatement != NULL &&
1566 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
1569 /// \brief Matches the index expression of an array subscript expression.
1573 /// void f() { i[1] = 42; }
1574 /// arraySubscriptExpression(hasIndex(integerLiteral()))
1575 /// matches \c i[1] with the \c integerLiteral() matching \c 1
1576 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
1577 internal::Matcher<Expr>, matcher) {
1578 if (const Expr* Expression = Node.getIdx())
1579 return matcher.matches(*Expression, Finder, Builder);
1583 /// \brief Matches the base expression of an array subscript expression.
1587 /// void f() { i[1] = 42; }
1588 /// arraySubscriptExpression(hasBase(implicitCast(
1589 /// hasSourceExpression(declarationReference()))))
1590 /// matches \c i[1] with the \c declarationReference() matching \c i
1591 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
1592 internal::Matcher<Expr>, matcher) {
1593 if (const Expr* Expression = Node.getBase())
1594 return matcher.matches(*Expression, Finder, Builder);
1598 /// \brief Matches a 'for', 'while', or 'do while' statement that has
1603 /// hasBody(compoundStatement())
1604 /// matches 'for (;;) {}'
1605 /// with compoundStatement()
1607 AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
1609 TOOLING_COMPILE_ASSERT(
1610 (llvm::is_base_of<DoStmt, NodeType>::value) ||
1611 (llvm::is_base_of<ForStmt, NodeType>::value) ||
1612 (llvm::is_base_of<WhileStmt, NodeType>::value),
1613 has_body_requires_for_while_or_do_statement);
1614 const Stmt *const Statement = Node.getBody();
1615 return (Statement != NULL &&
1616 InnerMatcher.matches(*Statement, Finder, Builder));
1619 /// \brief Matches compound statements where at least one substatement matches
1620 /// a given matcher.
1624 /// hasAnySubstatement(compoundStatement())
1625 /// matches '{ {}; 1+2; }'
1626 /// with compoundStatement()
1628 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
1629 internal::Matcher<Stmt>, InnerMatcher) {
1630 for (CompoundStmt::const_body_iterator It = Node.body_begin();
1631 It != Node.body_end();
1633 if (InnerMatcher.matches(**It, Finder, Builder)) return true;
1638 /// \brief Checks that a compound statement contains a specific number of
1639 /// child statements.
1643 /// compoundStatement(statementCountIs(0)))
1645 /// but does not match the outer compound statement.
1646 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
1647 return Node.size() == N;
1650 /// \brief Matches literals that are equal to the given value.
1652 /// Example matches true (matcher = boolLiteral(equals(true)))
1655 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
1656 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
1657 template <typename ValueT>
1658 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
1659 equals(const ValueT &Value) {
1660 return internal::PolymorphicMatcherWithParam1<
1661 internal::ValueEqualsMatcher,
1665 /// \brief Matches the operator Name of operator expressions (binary or
1668 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
1670 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
1671 TOOLING_COMPILE_ASSERT(
1672 (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
1673 (llvm::is_base_of<UnaryOperator, NodeType>::value),
1674 has_condition_requires_if_statement_or_conditional_operator);
1675 return Name == Node.getOpcodeStr(Node.getOpcode());
1678 /// \brief Matches the left hand side of binary operator expressions.
1680 /// Example matches a (matcher = binaryOperator(hasLHS()))
1682 AST_MATCHER_P(BinaryOperator, hasLHS,
1683 internal::Matcher<Expr>, InnerMatcher) {
1684 Expr *LeftHandSide = Node.getLHS();
1685 return (LeftHandSide != NULL &&
1686 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
1689 /// \brief Matches the right hand side of binary operator expressions.
1691 /// Example matches b (matcher = binaryOperator(hasRHS()))
1693 AST_MATCHER_P(BinaryOperator, hasRHS,
1694 internal::Matcher<Expr>, InnerMatcher) {
1695 Expr *RightHandSide = Node.getRHS();
1696 return (RightHandSide != NULL &&
1697 InnerMatcher.matches(*RightHandSide, Finder, Builder));
1700 /// \brief Matches if either the left hand side or the right hand side of a
1701 /// binary operator matches.
1702 inline internal::Matcher<BinaryOperator> hasEitherOperand(
1703 const internal::Matcher<Expr> &InnerMatcher) {
1704 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
1707 /// \brief Matches if the operand of a unary operator matches.
1709 /// Example matches true (matcher = hasOperand(boolLiteral(equals(true))))
1711 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
1712 internal::Matcher<Expr>, InnerMatcher) {
1713 const Expr * const Operand = Node.getSubExpr();
1714 return (Operand != NULL &&
1715 InnerMatcher.matches(*Operand, Finder, Builder));
1718 /// \brief Matches if the cast's source expression matches the given matcher.
1720 /// Example: matches "a string" (matcher =
1721 /// hasSourceExpression(constructorCall()))
1723 /// class URL { URL(string); };
1724 /// URL url = "a string";
1725 AST_MATCHER_P(CastExpr, hasSourceExpression,
1726 internal::Matcher<Expr>, InnerMatcher) {
1727 const Expr* const SubExpression = Node.getSubExpr();
1728 return (SubExpression != NULL &&
1729 InnerMatcher.matches(*SubExpression, Finder, Builder));
1732 /// \brief Matches casts whose destination type matches a given matcher.
1734 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
1735 /// actual casts "explicit" casts.)
1736 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
1737 internal::Matcher<QualType>, InnerMatcher) {
1738 const QualType NodeType = Node.getTypeAsWritten();
1739 return InnerMatcher.matches(NodeType, Finder, Builder);
1742 /// \brief Matches implicit casts whose destination type matches a given
1745 /// FIXME: Unit test this matcher
1746 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
1747 internal::Matcher<QualType>, InnerMatcher) {
1748 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1751 /// \brief Matches the true branch expression of a conditional operator.
1753 /// Example matches a
1754 /// condition ? a : b
1755 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
1756 internal::Matcher<Expr>, InnerMatcher) {
1757 Expr *Expression = Node.getTrueExpr();
1758 return (Expression != NULL &&
1759 InnerMatcher.matches(*Expression, Finder, Builder));
1762 /// \brief Matches the false branch expression of a conditional operator.
1764 /// Example matches b
1765 /// condition ? a : b
1766 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
1767 internal::Matcher<Expr>, InnerMatcher) {
1768 Expr *Expression = Node.getFalseExpr();
1769 return (Expression != NULL &&
1770 InnerMatcher.matches(*Expression, Finder, Builder));
1773 /// \brief Matches if a declaration has a body attached.
1775 /// Example matches A, va, fa
1777 /// class B; // Doesn't match, as it has no body.
1779 /// extern int vb; // Doesn't match, as it doesn't define the variable.
1781 /// void fb(); // Doesn't match, as it has no body.
1783 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
1784 inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher>
1786 return internal::PolymorphicMatcherWithParam0<
1787 internal::IsDefinitionMatcher>();
1790 /// \brief Matches the class declaration that the given method declaration
1793 /// FIXME: Generalize this for other kinds of declarations.
1794 /// FIXME: What other kind of declarations would we need to generalize
1797 /// Example matches A() in the last line
1798 /// (matcher = constructorCall(hasDeclaration(method(
1799 /// ofClass(hasName("A"))))))
1805 AST_MATCHER_P(CXXMethodDecl, ofClass,
1806 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
1807 const CXXRecordDecl *Parent = Node.getParent();
1808 return (Parent != NULL &&
1809 InnerMatcher.matches(*Parent, Finder, Builder));
1812 /// \brief Matches member expressions that are called with '->' as opposed
1815 /// Member calls on the implicit this pointer match as called with '->'.
1819 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1823 /// memberExpression(isArrow())
1824 /// matches this->x, x, y.x, a, this->b
1825 inline internal::Matcher<MemberExpr> isArrow() {
1826 return makeMatcher(new internal::IsArrowMatcher());
1829 /// \brief Matches QualType nodes that are of integer type.
1835 /// function(hasAnyParameter(hasType(isInteger())))
1836 /// matches "a(int)", "b(long)", but not "c(double)".
1837 AST_MATCHER(QualType, isInteger) {
1838 return Node->isIntegerType();
1841 /// \brief Matches QualType nodes that are const-qualified, i.e., that
1842 /// include "top-level" const.
1846 /// void b(int const);
1847 /// void c(const int);
1848 /// void d(const int*);
1849 /// void e(int const) {};
1850 /// function(hasAnyParameter(hasType(isConstQualified())))
1851 /// matches "void b(int const)", "void c(const int)" and
1852 /// "void e(int const) {}". It does not match d as there
1853 /// is no top-level const on the parameter type "const int *".
1854 inline internal::Matcher<QualType> isConstQualified() {
1855 return makeMatcher(new internal::IsConstQualifiedMatcher());
1858 /// \brief Matches a member expression where the member is matched by a
1862 /// struct { int first, second; } first, second;
1863 /// int i(second.first);
1864 /// int j(first.second);
1865 /// memberExpression(member(hasName("first")))
1866 /// matches second.first
1867 /// but not first.second (because the member name there is "second").
1868 AST_MATCHER_P(MemberExpr, member,
1869 internal::Matcher<ValueDecl>, InnerMatcher) {
1870 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
1873 /// \brief Matches a member expression where the object expression is
1874 /// matched by a given matcher.
1877 /// struct X { int m; };
1878 /// void f(X x) { x.m; m; }
1879 /// memberExpression(hasObjectExpression(hasType(record(hasName("X")))))))
1880 /// matches "x.m" and "m"
1881 /// with hasObjectExpression(...)
1882 /// matching "x" and the implicit object expression of "m" which has type X*.
1883 AST_MATCHER_P(MemberExpr, hasObjectExpression,
1884 internal::Matcher<Expr>, InnerMatcher) {
1885 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
1888 /// \brief Matches any using shadow declaration.
1891 /// namespace X { void b(); }
1893 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
1894 /// matches \code using X::b \endcode
1895 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
1896 internal::Matcher<UsingShadowDecl>, Matcher) {
1897 for (UsingDecl::shadow_iterator II = Node.shadow_begin();
1898 II != Node.shadow_end(); ++II) {
1899 if (Matcher.matches(**II, Finder, Builder))
1905 /// \brief Matches a using shadow declaration where the target declaration is
1906 /// matched by the given matcher.
1909 /// namespace X { int a; void b(); }
1912 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(function())))
1913 /// matches \code using X::b \endcode
1914 /// but not \code using X::a \endcode
1915 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
1916 internal::Matcher<NamedDecl>, Matcher) {
1917 return Matcher.matches(*Node.getTargetDecl(), Finder, Builder);
1920 /// \brief Matches template instantiations of function, class, or static
1921 /// member variable template instantiations.
1924 /// template <typename T> class X {}; class A {}; X<A> x;
1926 /// template <typename T> class X {}; class A {}; template class X<A>;
1927 /// record(hasName("::X"), isTemplateInstantiation())
1928 /// matches the template instantiation of X<A>.
1931 /// template <typename T> class X {}; class A {};
1932 /// template <> class X<A> {}; X<A> x;
1933 /// record(hasName("::X"), isTemplateInstantiation())
1934 /// does not match, as X<A> is an explicit template specialization.
1936 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
1937 inline internal::PolymorphicMatcherWithParam0<
1938 internal::IsTemplateInstantiationMatcher>
1939 isTemplateInstantiation() {
1940 return internal::PolymorphicMatcherWithParam0<
1941 internal::IsTemplateInstantiationMatcher>();
1944 } // end namespace ast_matchers
1945 } // end namespace clang
1947 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H