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"))))))
1957 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1959 return (!Node.isNull() && Node->isReferenceType() &&
1960 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1963 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1967 /// typedef int &int_ref;
1972 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1973 /// declaration of b but \c
1974 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1975 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1979 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1982 /// \brief Overloaded to match the referenced type's declaration.
1983 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
1985 return references(qualType(hasDeclaration(InnerMatcher)))
1986 .matches(Node, Finder, Builder);
1989 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1990 internal::Matcher<Expr>, InnerMatcher) {
1991 const Expr *ExprNode = Node.getImplicitObjectArgument();
1992 return (ExprNode != nullptr &&
1993 InnerMatcher.matches(*ExprNode, Finder, Builder));
1996 /// \brief Matches if the expression's type either matches the specified
1997 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1998 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
1999 internal::Matcher<QualType>, InnerMatcher, 0) {
2000 return onImplicitObjectArgument(
2001 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2002 .matches(Node, Finder, Builder);
2005 /// \brief Overloaded to match the type's declaration.
2006 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2007 internal::Matcher<Decl>, InnerMatcher, 1) {
2008 return onImplicitObjectArgument(
2009 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2010 .matches(Node, Finder, Builder);
2013 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2014 /// specified matcher.
2016 /// Example matches x in if(x)
2017 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2022 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2024 const Decl *DeclNode = Node.getDecl();
2025 return (DeclNode != nullptr &&
2026 InnerMatcher.matches(*DeclNode, Finder, Builder));
2029 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2030 /// specific using shadow declaration.
2032 /// FIXME: This currently only works for functions. Fix.
2036 /// namespace a { void f() {} }
2039 /// f(); // Matches this ..
2040 /// a::f(); // .. but not this.
2043 /// declRefExpr(throughUsingDeclaration(anything()))
2045 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2046 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2047 const NamedDecl *FoundDecl = Node.getFoundDecl();
2048 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2049 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2053 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2060 /// declStmt(hasSingleDecl(anything()))
2061 /// matches 'int c;' but not 'int a, b;'.
2062 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2063 if (Node.isSingleDecl()) {
2064 const Decl *FoundDecl = Node.getSingleDecl();
2065 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2070 /// \brief Matches a variable declaration that has an initializer expression
2071 /// that matches the given matcher.
2073 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2075 /// bool y() { return true; }
2079 VarDecl, hasInitializer, internal::Matcher<Expr>,
2081 const Expr *Initializer = Node.getAnyInitializer();
2082 return (Initializer != nullptr &&
2083 InnerMatcher.matches(*Initializer, Finder, Builder));
2086 /// \brief Matches a variable declaration that has function scope and is a
2087 /// non-static local variable.
2089 /// Example matches x (matcher = varDecl(hasLocalStorage())
2097 AST_MATCHER(VarDecl, hasLocalStorage) {
2098 return Node.hasLocalStorage();
2101 /// \brief Matches a variable declaration that does not have local storage.
2103 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2111 AST_MATCHER(VarDecl, hasGlobalStorage) {
2112 return Node.hasGlobalStorage();
2115 /// \brief Checks that a call expression or a constructor call expression has
2116 /// a specific number of arguments (including absent default arguments).
2118 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2120 /// void f(int x, int y);
2123 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2124 CallExpr, CXXConstructExpr),
2126 return Node.getNumArgs() == N;
2129 /// \brief Matches the n'th argument of a call expression or a constructor
2130 /// call expression.
2132 /// Example matches y in x(y)
2133 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2135 /// void x(int) { int y; x(y); }
2137 AST_POLYMORPHIC_MATCHER_P2(
2139 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr),
2140 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2141 return (N < Node.getNumArgs() &&
2142 InnerMatcher.matches(
2143 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2146 /// \brief Matches declaration statements that contain a specific number of
2156 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
2157 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2158 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2161 /// \brief Matches the n'th declaration of a declaration statement.
2163 /// Note that this does not work for global declarations because the AST
2164 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2166 /// Example: Given non-global declarations
2172 /// declStmt(containsDeclaration(
2173 /// 0, varDecl(hasInitializer(anything()))))
2174 /// matches only 'int d = 2, e;', and
2175 /// declStmt(containsDeclaration(1, varDecl()))
2177 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2178 /// but 'int c;' is not matched.
2180 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2181 internal::Matcher<Decl>, InnerMatcher) {
2182 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2185 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2186 std::advance(Iterator, N);
2187 return InnerMatcher.matches(**Iterator, Finder, Builder);
2190 /// \brief Matches a constructor initializer.
2195 /// Foo() : foo_(1) { }
2199 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2200 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2201 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2202 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2203 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2204 Node.init_end(), Finder, Builder);
2207 /// \brief Matches the field declaration of a constructor initializer.
2212 /// Foo() : foo_(1) { }
2216 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2217 /// forField(hasName("foo_"))))))
2219 /// with forField matching foo_
2220 AST_MATCHER_P(CXXCtorInitializer, forField,
2221 internal::Matcher<FieldDecl>, InnerMatcher) {
2222 const FieldDecl *NodeAsDecl = Node.getMember();
2223 return (NodeAsDecl != nullptr &&
2224 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2227 /// \brief Matches the initializer expression of a constructor initializer.
2232 /// Foo() : foo_(1) { }
2236 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2237 /// withInitializer(integerLiteral(equals(1)))))))
2239 /// with withInitializer matching (1)
2240 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2241 internal::Matcher<Expr>, InnerMatcher) {
2242 const Expr* NodeAsExpr = Node.getInit();
2243 return (NodeAsExpr != nullptr &&
2244 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2247 /// \brief Matches a constructor initializer if it is explicitly written in
2248 /// code (as opposed to implicitly added by the compiler).
2254 /// Foo(int) : foo_("A") { }
2258 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2259 /// will match Foo(int), but not Foo()
2260 AST_MATCHER(CXXCtorInitializer, isWritten) {
2261 return Node.isWritten();
2264 /// \brief Matches any argument of a call expression or a constructor call
2269 /// void x(int, int, int) { int y; x(1, y, 42); }
2271 /// callExpr(hasAnyArgument(declRefExpr()))
2272 /// matches x(1, y, 42)
2273 /// with hasAnyArgument(...)
2276 /// FIXME: Currently this will ignore parentheses and implicit casts on
2277 /// the argument before applying the inner matcher. We'll want to remove
2278 /// this to allow for greater control by the user once \c ignoreImplicit()
2279 /// has been implemented.
2280 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2281 CallExpr, CXXConstructExpr),
2282 internal::Matcher<Expr>, InnerMatcher) {
2283 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2284 BoundNodesTreeBuilder Result(*Builder);
2285 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
2294 /// \brief Matches a constructor call expression which uses list initialization.
2295 AST_MATCHER(CXXConstructExpr, isListInitialization) {
2296 return Node.isListInitialization();
2299 /// \brief Matches the n'th parameter of a function declaration.
2303 /// class X { void f(int x) {} };
2305 /// methodDecl(hasParameter(0, hasType(varDecl())))
2306 /// matches f(int x) {}
2307 /// with hasParameter(...)
2309 AST_MATCHER_P2(FunctionDecl, hasParameter,
2310 unsigned, N, internal::Matcher<ParmVarDecl>,
2312 return (N < Node.getNumParams() &&
2313 InnerMatcher.matches(
2314 *Node.getParamDecl(N), Finder, Builder));
2317 /// \brief Matches any parameter of a function declaration.
2319 /// Does not match the 'this' parameter of a method.
2323 /// class X { void f(int x, int y, int z) {} };
2325 /// methodDecl(hasAnyParameter(hasName("y")))
2326 /// matches f(int x, int y, int z) {}
2327 /// with hasAnyParameter(...)
2329 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2330 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2331 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2332 Node.param_end(), Finder, Builder);
2335 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2339 /// void f(int i) {}
2340 /// void g(int i, int j) {}
2342 /// functionDecl(parameterCountIs(2))
2343 /// matches g(int i, int j) {}
2344 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2345 return Node.getNumParams() == N;
2348 /// \brief Matches the return type of a function declaration.
2352 /// class X { int f() { return 1; } };
2354 /// methodDecl(returns(asString("int")))
2355 /// matches int f() { return 1; }
2356 AST_MATCHER_P(FunctionDecl, returns,
2357 internal::Matcher<QualType>, InnerMatcher) {
2358 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
2361 /// \brief Matches extern "C" function declarations.
2365 /// extern "C" void f() {}
2366 /// extern "C" { void g() {} }
2369 /// functionDecl(isExternC())
2370 /// matches the declaration of f and g, but not the declaration h
2371 AST_MATCHER(FunctionDecl, isExternC) {
2372 return Node.isExternC();
2375 /// \brief Matches the condition expression of an if statement, for loop,
2376 /// or conditional operator.
2378 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2382 AST_POLYMORPHIC_MATCHER_P(
2383 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5(
2384 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator),
2385 internal::Matcher<Expr>, InnerMatcher) {
2386 const Expr *const Condition = Node.getCond();
2387 return (Condition != nullptr &&
2388 InnerMatcher.matches(*Condition, Finder, Builder));
2391 /// \brief Matches the then-statement of an if statement.
2393 /// Examples matches the if statement
2394 /// (matcher = ifStmt(hasThen(boolLiteral(equals(true)))))
2396 /// if (false) true; else false;
2398 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
2399 const Stmt *const Then = Node.getThen();
2400 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
2403 /// \brief Matches the else-statement of an if statement.
2405 /// Examples matches the if statement
2406 /// (matcher = ifStmt(hasElse(boolLiteral(equals(true)))))
2408 /// if (false) false; else true;
2410 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
2411 const Stmt *const Else = Node.getElse();
2412 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
2415 /// \brief Matches if a node equals a previously bound node.
2417 /// Matches a node if it equals the node previously bound to \p ID.
2421 /// class X { int a; int b; };
2424 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2425 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
2426 /// matches the class \c X, as \c a and \c b have the same type.
2428 /// Note that when multiple matches are involved via \c forEach* matchers,
2429 /// \c equalsBoundNodes acts as a filter.
2432 /// forEachDescendant(varDecl().bind("d")),
2433 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
2434 /// will trigger a match for each combination of variable declaration
2435 /// and reference to that variable declaration within a compound statement.
2436 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4(
2437 Stmt, Decl, Type, QualType),
2439 // FIXME: Figure out whether it makes sense to allow this
2440 // on any other node types.
2441 // For *Loc it probably does not make sense, as those seem
2442 // unique. For NestedNameSepcifier it might make sense, as
2443 // those also have pointer identity, but I'm not sure whether
2444 // they're ever reused.
2445 internal::NotEqualsBoundNodePredicate Predicate;
2447 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
2448 return Builder->removeBindings(Predicate);
2451 /// \brief Matches the condition variable statement in an if statement.
2455 /// if (A* a = GetAPointer()) {}
2457 /// hasConditionVariableStatement(...)
2458 /// matches 'A* a = GetAPointer()'.
2459 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2460 internal::Matcher<DeclStmt>, InnerMatcher) {
2461 const DeclStmt* const DeclarationStatement =
2462 Node.getConditionVariableDeclStmt();
2463 return DeclarationStatement != nullptr &&
2464 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2467 /// \brief Matches the index expression of an array subscript expression.
2472 /// void f() { i[1] = 42; }
2474 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2475 /// matches \c i[1] with the \c integerLiteral() matching \c 1
2476 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2477 internal::Matcher<Expr>, InnerMatcher) {
2478 if (const Expr* Expression = Node.getIdx())
2479 return InnerMatcher.matches(*Expression, Finder, Builder);
2483 /// \brief Matches the base expression of an array subscript expression.
2488 /// void f() { i[1] = 42; }
2490 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2491 /// hasSourceExpression(declRefExpr()))))
2492 /// matches \c i[1] with the \c declRefExpr() matching \c i
2493 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2494 internal::Matcher<Expr>, InnerMatcher) {
2495 if (const Expr* Expression = Node.getBase())
2496 return InnerMatcher.matches(*Expression, Finder, Builder);
2500 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2507 /// hasBody(compoundStmt())
2508 /// matches 'for (;;) {}'
2509 /// with compoundStmt()
2511 AST_POLYMORPHIC_MATCHER_P(hasBody,
2512 AST_POLYMORPHIC_SUPPORTED_TYPES_4(DoStmt, ForStmt,
2515 internal::Matcher<Stmt>, InnerMatcher) {
2516 const Stmt *const Statement = Node.getBody();
2517 return (Statement != nullptr &&
2518 InnerMatcher.matches(*Statement, Finder, Builder));
2521 /// \brief Matches compound statements where at least one substatement matches
2522 /// a given matcher.
2528 /// hasAnySubstatement(compoundStmt())
2529 /// matches '{ {}; 1+2; }'
2530 /// with compoundStmt()
2532 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2533 internal::Matcher<Stmt>, InnerMatcher) {
2534 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
2535 Node.body_end(), Finder, Builder);
2538 /// \brief Checks that a compound statement contains a specific number of
2539 /// child statements.
2545 /// compoundStmt(statementCountIs(0)))
2547 /// but does not match the outer compound statement.
2548 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2549 return Node.size() == N;
2552 /// \brief Matches literals that are equal to the given value.
2554 /// Example matches true (matcher = boolLiteral(equals(true)))
2559 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2560 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2561 template <typename ValueT>
2562 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2563 equals(const ValueT &Value) {
2564 return internal::PolymorphicMatcherWithParam1<
2565 internal::ValueEqualsMatcher,
2569 /// \brief Matches the operator Name of operator expressions (binary or
2572 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2576 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2577 BinaryOperator, UnaryOperator),
2578 std::string, Name) {
2579 return Name == Node.getOpcodeStr(Node.getOpcode());
2582 /// \brief Matches the left hand side of binary operator expressions.
2584 /// Example matches a (matcher = binaryOperator(hasLHS()))
2588 AST_MATCHER_P(BinaryOperator, hasLHS,
2589 internal::Matcher<Expr>, InnerMatcher) {
2590 Expr *LeftHandSide = Node.getLHS();
2591 return (LeftHandSide != nullptr &&
2592 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2595 /// \brief Matches the right hand side of binary operator expressions.
2597 /// Example matches b (matcher = binaryOperator(hasRHS()))
2601 AST_MATCHER_P(BinaryOperator, hasRHS,
2602 internal::Matcher<Expr>, InnerMatcher) {
2603 Expr *RightHandSide = Node.getRHS();
2604 return (RightHandSide != nullptr &&
2605 InnerMatcher.matches(*RightHandSide, Finder, Builder));
2608 /// \brief Matches if either the left hand side or the right hand side of a
2609 /// binary operator matches.
2610 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2611 const internal::Matcher<Expr> &InnerMatcher) {
2612 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2615 /// \brief Matches if the operand of a unary operator matches.
2617 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2621 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2622 internal::Matcher<Expr>, InnerMatcher) {
2623 const Expr * const Operand = Node.getSubExpr();
2624 return (Operand != nullptr &&
2625 InnerMatcher.matches(*Operand, Finder, Builder));
2628 /// \brief Matches if the cast's source expression matches the given matcher.
2630 /// Example: matches "a string" (matcher =
2631 /// hasSourceExpression(constructExpr()))
2633 /// class URL { URL(string); };
2634 /// URL url = "a string";
2635 AST_MATCHER_P(CastExpr, hasSourceExpression,
2636 internal::Matcher<Expr>, InnerMatcher) {
2637 const Expr* const SubExpression = Node.getSubExpr();
2638 return (SubExpression != nullptr &&
2639 InnerMatcher.matches(*SubExpression, Finder, Builder));
2642 /// \brief Matches casts whose destination type matches a given matcher.
2644 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2645 /// actual casts "explicit" casts.)
2646 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2647 internal::Matcher<QualType>, InnerMatcher) {
2648 const QualType NodeType = Node.getTypeAsWritten();
2649 return InnerMatcher.matches(NodeType, Finder, Builder);
2652 /// \brief Matches implicit casts whose destination type matches a given
2655 /// FIXME: Unit test this matcher
2656 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2657 internal::Matcher<QualType>, InnerMatcher) {
2658 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2661 /// \brief Matches the true branch expression of a conditional operator.
2663 /// Example matches a
2665 /// condition ? a : b
2667 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2668 internal::Matcher<Expr>, InnerMatcher) {
2669 Expr *Expression = Node.getTrueExpr();
2670 return (Expression != nullptr &&
2671 InnerMatcher.matches(*Expression, Finder, Builder));
2674 /// \brief Matches the false branch expression of a conditional operator.
2676 /// Example matches b
2678 /// condition ? a : b
2680 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2681 internal::Matcher<Expr>, InnerMatcher) {
2682 Expr *Expression = Node.getFalseExpr();
2683 return (Expression != nullptr &&
2684 InnerMatcher.matches(*Expression, Finder, Builder));
2687 /// \brief Matches if a declaration has a body attached.
2689 /// Example matches A, va, fa
2692 /// class B; // Doesn't match, as it has no body.
2694 /// extern int vb; // Doesn't match, as it doesn't define the variable.
2696 /// void fb(); // Doesn't match, as it has no body.
2699 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2700 AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3(
2701 TagDecl, VarDecl, FunctionDecl)) {
2702 return Node.isThisDeclarationADefinition();
2705 /// \brief Matches the class declaration that the given method declaration
2708 /// FIXME: Generalize this for other kinds of declarations.
2709 /// FIXME: What other kind of declarations would we need to generalize
2712 /// Example matches A() in the last line
2713 /// (matcher = constructExpr(hasDeclaration(methodDecl(
2714 /// ofClass(hasName("A"))))))
2722 AST_MATCHER_P(CXXMethodDecl, ofClass,
2723 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2724 const CXXRecordDecl *Parent = Node.getParent();
2725 return (Parent != nullptr &&
2726 InnerMatcher.matches(*Parent, Finder, Builder));
2729 /// \brief Matches if the given method declaration is virtual.
2735 /// virtual void x();
2739 AST_MATCHER(CXXMethodDecl, isVirtual) {
2740 return Node.isVirtual();
2743 /// \brief Matches if the given method declaration is pure.
2749 /// virtual void x() = 0;
2753 AST_MATCHER(CXXMethodDecl, isPure) {
2754 return Node.isPure();
2757 /// \brief Matches if the given method declaration is const.
2762 /// void foo() const;
2767 /// methodDecl(isConst()) matches A::foo() but not A::bar()
2768 AST_MATCHER(CXXMethodDecl, isConst) {
2769 return Node.isConst();
2772 /// \brief Matches if the given method declaration overrides another method.
2778 /// virtual void x();
2780 /// class B : public A {
2782 /// virtual void x();
2786 AST_MATCHER(CXXMethodDecl, isOverride) {
2787 return Node.size_overridden_methods() > 0;
2790 /// \brief Matches member expressions that are called with '->' as opposed
2793 /// Member calls on the implicit this pointer match as called with '->'.
2798 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2803 /// memberExpr(isArrow())
2804 /// matches this->x, x, y.x, a, this->b
2805 AST_MATCHER(MemberExpr, isArrow) {
2806 return Node.isArrow();
2809 /// \brief Matches QualType nodes that are of integer type.
2817 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2818 /// matches "a(int)", "b(long)", but not "c(double)".
2819 AST_MATCHER(QualType, isInteger) {
2820 return Node->isIntegerType();
2823 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2824 /// include "top-level" const.
2829 /// void b(int const);
2830 /// void c(const int);
2831 /// void d(const int*);
2832 /// void e(int const) {};
2834 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2835 /// matches "void b(int const)", "void c(const int)" and
2836 /// "void e(int const) {}". It does not match d as there
2837 /// is no top-level const on the parameter type "const int *".
2838 AST_MATCHER(QualType, isConstQualified) {
2839 return Node.isConstQualified();
2842 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2843 /// the node, not hidden within a typedef.
2847 /// typedef const int const_int;
2850 /// int *volatile k;
2853 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2854 /// \c i is const-qualified but the qualifier is not local.
2855 AST_MATCHER(QualType, hasLocalQualifiers) {
2856 return Node.hasLocalQualifiers();
2859 /// \brief Matches a member expression where the member is matched by a
2864 /// struct { int first, second; } first, second;
2865 /// int i(second.first);
2866 /// int j(first.second);
2868 /// memberExpr(member(hasName("first")))
2869 /// matches second.first
2870 /// but not first.second (because the member name there is "second").
2871 AST_MATCHER_P(MemberExpr, member,
2872 internal::Matcher<ValueDecl>, InnerMatcher) {
2873 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2876 /// \brief Matches a member expression where the object expression is
2877 /// matched by a given matcher.
2881 /// struct X { int m; };
2882 /// void f(X x) { x.m; m; }
2884 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2885 /// matches "x.m" and "m"
2886 /// with hasObjectExpression(...)
2887 /// matching "x" and the implicit object expression of "m" which has type X*.
2888 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2889 internal::Matcher<Expr>, InnerMatcher) {
2890 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2893 /// \brief Matches any using shadow declaration.
2897 /// namespace X { void b(); }
2900 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2901 /// matches \code using X::b \endcode
2902 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2903 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2904 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
2905 Node.shadow_end(), Finder, Builder);
2908 /// \brief Matches a using shadow declaration where the target declaration is
2909 /// matched by the given matcher.
2913 /// namespace X { int a; void b(); }
2917 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2918 /// matches \code using X::b \endcode
2919 /// but not \code using X::a \endcode
2920 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2921 internal::Matcher<NamedDecl>, InnerMatcher) {
2922 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2925 /// \brief Matches template instantiations of function, class, or static
2926 /// member variable template instantiations.
2930 /// template <typename T> class X {}; class A {}; X<A> x;
2934 /// template <typename T> class X {}; class A {}; template class X<A>;
2936 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2937 /// matches the template instantiation of X<A>.
2941 /// template <typename T> class X {}; class A {};
2942 /// template <> class X<A> {}; X<A> x;
2944 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2945 /// does not match, as X<A> is an explicit template specialization.
2947 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2948 AST_POLYMORPHIC_MATCHER(
2949 isTemplateInstantiation,
2950 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2951 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2952 Node.getTemplateSpecializationKind() ==
2953 TSK_ExplicitInstantiationDefinition);
2956 /// \brief Matches explicit template specializations of function, class, or
2957 /// static member variable template instantiations.
2961 /// template<typename T> void A(T t) { }
2962 /// template<> void A(int N) { }
2964 /// functionDecl(isExplicitTemplateSpecialization())
2965 /// matches the specialization A<int>().
2967 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2968 AST_POLYMORPHIC_MATCHER(
2969 isExplicitTemplateSpecialization,
2970 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2971 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2974 /// \brief Matches \c TypeLocs for which the given inner
2975 /// QualType-matcher matches.
2976 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
2977 internal::Matcher<QualType>, InnerMatcher, 0) {
2978 return internal::BindableMatcher<TypeLoc>(
2979 new internal::TypeLocTypeMatcher(InnerMatcher));
2982 /// \brief Matches builtin Types.
2993 /// matches "int b", "float c" and "bool d"
2994 AST_TYPE_MATCHER(BuiltinType, builtinType);
2996 /// \brief Matches all kinds of arrays.
3000 /// int a[] = { 2, 3 };
3002 /// void f() { int c[a[0]]; }
3005 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
3006 AST_TYPE_MATCHER(ArrayType, arrayType);
3008 /// \brief Matches C99 complex types.
3012 /// _Complex float f;
3015 /// matches "_Complex float f"
3016 AST_TYPE_MATCHER(ComplexType, complexType);
3018 /// \brief Matches arrays and C99 complex types that have a specific element
3027 /// arrayType(hasElementType(builtinType()))
3028 /// matches "int b[7]"
3030 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
3031 AST_TYPELOC_TRAVERSE_MATCHER(
3032 hasElementType, getElement,
3033 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType));
3035 /// \brief Matches C arrays with a specified constant size.
3041 /// int b[] = { 2, 3 };
3045 /// constantArrayType()
3046 /// matches "int a[2]"
3047 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
3049 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
3055 /// int c[41], d[43];
3057 /// constantArrayType(hasSize(42))
3058 /// matches "int a[42]" and "int b[2 * 21]"
3059 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
3060 return Node.getSize() == N;
3063 /// \brief Matches C++ arrays whose size is a value-dependent expression.
3067 /// template<typename T, int Size>
3072 /// dependentSizedArrayType
3073 /// matches "T data[Size]"
3074 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
3076 /// \brief Matches C arrays with unspecified size.
3080 /// int a[] = { 2, 3 };
3082 /// void f(int c[]) { int d[a[0]]; };
3084 /// incompleteArrayType()
3085 /// matches "int a[]" and "int c[]"
3086 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
3088 /// \brief Matches C arrays with a specified size that is not an
3089 /// integer-constant-expression.
3094 /// int a[] = { 2, 3 }
3098 /// variableArrayType()
3099 /// matches "int c[a[0]]"
3100 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
3102 /// \brief Matches \c VariableArrayType nodes that have a specific size
3111 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3112 /// varDecl(hasName("b")))))))
3113 /// matches "int a[b]"
3114 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
3115 internal::Matcher<Expr>, InnerMatcher) {
3116 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
3119 /// \brief Matches atomic types.
3126 /// matches "_Atomic(int) i"
3127 AST_TYPE_MATCHER(AtomicType, atomicType);
3129 /// \brief Matches atomic types with a specific value type.
3134 /// _Atomic(float) f;
3136 /// atomicType(hasValueType(isInteger()))
3137 /// matches "_Atomic(int) i"
3139 /// Usable as: Matcher<AtomicType>
3140 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
3141 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType));
3143 /// \brief Matches types nodes representing C++11 auto types.
3148 /// int v[] = { 2, 3 }
3149 /// for (auto i : v) { }
3152 /// matches "auto n" and "auto i"
3153 AST_TYPE_MATCHER(AutoType, autoType);
3155 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3157 /// Note: There is no \c TypeLoc for the deduced type and thus no
3158 /// \c getDeducedLoc() matcher.
3165 /// autoType(hasDeducedType(isInteger()))
3166 /// matches "auto a"
3168 /// Usable as: Matcher<AutoType>
3169 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3170 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType));
3172 /// \brief Matches \c FunctionType nodes.
3180 /// matches "int (*f)(int)" and the type of "g".
3181 AST_TYPE_MATCHER(FunctionType, functionType);
3183 /// \brief Matches \c ParenType nodes.
3187 /// int (*ptr_to_array)[4];
3188 /// int *array_of_ptrs[4];
3191 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3192 /// \c array_of_ptrs.
3193 AST_TYPE_MATCHER(ParenType, parenType);
3195 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
3199 /// int (*ptr_to_array)[4];
3200 /// int (*ptr_to_func)(int);
3203 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
3204 /// \c ptr_to_func but not \c ptr_to_array.
3206 /// Usable as: Matcher<ParenType>
3207 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
3208 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType));
3210 /// \brief Matches block pointer types, i.e. types syntactically represented as
3211 /// "void (^)(int)".
3213 /// The \c pointee is always required to be a \c FunctionType.
3214 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
3216 /// \brief Matches member pointer types.
3219 /// struct A { int i; }
3220 /// A::* ptr = A::i;
3222 /// memberPointerType()
3223 /// matches "A::* ptr"
3224 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3226 /// \brief Matches pointer types.
3235 /// matches "int *a"
3236 AST_TYPE_MATCHER(PointerType, pointerType);
3238 /// \brief Matches both lvalue and rvalue reference types.
3251 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3252 AST_TYPE_MATCHER(ReferenceType, referenceType);
3254 /// \brief Matches lvalue reference types.
3267 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3268 /// matched since the type is deduced as int& by reference collapsing rules.
3269 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3271 /// \brief Matches rvalue reference types.
3284 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3285 /// matched as it is deduced to int& by reference collapsing rules.
3286 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3288 /// \brief Narrows PointerType (and similar) matchers to those where the
3289 /// \c pointee matches a given matcher.
3297 /// pointerType(pointee(isConstQualified(), isInteger()))
3298 /// matches "int const *b"
3300 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3301 /// Matcher<PointerType>, Matcher<ReferenceType>
3302 AST_TYPELOC_TRAVERSE_MATCHER(
3303 pointee, getPointee,
3304 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType,
3305 PointerType, ReferenceType));
3307 /// \brief Matches typedef types.
3314 /// matches "typedef int X"
3315 AST_TYPE_MATCHER(TypedefType, typedefType);
3317 /// \brief Matches template specialization types.
3321 /// template <typename T>
3324 /// template class C<int>; // A
3325 /// C<char> var; // B
3328 /// \c templateSpecializationType() matches the type of the explicit
3329 /// instantiation in \c A and the type of the variable declaration in \c B.
3330 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3332 /// \brief Matches types nodes representing unary type transformations.
3336 /// typedef __underlying_type(T) type;
3338 /// unaryTransformType()
3339 /// matches "__underlying_type(T)"
3340 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
3342 /// \brief Matches record types (e.g. structs, classes).
3353 /// \c recordType() matches the type of the variable declarations of both \c c
3355 AST_TYPE_MATCHER(RecordType, recordType);
3357 /// \brief Matches types specified with an elaborated type keyword or with a
3373 /// \c elaboratedType() matches the type of the variable declarations of both
3375 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3377 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3378 /// matches \c InnerMatcher if the qualifier exists.
3390 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3391 /// matches the type of the variable declaration of \c d.
3392 AST_MATCHER_P(ElaboratedType, hasQualifier,
3393 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3394 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3395 return InnerMatcher.matches(*Qualifier, Finder, Builder);
3400 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3412 /// \c elaboratedType(namesType(recordType(
3413 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3414 /// declaration of \c d.
3415 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3417 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3420 /// \brief Matches declarations whose declaration context, interpreted as a
3421 /// Decl, matches \c InnerMatcher.
3432 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3433 /// declaration of \c class \c D.
3434 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3435 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3439 /// \brief Matches nested name specifiers.
3444 /// struct A { static void f(); };
3446 /// void g() { A::f(); }
3450 /// nestedNameSpecifier()
3451 /// matches "ns::" and both "A::"
3452 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3454 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3455 const internal::VariadicAllOfMatcher<
3456 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3458 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3459 /// NestedNameSpecifier-matcher matches.
3460 AST_MATCHER_FUNCTION_P_OVERLOAD(
3461 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
3462 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
3463 return internal::BindableMatcher<NestedNameSpecifierLoc>(
3464 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3468 /// \brief Matches nested name specifiers that specify a type matching the
3469 /// given \c QualType matcher without qualifiers.
3473 /// struct A { struct B { struct C {}; }; };
3476 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3478 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3479 internal::Matcher<QualType>, InnerMatcher) {
3480 if (!Node.getAsType())
3482 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3485 /// \brief Matches nested name specifier locs that specify a type matching the
3486 /// given \c TypeLoc.
3490 /// struct A { struct B { struct C {}; }; };
3493 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3494 /// hasDeclaration(recordDecl(hasName("A")))))))
3496 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3497 internal::Matcher<TypeLoc>, InnerMatcher) {
3498 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3501 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3505 /// struct A { struct B { struct C {}; }; };
3508 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3510 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3511 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3513 NestedNameSpecifier *NextNode = Node.getPrefix();
3516 return InnerMatcher.matches(*NextNode, Finder, Builder);
3519 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3523 /// struct A { struct B { struct C {}; }; };
3526 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3528 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3529 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3531 NestedNameSpecifierLoc NextNode = Node.getPrefix();
3534 return InnerMatcher.matches(NextNode, Finder, Builder);
3537 /// \brief Matches nested name specifiers that specify a namespace matching the
3538 /// given namespace matcher.
3542 /// namespace ns { struct A {}; }
3545 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3547 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3548 internal::Matcher<NamespaceDecl>, InnerMatcher) {
3549 if (!Node.getAsNamespace())
3551 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3554 /// \brief Overloads for the \c equalsNode matcher.
3555 /// FIXME: Implement for other node types.
3558 /// \brief Matches if a node equals another node.
3560 /// \c Decl has pointer identity in the AST.
3561 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
3562 return &Node == Other;
3564 /// \brief Matches if a node equals another node.
3566 /// \c Stmt has pointer identity in the AST.
3568 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
3569 return &Node == Other;
3574 /// \brief Matches each case or default statement belonging to the given switch
3575 /// statement. This matcher may produce multiple matches.
3579 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
3581 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
3582 /// matches four times, with "c" binding each of "case 1:", "case 2:",
3583 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
3584 /// "switch (1)", "switch (2)" and "switch (2)".
3585 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
3587 BoundNodesTreeBuilder Result;
3588 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
3589 // iteration order. We should use the more general iterating matchers once
3590 // they are capable of expressing this matcher (for example, it should ignore
3591 // case statements belonging to nested switch statements).
3592 bool Matched = false;
3593 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
3594 SC = SC->getNextSwitchCase()) {
3595 BoundNodesTreeBuilder CaseBuilder(*Builder);
3596 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
3599 Result.addMatch(CaseBuilder);
3606 /// \brief Matches each constructor initializer in a constructor definition.
3610 /// class A { A() : i(42), j(42) {} int i; int j; };
3612 /// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x"))))
3613 /// will trigger two matches, binding for 'i' and 'j' respectively.
3614 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
3615 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3616 BoundNodesTreeBuilder Result;
3617 bool Matched = false;
3618 for (const auto *I : Node.inits()) {
3619 BoundNodesTreeBuilder InitBuilder(*Builder);
3620 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
3622 Result.addMatch(InitBuilder);
3629 /// \brief If the given case statement does not use the GNU case range
3630 /// extension, matches the constant given in the statement.
3634 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
3636 /// caseStmt(hasCaseConstant(integerLiteral()))
3637 /// matches "case 1:"
3638 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
3643 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
3646 } // end namespace ast_matchers
3647 } // end namespace clang
3649 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H