1 //===--- ASTMatchers.h - Structural query framework -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements matchers to be used together with the MatchFinder to
13 // Matchers are created by generator functions, which can be combined in
14 // a functional in-language DSL to express queries over the C++ AST.
16 // For example, to match a class with a certain name, one would call:
17 // recordDecl(hasName("MyClass"))
18 // which returns a matcher that can be used to find all AST nodes that declare
19 // a class named 'MyClass'.
21 // For more complicated match expressions we're often interested in accessing
22 // multiple parts of the matched AST nodes once a match is found. In that case,
23 // use the id(...) matcher around the match expressions that match the nodes
24 // you want to access.
26 // For example, when we're interested in child classes of a certain class, we
28 // recordDecl(hasName("MyClass"), hasChild(id("child", recordDecl())))
29 // When the match is found via the MatchFinder, a user provided callback will
30 // be called with a BoundNodes instance that contains a mapping from the
31 // strings that we provided for the id(...) calls to the nodes that were
33 // In the given example, each time our matcher finds a match we get a callback
34 // where "child" is bound to the CXXRecordDecl node of the matching child
37 // See ASTMatchersInternal.h for a more in-depth explanation of the
38 // implementation details of the matcher framework.
40 // See ASTMatchFinder.h for how to use the generated matchers to run over
43 //===----------------------------------------------------------------------===//
45 #ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
46 #define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
48 #include "clang/AST/DeclFriend.h"
49 #include "clang/AST/DeclTemplate.h"
50 #include "clang/ASTMatchers/ASTMatchersInternal.h"
51 #include "clang/ASTMatchers/ASTMatchersMacros.h"
52 #include "llvm/ADT/Twine.h"
53 #include "llvm/Support/Regex.h"
57 namespace ast_matchers {
59 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
61 /// The bound nodes are generated by calling \c bind("id") on the node matchers
62 /// of the nodes we want to access later.
64 /// The instances of BoundNodes are created by \c MatchFinder when the user's
65 /// callbacks are executed every time a match is found.
68 /// \brief Returns the AST node bound to \c ID.
70 /// Returns NULL if there was no node bound to \c ID or if there is a node but
71 /// it cannot be converted to the specified type.
73 const T *getNodeAs(StringRef ID) const {
74 return MyBoundNodes.getNodeAs<T>(ID);
77 /// \brief Deprecated. Please use \c getNodeAs instead.
80 const T *getDeclAs(StringRef ID) const {
81 return getNodeAs<T>(ID);
84 const T *getStmtAs(StringRef ID) const {
85 return getNodeAs<T>(ID);
89 /// \brief Type of mapping from binding identifiers to bound nodes. This type
90 /// is an associative container with a key type of \c std::string and a value
91 /// type of \c clang::ast_type_traits::DynTypedNode
92 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
94 /// \brief Retrieve mapping from binding identifiers to bound nodes.
95 const IDToNodeMap &getMap() const {
96 return MyBoundNodes.getMap();
100 /// \brief Create BoundNodes from a pre-filled map of bindings.
101 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
102 : MyBoundNodes(MyBoundNodes) {}
104 internal::BoundNodesMap MyBoundNodes;
106 friend class internal::BoundNodesTreeBuilder;
109 /// \brief If the provided matcher matches a node, binds the node to \c ID.
111 /// FIXME: Do we want to support this now that we have bind()?
112 template <typename T>
113 internal::Matcher<T> id(const std::string &ID,
114 const internal::BindableMatcher<T> &InnerMatcher) {
115 return InnerMatcher.bind(ID);
118 /// \brief Types of matchers for the top-level classes in the AST class
121 typedef internal::Matcher<Decl> DeclarationMatcher;
122 typedef internal::Matcher<Stmt> StatementMatcher;
123 typedef internal::Matcher<QualType> TypeMatcher;
124 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
125 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
126 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
129 /// \brief Matches any node.
131 /// Useful when another matcher requires a child matcher, but there's no
132 /// additional constraint. This will often be used with an explicit conversion
133 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
135 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
137 /// "int* p" and "void f()" in
142 /// Usable as: Any Matcher
143 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>
145 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
148 /// \brief Matches declarations.
150 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
157 const internal::VariadicAllOfMatcher<Decl> decl;
159 /// \brief Matches a declaration of anything that could have a name.
161 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
170 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
172 /// \brief Matches a declaration of a namespace.
177 /// namespace test {}
180 /// matches "namespace {}" and "namespace test {}"
181 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
183 /// \brief Matches C++ class declarations.
185 /// Example matches \c X, \c Z
188 /// template<class T> class Z {};
190 const internal::VariadicDynCastAllOfMatcher<
192 CXXRecordDecl> recordDecl;
194 /// \brief Matches C++ class template declarations.
196 /// Example matches \c Z
198 /// template<class T> class Z {};
200 const internal::VariadicDynCastAllOfMatcher<
202 ClassTemplateDecl> classTemplateDecl;
204 /// \brief Matches C++ class template specializations.
208 /// template<typename T> class A {};
209 /// template<> class A<double> {};
212 /// classTemplateSpecializationDecl()
213 /// matches the specializations \c A<int> and \c A<double>
214 const internal::VariadicDynCastAllOfMatcher<
216 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
218 /// \brief Matches declarator declarations (field, variable, function
219 /// and non-type template parameter declarations).
223 /// class X { int y; };
226 /// matches \c int y.
227 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
230 /// \brief Matches parameter variable declarations.
237 /// matches \c int x.
238 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
240 /// \brief Matches C++ access specifier declarations.
250 /// matches 'public:'
251 const internal::VariadicDynCastAllOfMatcher<
253 AccessSpecDecl> accessSpecDecl;
255 /// \brief Matches constructor initializers.
257 /// Examples matches \c i(42).
264 const internal::VariadicAllOfMatcher<CXXCtorInitializer> ctorInitializer;
266 /// \brief Matches public C++ declarations.
272 /// protected: int b;
276 /// fieldDecl(isPublic())
278 AST_MATCHER(Decl, isPublic) {
279 return Node.getAccess() == AS_public;
282 /// \brief Matches protected C++ declarations.
288 /// protected: int b;
292 /// fieldDecl(isProtected())
294 AST_MATCHER(Decl, isProtected) {
295 return Node.getAccess() == AS_protected;
298 /// \brief Matches private C++ declarations.
304 /// protected: int b;
308 /// fieldDecl(isPrivate())
310 AST_MATCHER(Decl, isPrivate) {
311 return Node.getAccess() == AS_private;
314 /// \brief Matches a declaration that has been implicitly added
315 /// by the compiler (eg. implicit default/copy constructors).
316 AST_MATCHER(Decl, isImplicit) {
317 return Node.isImplicit();
320 /// \brief Matches classTemplateSpecializations that have at least one
321 /// TemplateArgument matching the given InnerMatcher.
325 /// template<typename T> class A {};
326 /// template<> class A<double> {};
329 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
330 /// refersToType(asString("int"))))
331 /// matches the specialization \c A<int>
332 AST_POLYMORPHIC_MATCHER_P(
333 hasAnyTemplateArgument,
334 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
335 TemplateSpecializationType),
336 internal::Matcher<TemplateArgument>, InnerMatcher) {
337 ArrayRef<TemplateArgument> List =
338 internal::getTemplateSpecializationArgs(Node);
339 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
343 /// \brief Matches expressions that match InnerMatcher after any implicit casts
344 /// are stripped off.
346 /// Parentheses and explicit casts are not discarded.
354 /// long e = (long) 0l;
358 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
359 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
361 /// would match the declarations for a, b, c, and d, but not e.
364 /// varDecl(hasInitializer(integerLiteral()))
365 /// varDecl(hasInitializer(declRefExpr()))
367 /// only match the declarations for b, c, and d.
368 AST_MATCHER_P(Expr, ignoringImpCasts,
369 internal::Matcher<Expr>, InnerMatcher) {
370 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
373 /// \brief Matches expressions that match InnerMatcher after parentheses and
374 /// casts are stripped off.
376 /// Implicit and non-C Style casts are also discarded.
381 /// void* c = reinterpret_cast<char*>(0);
382 /// char d = char(0);
385 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
386 /// would match the declarations for a, b, c, and d.
388 /// varDecl(hasInitializer(integerLiteral()))
389 /// only match the declaration for a.
390 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
391 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
394 /// \brief Matches expressions that match InnerMatcher after implicit casts and
395 /// parentheses are stripped off.
397 /// Explicit casts are not discarded.
405 /// long e = ((long) 0l);
408 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
409 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
410 /// would match the declarations for a, b, c, and d, but not e.
412 /// varDecl(hasInitializer(integerLiteral()))
413 /// varDecl(hasInitializer(declRefExpr()))
414 /// would only match the declaration for a.
415 AST_MATCHER_P(Expr, ignoringParenImpCasts,
416 internal::Matcher<Expr>, InnerMatcher) {
417 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
420 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
421 /// matches the given InnerMatcher.
425 /// template<typename T, typename U> class A {};
429 /// classTemplateSpecializationDecl(hasTemplateArgument(
430 /// 1, refersToType(asString("int"))))
431 /// matches the specialization \c A<bool, int>
432 AST_POLYMORPHIC_MATCHER_P2(
434 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
435 TemplateSpecializationType),
436 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
437 ArrayRef<TemplateArgument> List =
438 internal::getTemplateSpecializationArgs(Node);
439 if (List.size() <= N)
441 return InnerMatcher.matches(List[N], Finder, Builder);
444 /// \brief Matches a TemplateArgument that refers to a certain type.
449 /// template<typename T> struct A {};
452 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
453 /// refersToType(class(hasName("X")))))
454 /// matches the specialization \c A<X>
455 AST_MATCHER_P(TemplateArgument, refersToType,
456 internal::Matcher<QualType>, InnerMatcher) {
457 if (Node.getKind() != TemplateArgument::Type)
459 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
462 /// \brief Matches a canonical TemplateArgument that refers to a certain
467 /// template<typename T> struct A {};
468 /// struct B { B* next; };
471 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
472 /// refersToDeclaration(fieldDecl(hasName("next"))))
473 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
475 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
476 internal::Matcher<Decl>, InnerMatcher) {
477 if (Node.getKind() == TemplateArgument::Declaration)
478 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
482 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
486 /// template<typename T> struct A {};
487 /// struct B { B* next; };
490 /// templateSpecializationType(hasAnyTemplateArgument(
491 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
492 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
494 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
495 if (Node.getKind() == TemplateArgument::Expression)
496 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
500 /// \brief Matches C++ constructor declarations.
502 /// Example matches Foo::Foo() and Foo::Foo(int)
508 /// int DoSomething();
511 const internal::VariadicDynCastAllOfMatcher<
513 CXXConstructorDecl> constructorDecl;
515 /// \brief Matches explicit C++ destructor declarations.
517 /// Example matches Foo::~Foo()
524 const internal::VariadicDynCastAllOfMatcher<
526 CXXDestructorDecl> destructorDecl;
528 /// \brief Matches enum declarations.
530 /// Example matches X
536 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
538 /// \brief Matches enum constants.
540 /// Example matches A, B, C
546 const internal::VariadicDynCastAllOfMatcher<
548 EnumConstantDecl> enumConstantDecl;
550 /// \brief Matches method declarations.
552 /// Example matches y
554 /// class X { void y(); };
556 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
558 /// \brief Matches variable declarations.
560 /// Note: this does not match declarations of member variables, which are
561 /// "field" declarations in Clang parlance.
563 /// Example matches a
567 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
569 /// \brief Matches field declarations.
573 /// class X { int m; };
577 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
579 /// \brief Matches function declarations.
581 /// Example matches f
585 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
587 /// \brief Matches C++ function template declarations.
589 /// Example matches f
591 /// template<class T> void f(T t) {}
593 const internal::VariadicDynCastAllOfMatcher<
595 FunctionTemplateDecl> functionTemplateDecl;
597 /// \brief Matches friend declarations.
601 /// class X { friend void foo(); };
604 /// matches 'friend void foo()'.
605 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
607 /// \brief Matches statements.
614 /// matches both the compound statement '{ ++a; }' and '++a'.
615 const internal::VariadicAllOfMatcher<Stmt> stmt;
617 /// \brief Matches declaration statements.
625 const internal::VariadicDynCastAllOfMatcher<
629 /// \brief Matches member expressions.
634 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
635 /// int a; static int b;
639 /// matches this->x, x, y.x, a, this->b
640 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
642 /// \brief Matches call expressions.
644 /// Example matches x.y() and y()
650 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
652 /// \brief Matches lambda expressions.
654 /// Example matches [&](){return 5;}
658 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
660 /// \brief Matches member call expressions.
662 /// Example matches x.y()
667 const internal::VariadicDynCastAllOfMatcher<
669 CXXMemberCallExpr> memberCallExpr;
671 /// \brief Matches expressions that introduce cleanups to be run at the end
672 /// of the sub-expression's evaluation.
674 /// Example matches std::string()
676 /// const std::string str = std::string();
678 const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
681 /// \brief Matches init list expressions.
685 /// int a[] = { 1, 2 };
686 /// struct B { int x, y; };
690 /// matches "{ 1, 2 }" and "{ 5, 6 }"
691 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
693 /// \brief Matches substitutions of non-type template parameters.
698 /// struct A { static const int n = N; };
699 /// struct B : public A<42> {};
701 /// substNonTypeTemplateParmExpr()
702 /// matches "N" in the right-hand side of "static const int n = N;"
703 const internal::VariadicDynCastAllOfMatcher<Stmt, SubstNonTypeTemplateParmExpr>
704 substNonTypeTemplateParmExpr;
706 /// \brief Matches using declarations.
710 /// namespace X { int x; }
714 /// matches \code using X::x \endcode
715 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
717 /// \brief Matches using namespace declarations.
721 /// namespace X { int x; }
722 /// using namespace X;
724 /// usingDirectiveDecl()
725 /// matches \code using namespace X \endcode
726 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
729 /// \brief Matches unresolved using value declarations.
733 /// template<typename X>
734 /// class C : private X {
738 /// unresolvedUsingValueDecl()
739 /// matches \code using X::x \endcode
740 const internal::VariadicDynCastAllOfMatcher<
742 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
744 /// \brief Matches constructor call expressions (including implicit ones).
746 /// Example matches string(ptr, n) and ptr within arguments of f
747 /// (matcher = constructExpr())
749 /// void f(const string &a, const string &b);
752 /// f(string(ptr, n), ptr);
754 const internal::VariadicDynCastAllOfMatcher<
756 CXXConstructExpr> constructExpr;
758 /// \brief Matches unresolved constructor call expressions.
760 /// Example matches T(t) in return statement of f
761 /// (matcher = unresolvedConstructExpr())
763 /// template <typename T>
764 /// void f(const T& t) { return T(t); }
766 const internal::VariadicDynCastAllOfMatcher<
768 CXXUnresolvedConstructExpr> unresolvedConstructExpr;
770 /// \brief Matches implicit and explicit this expressions.
772 /// Example matches the implicit this expression in "return i".
773 /// (matcher = thisExpr())
777 /// int f() { return i; }
780 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr;
782 /// \brief Matches nodes where temporaries are created.
784 /// Example matches FunctionTakesString(GetStringByValue())
785 /// (matcher = bindTemporaryExpr())
787 /// FunctionTakesString(GetStringByValue());
788 /// FunctionTakesStringByPointer(GetStringPointer());
790 const internal::VariadicDynCastAllOfMatcher<
792 CXXBindTemporaryExpr> bindTemporaryExpr;
794 /// \brief Matches nodes where temporaries are materialized.
798 /// struct T {void func()};
802 /// materializeTemporaryExpr() matches 'f()' in these statements
807 /// but does not match
812 const internal::VariadicDynCastAllOfMatcher<
814 MaterializeTemporaryExpr> materializeTemporaryExpr;
816 /// \brief Matches new expressions.
824 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr;
826 /// \brief Matches delete expressions.
833 /// matches 'delete X'.
834 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr;
836 /// \brief Matches array subscript expressions.
842 /// arraySubscriptExpr()
844 const internal::VariadicDynCastAllOfMatcher<
846 ArraySubscriptExpr> arraySubscriptExpr;
848 /// \brief Matches the value of a default argument at the call site.
850 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
851 /// default value of the second parameter in the call expression f(42)
852 /// (matcher = defaultArgExpr())
854 /// void f(int x, int y = 0);
857 const internal::VariadicDynCastAllOfMatcher<
859 CXXDefaultArgExpr> defaultArgExpr;
861 /// \brief Matches overloaded operator calls.
863 /// Note that if an operator isn't overloaded, it won't match. Instead, use
864 /// binaryOperator matcher.
865 /// Currently it does not match operators such as new delete.
866 /// FIXME: figure out why these do not match?
868 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
869 /// (matcher = operatorCallExpr())
871 /// ostream &operator<< (ostream &out, int i) { };
872 /// ostream &o; int b = 1, c = 1;
875 const internal::VariadicDynCastAllOfMatcher<
877 CXXOperatorCallExpr> operatorCallExpr;
879 /// \brief Matches expressions.
881 /// Example matches x()
883 /// void f() { x(); }
885 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
887 /// \brief Matches expressions that refer to declarations.
889 /// Example matches x in if (x)
894 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
896 /// \brief Matches if statements.
898 /// Example matches 'if (x) {}'
902 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
904 /// \brief Matches for statements.
906 /// Example matches 'for (;;) {}'
909 /// int i[] = {1, 2, 3}; for (auto a : i);
911 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
913 /// \brief Matches the increment statement of a for loop.
916 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
919 /// for (x; x < N; ++x) { }
921 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
923 const Stmt *const Increment = Node.getInc();
924 return (Increment != nullptr &&
925 InnerMatcher.matches(*Increment, Finder, Builder));
928 /// \brief Matches the initialization statement of a for loop.
931 /// forStmt(hasLoopInit(declStmt()))
932 /// matches 'int x = 0' in
934 /// for (int x = 0; x < N; ++x) { }
936 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
938 const Stmt *const Init = Node.getInit();
939 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
942 /// \brief Matches range-based for statements.
944 /// forRangeStmt() matches 'for (auto a : i)'
946 /// int i[] = {1, 2, 3}; for (auto a : i);
947 /// for(int j = 0; j < 5; ++j);
949 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt;
951 /// \brief Matches the initialization statement of a for loop.
954 /// forStmt(hasLoopVariable(anything()))
955 /// matches 'int x' in
957 /// for (int x : a) { }
959 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
961 const VarDecl *const Var = Node.getLoopVariable();
962 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
965 /// \brief Matches the range initialization statement of a for loop.
968 /// forStmt(hasRangeInit(anything()))
971 /// for (int x : a) { }
973 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
975 const Expr *const Init = Node.getRangeInit();
976 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
979 /// \brief Matches while statements.
986 /// matches 'while (true) {}'.
987 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
989 /// \brief Matches do statements.
993 /// do {} while (true);
996 /// matches 'do {} while(true)'
997 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
999 /// \brief Matches break statements.
1003 /// while (true) { break; }
1007 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1009 /// \brief Matches continue statements.
1013 /// while (true) { continue; }
1016 /// matches 'continue'
1017 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1019 /// \brief Matches return statements.
1026 /// matches 'return 1'
1027 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1029 /// \brief Matches goto statements.
1037 /// matches 'goto FOO'
1038 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1040 /// \brief Matches label statements.
1049 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1051 /// \brief Matches switch statements.
1055 /// switch(a) { case 42: break; default: break; }
1058 /// matches 'switch(a)'.
1059 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1061 /// \brief Matches case and default statements inside switch statements.
1065 /// switch(a) { case 42: break; default: break; }
1068 /// matches 'case 42: break;' and 'default: break;'.
1069 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1071 /// \brief Matches case statements inside switch statements.
1075 /// switch(a) { case 42: break; default: break; }
1078 /// matches 'case 42: break;'.
1079 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1081 /// \brief Matches default statements inside switch statements.
1085 /// switch(a) { case 42: break; default: break; }
1088 /// matches 'default: break;'.
1089 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1091 /// \brief Matches compound statements.
1093 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1097 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1099 /// \brief Matches catch statements.
1102 /// try {} catch(int i) {}
1105 /// matches 'catch(int i)'
1106 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt;
1108 /// \brief Matches try statements.
1111 /// try {} catch(int i) {}
1114 /// matches 'try {}'
1115 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt;
1117 /// \brief Matches throw expressions.
1120 /// try { throw 5; } catch(int i) {}
1123 /// matches 'throw 5'
1124 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr;
1126 /// \brief Matches null statements.
1132 /// matches the second ';'
1133 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1135 /// \brief Matches asm statements.
1139 /// __asm("mov al, 2");
1142 /// matches '__asm("mov al, 2")'
1143 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1145 /// \brief Matches bool literals.
1147 /// Example matches true
1151 const internal::VariadicDynCastAllOfMatcher<
1153 CXXBoolLiteralExpr> boolLiteral;
1155 /// \brief Matches string literals (also matches wide string literals).
1157 /// Example matches "abcd", L"abcd"
1159 /// char *s = "abcd"; wchar_t *ws = L"abcd"
1161 const internal::VariadicDynCastAllOfMatcher<
1163 StringLiteral> stringLiteral;
1165 /// \brief Matches character literals (also matches wchar_t).
1167 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1170 /// Example matches 'a', L'a'
1172 /// char ch = 'a'; wchar_t chw = L'a';
1174 const internal::VariadicDynCastAllOfMatcher<
1176 CharacterLiteral> characterLiteral;
1178 /// \brief Matches integer literals of all sizes / encodings, e.g.
1179 /// 1, 1L, 0x1 and 1U.
1181 /// Does not match character-encoded integers such as L'a'.
1182 const internal::VariadicDynCastAllOfMatcher<
1184 IntegerLiteral> integerLiteral;
1186 /// \brief Matches float literals of all sizes / encodings, e.g.
1187 /// 1.0, 1.0f, 1.0L and 1e10.
1189 /// Does not match implicit conversions such as
1193 const internal::VariadicDynCastAllOfMatcher<
1195 FloatingLiteral> floatLiteral;
1197 /// \brief Matches user defined literal operator call.
1199 /// Example match: "foo"_suffix
1200 const internal::VariadicDynCastAllOfMatcher<
1202 UserDefinedLiteral> userDefinedLiteral;
1204 /// \brief Matches compound (i.e. non-scalar) literals
1206 /// Example match: {1}, (1, 2)
1208 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1210 const internal::VariadicDynCastAllOfMatcher<
1212 CompoundLiteralExpr> compoundLiteralExpr;
1214 /// \brief Matches nullptr literal.
1215 const internal::VariadicDynCastAllOfMatcher<
1217 CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
1219 /// \brief Matches binary operator expressions.
1221 /// Example matches a || b
1225 const internal::VariadicDynCastAllOfMatcher<
1227 BinaryOperator> binaryOperator;
1229 /// \brief Matches unary operator expressions.
1231 /// Example matches !a
1235 const internal::VariadicDynCastAllOfMatcher<
1237 UnaryOperator> unaryOperator;
1239 /// \brief Matches conditional operator expressions.
1241 /// Example matches a ? b : c
1243 /// (a ? b : c) + 42
1245 const internal::VariadicDynCastAllOfMatcher<
1247 ConditionalOperator> conditionalOperator;
1249 /// \brief Matches a reinterpret_cast expression.
1251 /// Either the source expression or the destination type can be matched
1252 /// using has(), but hasDestinationType() is more specific and can be
1255 /// Example matches reinterpret_cast<char*>(&p) in
1257 /// void* p = reinterpret_cast<char*>(&p);
1259 const internal::VariadicDynCastAllOfMatcher<
1261 CXXReinterpretCastExpr> reinterpretCastExpr;
1263 /// \brief Matches a C++ static_cast expression.
1265 /// \see hasDestinationType
1266 /// \see reinterpretCast
1269 /// staticCastExpr()
1271 /// static_cast<long>(8)
1274 /// long eight(static_cast<long>(8));
1276 const internal::VariadicDynCastAllOfMatcher<
1278 CXXStaticCastExpr> staticCastExpr;
1280 /// \brief Matches a dynamic_cast expression.
1283 /// dynamicCastExpr()
1285 /// dynamic_cast<D*>(&b);
1288 /// struct B { virtual ~B() {} }; struct D : B {};
1290 /// D* p = dynamic_cast<D*>(&b);
1292 const internal::VariadicDynCastAllOfMatcher<
1294 CXXDynamicCastExpr> dynamicCastExpr;
1296 /// \brief Matches a const_cast expression.
1298 /// Example: Matches const_cast<int*>(&r) in
1301 /// const int &r(n);
1302 /// int* p = const_cast<int*>(&r);
1304 const internal::VariadicDynCastAllOfMatcher<
1306 CXXConstCastExpr> constCastExpr;
1308 /// \brief Matches a C-style cast expression.
1310 /// Example: Matches (int*) 2.2f in
1312 /// int i = (int) 2.2f;
1314 const internal::VariadicDynCastAllOfMatcher<
1316 CStyleCastExpr> cStyleCastExpr;
1318 /// \brief Matches explicit cast expressions.
1320 /// Matches any cast expression written in user code, whether it be a
1321 /// C-style cast, a functional-style cast, or a keyword cast.
1323 /// Does not match implicit conversions.
1325 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1326 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1327 /// actual cast expressions.
1329 /// \see hasDestinationType.
1331 /// Example: matches all five of the casts in
1333 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1335 /// but does not match the implicit conversion in
1339 const internal::VariadicDynCastAllOfMatcher<
1341 ExplicitCastExpr> explicitCastExpr;
1343 /// \brief Matches the implicit cast nodes of Clang's AST.
1345 /// This matches many different places, including function call return value
1346 /// eliding, as well as any type conversions.
1347 const internal::VariadicDynCastAllOfMatcher<
1349 ImplicitCastExpr> implicitCastExpr;
1351 /// \brief Matches any cast nodes of Clang's AST.
1353 /// Example: castExpr() matches each of the following:
1356 /// const_cast<Expr *>(SubExpr);
1359 /// but does not match
1364 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1366 /// \brief Matches functional cast expressions
1368 /// Example: Matches Foo(bar);
1371 /// Foo g = (Foo) bar;
1372 /// Foo h = Foo(bar);
1374 const internal::VariadicDynCastAllOfMatcher<
1376 CXXFunctionalCastExpr> functionalCastExpr;
1378 /// \brief Matches functional cast expressions having N != 1 arguments
1380 /// Example: Matches Foo(bar, bar)
1382 /// Foo h = Foo(bar, bar);
1384 const internal::VariadicDynCastAllOfMatcher<
1386 CXXTemporaryObjectExpr> temporaryObjectExpr;
1388 /// \brief Matches \c QualTypes in the clang AST.
1389 const internal::VariadicAllOfMatcher<QualType> qualType;
1391 /// \brief Matches \c Types in the clang AST.
1392 const internal::VariadicAllOfMatcher<Type> type;
1394 /// \brief Matches \c TypeLocs in the clang AST.
1395 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1397 /// \brief Matches if any of the given matchers matches.
1399 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1400 /// matching submatcher.
1402 /// For example, in:
1404 /// class A { int a; int b; };
1408 /// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1409 /// has(fieldDecl(hasName("b")).bind("v"))))
1411 /// will generate two results binding "v", the first of which binds
1412 /// the field declaration of \c a, the second the field declaration of
1415 /// Usable as: Any Matcher
1416 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
1417 internal::EachOfVariadicOperator
1420 /// \brief Matches if any of the given matchers matches.
1422 /// Usable as: Any Matcher
1423 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
1424 internal::AnyOfVariadicOperator
1427 /// \brief Matches if all given matchers match.
1429 /// Usable as: Any Matcher
1430 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
1431 internal::AllOfVariadicOperator
1434 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1439 /// int y = sizeof(x) + alignof(x);
1441 /// unaryExprOrTypeTraitExpr()
1442 /// matches \c sizeof(x) and \c alignof(x)
1443 const internal::VariadicDynCastAllOfMatcher<
1445 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1447 /// \brief Matches unary expressions that have a specific type of argument.
1451 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1453 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1454 /// matches \c sizeof(a) and \c alignof(c)
1455 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1456 internal::Matcher<QualType>, InnerMatcher) {
1457 const QualType ArgumentType = Node.getTypeOfArgument();
1458 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1461 /// \brief Matches unary expressions of a certain kind.
1466 /// int s = sizeof(x) + alignof(x)
1468 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1469 /// matches \c sizeof(x)
1470 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1471 return Node.getKind() == Kind;
1474 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1476 inline internal::Matcher<Stmt> alignOfExpr(
1477 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1478 return stmt(unaryExprOrTypeTraitExpr(allOf(
1479 ofKind(UETT_AlignOf), InnerMatcher)));
1482 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1484 inline internal::Matcher<Stmt> sizeOfExpr(
1485 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1486 return stmt(unaryExprOrTypeTraitExpr(
1487 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1490 /// \brief Matches NamedDecl nodes that have the specified name.
1492 /// Supports specifying enclosing namespaces or classes by prefixing the name
1493 /// with '<enclosing>::'.
1494 /// Does not match typedefs of an underlying type with the given name.
1496 /// Example matches X (Name == "X")
1501 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1503 /// namespace a { namespace b { class X; } }
1505 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1506 assert(!Name.empty());
1507 const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1508 const StringRef FullName = FullNameString;
1509 const StringRef Pattern = Name;
1510 if (Pattern.startswith("::")) {
1511 return FullName == Pattern;
1513 return FullName.endswith(("::" + Pattern).str());
1517 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1518 /// a substring matched by the given RegExp.
1520 /// Supports specifying enclosing namespaces or classes by
1521 /// prefixing the name with '<enclosing>::'. Does not match typedefs
1522 /// of an underlying type with the given name.
1524 /// Example matches X (regexp == "::X")
1529 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1531 /// namespace foo { namespace bar { class X; } }
1533 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1534 assert(!RegExp.empty());
1535 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1536 llvm::Regex RE(RegExp);
1537 return RE.match(FullNameString);
1540 /// \brief Matches overloaded operator names.
1542 /// Matches overloaded operator names specified in strings without the
1543 /// "operator" prefix: e.g. "<<".
1547 /// class A { int operator*(); };
1548 /// const A &operator<<(const A &a, const A &b);
1550 /// a << a; // <-- This matches
1553 /// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified
1554 /// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
1555 /// the declaration of \c A.
1557 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
1558 inline internal::PolymorphicMatcherWithParam1<
1559 internal::HasOverloadedOperatorNameMatcher, StringRef,
1560 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, FunctionDecl)>
1561 hasOverloadedOperatorName(const StringRef Name) {
1562 return internal::PolymorphicMatcherWithParam1<
1563 internal::HasOverloadedOperatorNameMatcher, StringRef,
1564 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, FunctionDecl)>(
1568 /// \brief Matches C++ classes that are directly or indirectly derived from
1569 /// a class matching \c Base.
1571 /// Note that a class is not considered to be derived from itself.
1573 /// Example matches Y, Z, C (Base == hasName("X"))
1576 /// class Y : public X {}; // directly derived
1577 /// class Z : public Y {}; // indirectly derived
1580 /// class C : public B {}; // derived from a typedef of X
1583 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1587 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
1589 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1590 internal::Matcher<NamedDecl>, Base) {
1591 return Finder->classIsDerivedFrom(&Node, Base, Builder);
1594 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1595 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, StringRef, BaseName, 1) {
1596 assert(!BaseName.empty());
1597 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1600 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1602 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
1603 internal::Matcher<NamedDecl>, Base, 0) {
1604 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
1605 .matches(Node, Finder, Builder);
1608 /// \brief Overloaded method as shortcut for
1609 /// \c isSameOrDerivedFrom(hasName(...)).
1610 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, StringRef, BaseName,
1612 assert(!BaseName.empty());
1613 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1616 /// \brief Matches the first method of a class or struct that satisfies \c
1621 /// class A { void func(); };
1622 /// class B { void member(); };
1625 /// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A
1627 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1629 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
1630 Node.method_end(), Finder, Builder);
1633 /// \brief Matches AST nodes that have child AST nodes that match the
1634 /// provided matcher.
1636 /// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1638 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1639 /// class Y { class X {}; };
1640 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1643 /// ChildT must be an AST base type.
1645 /// Usable as: Any Matcher
1646 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
1647 LLVM_ATTRIBUTE_UNUSED has = {};
1649 /// \brief Matches AST nodes that have descendant AST nodes that match the
1650 /// provided matcher.
1652 /// Example matches X, Y, Z
1653 /// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1655 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1656 /// class Y { class X {}; };
1657 /// class Z { class Y { class X {}; }; };
1660 /// DescendantT must be an AST base type.
1662 /// Usable as: Any Matcher
1663 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
1664 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
1666 /// \brief Matches AST nodes that have child AST nodes that match the
1667 /// provided matcher.
1669 /// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1671 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1672 /// class Y { class X {}; };
1673 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1676 /// ChildT must be an AST base type.
1678 /// As opposed to 'has', 'forEach' will cause a match for each result that
1679 /// matches instead of only on the first one.
1681 /// Usable as: Any Matcher
1682 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
1683 LLVM_ATTRIBUTE_UNUSED forEach = {};
1685 /// \brief Matches AST nodes that have descendant AST nodes that match the
1686 /// provided matcher.
1688 /// Example matches X, A, B, C
1689 /// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1691 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1692 /// class A { class X {}; };
1693 /// class B { class C { class X {}; }; };
1696 /// DescendantT must be an AST base type.
1698 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1699 /// each result that matches instead of only on the first one.
1701 /// Note: Recursively combined ForEachDescendant can cause many matches:
1702 /// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1703 /// will match 10 times (plus injected class name matches) on:
1705 /// class A { class B { class C { class D { class E {}; }; }; }; };
1708 /// Usable as: Any Matcher
1709 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
1710 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
1712 /// \brief Matches if the node or any descendant matches.
1714 /// Generates results for each match.
1716 /// For example, in:
1718 /// class A { class B {}; class C {}; };
1722 /// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1724 /// will generate results for \c A, \c B and \c C.
1726 /// Usable as: Any Matcher
1727 template <typename T>
1728 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
1729 return eachOf(Matcher, forEachDescendant(Matcher));
1732 /// \brief Matches AST nodes that have a parent that matches the provided
1737 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1739 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1741 /// Usable as: Any Matcher
1742 const internal::ArgumentAdaptingMatcherFunc<
1743 internal::HasParentMatcher, internal::TypeList<Decl, Stmt>,
1744 internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasParent = {};
1746 /// \brief Matches AST nodes that have an ancestor that matches the provided
1751 /// void f() { if (true) { int x = 42; } }
1752 /// void g() { for (;;) { int x = 43; } }
1754 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1756 /// Usable as: Any Matcher
1757 const internal::ArgumentAdaptingMatcherFunc<
1758 internal::HasAncestorMatcher, internal::TypeList<Decl, Stmt>,
1759 internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
1761 /// \brief Matches if the provided matcher does not match.
1763 /// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1769 /// Usable as: Any Matcher
1770 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
1771 internal::NotUnaryOperator
1774 /// \brief Matches a node if the declaration associated with that node
1775 /// matches the given matcher.
1777 /// The associated declaration is:
1778 /// - for type nodes, the declaration of the underlying type
1779 /// - for CallExpr, the declaration of the callee
1780 /// - for MemberExpr, the declaration of the referenced member
1781 /// - for CXXConstructExpr, the declaration of the constructor
1783 /// Also usable as Matcher<T> for any T supporting the getDecl() member
1784 /// function. e.g. various subtypes of clang::Type and various expressions.
1786 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1787 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
1788 /// Matcher<LabelStmt>, Matcher<MemberExpr>, Matcher<QualType>,
1789 /// Matcher<RecordType>, Matcher<TagType>,
1790 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
1791 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
1792 inline internal::PolymorphicMatcherWithParam1<
1793 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
1794 void(internal::HasDeclarationSupportedTypes)>
1795 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1796 return internal::PolymorphicMatcherWithParam1<
1797 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
1798 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
1801 /// \brief Matches on the implicit object argument of a member call expression.
1803 /// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1805 /// class Y { public: void x(); };
1806 /// void z() { Y y; y.x(); }",
1809 /// FIXME: Overload to allow directly matching types?
1810 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1812 const Expr *ExprNode = Node.getImplicitObjectArgument()
1813 ->IgnoreParenImpCasts();
1814 return (ExprNode != nullptr &&
1815 InnerMatcher.matches(*ExprNode, Finder, Builder));
1818 /// \brief Matches if the call expression's callee expression matches.
1822 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
1823 /// void f() { f(); }
1825 /// callExpr(callee(expr()))
1826 /// matches this->x(), x(), y.x(), f()
1827 /// with callee(...)
1828 /// matching this->x, x, y.x, f respectively
1830 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1831 /// because this introduces ambiguous overloads with calls to Callee taking a
1832 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1833 /// implemented in terms of implicit casts.
1834 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1836 const Expr *ExprNode = Node.getCallee();
1837 return (ExprNode != nullptr &&
1838 InnerMatcher.matches(*ExprNode, Finder, Builder));
1841 /// \brief Matches if the call expression's callee's declaration matches the
1844 /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1846 /// class Y { public: void x(); };
1847 /// void z() { Y y; y.x(); }
1849 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
1851 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
1854 /// \brief Matches if the expression's or declaration's type matches a type
1857 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1858 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1861 /// void y(X &x) { x; X z; }
1863 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
1864 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl),
1865 internal::Matcher<QualType>, InnerMatcher, 0) {
1866 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1869 /// \brief Overloaded to match the declaration of the expression's or value
1870 /// declaration's type.
1872 /// In case of a value declaration (for example a variable declaration),
1873 /// this resolves one layer of indirection. For example, in the value
1874 /// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1875 /// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1878 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1879 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1882 /// void y(X &x) { x; X z; }
1885 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1886 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
1887 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl),
1888 internal::Matcher<Decl>, InnerMatcher, 1) {
1889 return qualType(hasDeclaration(InnerMatcher))
1890 .matches(Node.getType(), Finder, Builder);
1893 /// \brief Matches if the type location of the declarator decl's type matches
1894 /// the inner matcher.
1900 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
1902 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
1903 if (!Node.getTypeSourceInfo())
1904 // This happens for example for implicit destructors.
1906 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
1909 /// \brief Matches if the matched type is represented by the given string.
1913 /// class Y { public: void x(); };
1914 /// void z() { Y* y; y->x(); }
1916 /// callExpr(on(hasType(asString("class Y *"))))
1918 AST_MATCHER_P(QualType, asString, std::string, Name) {
1919 return Name == Node.getAsString();
1922 /// \brief Matches if the matched type is a pointer type and the pointee type
1923 /// matches the specified matcher.
1925 /// Example matches y->x()
1926 /// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1928 /// class Y { public: void x(); };
1929 /// void z() { Y *y; y->x(); }
1932 QualType, pointsTo, internal::Matcher<QualType>,
1934 return (!Node.isNull() && Node->isPointerType() &&
1935 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1938 /// \brief Overloaded to match the pointee type's declaration.
1939 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
1941 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
1942 .matches(Node, Finder, Builder);
1945 /// \brief Matches if the matched type is a reference type and the referenced
1946 /// type matches the specified matcher.
1948 /// Example matches X &x and const X &y
1949 /// (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1958 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1960 return (!Node.isNull() && Node->isReferenceType() &&
1961 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1964 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1968 /// typedef int &int_ref;
1973 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1974 /// declaration of b but \c
1975 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1976 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1980 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1983 /// \brief Overloaded to match the referenced type's declaration.
1984 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
1986 return references(qualType(hasDeclaration(InnerMatcher)))
1987 .matches(Node, Finder, Builder);
1990 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1991 internal::Matcher<Expr>, InnerMatcher) {
1992 const Expr *ExprNode = Node.getImplicitObjectArgument();
1993 return (ExprNode != nullptr &&
1994 InnerMatcher.matches(*ExprNode, Finder, Builder));
1997 /// \brief Matches if the expression's type either matches the specified
1998 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1999 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2000 internal::Matcher<QualType>, InnerMatcher, 0) {
2001 return onImplicitObjectArgument(
2002 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2003 .matches(Node, Finder, Builder);
2006 /// \brief Overloaded to match the type's declaration.
2007 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2008 internal::Matcher<Decl>, InnerMatcher, 1) {
2009 return onImplicitObjectArgument(
2010 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2011 .matches(Node, Finder, Builder);
2014 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2015 /// specified matcher.
2017 /// Example matches x in if(x)
2018 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2023 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2025 const Decl *DeclNode = Node.getDecl();
2026 return (DeclNode != nullptr &&
2027 InnerMatcher.matches(*DeclNode, Finder, Builder));
2030 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2031 /// specific using shadow declaration.
2033 /// FIXME: This currently only works for functions. Fix.
2037 /// namespace a { void f() {} }
2040 /// f(); // Matches this ..
2041 /// a::f(); // .. but not this.
2044 /// declRefExpr(throughUsingDeclaration(anything()))
2046 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2047 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2048 const NamedDecl *FoundDecl = Node.getFoundDecl();
2049 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2050 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2054 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2061 /// declStmt(hasSingleDecl(anything()))
2062 /// matches 'int c;' but not 'int a, b;'.
2063 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2064 if (Node.isSingleDecl()) {
2065 const Decl *FoundDecl = Node.getSingleDecl();
2066 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2071 /// \brief Matches a variable declaration that has an initializer expression
2072 /// that matches the given matcher.
2074 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2076 /// bool y() { return true; }
2080 VarDecl, hasInitializer, internal::Matcher<Expr>,
2082 const Expr *Initializer = Node.getAnyInitializer();
2083 return (Initializer != nullptr &&
2084 InnerMatcher.matches(*Initializer, Finder, Builder));
2087 /// \brief Matches a variable declaration that has function scope and is a
2088 /// non-static local variable.
2090 /// Example matches x (matcher = varDecl(hasLocalStorage())
2098 AST_MATCHER(VarDecl, hasLocalStorage) {
2099 return Node.hasLocalStorage();
2102 /// \brief Matches a variable declaration that does not have local storage.
2104 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2112 AST_MATCHER(VarDecl, hasGlobalStorage) {
2113 return Node.hasGlobalStorage();
2116 /// \brief Checks that a call expression or a constructor call expression has
2117 /// a specific number of arguments (including absent default arguments).
2119 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2121 /// void f(int x, int y);
2124 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2125 CallExpr, CXXConstructExpr),
2127 return Node.getNumArgs() == N;
2130 /// \brief Matches the n'th argument of a call expression or a constructor
2131 /// call expression.
2133 /// Example matches y in x(y)
2134 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2136 /// void x(int) { int y; x(y); }
2138 AST_POLYMORPHIC_MATCHER_P2(
2140 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr),
2141 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2142 return (N < Node.getNumArgs() &&
2143 InnerMatcher.matches(
2144 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2147 /// \brief Matches declaration statements that contain a specific number of
2157 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2158 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2159 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2162 /// \brief Matches the n'th declaration of a declaration statement.
2164 /// Note that this does not work for global declarations because the AST
2165 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2167 /// Example: Given non-global declarations
2173 /// declStmt(containsDeclaration(
2174 /// 0, varDecl(hasInitializer(anything()))))
2175 /// matches only 'int d = 2, e;', and
2176 /// declStmt(containsDeclaration(1, varDecl()))
2178 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2179 /// but 'int c;' is not matched.
2181 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2182 internal::Matcher<Decl>, InnerMatcher) {
2183 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2186 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2187 std::advance(Iterator, N);
2188 return InnerMatcher.matches(**Iterator, Finder, Builder);
2191 /// \brief Matches a constructor initializer.
2196 /// Foo() : foo_(1) { }
2200 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2201 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2202 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2203 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2204 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2205 Node.init_end(), Finder, Builder);
2208 /// \brief Matches the field declaration of a constructor initializer.
2213 /// Foo() : foo_(1) { }
2217 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2218 /// forField(hasName("foo_"))))))
2220 /// with forField matching foo_
2221 AST_MATCHER_P(CXXCtorInitializer, forField,
2222 internal::Matcher<FieldDecl>, InnerMatcher) {
2223 const FieldDecl *NodeAsDecl = Node.getMember();
2224 return (NodeAsDecl != nullptr &&
2225 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2228 /// \brief Matches the initializer expression of a constructor initializer.
2233 /// Foo() : foo_(1) { }
2237 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2238 /// withInitializer(integerLiteral(equals(1)))))))
2240 /// with withInitializer matching (1)
2241 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2242 internal::Matcher<Expr>, InnerMatcher) {
2243 const Expr* NodeAsExpr = Node.getInit();
2244 return (NodeAsExpr != nullptr &&
2245 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2248 /// \brief Matches a constructor initializer if it is explicitly written in
2249 /// code (as opposed to implicitly added by the compiler).
2255 /// Foo(int) : foo_("A") { }
2259 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2260 /// will match Foo(int), but not Foo()
2261 AST_MATCHER(CXXCtorInitializer, isWritten) {
2262 return Node.isWritten();
2265 /// \brief Matches any argument of a call expression or a constructor call
2270 /// void x(int, int, int) { int y; x(1, y, 42); }
2272 /// callExpr(hasAnyArgument(declRefExpr()))
2273 /// matches x(1, y, 42)
2274 /// with hasAnyArgument(...)
2277 /// FIXME: Currently this will ignore parentheses and implicit casts on
2278 /// the argument before applying the inner matcher. We'll want to remove
2279 /// this to allow for greater control by the user once \c ignoreImplicit()
2280 /// has been implemented.
2281 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2282 CallExpr, CXXConstructExpr),
2283 internal::Matcher<Expr>, InnerMatcher) {
2284 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2285 BoundNodesTreeBuilder Result(*Builder);
2286 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
2295 /// \brief Matches a constructor call expression which uses list initialization.
2296 AST_MATCHER(CXXConstructExpr, isListInitialization) {
2297 return Node.isListInitialization();
2300 /// \brief Matches the n'th parameter of a function declaration.
2304 /// class X { void f(int x) {} };
2306 /// methodDecl(hasParameter(0, hasType(varDecl())))
2307 /// matches f(int x) {}
2308 /// with hasParameter(...)
2310 AST_MATCHER_P2(FunctionDecl, hasParameter,
2311 unsigned, N, internal::Matcher<ParmVarDecl>,
2313 return (N < Node.getNumParams() &&
2314 InnerMatcher.matches(
2315 *Node.getParamDecl(N), Finder, Builder));
2318 /// \brief Matches any parameter of a function declaration.
2320 /// Does not match the 'this' parameter of a method.
2324 /// class X { void f(int x, int y, int z) {} };
2326 /// methodDecl(hasAnyParameter(hasName("y")))
2327 /// matches f(int x, int y, int z) {}
2328 /// with hasAnyParameter(...)
2330 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2331 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2332 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2333 Node.param_end(), Finder, Builder);
2336 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2340 /// void f(int i) {}
2341 /// void g(int i, int j) {}
2343 /// functionDecl(parameterCountIs(2))
2344 /// matches g(int i, int j) {}
2345 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2346 return Node.getNumParams() == N;
2349 /// \brief Matches the return type of a function declaration.
2353 /// class X { int f() { return 1; } };
2355 /// methodDecl(returns(asString("int")))
2356 /// matches int f() { return 1; }
2357 AST_MATCHER_P(FunctionDecl, returns,
2358 internal::Matcher<QualType>, InnerMatcher) {
2359 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
2362 /// \brief Matches extern "C" function declarations.
2366 /// extern "C" void f() {}
2367 /// extern "C" { void g() {} }
2370 /// functionDecl(isExternC())
2371 /// matches the declaration of f and g, but not the declaration h
2372 AST_MATCHER(FunctionDecl, isExternC) {
2373 return Node.isExternC();
2376 /// \brief Matches the condition expression of an if statement, for loop,
2377 /// or conditional operator.
2379 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2383 AST_POLYMORPHIC_MATCHER_P(
2384 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5(
2385 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator),
2386 internal::Matcher<Expr>, InnerMatcher) {
2387 const Expr *const Condition = Node.getCond();
2388 return (Condition != nullptr &&
2389 InnerMatcher.matches(*Condition, Finder, Builder));
2392 /// \brief Matches the then-statement of an if statement.
2394 /// Examples matches the if statement
2395 /// (matcher = ifStmt(hasThen(boolLiteral(equals(true)))))
2397 /// if (false) true; else false;
2399 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
2400 const Stmt *const Then = Node.getThen();
2401 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
2404 /// \brief Matches the else-statement of an if statement.
2406 /// Examples matches the if statement
2407 /// (matcher = ifStmt(hasElse(boolLiteral(equals(true)))))
2409 /// if (false) false; else true;
2411 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
2412 const Stmt *const Else = Node.getElse();
2413 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
2416 /// \brief Matches if a node equals a previously bound node.
2418 /// Matches a node if it equals the node previously bound to \p ID.
2422 /// class X { int a; int b; };
2425 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2426 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
2427 /// matches the class \c X, as \c a and \c b have the same type.
2429 /// Note that when multiple matches are involved via \c forEach* matchers,
2430 /// \c equalsBoundNodes acts as a filter.
2433 /// forEachDescendant(varDecl().bind("d")),
2434 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
2435 /// will trigger a match for each combination of variable declaration
2436 /// and reference to that variable declaration within a compound statement.
2437 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4(
2438 Stmt, Decl, Type, QualType),
2440 // FIXME: Figure out whether it makes sense to allow this
2441 // on any other node types.
2442 // For *Loc it probably does not make sense, as those seem
2443 // unique. For NestedNameSepcifier it might make sense, as
2444 // those also have pointer identity, but I'm not sure whether
2445 // they're ever reused.
2446 internal::NotEqualsBoundNodePredicate Predicate;
2448 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
2449 return Builder->removeBindings(Predicate);
2452 /// \brief Matches the condition variable statement in an if statement.
2456 /// if (A* a = GetAPointer()) {}
2458 /// hasConditionVariableStatement(...)
2459 /// matches 'A* a = GetAPointer()'.
2460 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2461 internal::Matcher<DeclStmt>, InnerMatcher) {
2462 const DeclStmt* const DeclarationStatement =
2463 Node.getConditionVariableDeclStmt();
2464 return DeclarationStatement != nullptr &&
2465 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2468 /// \brief Matches the index expression of an array subscript expression.
2473 /// void f() { i[1] = 42; }
2475 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2476 /// matches \c i[1] with the \c integerLiteral() matching \c 1
2477 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2478 internal::Matcher<Expr>, InnerMatcher) {
2479 if (const Expr* Expression = Node.getIdx())
2480 return InnerMatcher.matches(*Expression, Finder, Builder);
2484 /// \brief Matches the base expression of an array subscript expression.
2489 /// void f() { i[1] = 42; }
2491 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2492 /// hasSourceExpression(declRefExpr()))))
2493 /// matches \c i[1] with the \c declRefExpr() matching \c i
2494 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2495 internal::Matcher<Expr>, InnerMatcher) {
2496 if (const Expr* Expression = Node.getBase())
2497 return InnerMatcher.matches(*Expression, Finder, Builder);
2501 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2508 /// hasBody(compoundStmt())
2509 /// matches 'for (;;) {}'
2510 /// with compoundStmt()
2512 AST_POLYMORPHIC_MATCHER_P(hasBody,
2513 AST_POLYMORPHIC_SUPPORTED_TYPES_4(DoStmt, ForStmt,
2516 internal::Matcher<Stmt>, InnerMatcher) {
2517 const Stmt *const Statement = Node.getBody();
2518 return (Statement != nullptr &&
2519 InnerMatcher.matches(*Statement, Finder, Builder));
2522 /// \brief Matches compound statements where at least one substatement matches
2523 /// a given matcher.
2529 /// hasAnySubstatement(compoundStmt())
2530 /// matches '{ {}; 1+2; }'
2531 /// with compoundStmt()
2533 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2534 internal::Matcher<Stmt>, InnerMatcher) {
2535 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
2536 Node.body_end(), Finder, Builder);
2539 /// \brief Checks that a compound statement contains a specific number of
2540 /// child statements.
2546 /// compoundStmt(statementCountIs(0)))
2548 /// but does not match the outer compound statement.
2549 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2550 return Node.size() == N;
2553 /// \brief Matches literals that are equal to the given value.
2555 /// Example matches true (matcher = boolLiteral(equals(true)))
2560 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2561 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2562 template <typename ValueT>
2563 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2564 equals(const ValueT &Value) {
2565 return internal::PolymorphicMatcherWithParam1<
2566 internal::ValueEqualsMatcher,
2570 /// \brief Matches the operator Name of operator expressions (binary or
2573 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2577 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2578 BinaryOperator, UnaryOperator),
2579 std::string, Name) {
2580 return Name == Node.getOpcodeStr(Node.getOpcode());
2583 /// \brief Matches the left hand side of binary operator expressions.
2585 /// Example matches a (matcher = binaryOperator(hasLHS()))
2589 AST_MATCHER_P(BinaryOperator, hasLHS,
2590 internal::Matcher<Expr>, InnerMatcher) {
2591 Expr *LeftHandSide = Node.getLHS();
2592 return (LeftHandSide != nullptr &&
2593 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2596 /// \brief Matches the right hand side of binary operator expressions.
2598 /// Example matches b (matcher = binaryOperator(hasRHS()))
2602 AST_MATCHER_P(BinaryOperator, hasRHS,
2603 internal::Matcher<Expr>, InnerMatcher) {
2604 Expr *RightHandSide = Node.getRHS();
2605 return (RightHandSide != nullptr &&
2606 InnerMatcher.matches(*RightHandSide, Finder, Builder));
2609 /// \brief Matches if either the left hand side or the right hand side of a
2610 /// binary operator matches.
2611 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2612 const internal::Matcher<Expr> &InnerMatcher) {
2613 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2616 /// \brief Matches if the operand of a unary operator matches.
2618 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2622 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2623 internal::Matcher<Expr>, InnerMatcher) {
2624 const Expr * const Operand = Node.getSubExpr();
2625 return (Operand != nullptr &&
2626 InnerMatcher.matches(*Operand, Finder, Builder));
2629 /// \brief Matches if the cast's source expression matches the given matcher.
2631 /// Example: matches "a string" (matcher =
2632 /// hasSourceExpression(constructExpr()))
2634 /// class URL { URL(string); };
2635 /// URL url = "a string";
2636 AST_MATCHER_P(CastExpr, hasSourceExpression,
2637 internal::Matcher<Expr>, InnerMatcher) {
2638 const Expr* const SubExpression = Node.getSubExpr();
2639 return (SubExpression != nullptr &&
2640 InnerMatcher.matches(*SubExpression, Finder, Builder));
2643 /// \brief Matches casts whose destination type matches a given matcher.
2645 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2646 /// actual casts "explicit" casts.)
2647 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2648 internal::Matcher<QualType>, InnerMatcher) {
2649 const QualType NodeType = Node.getTypeAsWritten();
2650 return InnerMatcher.matches(NodeType, Finder, Builder);
2653 /// \brief Matches implicit casts whose destination type matches a given
2656 /// FIXME: Unit test this matcher
2657 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2658 internal::Matcher<QualType>, InnerMatcher) {
2659 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2662 /// \brief Matches the true branch expression of a conditional operator.
2664 /// Example matches a
2666 /// condition ? a : b
2668 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2669 internal::Matcher<Expr>, InnerMatcher) {
2670 Expr *Expression = Node.getTrueExpr();
2671 return (Expression != nullptr &&
2672 InnerMatcher.matches(*Expression, Finder, Builder));
2675 /// \brief Matches the false branch expression of a conditional operator.
2677 /// Example matches b
2679 /// condition ? a : b
2681 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2682 internal::Matcher<Expr>, InnerMatcher) {
2683 Expr *Expression = Node.getFalseExpr();
2684 return (Expression != nullptr &&
2685 InnerMatcher.matches(*Expression, Finder, Builder));
2688 /// \brief Matches if a declaration has a body attached.
2690 /// Example matches A, va, fa
2693 /// class B; // Doesn't match, as it has no body.
2695 /// extern int vb; // Doesn't match, as it doesn't define the variable.
2697 /// void fb(); // Doesn't match, as it has no body.
2700 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2701 AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3(
2702 TagDecl, VarDecl, FunctionDecl)) {
2703 return Node.isThisDeclarationADefinition();
2706 /// \brief Matches the class declaration that the given method declaration
2709 /// FIXME: Generalize this for other kinds of declarations.
2710 /// FIXME: What other kind of declarations would we need to generalize
2713 /// Example matches A() in the last line
2714 /// (matcher = constructExpr(hasDeclaration(methodDecl(
2715 /// ofClass(hasName("A"))))))
2723 AST_MATCHER_P(CXXMethodDecl, ofClass,
2724 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2725 const CXXRecordDecl *Parent = Node.getParent();
2726 return (Parent != nullptr &&
2727 InnerMatcher.matches(*Parent, Finder, Builder));
2730 /// \brief Matches if the given method declaration is virtual.
2736 /// virtual void x();
2740 AST_MATCHER(CXXMethodDecl, isVirtual) {
2741 return Node.isVirtual();
2744 /// \brief Matches if the given method declaration is pure.
2750 /// virtual void x() = 0;
2754 AST_MATCHER(CXXMethodDecl, isPure) {
2755 return Node.isPure();
2758 /// \brief Matches if the given method declaration is const.
2763 /// void foo() const;
2768 /// methodDecl(isConst()) matches A::foo() but not A::bar()
2769 AST_MATCHER(CXXMethodDecl, isConst) {
2770 return Node.isConst();
2773 /// \brief Matches if the given method declaration overrides another method.
2779 /// virtual void x();
2781 /// class B : public A {
2783 /// virtual void x();
2787 AST_MATCHER(CXXMethodDecl, isOverride) {
2788 return Node.size_overridden_methods() > 0;
2791 /// \brief Matches member expressions that are called with '->' as opposed
2794 /// Member calls on the implicit this pointer match as called with '->'.
2799 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2804 /// memberExpr(isArrow())
2805 /// matches this->x, x, y.x, a, this->b
2806 AST_MATCHER(MemberExpr, isArrow) {
2807 return Node.isArrow();
2810 /// \brief Matches QualType nodes that are of integer type.
2818 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2819 /// matches "a(int)", "b(long)", but not "c(double)".
2820 AST_MATCHER(QualType, isInteger) {
2821 return Node->isIntegerType();
2824 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2825 /// include "top-level" const.
2830 /// void b(int const);
2831 /// void c(const int);
2832 /// void d(const int*);
2833 /// void e(int const) {};
2835 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2836 /// matches "void b(int const)", "void c(const int)" and
2837 /// "void e(int const) {}". It does not match d as there
2838 /// is no top-level const on the parameter type "const int *".
2839 AST_MATCHER(QualType, isConstQualified) {
2840 return Node.isConstQualified();
2843 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2844 /// the node, not hidden within a typedef.
2848 /// typedef const int const_int;
2851 /// int *volatile k;
2854 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2855 /// \c i is const-qualified but the qualifier is not local.
2856 AST_MATCHER(QualType, hasLocalQualifiers) {
2857 return Node.hasLocalQualifiers();
2860 /// \brief Matches a member expression where the member is matched by a
2865 /// struct { int first, second; } first, second;
2866 /// int i(second.first);
2867 /// int j(first.second);
2869 /// memberExpr(member(hasName("first")))
2870 /// matches second.first
2871 /// but not first.second (because the member name there is "second").
2872 AST_MATCHER_P(MemberExpr, member,
2873 internal::Matcher<ValueDecl>, InnerMatcher) {
2874 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2877 /// \brief Matches a member expression where the object expression is
2878 /// matched by a given matcher.
2882 /// struct X { int m; };
2883 /// void f(X x) { x.m; m; }
2885 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2886 /// matches "x.m" and "m"
2887 /// with hasObjectExpression(...)
2888 /// matching "x" and the implicit object expression of "m" which has type X*.
2889 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2890 internal::Matcher<Expr>, InnerMatcher) {
2891 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2894 /// \brief Matches any using shadow declaration.
2898 /// namespace X { void b(); }
2901 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2902 /// matches \code using X::b \endcode
2903 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2904 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2905 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
2906 Node.shadow_end(), Finder, Builder);
2909 /// \brief Matches a using shadow declaration where the target declaration is
2910 /// matched by the given matcher.
2914 /// namespace X { int a; void b(); }
2918 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2919 /// matches \code using X::b \endcode
2920 /// but not \code using X::a \endcode
2921 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2922 internal::Matcher<NamedDecl>, InnerMatcher) {
2923 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2926 /// \brief Matches template instantiations of function, class, or static
2927 /// member variable template instantiations.
2931 /// template <typename T> class X {}; class A {}; X<A> x;
2935 /// template <typename T> class X {}; class A {}; template class X<A>;
2937 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2938 /// matches the template instantiation of X<A>.
2942 /// template <typename T> class X {}; class A {};
2943 /// template <> class X<A> {}; X<A> x;
2945 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2946 /// does not match, as X<A> is an explicit template specialization.
2948 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2949 AST_POLYMORPHIC_MATCHER(
2950 isTemplateInstantiation,
2951 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2952 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2953 Node.getTemplateSpecializationKind() ==
2954 TSK_ExplicitInstantiationDefinition);
2957 /// \brief Matches explicit template specializations of function, class, or
2958 /// static member variable template instantiations.
2962 /// template<typename T> void A(T t) { }
2963 /// template<> void A(int N) { }
2965 /// functionDecl(isExplicitTemplateSpecialization())
2966 /// matches the specialization A<int>().
2968 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2969 AST_POLYMORPHIC_MATCHER(
2970 isExplicitTemplateSpecialization,
2971 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2972 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2975 /// \brief Matches \c TypeLocs for which the given inner
2976 /// QualType-matcher matches.
2977 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
2978 internal::Matcher<QualType>, InnerMatcher, 0) {
2979 return internal::BindableMatcher<TypeLoc>(
2980 new internal::TypeLocTypeMatcher(InnerMatcher));
2983 /// \brief Matches builtin Types.
2994 /// matches "int b", "float c" and "bool d"
2995 AST_TYPE_MATCHER(BuiltinType, builtinType);
2997 /// \brief Matches all kinds of arrays.
3001 /// int a[] = { 2, 3 };
3003 /// void f() { int c[a[0]]; }
3006 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
3007 AST_TYPE_MATCHER(ArrayType, arrayType);
3009 /// \brief Matches C99 complex types.
3013 /// _Complex float f;
3016 /// matches "_Complex float f"
3017 AST_TYPE_MATCHER(ComplexType, complexType);
3019 /// \brief Matches arrays and C99 complex types that have a specific element
3028 /// arrayType(hasElementType(builtinType()))
3029 /// matches "int b[7]"
3031 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
3032 AST_TYPELOC_TRAVERSE_MATCHER(
3033 hasElementType, getElement,
3034 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType));
3036 /// \brief Matches C arrays with a specified constant size.
3042 /// int b[] = { 2, 3 };
3046 /// constantArrayType()
3047 /// matches "int a[2]"
3048 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
3050 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
3056 /// int c[41], d[43];
3058 /// constantArrayType(hasSize(42))
3059 /// matches "int a[42]" and "int b[2 * 21]"
3060 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
3061 return Node.getSize() == N;
3064 /// \brief Matches C++ arrays whose size is a value-dependent expression.
3068 /// template<typename T, int Size>
3073 /// dependentSizedArrayType
3074 /// matches "T data[Size]"
3075 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
3077 /// \brief Matches C arrays with unspecified size.
3081 /// int a[] = { 2, 3 };
3083 /// void f(int c[]) { int d[a[0]]; };
3085 /// incompleteArrayType()
3086 /// matches "int a[]" and "int c[]"
3087 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
3089 /// \brief Matches C arrays with a specified size that is not an
3090 /// integer-constant-expression.
3095 /// int a[] = { 2, 3 }
3100 /// variableArrayType()
3101 /// matches "int c[a[0]]"
3102 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
3104 /// \brief Matches \c VariableArrayType nodes that have a specific size
3113 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3114 /// varDecl(hasName("b")))))))
3115 /// matches "int a[b]"
3116 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
3117 internal::Matcher<Expr>, InnerMatcher) {
3118 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
3121 /// \brief Matches atomic types.
3128 /// matches "_Atomic(int) i"
3129 AST_TYPE_MATCHER(AtomicType, atomicType);
3131 /// \brief Matches atomic types with a specific value type.
3136 /// _Atomic(float) f;
3138 /// atomicType(hasValueType(isInteger()))
3139 /// matches "_Atomic(int) i"
3141 /// Usable as: Matcher<AtomicType>
3142 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
3143 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType));
3145 /// \brief Matches types nodes representing C++11 auto types.
3150 /// int v[] = { 2, 3 }
3151 /// for (auto i : v) { }
3154 /// matches "auto n" and "auto i"
3155 AST_TYPE_MATCHER(AutoType, autoType);
3157 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3159 /// Note: There is no \c TypeLoc for the deduced type and thus no
3160 /// \c getDeducedLoc() matcher.
3167 /// autoType(hasDeducedType(isInteger()))
3168 /// matches "auto a"
3170 /// Usable as: Matcher<AutoType>
3171 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3172 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType));
3174 /// \brief Matches \c FunctionType nodes.
3182 /// matches "int (*f)(int)" and the type of "g".
3183 AST_TYPE_MATCHER(FunctionType, functionType);
3185 /// \brief Matches \c ParenType nodes.
3189 /// int (*ptr_to_array)[4];
3190 /// int *array_of_ptrs[4];
3193 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3194 /// \c array_of_ptrs.
3195 AST_TYPE_MATCHER(ParenType, parenType);
3197 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
3201 /// int (*ptr_to_array)[4];
3202 /// int (*ptr_to_func)(int);
3205 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
3206 /// \c ptr_to_func but not \c ptr_to_array.
3208 /// Usable as: Matcher<ParenType>
3209 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
3210 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType));
3212 /// \brief Matches block pointer types, i.e. types syntactically represented as
3213 /// "void (^)(int)".
3215 /// The \c pointee is always required to be a \c FunctionType.
3216 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
3218 /// \brief Matches member pointer types.
3221 /// struct A { int i; }
3222 /// A::* ptr = A::i;
3224 /// memberPointerType()
3225 /// matches "A::* ptr"
3226 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3228 /// \brief Matches pointer types.
3237 /// matches "int *a"
3238 AST_TYPE_MATCHER(PointerType, pointerType);
3240 /// \brief Matches both lvalue and rvalue reference types.
3253 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3254 AST_TYPE_MATCHER(ReferenceType, referenceType);
3256 /// \brief Matches lvalue reference types.
3269 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3270 /// matched since the type is deduced as int& by reference collapsing rules.
3271 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3273 /// \brief Matches rvalue reference types.
3286 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3287 /// matched as it is deduced to int& by reference collapsing rules.
3288 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3290 /// \brief Narrows PointerType (and similar) matchers to those where the
3291 /// \c pointee matches a given matcher.
3299 /// pointerType(pointee(isConstQualified(), isInteger()))
3300 /// matches "int const *b"
3302 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3303 /// Matcher<PointerType>, Matcher<ReferenceType>
3304 AST_TYPELOC_TRAVERSE_MATCHER(
3305 pointee, getPointee,
3306 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType,
3307 PointerType, ReferenceType));
3309 /// \brief Matches typedef types.
3316 /// matches "typedef int X"
3317 AST_TYPE_MATCHER(TypedefType, typedefType);
3319 /// \brief Matches template specialization types.
3323 /// template <typename T>
3326 /// template class C<int>; // A
3327 /// C<char> var; // B
3330 /// \c templateSpecializationType() matches the type of the explicit
3331 /// instantiation in \c A and the type of the variable declaration in \c B.
3332 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3334 /// \brief Matches types nodes representing unary type transformations.
3338 /// typedef __underlying_type(T) type;
3340 /// unaryTransformType()
3341 /// matches "__underlying_type(T)"
3342 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
3344 /// \brief Matches record types (e.g. structs, classes).
3355 /// \c recordType() matches the type of the variable declarations of both \c c
3357 AST_TYPE_MATCHER(RecordType, recordType);
3359 /// \brief Matches types specified with an elaborated type keyword or with a
3375 /// \c elaboratedType() matches the type of the variable declarations of both
3377 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3379 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3380 /// matches \c InnerMatcher if the qualifier exists.
3392 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3393 /// matches the type of the variable declaration of \c d.
3394 AST_MATCHER_P(ElaboratedType, hasQualifier,
3395 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3396 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3397 return InnerMatcher.matches(*Qualifier, Finder, Builder);
3402 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3414 /// \c elaboratedType(namesType(recordType(
3415 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3416 /// declaration of \c d.
3417 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3419 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3422 /// \brief Matches declarations whose declaration context, interpreted as a
3423 /// Decl, matches \c InnerMatcher.
3434 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3435 /// declaration of \c class \c D.
3436 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3437 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3441 /// \brief Matches nested name specifiers.
3446 /// struct A { static void f(); };
3448 /// void g() { A::f(); }
3452 /// nestedNameSpecifier()
3453 /// matches "ns::" and both "A::"
3454 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3456 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3457 const internal::VariadicAllOfMatcher<
3458 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3460 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3461 /// NestedNameSpecifier-matcher matches.
3462 AST_MATCHER_FUNCTION_P_OVERLOAD(
3463 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
3464 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
3465 return internal::BindableMatcher<NestedNameSpecifierLoc>(
3466 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3470 /// \brief Matches nested name specifiers that specify a type matching the
3471 /// given \c QualType matcher without qualifiers.
3475 /// struct A { struct B { struct C {}; }; };
3478 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3480 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3481 internal::Matcher<QualType>, InnerMatcher) {
3482 if (!Node.getAsType())
3484 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3487 /// \brief Matches nested name specifier locs that specify a type matching the
3488 /// given \c TypeLoc.
3492 /// struct A { struct B { struct C {}; }; };
3495 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3496 /// hasDeclaration(recordDecl(hasName("A")))))))
3498 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3499 internal::Matcher<TypeLoc>, InnerMatcher) {
3500 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3503 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3507 /// struct A { struct B { struct C {}; }; };
3510 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3512 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3513 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3515 NestedNameSpecifier *NextNode = Node.getPrefix();
3518 return InnerMatcher.matches(*NextNode, Finder, Builder);
3521 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3525 /// struct A { struct B { struct C {}; }; };
3528 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3530 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3531 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3533 NestedNameSpecifierLoc NextNode = Node.getPrefix();
3536 return InnerMatcher.matches(NextNode, Finder, Builder);
3539 /// \brief Matches nested name specifiers that specify a namespace matching the
3540 /// given namespace matcher.
3544 /// namespace ns { struct A {}; }
3547 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3549 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3550 internal::Matcher<NamespaceDecl>, InnerMatcher) {
3551 if (!Node.getAsNamespace())
3553 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3556 /// \brief Overloads for the \c equalsNode matcher.
3557 /// FIXME: Implement for other node types.
3560 /// \brief Matches if a node equals another node.
3562 /// \c Decl has pointer identity in the AST.
3563 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
3564 return &Node == Other;
3566 /// \brief Matches if a node equals another node.
3568 /// \c Stmt has pointer identity in the AST.
3570 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
3571 return &Node == Other;
3576 /// \brief Matches each case or default statement belonging to the given switch
3577 /// statement. This matcher may produce multiple matches.
3581 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
3583 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
3584 /// matches four times, with "c" binding each of "case 1:", "case 2:",
3585 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
3586 /// "switch (1)", "switch (2)" and "switch (2)".
3587 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
3589 BoundNodesTreeBuilder Result;
3590 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
3591 // iteration order. We should use the more general iterating matchers once
3592 // they are capable of expressing this matcher (for example, it should ignore
3593 // case statements belonging to nested switch statements).
3594 bool Matched = false;
3595 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
3596 SC = SC->getNextSwitchCase()) {
3597 BoundNodesTreeBuilder CaseBuilder(*Builder);
3598 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
3601 Result.addMatch(CaseBuilder);
3608 /// \brief Matches each constructor initializer in a constructor definition.
3612 /// class A { A() : i(42), j(42) {} int i; int j; };
3614 /// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x"))))
3615 /// will trigger two matches, binding for 'i' and 'j' respectively.
3616 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
3617 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3618 BoundNodesTreeBuilder Result;
3619 bool Matched = false;
3620 for (const auto *I : Node.inits()) {
3621 BoundNodesTreeBuilder InitBuilder(*Builder);
3622 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
3624 Result.addMatch(InitBuilder);
3631 /// \brief If the given case statement does not use the GNU case range
3632 /// extension, matches the constant given in the statement.
3636 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
3638 /// caseStmt(hasCaseConstant(integerLiteral()))
3639 /// matches "case 1:"
3640 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
3645 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
3648 /// \brief Matches CUDA kernel call expression.
3650 /// Example matches,
3652 /// kernel<<<i,j>>>();
3654 const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
3657 /// \brief Matches declaration that has CUDA device attribute.
3661 /// __attribute__((device)) void f() { ... }
3663 /// matches the function declaration of f.
3664 AST_MATCHER(Decl, hasCudaDeviceAttr) {
3665 return Node.hasAttr<clang::CUDADeviceAttr>();
3668 /// \brief Matches declaration that has CUDA host attribute.
3672 /// __attribute__((host)) void f() { ... }
3674 /// matches the function declaration of f.
3675 AST_MATCHER(Decl, hasCudaHostAttr) {
3676 return Node.hasAttr<clang::CUDAHostAttr>();
3679 /// \brief Matches declaration that has CUDA global attribute.
3683 /// __attribute__((global)) void f() { ... }
3685 /// matches the function declaration of f.
3686 AST_MATCHER(Decl, hasCudaGlobalAttr) {
3687 return Node.hasAttr<clang::CUDAGlobalAttr>();
3690 } // end namespace ast_matchers
3691 } // end namespace clang
3693 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H