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"
55 namespace ast_matchers {
57 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
59 /// The bound nodes are generated by adding id(...) matchers into the
60 /// match expression around the matchers for the nodes we want to access later.
62 /// The instances of BoundNodes are created by MatchFinder when the user's
63 /// callbacks are executed every time a match is found.
66 /// \brief Returns the AST node bound to 'ID'.
67 /// Returns NULL if there was no node bound to 'ID' or if there is a node but
68 /// it cannot be converted to the specified type.
69 /// FIXME: We'll need one of those for every base type.
72 const T *getDeclAs(StringRef ID) const {
73 return getNodeAs<T>(DeclBindings, ID);
76 const T *getStmtAs(StringRef ID) const {
77 return getNodeAs<T>(StmtBindings, ID);
82 /// \brief Create BoundNodes from a pre-filled map of bindings.
83 BoundNodes(const std::map<std::string, const Decl*> &DeclBindings,
84 const std::map<std::string, const Stmt*> &StmtBindings)
85 : DeclBindings(DeclBindings), StmtBindings(StmtBindings) {}
87 template <typename T, typename MapT>
88 const T *getNodeAs(const MapT &Bindings, StringRef ID) const {
89 typename MapT::const_iterator It = Bindings.find(ID);
90 if (It == Bindings.end()) {
93 return llvm::dyn_cast<T>(It->second);
96 std::map<std::string, const Decl*> DeclBindings;
97 std::map<std::string, const Stmt*> StmtBindings;
99 friend class internal::BoundNodesTree;
102 /// \brief If the provided matcher matches a node, binds the node to 'ID'.
104 /// FIXME: Add example for accessing it.
105 template <typename T>
106 internal::Matcher<T> id(const std::string &ID,
107 const internal::BindableMatcher<T> &InnerMatcher) {
108 return InnerMatcher.bind(ID);
111 /// \brief Types of matchers for the top-level classes in the AST class
114 typedef internal::Matcher<Decl> DeclarationMatcher;
115 typedef internal::Matcher<QualType> TypeMatcher;
116 typedef internal::Matcher<Stmt> StatementMatcher;
119 /// \brief Matches any node.
121 /// Useful when another matcher requires a child matcher, but there's no
122 /// additional constraint. This will often be used with an explicit conversion
123 /// to a internal::Matcher<> type such as TypeMatcher.
125 /// Example: DeclarationMatcher(anything()) matches all declarations, e.g.,
126 /// "int* p" and "void f()" in
129 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() {
130 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
133 /// \brief Matches declarations.
135 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
142 const internal::VariadicDynCastAllOfMatcher<Decl, Decl> decl;
144 /// \brief Matches a declaration of anything that could have a name.
146 /// Example matches X, S, the anonymous union type, i, and U;
153 const internal::VariadicDynCastAllOfMatcher<
155 NamedDecl> nameableDeclaration;
157 /// \brief Matches C++ class declarations.
159 /// Example matches X, Z
161 /// template<class T> class Z {};
162 const internal::VariadicDynCastAllOfMatcher<
164 CXXRecordDecl> record;
166 /// \brief Matches C++ class template specializations.
169 /// template<typename T> class A {};
170 /// template<> class A<double> {};
172 /// classTemplateSpecialization()
173 /// matches the specializations \c A<int> and \c A<double>
174 const internal::VariadicDynCastAllOfMatcher<
176 ClassTemplateSpecializationDecl> classTemplateSpecialization;
178 /// \brief Matches classTemplateSpecializations that have at least one
179 /// TemplateArgument matching the given Matcher.
182 /// template<typename T> class A {};
183 /// template<> class A<double> {};
185 /// classTemplateSpecialization(hasAnyTemplateArgument(
186 /// refersToType(asString("int"))))
187 /// matches the specialization \c A<int>
188 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
189 internal::Matcher<TemplateArgument>, Matcher) {
190 const TemplateArgumentList &List = Node.getTemplateArgs();
191 for (unsigned i = 0; i < List.size(); ++i) {
192 if (Matcher.matches(List.get(i), Finder, Builder))
198 /// \brief Matches expressions that match InnerMatcher after any implicit casts
199 /// are stripped off.
201 /// Parentheses and explicit casts are not discarded.
208 /// long e = (long) 0l;
210 /// variable(hasInitializer(ignoringImpCasts(integerLiteral())))
211 /// variable(hasInitializer(ignoringImpCasts(declarationReference())))
212 /// would match the declarations for a, b, c, and d, but not e.
214 /// variable(hasInitializer(integerLiteral()))
215 /// variable(hasInitializer(declarationReference()))
216 /// only match the declarations for b, c, and d.
217 AST_MATCHER_P(Expr, ignoringImpCasts,
218 internal::Matcher<Expr>, InnerMatcher) {
219 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
222 /// \brief Matches expressions that match InnerMatcher after parentheses and
223 /// casts are stripped off.
225 /// Implicit and non-C Style casts are also discarded.
229 /// void* c = reinterpret_cast<char*>(0);
230 /// char d = char(0);
232 /// variable(hasInitializer(ignoringParenCasts(integerLiteral())))
233 /// would match the declarations for a, b, c, and d.
235 /// variable(hasInitializer(integerLiteral()))
236 /// only match the declaration for a.
237 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
238 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
241 /// \brief Matches expressions that match InnerMatcher after implicit casts and
242 /// parentheses are stripped off.
244 /// Explicit casts are not discarded.
251 /// long e = ((long) 0l);
253 /// variable(hasInitializer(ignoringParenImpCasts(
254 /// integerLiteral())))
255 /// variable(hasInitializer(ignoringParenImpCasts(
256 /// declarationReference())))
257 /// would match the declarations for a, b, c, and d, but not e.
259 /// variable(hasInitializer(integerLiteral()))
260 /// variable(hasInitializer(declarationReference()))
261 /// would only match the declaration for a.
262 AST_MATCHER_P(Expr, ignoringParenImpCasts,
263 internal::Matcher<Expr>, InnerMatcher) {
264 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
267 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
268 /// matches the given Matcher.
271 /// template<typename T, typename U> class A {};
274 /// classTemplateSpecialization(hasTemplateArgument(
275 /// 1, refersToType(asString("int"))))
276 /// matches the specialization \c A<bool, int>
277 AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
278 unsigned, N, internal::Matcher<TemplateArgument>, Matcher) {
279 const TemplateArgumentList &List = Node.getTemplateArgs();
280 if (List.size() <= N)
282 return Matcher.matches(List.get(N), Finder, Builder);
285 /// \brief Matches a TemplateArgument that refers to a certain type.
289 /// template<typename T> struct A {};
291 /// classTemplateSpecialization(hasAnyTemplateArgument(
292 /// refersToType(class(hasName("X")))))
293 /// matches the specialization \c A<X>
294 AST_MATCHER_P(TemplateArgument, refersToType,
295 internal::Matcher<QualType>, Matcher) {
296 if (Node.getKind() != TemplateArgument::Type)
298 return Matcher.matches(Node.getAsType(), Finder, Builder);
301 /// \brief Matches a TemplateArgument that refers to a certain declaration.
304 /// template<typename T> struct A {};
305 /// struct B { B* next; };
307 /// classTemplateSpecialization(hasAnyTemplateArgument(
308 /// refersToDeclaration(field(hasName("next"))))
309 /// matches the specialization \c A<&B::next> with \c field(...) matching
311 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
312 internal::Matcher<Decl>, Matcher) {
313 if (const Decl *Declaration = Node.getAsDecl())
314 return Matcher.matches(*Declaration, Finder, Builder);
318 /// \brief Matches C++ constructor declarations.
320 /// Example matches Foo::Foo() and Foo::Foo(int)
325 /// int DoSomething();
327 const internal::VariadicDynCastAllOfMatcher<
329 CXXConstructorDecl> constructor;
331 /// \brief Matches explicit C++ destructor declarations.
333 /// Example matches Foo::~Foo()
338 const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> destructor;
340 /// \brief Matches enum declarations.
342 /// Example matches X
346 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
348 /// \brief Matches enum constants.
350 /// Example matches A, B, C
354 const internal::VariadicDynCastAllOfMatcher<
356 EnumConstantDecl> enumConstant;
358 /// \brief Matches method declarations.
360 /// Example matches y
361 /// class X { void y() };
362 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> method;
364 /// \brief Matches variable declarations.
366 /// Note: this does not match declarations of member variables, which are
367 /// "field" declarations in Clang parlance.
369 /// Example matches a
371 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> variable;
373 /// \brief Matches field declarations.
376 /// class X { int m; };
379 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> field;
381 /// \brief Matches function declarations.
383 /// Example matches f
385 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> function;
388 /// \brief Matches statements.
393 /// matches both the compound statement '{ ++a; }' and '++a'.
394 const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> statement;
396 /// \brief Matches declaration statements.
400 /// declarationStatement()
402 const internal::VariadicDynCastAllOfMatcher<
404 DeclStmt> declarationStatement;
406 /// \brief Matches member expressions.
410 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
411 /// int a; static int b;
413 /// memberExpression()
414 /// matches this->x, x, y.x, a, this->b
415 const internal::VariadicDynCastAllOfMatcher<
417 MemberExpr> memberExpression;
419 /// \brief Matches call expressions.
421 /// Example matches x.y() and y()
425 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> call;
427 /// \brief Matches member call expressions.
429 /// Example matches x.y()
432 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr> memberCall;
434 /// \brief Matches init list expressions.
437 /// int a[] = { 1, 2 };
438 /// struct B { int x, y; };
441 /// matches "{ 1, 2 }" and "{ 5, 6 }"
442 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
444 /// \brief Matches using declarations.
447 /// namespace X { int x; }
450 /// matches \code using X::x \endcode
451 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
453 /// \brief Matches constructor call expressions (including implicit ones).
455 /// Example matches string(ptr, n) and ptr within arguments of f
456 /// (matcher = constructorCall())
457 /// void f(const string &a, const string &b);
460 /// f(string(ptr, n), ptr);
461 const internal::VariadicDynCastAllOfMatcher<
463 CXXConstructExpr> constructorCall;
465 /// \brief Matches nodes where temporaries are created.
467 /// Example matches FunctionTakesString(GetStringByValue())
468 /// (matcher = bindTemporaryExpression())
469 /// FunctionTakesString(GetStringByValue());
470 /// FunctionTakesStringByPointer(GetStringPointer());
471 const internal::VariadicDynCastAllOfMatcher<
473 CXXBindTemporaryExpr> bindTemporaryExpression;
475 /// \brief Matches new expressions.
481 const internal::VariadicDynCastAllOfMatcher<
483 CXXNewExpr> newExpression;
485 /// \brief Matches delete expressions.
489 /// deleteExpression()
490 /// matches 'delete X'.
491 const internal::VariadicDynCastAllOfMatcher<
493 CXXDeleteExpr> deleteExpression;
495 /// \brief Matches array subscript expressions.
499 /// arraySubscriptExpr()
501 const internal::VariadicDynCastAllOfMatcher<
503 ArraySubscriptExpr> arraySubscriptExpr;
505 /// \brief Matches the value of a default argument at the call site.
507 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
508 /// default value of the second parameter in the call expression f(42)
509 /// (matcher = defaultArgument())
510 /// void f(int x, int y = 0);
512 const internal::VariadicDynCastAllOfMatcher<
514 CXXDefaultArgExpr> defaultArgument;
516 /// \brief Matches overloaded operator calls.
518 /// Note that if an operator isn't overloaded, it won't match. Instead, use
519 /// binaryOperator matcher.
520 /// Currently it does not match operators such as new delete.
521 /// FIXME: figure out why these do not match?
523 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
524 /// (matcher = overloadedOperatorCall())
525 /// ostream &operator<< (ostream &out, int i) { };
526 /// ostream &o; int b = 1, c = 1;
528 const internal::VariadicDynCastAllOfMatcher<
530 CXXOperatorCallExpr> overloadedOperatorCall;
532 /// \brief Matches expressions.
534 /// Example matches x()
535 /// void f() { x(); }
536 const internal::VariadicDynCastAllOfMatcher<
540 /// \brief Matches expressions that refer to declarations.
542 /// Example matches x in if (x)
545 const internal::VariadicDynCastAllOfMatcher<
547 DeclRefExpr> declarationReference;
549 /// \brief Matches if statements.
551 /// Example matches 'if (x) {}'
553 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
555 /// \brief Matches for statements.
557 /// Example matches 'for (;;) {}'
559 const internal::VariadicDynCastAllOfMatcher<
560 Stmt, ForStmt> forStmt;
562 /// \brief Matches the increment statement of a for loop.
565 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
567 /// for (x; x < N; ++x) { }
568 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
570 const Stmt *const Increment = Node.getInc();
571 return (Increment != NULL &&
572 InnerMatcher.matches(*Increment, Finder, Builder));
575 /// \brief Matches the initialization statement of a for loop.
578 /// forStmt(hasLoopInit(declarationStatement()))
579 /// matches 'int x = 0' in
580 /// for (int x = 0; x < N; ++x) { }
581 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
583 const Stmt *const Init = Node.getInit();
584 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
587 /// \brief Matches while statements.
592 /// matches 'while (true) {}'.
593 const internal::VariadicDynCastAllOfMatcher<
595 WhileStmt> whileStmt;
597 /// \brief Matches do statements.
600 /// do {} while (true);
602 /// matches 'do {} while(true)'
603 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
605 /// \brief Matches case and default statements inside switch statements.
608 /// switch(a) { case 42: break; default: break; }
610 /// matches 'case 42: break;' and 'default: break;'.
611 const internal::VariadicDynCastAllOfMatcher<
613 SwitchCase> switchCase;
615 /// \brief Matches compound statements.
617 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
619 const internal::VariadicDynCastAllOfMatcher<
621 CompoundStmt> compoundStatement;
623 /// \brief Matches bool literals.
625 /// Example matches true
627 const internal::VariadicDynCastAllOfMatcher<
629 CXXBoolLiteralExpr> boolLiteral;
631 /// \brief Matches string literals (also matches wide string literals).
633 /// Example matches "abcd", L"abcd"
634 /// char *s = "abcd"; wchar_t *ws = L"abcd"
635 const internal::VariadicDynCastAllOfMatcher<
637 StringLiteral> stringLiteral;
639 /// \brief Matches character literals (also matches wchar_t).
641 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
644 /// Example matches 'a', L'a'
645 /// char ch = 'a'; wchar_t chw = L'a';
646 const internal::VariadicDynCastAllOfMatcher<
648 CharacterLiteral> characterLiteral;
650 /// \brief Matches integer literals of all sizes / encodings.
652 /// Not matching character-encoded integers such as L'a'.
654 /// Example matches 1, 1L, 0x1, 1U
655 const internal::VariadicDynCastAllOfMatcher<
657 IntegerLiteral> integerLiteral;
659 /// \brief Matches binary operator expressions.
661 /// Example matches a || b
663 const internal::VariadicDynCastAllOfMatcher<
665 BinaryOperator> binaryOperator;
667 /// \brief Matches unary operator expressions.
669 /// Example matches !a
671 const internal::VariadicDynCastAllOfMatcher<
673 UnaryOperator> unaryOperator;
675 /// \brief Matches conditional operator expressions.
677 /// Example matches a ? b : c
679 const internal::VariadicDynCastAllOfMatcher<
681 ConditionalOperator> conditionalOperator;
683 /// \brief Matches a reinterpret_cast expression.
685 /// Either the source expression or the destination type can be matched
686 /// using has(), but hasDestinationType() is more specific and can be
689 /// Example matches reinterpret_cast<char*>(&p) in
690 /// void* p = reinterpret_cast<char*>(&p);
691 const internal::VariadicDynCastAllOfMatcher<
693 CXXReinterpretCastExpr> reinterpretCast;
695 /// \brief Matches a C++ static_cast expression.
697 /// \see hasDestinationType
698 /// \see reinterpretCast
703 /// static_cast<long>(8)
705 /// long eight(static_cast<long>(8));
706 const internal::VariadicDynCastAllOfMatcher<
708 CXXStaticCastExpr> staticCast;
710 /// \brief Matches a dynamic_cast expression.
715 /// dynamic_cast<D*>(&b);
717 /// struct B { virtual ~B() {} }; struct D : B {};
719 /// D* p = dynamic_cast<D*>(&b);
720 const internal::VariadicDynCastAllOfMatcher<
722 CXXDynamicCastExpr> dynamicCast;
724 /// \brief Matches a const_cast expression.
726 /// Example: Matches const_cast<int*>(&r) in
729 /// int* p = const_cast<int*>(&r);
730 const internal::VariadicDynCastAllOfMatcher<
732 CXXConstCastExpr> constCast;
734 /// \brief Matches explicit cast expressions.
736 /// Matches any cast expression written in user code, whether it be a
737 /// C-style cast, a functional-style cast, or a keyword cast.
739 /// Does not match implicit conversions.
741 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
742 /// Clang uses the term "cast" to apply to implicit conversions as well as to
743 /// actual cast expressions.
745 /// \see hasDestinationType.
747 /// Example: matches all five of the casts in
748 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
749 /// but does not match the implicit conversion in
751 const internal::VariadicDynCastAllOfMatcher<
753 ExplicitCastExpr> explicitCast;
755 /// \brief Matches the implicit cast nodes of Clang's AST.
757 /// This matches many different places, including function call return value
758 /// eliding, as well as any type conversions.
759 const internal::VariadicDynCastAllOfMatcher<
761 ImplicitCastExpr> implicitCast;
763 /// \brief Matches any cast nodes of Clang's AST.
765 /// Example: castExpr() matches each of the following:
767 /// const_cast<Expr *>(SubExpr);
769 /// but does not match
772 const internal::VariadicDynCastAllOfMatcher<
776 /// \brief Matches functional cast expressions
778 /// Example: Matches Foo(bar);
780 /// Foo g = (Foo) bar;
781 /// Foo h = Foo(bar);
782 const internal::VariadicDynCastAllOfMatcher<
784 CXXFunctionalCastExpr> functionalCast;
786 /// \brief Various overloads for the anyOf matcher.
788 template<typename C1, typename C2>
789 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, C2>
790 anyOf(const C1 &P1, const C2 &P2) {
791 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
794 template<typename C1, typename C2, typename C3>
795 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
796 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, C3> >
797 anyOf(const C1 &P1, const C2 &P2, const C3 &P3) {
798 return anyOf(P1, anyOf(P2, P3));
800 template<typename C1, typename C2, typename C3, typename C4>
801 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
802 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2,
803 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
805 anyOf(const C1 &P1, const C2 &P2, const C3 &P3, const C4 &P4) {
806 return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
808 template<typename C1, typename C2, typename C3, typename C4, typename C5>
809 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1,
810 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2,
811 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C3,
812 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
814 anyOf(const C1& P1, const C2& P2, const C3& P3, const C4& P4, const C5& P5) {
815 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
819 /// \brief Various overloads for the allOf matcher.
821 template<typename C1, typename C2>
822 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, C2>
823 allOf(const C1 &P1, const C2 &P2) {
824 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher,
827 template<typename C1, typename C2, typename C3>
828 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1,
829 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C2, C3> >
830 allOf(const C1& P1, const C2& P2, const C3& P3) {
831 return allOf(P1, allOf(P2, P3));
835 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
839 /// int y = sizeof(x) + alignof(x);
840 /// unaryExprOrTypeTraitExpr()
841 /// matches \c sizeof(x) and \c alignof(x)
842 const internal::VariadicDynCastAllOfMatcher<
844 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
846 /// \brief Matches unary expressions that have a specific type of argument.
849 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
850 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
851 /// matches \c sizeof(a) and \c alignof(c)
852 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
853 internal::Matcher<QualType>, Matcher) {
854 const QualType ArgumentType = Node.getTypeOfArgument();
855 return Matcher.matches(ArgumentType, Finder, Builder);
858 /// \brief Matches unary expressions of a certain kind.
862 /// int s = sizeof(x) + alignof(x)
863 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
864 /// matches \c sizeof(x)
865 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
866 return Node.getKind() == Kind;
869 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
871 inline internal::Matcher<Stmt> alignOfExpr(
872 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) {
873 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
874 ofKind(UETT_AlignOf), Matcher)));
877 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
879 inline internal::Matcher<Stmt> sizeOfExpr(
880 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) {
881 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf(
882 ofKind(UETT_SizeOf), Matcher)));
885 /// \brief Matches NamedDecl nodes that have the specified name.
887 /// Supports specifying enclosing namespaces or classes by prefixing the name
888 /// with '<enclosing>::'.
889 /// Does not match typedefs of an underlying type with the given name.
891 /// Example matches X (Name == "X")
894 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
895 /// namespace a { namespace b { class X; } }
896 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
897 assert(!Name.empty());
898 const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
899 const llvm::StringRef FullName = FullNameString;
900 const llvm::StringRef Pattern = Name;
901 if (Pattern.startswith("::")) {
902 return FullName == Pattern;
904 return FullName.endswith(("::" + Pattern).str());
908 /// \brief Matches NamedDecl nodes whose full names partially match the
911 /// Supports specifying enclosing namespaces or classes by
912 /// prefixing the name with '<enclosing>::'. Does not match typedefs
913 /// of an underlying type with the given name.
915 /// Example matches X (regexp == "::X")
918 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
919 /// namespace foo { namespace bar { class X; } }
920 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
921 assert(!RegExp.empty());
922 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
923 llvm::Regex RE(RegExp);
924 return RE.match(FullNameString);
927 /// \brief Matches overloaded operator names.
929 /// Matches overloaded operator names specified in strings without the
930 /// "operator" prefix, such as "<<", for OverloadedOperatorCall's.
932 /// Example matches a << b
933 /// (matcher == overloadedOperatorCall(hasOverloadedOperatorName("<<")))
935 /// c && d; // assuming both operator<<
936 /// // and operator&& are overloaded somewhere.
937 AST_MATCHER_P(CXXOperatorCallExpr,
938 hasOverloadedOperatorName, std::string, Name) {
939 return getOperatorSpelling(Node.getOperator()) == Name;
942 /// \brief Matches C++ classes that are directly or indirectly derived from
943 /// a class matching \c Base.
945 /// Note that a class is considered to be also derived from itself.
947 /// Example matches X, Y, Z, C (Base == hasName("X"))
948 /// class X; // A class is considered to be derived from itself
949 /// class Y : public X {}; // directly derived
950 /// class Z : public Y {}; // indirectly derived
953 /// class C : public B {}; // derived from a typedef of X
955 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
958 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
959 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
960 internal::Matcher<NamedDecl>, Base) {
961 return Finder->classIsDerivedFrom(&Node, Base, Builder);
964 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
965 inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
966 assert(!BaseName.empty());
967 return isDerivedFrom(hasName(BaseName));
970 /// \brief Matches AST nodes that have child AST nodes that match the
971 /// provided matcher.
973 /// Example matches X, Y (matcher = record(has(record(hasName("X")))
974 /// class X {}; // Matches X, because X::X is a class of name X inside X.
975 /// class Y { class X {}; };
976 /// class Z { class Y { class X {}; }; }; // Does not match Z.
978 /// ChildT must be an AST base type.
979 template <typename ChildT>
980 internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
981 const internal::Matcher<ChildT> &ChildMatcher) {
982 return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
983 ChildT>(ChildMatcher);
986 /// \brief Matches AST nodes that have descendant AST nodes that match the
987 /// provided matcher.
989 /// Example matches X, Y, Z
990 /// (matcher = record(hasDescendant(record(hasName("X")))))
991 /// class X {}; // Matches X, because X::X is a class of name X inside X.
992 /// class Y { class X {}; };
993 /// class Z { class Y { class X {}; }; };
995 /// DescendantT must be an AST base type.
996 template <typename DescendantT>
997 internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
998 hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
999 return internal::ArgumentAdaptingMatcher<
1000 internal::HasDescendantMatcher,
1001 DescendantT>(DescendantMatcher);
1005 /// \brief Matches AST nodes that have child AST nodes that match the
1006 /// provided matcher.
1008 /// Example matches X, Y (matcher = record(forEach(record(hasName("X")))
1009 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1010 /// class Y { class X {}; };
1011 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1013 /// ChildT must be an AST base type.
1015 /// As opposed to 'has', 'forEach' will cause a match for each result that
1016 /// matches instead of only on the first one.
1017 template <typename ChildT>
1018 internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1019 const internal::Matcher<ChildT>& ChildMatcher) {
1020 return internal::ArgumentAdaptingMatcher<
1021 internal::ForEachMatcher,
1022 ChildT>(ChildMatcher);
1025 /// \brief Matches AST nodes that have descendant AST nodes that match the
1026 /// provided matcher.
1028 /// Example matches X, A, B, C
1029 /// (matcher = record(forEachDescendant(record(hasName("X")))))
1030 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1031 /// class A { class X {}; };
1032 /// class B { class C { class X {}; }; };
1034 /// DescendantT must be an AST base type.
1036 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1037 /// each result that matches instead of only on the first one.
1039 /// Note: Recursively combined ForEachDescendant can cause many matches:
1040 /// record(forEachDescendant(record(forEachDescendant(record()))))
1041 /// will match 10 times (plus injected class name matches) on:
1042 /// class A { class B { class C { class D { class E {}; }; }; }; };
1043 template <typename DescendantT>
1044 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT>
1046 const internal::Matcher<DescendantT>& DescendantMatcher) {
1047 return internal::ArgumentAdaptingMatcher<
1048 internal::ForEachDescendantMatcher,
1049 DescendantT>(DescendantMatcher);
1052 /// \brief Matches if the provided matcher does not match.
1054 /// Example matches Y (matcher = record(unless(hasName("X"))))
1057 template <typename M>
1058 internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> unless(const M &InnerMatcher) {
1059 return internal::PolymorphicMatcherWithParam1<
1060 internal::NotMatcher, M>(InnerMatcher);
1063 /// \brief Matches a type if the declaration of the type matches the given
1066 /// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>
1067 inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1068 internal::Matcher<Decl> >
1069 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1070 return internal::PolymorphicMatcherWithParam1<
1071 internal::HasDeclarationMatcher,
1072 internal::Matcher<Decl> >(InnerMatcher);
1075 /// \brief Matches on the implicit object argument of a member call expression.
1077 /// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y"))))))
1078 /// class Y { public: void x(); };
1079 /// void z() { Y y; y.x(); }",
1081 /// FIXME: Overload to allow directly matching types?
1082 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1084 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node)
1085 .getImplicitObjectArgument()
1086 ->IgnoreParenImpCasts();
1087 return (ExprNode != NULL &&
1088 InnerMatcher.matches(*ExprNode, Finder, Builder));
1091 /// \brief Matches if the call expression's callee expression matches.
1094 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
1095 /// void f() { f(); }
1096 /// call(callee(expression()))
1097 /// matches this->x(), x(), y.x(), f()
1098 /// with callee(...)
1099 /// matching this->x, x, y.x, f respectively
1101 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1102 /// because this introduces ambiguous overloads with calls to Callee taking a
1103 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1104 /// implemented in terms of implicit casts.
1105 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1107 const Expr *ExprNode = Node.getCallee();
1108 return (ExprNode != NULL &&
1109 InnerMatcher.matches(*ExprNode, Finder, Builder));
1112 /// \brief Matches if the call expression's callee's declaration matches the
1115 /// Example matches y.x() (matcher = call(callee(method(hasName("x")))))
1116 /// class Y { public: void x(); };
1117 /// void z() { Y y; y.x();
1118 inline internal::Matcher<CallExpr> callee(
1119 const internal::Matcher<Decl> &InnerMatcher) {
1120 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher));
1123 /// \brief Matches if the expression's or declaration's type matches a type
1126 /// Example matches x (matcher = expression(hasType(
1127 /// hasDeclaration(record(hasName("X"))))))
1128 /// and z (matcher = variable(hasType(
1129 /// hasDeclaration(record(hasName("X"))))))
1131 /// void y(X &x) { x; X z; }
1132 AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1134 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1135 llvm::is_base_of<ValueDecl, NodeType>::value),
1136 instantiated_with_wrong_types);
1137 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1140 /// \brief Overloaded to match the declaration of the expression's or value
1141 /// declaration's type.
1143 /// In case of a value declaration (for example a variable declaration),
1144 /// this resolves one layer of indirection. For example, in the value
1145 /// declaration "X x;", record(hasName("X")) matches the declaration of X,
1146 /// while variable(hasType(record(hasName("X")))) matches the declaration
1149 /// Example matches x (matcher = expression(hasType(record(hasName("X")))))
1150 /// and z (matcher = variable(hasType(record(hasName("X")))))
1152 /// void y(X &x) { x; X z; }
1154 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1155 inline internal::PolymorphicMatcherWithParam1<
1156 internal::matcher_hasTypeMatcher,
1157 internal::Matcher<QualType> >
1158 hasType(const internal::Matcher<Decl> &InnerMatcher) {
1159 return hasType(internal::Matcher<QualType>(
1160 hasDeclaration(InnerMatcher)));
1163 /// \brief Matches if the matched type is represented by the given string.
1166 /// class Y { public: void x(); };
1167 /// void z() { Y* y; y->x(); }
1168 /// call(on(hasType(asString("class Y *"))))
1170 AST_MATCHER_P(QualType, asString, std::string, Name) {
1171 return Name == Node.getAsString();
1174 /// \brief Matches if the matched type is a pointer type and the pointee type
1175 /// matches the specified matcher.
1177 /// Example matches y->x()
1178 /// (matcher = call(on(hasType(pointsTo(record(hasName("Y")))))))
1179 /// class Y { public: void x(); };
1180 /// void z() { Y *y; y->x(); }
1182 QualType, pointsTo, internal::Matcher<QualType>,
1184 return (!Node.isNull() && Node->isPointerType() &&
1185 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1188 /// \brief Overloaded to match the pointee type's declaration.
1189 inline internal::Matcher<QualType> pointsTo(
1190 const internal::Matcher<Decl> &InnerMatcher) {
1191 return pointsTo(internal::Matcher<QualType>(
1192 hasDeclaration(InnerMatcher)));
1195 /// \brief Matches if the matched type is a reference type and the referenced
1196 /// type matches the specified matcher.
1198 /// Example matches X &x and const X &y
1199 /// (matcher = variable(hasType(references(record(hasName("X"))))))
1205 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1207 return (!Node.isNull() && Node->isReferenceType() &&
1208 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1211 /// \brief Overloaded to match the referenced type's declaration.
1212 inline internal::Matcher<QualType> references(
1213 const internal::Matcher<Decl> &InnerMatcher) {
1214 return references(internal::Matcher<QualType>(
1215 hasDeclaration(InnerMatcher)));
1218 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1219 internal::Matcher<Expr>, InnerMatcher) {
1220 const Expr *ExprNode =
1221 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument();
1222 return (ExprNode != NULL &&
1223 InnerMatcher.matches(*ExprNode, Finder, Builder));
1226 /// \brief Matches if the expression's type either matches the specified
1227 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1228 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1229 const internal::Matcher<QualType> &InnerMatcher) {
1230 return onImplicitObjectArgument(
1231 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1234 /// \brief Overloaded to match the type's declaration.
1235 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1236 const internal::Matcher<Decl> &InnerMatcher) {
1237 return onImplicitObjectArgument(
1238 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1241 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1242 /// specified matcher.
1244 /// Example matches x in if(x)
1245 /// (matcher = declarationReference(to(variable(hasName("x")))))
1248 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1250 const Decl *DeclNode = Node.getDecl();
1251 return (DeclNode != NULL &&
1252 InnerMatcher.matches(*DeclNode, Finder, Builder));
1255 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1256 /// specific using shadow declaration.
1258 /// FIXME: This currently only works for functions. Fix.
1261 /// namespace a { void f() {} }
1264 /// f(); // Matches this ..
1265 /// a::f(); // .. but not this.
1267 /// declarationReference(throughUsingDeclaration(anything()))
1269 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1270 internal::Matcher<UsingShadowDecl>, Matcher) {
1271 const NamedDecl *FoundDecl = Node.getFoundDecl();
1272 if (const UsingShadowDecl *UsingDecl =
1273 llvm::dyn_cast<UsingShadowDecl>(FoundDecl))
1274 return Matcher.matches(*UsingDecl, Finder, Builder);
1278 /// \brief Matches a variable declaration that has an initializer expression
1279 /// that matches the given matcher.
1281 /// Example matches x (matcher = variable(hasInitializer(call())))
1282 /// bool y() { return true; }
1285 VarDecl, hasInitializer, internal::Matcher<Expr>,
1287 const Expr *Initializer = Node.getAnyInitializer();
1288 return (Initializer != NULL &&
1289 InnerMatcher.matches(*Initializer, Finder, Builder));
1292 /// \brief Checks that a call expression or a constructor call expression has
1293 /// a specific number of arguments (including absent default arguments).
1295 /// Example matches f(0, 0) (matcher = call(argumentCountIs(2)))
1296 /// void f(int x, int y);
1298 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1299 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1300 llvm::is_base_of<CXXConstructExpr,
1302 instantiated_with_wrong_types);
1303 return Node.getNumArgs() == N;
1306 /// \brief Matches the n'th argument of a call expression or a constructor
1307 /// call expression.
1309 /// Example matches y in x(y)
1310 /// (matcher = call(hasArgument(0, declarationReference())))
1311 /// void x(int) { int y; x(y); }
1312 AST_POLYMORPHIC_MATCHER_P2(
1313 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1314 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1315 llvm::is_base_of<CXXConstructExpr,
1317 instantiated_with_wrong_types);
1318 return (N < Node.getNumArgs() &&
1319 InnerMatcher.matches(
1320 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1323 /// \brief Matches a constructor initializer.
1327 /// Foo() : foo_(1) { }
1330 /// record(has(constructor(hasAnyConstructorInitializer(anything()))))
1331 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
1332 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
1333 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
1334 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
1335 I != Node.init_end(); ++I) {
1336 if (InnerMatcher.matches(**I, Finder, Builder)) {
1343 /// \brief Matches the field declaration of a constructor initializer.
1347 /// Foo() : foo_(1) { }
1350 /// record(has(constructor(hasAnyConstructorInitializer(
1351 /// forField(hasName("foo_"))))))
1353 /// with forField matching foo_
1354 AST_MATCHER_P(CXXCtorInitializer, forField,
1355 internal::Matcher<FieldDecl>, InnerMatcher) {
1356 const FieldDecl *NodeAsDecl = Node.getMember();
1357 return (NodeAsDecl != NULL &&
1358 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
1361 /// \brief Matches the initializer expression of a constructor initializer.
1365 /// Foo() : foo_(1) { }
1368 /// record(has(constructor(hasAnyConstructorInitializer(
1369 /// withInitializer(integerLiteral(equals(1)))))))
1371 /// with withInitializer matching (1)
1372 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
1373 internal::Matcher<Expr>, InnerMatcher) {
1374 const Expr* NodeAsExpr = Node.getInit();
1375 return (NodeAsExpr != NULL &&
1376 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
1379 /// \brief Matches a contructor initializer if it is explicitly written in
1380 /// code (as opposed to implicitly added by the compiler).
1385 /// Foo(int) : foo_("A") { }
1388 /// constructor(hasAnyConstructorInitializer(isWritten()))
1389 /// will match Foo(int), but not Foo()
1390 AST_MATCHER(CXXCtorInitializer, isWritten) {
1391 return Node.isWritten();
1394 /// \brief Matches a constructor declaration that has been implicitly added
1395 /// by the compiler (eg. implicit default/copy constructors).
1396 AST_MATCHER(CXXConstructorDecl, isImplicit) {
1397 return Node.isImplicit();
1400 /// \brief Matches any argument of a call expression or a constructor call
1404 /// void x(int, int, int) { int y; x(1, y, 42); }
1405 /// call(hasAnyArgument(declarationReference()))
1406 /// matches x(1, y, 42)
1407 /// with hasAnyArgument(...)
1409 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
1411 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1412 llvm::is_base_of<CXXConstructExpr,
1414 instantiated_with_wrong_types);
1415 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
1416 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
1424 /// \brief Matches the n'th parameter of a function declaration.
1427 /// class X { void f(int x) {} };
1428 /// method(hasParameter(0, hasType(variable())))
1429 /// matches f(int x) {}
1430 /// with hasParameter(...)
1432 AST_MATCHER_P2(FunctionDecl, hasParameter,
1433 unsigned, N, internal::Matcher<ParmVarDecl>,
1435 return (N < Node.getNumParams() &&
1436 InnerMatcher.matches(
1437 *Node.getParamDecl(N), Finder, Builder));
1440 /// \brief Matches any parameter of a function declaration.
1442 /// Does not match the 'this' parameter of a method.
1445 /// class X { void f(int x, int y, int z) {} };
1446 /// method(hasAnyParameter(hasName("y")))
1447 /// matches f(int x, int y, int z) {}
1448 /// with hasAnyParameter(...)
1450 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
1451 internal::Matcher<ParmVarDecl>, InnerMatcher) {
1452 for (unsigned I = 0; I < Node.getNumParams(); ++I) {
1453 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
1460 /// \brief Matches the return type of a function declaration.
1463 /// class X { int f() { return 1; } };
1464 /// method(returns(asString("int")))
1465 /// matches int f() { return 1; }
1466 AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, Matcher) {
1467 return Matcher.matches(Node.getResultType(), Finder, Builder);
1470 /// \brief Matches extern "C" function declarations.
1473 /// extern "C" void f() {}
1474 /// extern "C" { void g() {} }
1476 /// function(isExternC())
1477 /// matches the declaration of f and g, but not the declaration h
1478 AST_MATCHER(FunctionDecl, isExternC) {
1479 return Node.isExternC();
1482 /// \brief Matches the condition expression of an if statement, for loop,
1483 /// or conditional operator.
1485 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
1487 AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
1489 TOOLING_COMPILE_ASSERT(
1490 (llvm::is_base_of<IfStmt, NodeType>::value) ||
1491 (llvm::is_base_of<ForStmt, NodeType>::value) ||
1492 (llvm::is_base_of<WhileStmt, NodeType>::value) ||
1493 (llvm::is_base_of<DoStmt, NodeType>::value) ||
1494 (llvm::is_base_of<ConditionalOperator, NodeType>::value),
1495 has_condition_requires_if_statement_conditional_operator_or_loop);
1496 const Expr *const Condition = Node.getCond();
1497 return (Condition != NULL &&
1498 InnerMatcher.matches(*Condition, Finder, Builder));
1501 /// \brief Matches the condition variable statement in an if statement.
1504 /// if (A* a = GetAPointer()) {}
1505 /// hasConditionVariableStatment(...)
1506 /// matches 'A* a = GetAPointer()'.
1507 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
1508 internal::Matcher<DeclStmt>, InnerMatcher) {
1509 const DeclStmt* const DeclarationStatement =
1510 Node.getConditionVariableDeclStmt();
1511 return DeclarationStatement != NULL &&
1512 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
1515 /// \brief Matches the index expression of an array subscript expression.
1519 /// void f() { i[1] = 42; }
1520 /// arraySubscriptExpression(hasIndex(integerLiteral()))
1521 /// matches \c i[1] with the \c integerLiteral() matching \c 1
1522 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
1523 internal::Matcher<Expr>, matcher) {
1524 if (const Expr* Expression = Node.getIdx())
1525 return matcher.matches(*Expression, Finder, Builder);
1529 /// \brief Matches the base expression of an array subscript expression.
1533 /// void f() { i[1] = 42; }
1534 /// arraySubscriptExpression(hasBase(implicitCast(
1535 /// hasSourceExpression(declarationReference()))))
1536 /// matches \c i[1] with the \c declarationReference() matching \c i
1537 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
1538 internal::Matcher<Expr>, matcher) {
1539 if (const Expr* Expression = Node.getBase())
1540 return matcher.matches(*Expression, Finder, Builder);
1544 /// \brief Matches a 'for', 'while', or 'do while' statement that has
1549 /// hasBody(compoundStatement())
1550 /// matches 'for (;;) {}'
1551 /// with compoundStatement()
1553 AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
1555 TOOLING_COMPILE_ASSERT(
1556 (llvm::is_base_of<DoStmt, NodeType>::value) ||
1557 (llvm::is_base_of<ForStmt, NodeType>::value) ||
1558 (llvm::is_base_of<WhileStmt, NodeType>::value),
1559 has_body_requires_for_while_or_do_statement);
1560 const Stmt *const Statement = Node.getBody();
1561 return (Statement != NULL &&
1562 InnerMatcher.matches(*Statement, Finder, Builder));
1565 /// \brief Matches compound statements where at least one substatement matches
1566 /// a given matcher.
1570 /// hasAnySubstatement(compoundStatement())
1571 /// matches '{ {}; 1+2; }'
1572 /// with compoundStatement()
1574 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
1575 internal::Matcher<Stmt>, InnerMatcher) {
1576 for (CompoundStmt::const_body_iterator It = Node.body_begin();
1577 It != Node.body_end();
1579 if (InnerMatcher.matches(**It, Finder, Builder)) return true;
1584 /// \brief Checks that a compound statement contains a specific number of
1585 /// child statements.
1589 /// compoundStatement(statementCountIs(0)))
1591 /// but does not match the outer compound statement.
1592 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
1593 return Node.size() == N;
1596 /// \brief Matches literals that are equal to the given value.
1598 /// Example matches true (matcher = boolLiteral(equals(true)))
1601 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
1602 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
1603 template <typename ValueT>
1604 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
1605 equals(const ValueT &Value) {
1606 return internal::PolymorphicMatcherWithParam1<
1607 internal::ValueEqualsMatcher,
1611 /// \brief Matches the operator Name of operator expressions (binary or
1614 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
1616 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
1617 TOOLING_COMPILE_ASSERT(
1618 (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
1619 (llvm::is_base_of<UnaryOperator, NodeType>::value),
1620 has_condition_requires_if_statement_or_conditional_operator);
1621 return Name == Node.getOpcodeStr(Node.getOpcode());
1624 /// \brief Matches the left hand side of binary operator expressions.
1626 /// Example matches a (matcher = binaryOperator(hasLHS()))
1628 AST_MATCHER_P(BinaryOperator, hasLHS,
1629 internal::Matcher<Expr>, InnerMatcher) {
1630 Expr *LeftHandSide = Node.getLHS();
1631 return (LeftHandSide != NULL &&
1632 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
1635 /// \brief Matches the right hand side of binary operator expressions.
1637 /// Example matches b (matcher = binaryOperator(hasRHS()))
1639 AST_MATCHER_P(BinaryOperator, hasRHS,
1640 internal::Matcher<Expr>, InnerMatcher) {
1641 Expr *RightHandSide = Node.getRHS();
1642 return (RightHandSide != NULL &&
1643 InnerMatcher.matches(*RightHandSide, Finder, Builder));
1646 /// \brief Matches if either the left hand side or the right hand side of a
1647 /// binary operator matches.
1648 inline internal::Matcher<BinaryOperator> hasEitherOperand(
1649 const internal::Matcher<Expr> &InnerMatcher) {
1650 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
1653 /// \brief Matches if the operand of a unary operator matches.
1655 /// Example matches true (matcher = hasOperand(boolLiteral(equals(true))))
1657 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
1658 internal::Matcher<Expr>, InnerMatcher) {
1659 const Expr * const Operand = Node.getSubExpr();
1660 return (Operand != NULL &&
1661 InnerMatcher.matches(*Operand, Finder, Builder));
1664 /// \brief Matches if the cast's source expression matches the given matcher.
1666 /// Example: matches "a string" (matcher =
1667 /// hasSourceExpression(constructorCall()))
1669 /// class URL { URL(string); };
1670 /// URL url = "a string";
1671 AST_MATCHER_P(CastExpr, hasSourceExpression,
1672 internal::Matcher<Expr>, InnerMatcher) {
1673 const Expr* const SubExpression = Node.getSubExpr();
1674 return (SubExpression != NULL &&
1675 InnerMatcher.matches(*SubExpression, Finder, Builder));
1678 /// \brief Matches casts whose destination type matches a given matcher.
1680 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
1681 /// actual casts "explicit" casts.)
1682 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
1683 internal::Matcher<QualType>, InnerMatcher) {
1684 const QualType NodeType = Node.getTypeAsWritten();
1685 return InnerMatcher.matches(NodeType, Finder, Builder);
1688 /// \brief Matches implicit casts whose destination type matches a given
1691 /// FIXME: Unit test this matcher
1692 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
1693 internal::Matcher<QualType>, InnerMatcher) {
1694 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1697 /// \brief Matches the true branch expression of a conditional operator.
1699 /// Example matches a
1700 /// condition ? a : b
1701 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
1702 internal::Matcher<Expr>, InnerMatcher) {
1703 Expr *Expression = Node.getTrueExpr();
1704 return (Expression != NULL &&
1705 InnerMatcher.matches(*Expression, Finder, Builder));
1708 /// \brief Matches the false branch expression of a conditional operator.
1710 /// Example matches b
1711 /// condition ? a : b
1712 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
1713 internal::Matcher<Expr>, InnerMatcher) {
1714 Expr *Expression = Node.getFalseExpr();
1715 return (Expression != NULL &&
1716 InnerMatcher.matches(*Expression, Finder, Builder));
1719 /// \brief Matches if a declaration has a body attached.
1721 /// Example matches A, va, fa
1723 /// class B; // Doesn't match, as it has no body.
1725 /// extern int vb; // Doesn't match, as it doesn't define the variable.
1727 /// void fb(); // Doesn't match, as it has no body.
1729 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
1730 inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher>
1732 return internal::PolymorphicMatcherWithParam0<
1733 internal::IsDefinitionMatcher>();
1736 /// \brief Matches the class declaration that the given method declaration
1739 /// FIXME: Generalize this for other kinds of declarations.
1740 /// FIXME: What other kind of declarations would we need to generalize
1743 /// Example matches A() in the last line
1744 /// (matcher = constructorCall(hasDeclaration(method(
1745 /// ofClass(hasName("A"))))))
1751 AST_MATCHER_P(CXXMethodDecl, ofClass,
1752 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
1753 const CXXRecordDecl *Parent = Node.getParent();
1754 return (Parent != NULL &&
1755 InnerMatcher.matches(*Parent, Finder, Builder));
1758 /// \brief Matches member expressions that are called with '->' as opposed
1761 /// Member calls on the implicit this pointer match as called with '->'.
1765 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1769 /// memberExpression(isArrow())
1770 /// matches this->x, x, y.x, a, this->b
1771 inline internal::Matcher<MemberExpr> isArrow() {
1772 return makeMatcher(new internal::IsArrowMatcher());
1775 /// \brief Matches QualType nodes that are of integer type.
1781 /// function(hasAnyParameter(hasType(isInteger())))
1782 /// matches "a(int)", "b(long)", but not "c(double)".
1783 AST_MATCHER(QualType, isInteger) {
1784 return Node->isIntegerType();
1787 /// \brief Matches QualType nodes that are const-qualified, i.e., that
1788 /// include "top-level" const.
1792 /// void b(int const);
1793 /// void c(const int);
1794 /// void d(const int*);
1795 /// void e(int const) {};
1796 /// function(hasAnyParameter(hasType(isConstQualified())))
1797 /// matches "void b(int const)", "void c(const int)" and
1798 /// "void e(int const) {}". It does not match d as there
1799 /// is no top-level const on the parameter type "const int *".
1800 inline internal::Matcher<QualType> isConstQualified() {
1801 return makeMatcher(new internal::IsConstQualifiedMatcher());
1804 /// \brief Matches a member expression where the member is matched by a
1808 /// struct { int first, second; } first, second;
1809 /// int i(second.first);
1810 /// int j(first.second);
1811 /// memberExpression(member(hasName("first")))
1812 /// matches second.first
1813 /// but not first.second (because the member name there is "second").
1814 AST_MATCHER_P(MemberExpr, member,
1815 internal::Matcher<ValueDecl>, InnerMatcher) {
1816 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
1819 /// \brief Matches a member expression where the object expression is
1820 /// matched by a given matcher.
1823 /// struct X { int m; };
1824 /// void f(X x) { x.m; m; }
1825 /// memberExpression(hasObjectExpression(hasType(record(hasName("X")))))))
1826 /// matches "x.m" and "m"
1827 /// with hasObjectExpression(...)
1828 /// matching "x" and the implicit object expression of "m" which has type X*.
1829 AST_MATCHER_P(MemberExpr, hasObjectExpression,
1830 internal::Matcher<Expr>, InnerMatcher) {
1831 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
1834 /// \brief Matches any using shadow declaration.
1837 /// namespace X { void b(); }
1839 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
1840 /// matches \code using X::b \endcode
1841 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
1842 internal::Matcher<UsingShadowDecl>, Matcher) {
1843 for (UsingDecl::shadow_iterator II = Node.shadow_begin();
1844 II != Node.shadow_end(); ++II) {
1845 if (Matcher.matches(**II, Finder, Builder))
1851 /// \brief Matches a using shadow declaration where the target declaration is
1852 /// matched by the given matcher.
1855 /// namespace X { int a; void b(); }
1858 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(function())))
1859 /// matches \code using X::b \endcode
1860 /// but not \code using X::a \endcode
1861 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
1862 internal::Matcher<NamedDecl>, Matcher) {
1863 return Matcher.matches(*Node.getTargetDecl(), Finder, Builder);
1866 /// \brief Matches template instantiations of function, class, or static
1867 /// member variable template instantiations.
1870 /// template <typename T> class X {}; class A {}; X<A> x;
1872 /// template <typename T> class X {}; class A {}; template class X<A>;
1873 /// record(hasName("::X"), isTemplateInstantiation())
1874 /// matches the template instantiation of X<A>.
1877 /// template <typename T> class X {}; class A {};
1878 /// template <> class X<A> {}; X<A> x;
1879 /// record(hasName("::X"), isTemplateInstantiation())
1880 /// does not match, as X<A> is an explicit template specialization.
1882 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
1883 inline internal::PolymorphicMatcherWithParam0<
1884 internal::IsTemplateInstantiationMatcher>
1885 isTemplateInstantiation() {
1886 return internal::PolymorphicMatcherWithParam0<
1887 internal::IsTemplateInstantiationMatcher>();
1890 } // end namespace ast_matchers
1891 } // end namespace clang
1893 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H