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 // cxxRecordDecl(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 // cxxRecordDecl(hasName("MyClass"), has(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 RecordDecl 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_ASTMATCHERS_ASTMATCHERS_H
46 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/ASTTypeTraits.h"
50 #include "clang/AST/Attr.h"
51 #include "clang/AST/Decl.h"
52 #include "clang/AST/DeclCXX.h"
53 #include "clang/AST/DeclFriend.h"
54 #include "clang/AST/DeclObjC.h"
55 #include "clang/AST/DeclTemplate.h"
56 #include "clang/AST/Expr.h"
57 #include "clang/AST/ExprCXX.h"
58 #include "clang/AST/ExprObjC.h"
59 #include "clang/AST/NestedNameSpecifier.h"
60 #include "clang/AST/OperationKinds.h"
61 #include "clang/AST/Stmt.h"
62 #include "clang/AST/StmtCXX.h"
63 #include "clang/AST/StmtObjC.h"
64 #include "clang/AST/TemplateBase.h"
65 #include "clang/AST/TemplateName.h"
66 #include "clang/AST/Type.h"
67 #include "clang/AST/TypeLoc.h"
68 #include "clang/ASTMatchers/ASTMatchersInternal.h"
69 #include "clang/ASTMatchers/ASTMatchersMacros.h"
70 #include "clang/Basic/AttrKinds.h"
71 #include "clang/Basic/ExceptionSpecificationType.h"
72 #include "clang/Basic/IdentifierTable.h"
73 #include "clang/Basic/LLVM.h"
74 #include "clang/Basic/SourceManager.h"
75 #include "clang/Basic/Specifiers.h"
76 #include "clang/Basic/TypeTraits.h"
77 #include "llvm/ADT/ArrayRef.h"
78 #include "llvm/ADT/SmallVector.h"
79 #include "llvm/ADT/StringRef.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/Regex.h"
93 namespace ast_matchers {
95 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
97 /// The bound nodes are generated by calling \c bind("id") on the node matchers
98 /// of the nodes we want to access later.
100 /// The instances of BoundNodes are created by \c MatchFinder when the user's
101 /// callbacks are executed every time a match is found.
104 /// \brief Returns the AST node bound to \c ID.
106 /// Returns NULL if there was no node bound to \c ID or if there is a node but
107 /// it cannot be converted to the specified type.
108 template <typename T>
109 const T *getNodeAs(StringRef ID) const {
110 return MyBoundNodes.getNodeAs<T>(ID);
113 /// \brief Type of mapping from binding identifiers to bound nodes. This type
114 /// is an associative container with a key type of \c std::string and a value
115 /// type of \c clang::ast_type_traits::DynTypedNode
116 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
118 /// \brief Retrieve mapping from binding identifiers to bound nodes.
119 const IDToNodeMap &getMap() const {
120 return MyBoundNodes.getMap();
124 friend class internal::BoundNodesTreeBuilder;
126 /// \brief Create BoundNodes from a pre-filled map of bindings.
127 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
128 : MyBoundNodes(MyBoundNodes) {}
130 internal::BoundNodesMap MyBoundNodes;
133 /// \brief If the provided matcher matches a node, binds the node to \c ID.
135 /// FIXME: Do we want to support this now that we have bind()?
136 template <typename T>
137 internal::Matcher<T> id(StringRef ID,
138 const internal::BindableMatcher<T> &InnerMatcher) {
139 return InnerMatcher.bind(ID);
142 /// \brief Types of matchers for the top-level classes in the AST class
145 using DeclarationMatcher = internal::Matcher<Decl>;
146 using StatementMatcher = internal::Matcher<Stmt>;
147 using TypeMatcher = internal::Matcher<QualType>;
148 using TypeLocMatcher = internal::Matcher<TypeLoc>;
149 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
150 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
151 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
154 /// \brief Matches any node.
156 /// Useful when another matcher requires a child matcher, but there's no
157 /// additional constraint. This will often be used with an explicit conversion
158 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
160 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
162 /// "int* p" and "void f()" in
167 /// Usable as: Any Matcher
168 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
170 /// \brief Matches the top declaration context.
177 /// } // namespace NS
179 /// decl(hasDeclContext(translationUnitDecl()))
180 /// matches "int X", but not "int Y".
181 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
184 /// \brief Matches typedef declarations.
192 /// matches "typedef int X", but not "using Y = int"
193 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
196 /// \brief Matches typedef name declarations.
203 /// typedefNameDecl()
204 /// matches "typedef int X" and "using Y = int"
205 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
208 /// \brief Matches type alias declarations.
216 /// matches "using Y = int", but not "typedef int X"
217 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
220 /// \brief Matches type alias template declarations.
222 /// typeAliasTemplateDecl() matches
224 /// template <typename T>
227 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
228 typeAliasTemplateDecl;
230 /// \brief Matches AST nodes that were expanded within the main-file.
232 /// Example matches X but not Y
233 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
243 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
244 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
245 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
246 auto &SourceManager = Finder->getASTContext().getSourceManager();
247 return SourceManager.isInMainFile(
248 SourceManager.getExpansionLoc(Node.getLocStart()));
251 /// \brief Matches AST nodes that were expanded within system-header-files.
253 /// Example matches Y but not X
254 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
256 /// #include <SystemHeader.h>
264 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
265 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
266 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
267 auto &SourceManager = Finder->getASTContext().getSourceManager();
268 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
269 if (ExpansionLoc.isInvalid()) {
272 return SourceManager.isInSystemHeader(ExpansionLoc);
275 /// \brief Matches AST nodes that were expanded within files whose name is
276 /// partially matching a given regex.
278 /// Example matches Y but not X
279 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
281 /// #include "ASTMatcher.h"
289 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
290 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
291 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
292 std::string, RegExp) {
293 auto &SourceManager = Finder->getASTContext().getSourceManager();
294 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
295 if (ExpansionLoc.isInvalid()) {
299 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
304 auto Filename = FileEntry->getName();
305 llvm::Regex RE(RegExp);
306 return RE.match(Filename);
309 /// \brief Matches declarations.
311 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
318 extern const internal::VariadicAllOfMatcher<Decl> decl;
320 /// \brief Matches a declaration of a linkage specification.
326 /// linkageSpecDecl()
327 /// matches "extern "C" {}"
328 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
331 /// \brief Matches a declaration of anything that could have a name.
333 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
342 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
344 /// \brief Matches a declaration of label.
353 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
355 /// \brief Matches a declaration of a namespace.
360 /// namespace test {}
363 /// matches "namespace {}" and "namespace test {}"
364 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
367 /// \brief Matches a declaration of a namespace alias.
371 /// namespace test {}
372 /// namespace alias = ::test;
374 /// namespaceAliasDecl()
375 /// matches "namespace alias" but not "namespace test"
376 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
379 /// \brief Matches class, struct, and union declarations.
381 /// Example matches \c X, \c Z, \c U, and \c S
384 /// template<class T> class Z {};
388 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
390 /// \brief Matches C++ class declarations.
392 /// Example matches \c X, \c Z
395 /// template<class T> class Z {};
397 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
400 /// \brief Matches C++ class template declarations.
402 /// Example matches \c Z
404 /// template<class T> class Z {};
406 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
409 /// \brief Matches C++ class template specializations.
413 /// template<typename T> class A {};
414 /// template<> class A<double> {};
417 /// classTemplateSpecializationDecl()
418 /// matches the specializations \c A<int> and \c A<double>
419 extern const internal::VariadicDynCastAllOfMatcher<
420 Decl, ClassTemplateSpecializationDecl>
421 classTemplateSpecializationDecl;
423 /// \brief Matches declarator declarations (field, variable, function
424 /// and non-type template parameter declarations).
428 /// class X { int y; };
431 /// matches \c int y.
432 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
435 /// \brief Matches parameter variable declarations.
442 /// matches \c int x.
443 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
446 /// \brief Matches C++ access specifier declarations.
456 /// matches 'public:'
457 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
460 /// \brief Matches constructor initializers.
462 /// Examples matches \c i(42).
469 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
472 /// \brief Matches template arguments.
476 /// template <typename T> struct C {};
479 /// templateArgument()
480 /// matches 'int' in C<int>.
481 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
483 /// \brief Matches template name.
487 /// template <typename T> class X { };
491 /// matches 'X' in X<int>.
492 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
494 /// \brief Matches non-type template parameter declarations.
498 /// template <typename T, int N> struct C {};
500 /// nonTypeTemplateParmDecl()
501 /// matches 'N', but not 'T'.
502 extern const internal::VariadicDynCastAllOfMatcher<Decl,
503 NonTypeTemplateParmDecl>
504 nonTypeTemplateParmDecl;
506 /// \brief Matches template type parameter declarations.
510 /// template <typename T, int N> struct C {};
512 /// templateTypeParmDecl()
513 /// matches 'T', but not 'N'.
514 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
515 templateTypeParmDecl;
517 /// \brief Matches public C++ declarations.
523 /// protected: int b;
527 /// fieldDecl(isPublic())
529 AST_MATCHER(Decl, isPublic) {
530 return Node.getAccess() == AS_public;
533 /// \brief Matches protected C++ declarations.
539 /// protected: int b;
543 /// fieldDecl(isProtected())
545 AST_MATCHER(Decl, isProtected) {
546 return Node.getAccess() == AS_protected;
549 /// \brief Matches private C++ declarations.
555 /// protected: int b;
559 /// fieldDecl(isPrivate())
561 AST_MATCHER(Decl, isPrivate) {
562 return Node.getAccess() == AS_private;
565 /// \brief Matches non-static data members that are bit-fields.
574 /// fieldDecl(isBitField())
575 /// matches 'int a;' but not 'int b;'.
576 AST_MATCHER(FieldDecl, isBitField) {
577 return Node.isBitField();
580 /// \brief Matches non-static data members that are bit-fields of the specified
591 /// fieldDecl(hasBitWidth(2))
592 /// matches 'int a;' and 'int c;' but not 'int b;'.
593 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
594 return Node.isBitField() &&
595 Node.getBitWidthValue(Finder->getASTContext()) == Width;
598 /// \brief Matches non-static data members that have an in-class initializer.
608 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
609 /// matches 'int a;' but not 'int b;'.
610 /// fieldDecl(hasInClassInitializer(anything()))
611 /// matches 'int a;' and 'int b;' but not 'int c;'.
612 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
614 const Expr *Initializer = Node.getInClassInitializer();
615 return (Initializer != nullptr &&
616 InnerMatcher.matches(*Initializer, Finder, Builder));
619 /// \brief Matches the specialized template of a specialization declaration.
623 /// tempalate<typename T> class A {};
624 /// typedef A<int> B;
626 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
627 /// matches 'B' with classTemplateDecl() matching the class template
628 /// declaration of 'A'.
629 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
630 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
631 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
632 return (Decl != nullptr &&
633 InnerMatcher.matches(*Decl, Finder, Builder));
636 /// \brief Matches a declaration that has been implicitly added
637 /// by the compiler (eg. implicit default/copy constructors).
638 AST_MATCHER(Decl, isImplicit) {
639 return Node.isImplicit();
642 /// \brief Matches classTemplateSpecializations, templateSpecializationType and
643 /// functionDecl that have at least one TemplateArgument matching the given
648 /// template<typename T> class A {};
649 /// template<> class A<double> {};
652 /// template<typename T> f() {};
653 /// void func() { f<int>(); };
657 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
658 /// refersToType(asString("int"))))
659 /// matches the specialization \c A<int>
661 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
662 /// matches the specialization \c f<int>
663 AST_POLYMORPHIC_MATCHER_P(
664 hasAnyTemplateArgument,
665 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
666 TemplateSpecializationType,
668 internal::Matcher<TemplateArgument>, InnerMatcher) {
669 ArrayRef<TemplateArgument> List =
670 internal::getTemplateSpecializationArgs(Node);
671 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
675 /// \brief Matches expressions that match InnerMatcher after any implicit AST
676 /// nodes are stripped off.
678 /// Parentheses and explicit casts are not discarded.
688 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
690 /// would match the declarations for a, b, and c.
693 /// varDecl(hasInitializer(cxxConstructExpr()))
695 /// only match the declarations for b and c.
696 AST_MATCHER_P(Expr, ignoringImplicit, ast_matchers::internal::Matcher<Expr>,
698 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
701 /// \brief Matches expressions that match InnerMatcher after any implicit casts
702 /// are stripped off.
704 /// Parentheses and explicit casts are not discarded.
712 /// long e = (long) 0l;
716 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
717 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
719 /// would match the declarations for a, b, c, and d, but not e.
722 /// varDecl(hasInitializer(integerLiteral()))
723 /// varDecl(hasInitializer(declRefExpr()))
725 /// only match the declarations for b, c, and d.
726 AST_MATCHER_P(Expr, ignoringImpCasts,
727 internal::Matcher<Expr>, InnerMatcher) {
728 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
731 /// \brief Matches expressions that match InnerMatcher after parentheses and
732 /// casts are stripped off.
734 /// Implicit and non-C Style casts are also discarded.
739 /// void* c = reinterpret_cast<char*>(0);
740 /// char d = char(0);
743 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
744 /// would match the declarations for a, b, c, and d.
746 /// varDecl(hasInitializer(integerLiteral()))
747 /// only match the declaration for a.
748 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
749 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
752 /// \brief Matches expressions that match InnerMatcher after implicit casts and
753 /// parentheses are stripped off.
755 /// Explicit casts are not discarded.
763 /// long e = ((long) 0l);
766 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
767 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
768 /// would match the declarations for a, b, c, and d, but not e.
770 /// varDecl(hasInitializer(integerLiteral()))
771 /// varDecl(hasInitializer(declRefExpr()))
772 /// would only match the declaration for a.
773 AST_MATCHER_P(Expr, ignoringParenImpCasts,
774 internal::Matcher<Expr>, InnerMatcher) {
775 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
778 /// \brief Matches types that match InnerMatcher after any parens are stripped.
782 /// void (*fp)(void);
786 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
788 /// would match the declaration for fp.
789 AST_MATCHER_P(QualType, ignoringParens,
790 internal::Matcher<QualType>, InnerMatcher) {
791 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
794 /// \brief Matches classTemplateSpecializations, templateSpecializationType and
795 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
799 /// template<typename T, typename U> class A {};
803 /// template<typename T> f() {};
804 /// void func() { f<int>(); };
806 /// classTemplateSpecializationDecl(hasTemplateArgument(
807 /// 1, refersToType(asString("int"))))
808 /// matches the specialization \c A<bool, int>
810 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
811 /// matches the specialization \c f<int>
812 AST_POLYMORPHIC_MATCHER_P2(
814 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
815 TemplateSpecializationType,
817 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
818 ArrayRef<TemplateArgument> List =
819 internal::getTemplateSpecializationArgs(Node);
820 if (List.size() <= N)
822 return InnerMatcher.matches(List[N], Finder, Builder);
825 /// \brief Matches if the number of template arguments equals \p N.
829 /// template<typename T> struct C {};
832 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
834 AST_POLYMORPHIC_MATCHER_P(
835 templateArgumentCountIs,
836 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
837 TemplateSpecializationType),
839 return internal::getTemplateSpecializationArgs(Node).size() == N;
842 /// \brief Matches a TemplateArgument that refers to a certain type.
847 /// template<typename T> struct A {};
850 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
851 /// refersToType(class(hasName("X")))))
852 /// matches the specialization \c A<X>
853 AST_MATCHER_P(TemplateArgument, refersToType,
854 internal::Matcher<QualType>, InnerMatcher) {
855 if (Node.getKind() != TemplateArgument::Type)
857 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
860 /// \brief Matches a TemplateArgument that refers to a certain template.
864 /// template<template <typename> class S> class X {};
865 /// template<typename T> class Y {};"
868 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
869 /// refersToTemplate(templateName())))
870 /// matches the specialization \c X<Y>
871 AST_MATCHER_P(TemplateArgument, refersToTemplate,
872 internal::Matcher<TemplateName>, InnerMatcher) {
873 if (Node.getKind() != TemplateArgument::Template)
875 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
878 /// \brief Matches a canonical TemplateArgument that refers to a certain
883 /// template<typename T> struct A {};
884 /// struct B { B* next; };
887 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
888 /// refersToDeclaration(fieldDecl(hasName("next"))))
889 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
891 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
892 internal::Matcher<Decl>, InnerMatcher) {
893 if (Node.getKind() == TemplateArgument::Declaration)
894 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
898 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
902 /// template<typename T> struct A {};
903 /// struct B { B* next; };
906 /// templateSpecializationType(hasAnyTemplateArgument(
907 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
908 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
910 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
911 if (Node.getKind() == TemplateArgument::Expression)
912 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
916 /// \brief Matches a TemplateArgument that is an integral value.
920 /// template<int T> struct A {};
923 /// classTemplateSpecializationDecl(
924 /// hasAnyTemplateArgument(isIntegral()))
925 /// matches the implicit instantiation of C in C<42>
926 /// with isIntegral() matching 42.
927 AST_MATCHER(TemplateArgument, isIntegral) {
928 return Node.getKind() == TemplateArgument::Integral;
931 /// \brief Matches a TemplateArgument that referes to an integral type.
935 /// template<int T> struct A {};
938 /// classTemplateSpecializationDecl(
939 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
940 /// matches the implicit instantiation of C in C<42>.
941 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
942 internal::Matcher<QualType>, InnerMatcher) {
943 if (Node.getKind() != TemplateArgument::Integral)
945 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
948 /// \brief Matches a TemplateArgument of integral type with a given value.
950 /// Note that 'Value' is a string as the template argument's value is
951 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
952 /// representation of that integral value in base 10.
956 /// template<int T> struct A {};
959 /// classTemplateSpecializationDecl(
960 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
961 /// matches the implicit instantiation of C in C<42>.
962 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
963 std::string, Value) {
964 if (Node.getKind() != TemplateArgument::Integral)
966 return Node.getAsIntegral().toString(10) == Value;
969 /// \brief Matches any value declaration.
971 /// Example matches A, B, C and F
973 /// enum X { A, B, C };
976 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
978 /// \brief Matches C++ constructor declarations.
980 /// Example matches Foo::Foo() and Foo::Foo(int)
986 /// int DoSomething();
989 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
992 /// \brief Matches explicit C++ destructor declarations.
994 /// Example matches Foo::~Foo()
1001 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1004 /// \brief Matches enum declarations.
1006 /// Example matches X
1012 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1014 /// \brief Matches enum constants.
1016 /// Example matches A, B, C
1022 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1025 /// \brief Matches method declarations.
1027 /// Example matches y
1029 /// class X { void y(); };
1031 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1034 /// \brief Matches conversion operator declarations.
1036 /// Example matches the operator.
1038 /// class X { operator int() const; };
1040 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1043 /// \brief Matches variable declarations.
1045 /// Note: this does not match declarations of member variables, which are
1046 /// "field" declarations in Clang parlance.
1048 /// Example matches a
1052 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1054 /// \brief Matches field declarations.
1058 /// class X { int m; };
1062 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1064 /// \brief Matches function declarations.
1066 /// Example matches f
1070 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1073 /// \brief Matches C++ function template declarations.
1075 /// Example matches f
1077 /// template<class T> void f(T t) {}
1079 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1080 functionTemplateDecl;
1082 /// \brief Matches friend declarations.
1086 /// class X { friend void foo(); };
1089 /// matches 'friend void foo()'.
1090 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1092 /// \brief Matches statements.
1099 /// matches both the compound statement '{ ++a; }' and '++a'.
1100 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1102 /// \brief Matches declaration statements.
1109 /// matches 'int a'.
1110 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1112 /// \brief Matches member expressions.
1117 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1118 /// int a; static int b;
1122 /// matches this->x, x, y.x, a, this->b
1123 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1125 /// \brief Matches call expressions.
1127 /// Example matches x.y() and y()
1133 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1135 /// \brief Matches lambda expressions.
1137 /// Example matches [&](){return 5;}
1139 /// [&](){return 5;}
1141 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1143 /// \brief Matches member call expressions.
1145 /// Example matches x.y()
1150 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1153 /// \brief Matches ObjectiveC Message invocation expressions.
1155 /// The innermost message send invokes the "alloc" class method on the
1156 /// NSString class, while the outermost message send invokes the
1157 /// "initWithString" instance method on the object returned from
1158 /// NSString's "alloc". This matcher should match both message sends.
1160 /// [[NSString alloc] initWithString:@"Hello"]
1162 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1165 /// \brief Matches Objective-C interface declarations.
1167 /// Example matches Foo
1172 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1175 /// \brief Matches Objective-C implementation declarations.
1177 /// Example matches Foo
1179 /// @implementation Foo
1182 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1183 objcImplementationDecl;
1185 /// \brief Matches Objective-C protocol declarations.
1187 /// Example matches FooDelegate
1189 /// @protocol FooDelegate
1192 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1195 /// \brief Matches Objective-C category declarations.
1197 /// Example matches Foo (Additions)
1199 /// @interface Foo (Additions)
1202 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1205 /// \brief Matches Objective-C category definitions.
1207 /// Example matches Foo (Additions)
1209 /// @implementation Foo (Additions)
1212 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1213 objcCategoryImplDecl;
1215 /// \brief Matches Objective-C method declarations.
1217 /// Example matches both declaration and definition of -[Foo method]
1223 /// @implementation Foo
1224 /// - (void)method {}
1227 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1230 /// \brief Matches Objective-C instance variable declarations.
1232 /// Example matches _enabled
1234 /// @implementation Foo {
1239 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1242 /// \brief Matches Objective-C property declarations.
1244 /// Example matches enabled
1247 /// @property BOOL enabled;
1250 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1253 /// \brief Matches Objective-C \@throw statements.
1255 /// Example matches \@throw
1259 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1262 /// \brief Matches Objective-C @try statements.
1264 /// Example matches @try
1269 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1272 /// \brief Matches Objective-C @catch statements.
1274 /// Example matches @catch
1279 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1282 /// \brief Matches Objective-C @finally statements.
1284 /// Example matches @finally
1289 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1292 /// \brief Matches expressions that introduce cleanups to be run at the end
1293 /// of the sub-expression's evaluation.
1295 /// Example matches std::string()
1297 /// const std::string str = std::string();
1299 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1302 /// \brief Matches init list expressions.
1306 /// int a[] = { 1, 2 };
1307 /// struct B { int x, y; };
1311 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1312 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1315 /// \brief Matches the syntactic form of init list expressions
1316 /// (if expression have it).
1317 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1318 internal::Matcher<Expr>, InnerMatcher) {
1319 const Expr *SyntForm = Node.getSyntacticForm();
1320 return (SyntForm != nullptr &&
1321 InnerMatcher.matches(*SyntForm, Finder, Builder));
1324 /// \brief Matches C++ initializer list expressions.
1328 /// std::vector<int> a({ 1, 2, 3 });
1329 /// std::vector<int> b = { 4, 5 };
1330 /// int c[] = { 6, 7 };
1331 /// std::pair<int, int> d = { 8, 9 };
1333 /// cxxStdInitializerListExpr()
1334 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1335 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1336 CXXStdInitializerListExpr>
1337 cxxStdInitializerListExpr;
1339 /// \brief Matches implicit initializers of init list expressions.
1343 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1345 /// implicitValueInitExpr()
1346 /// matches "[0].y" (implicitly)
1347 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1348 implicitValueInitExpr;
1350 /// \brief Matches paren list expressions.
1351 /// ParenListExprs don't have a predefined type and are used for late parsing.
1352 /// In the final AST, they can be met in template declarations.
1356 /// template<typename T> class X {
1359 /// int a = 0, b = 1; int i = (a, b);
1363 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1364 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1365 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1368 /// \brief Matches substitutions of non-type template parameters.
1372 /// template <int N>
1373 /// struct A { static const int n = N; };
1374 /// struct B : public A<42> {};
1376 /// substNonTypeTemplateParmExpr()
1377 /// matches "N" in the right-hand side of "static const int n = N;"
1378 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1379 SubstNonTypeTemplateParmExpr>
1380 substNonTypeTemplateParmExpr;
1382 /// \brief Matches using declarations.
1386 /// namespace X { int x; }
1390 /// matches \code using X::x \endcode
1391 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1393 /// \brief Matches using namespace declarations.
1397 /// namespace X { int x; }
1398 /// using namespace X;
1400 /// usingDirectiveDecl()
1401 /// matches \code using namespace X \endcode
1402 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1405 /// \brief Matches reference to a name that can be looked up during parsing
1406 /// but could not be resolved to a specific declaration.
1410 /// template<typename T>
1411 /// T foo() { T a; return a; }
1412 /// template<typename T>
1417 /// unresolvedLookupExpr()
1418 /// matches \code foo<T>() \endcode
1419 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1420 unresolvedLookupExpr;
1422 /// \brief Matches unresolved using value declarations.
1426 /// template<typename X>
1427 /// class C : private X {
1431 /// unresolvedUsingValueDecl()
1432 /// matches \code using X::x \endcode
1433 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1434 UnresolvedUsingValueDecl>
1435 unresolvedUsingValueDecl;
1437 /// \brief Matches unresolved using value declarations that involve the
1442 /// template <typename T>
1443 /// struct Base { typedef T Foo; };
1445 /// template<typename T>
1446 /// struct S : private Base<T> {
1447 /// using typename Base<T>::Foo;
1450 /// unresolvedUsingTypenameDecl()
1451 /// matches \code using Base<T>::Foo \endcode
1452 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1453 UnresolvedUsingTypenameDecl>
1454 unresolvedUsingTypenameDecl;
1456 /// \brief Matches parentheses used in expressions.
1458 /// Example matches (foo() + 1)
1460 /// int foo() { return 1; }
1461 /// int a = (foo() + 1);
1463 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1465 /// \brief Matches constructor call expressions (including implicit ones).
1467 /// Example matches string(ptr, n) and ptr within arguments of f
1468 /// (matcher = cxxConstructExpr())
1470 /// void f(const string &a, const string &b);
1473 /// f(string(ptr, n), ptr);
1475 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1478 /// \brief Matches unresolved constructor call expressions.
1480 /// Example matches T(t) in return statement of f
1481 /// (matcher = cxxUnresolvedConstructExpr())
1483 /// template <typename T>
1484 /// void f(const T& t) { return T(t); }
1486 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1487 CXXUnresolvedConstructExpr>
1488 cxxUnresolvedConstructExpr;
1490 /// \brief Matches implicit and explicit this expressions.
1492 /// Example matches the implicit this expression in "return i".
1493 /// (matcher = cxxThisExpr())
1497 /// int f() { return i; }
1500 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1503 /// \brief Matches nodes where temporaries are created.
1505 /// Example matches FunctionTakesString(GetStringByValue())
1506 /// (matcher = cxxBindTemporaryExpr())
1508 /// FunctionTakesString(GetStringByValue());
1509 /// FunctionTakesStringByPointer(GetStringPointer());
1511 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1512 cxxBindTemporaryExpr;
1514 /// \brief Matches nodes where temporaries are materialized.
1518 /// struct T {void func();};
1522 /// materializeTemporaryExpr() matches 'f()' in these statements
1527 /// but does not match
1532 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1533 MaterializeTemporaryExpr>
1534 materializeTemporaryExpr;
1536 /// \brief Matches new expressions.
1543 /// matches 'new X'.
1544 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1546 /// \brief Matches delete expressions.
1553 /// matches 'delete X'.
1554 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1557 /// \brief Matches array subscript expressions.
1563 /// arraySubscriptExpr()
1565 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1568 /// \brief Matches the value of a default argument at the call site.
1570 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1571 /// default value of the second parameter in the call expression f(42)
1572 /// (matcher = cxxDefaultArgExpr())
1574 /// void f(int x, int y = 0);
1577 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1580 /// \brief Matches overloaded operator calls.
1582 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1583 /// binaryOperator matcher.
1584 /// Currently it does not match operators such as new delete.
1585 /// FIXME: figure out why these do not match?
1587 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1588 /// (matcher = cxxOperatorCallExpr())
1590 /// ostream &operator<< (ostream &out, int i) { };
1591 /// ostream &o; int b = 1, c = 1;
1594 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1595 cxxOperatorCallExpr;
1597 /// \brief Matches expressions.
1599 /// Example matches x()
1601 /// void f() { x(); }
1603 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1605 /// \brief Matches expressions that refer to declarations.
1607 /// Example matches x in if (x)
1612 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1615 /// \brief Matches if statements.
1617 /// Example matches 'if (x) {}'
1621 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1623 /// \brief Matches for statements.
1625 /// Example matches 'for (;;) {}'
1628 /// int i[] = {1, 2, 3}; for (auto a : i);
1630 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1632 /// \brief Matches the increment statement of a for loop.
1635 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1636 /// matches '++x' in
1638 /// for (x; x < N; ++x) { }
1640 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1642 const Stmt *const Increment = Node.getInc();
1643 return (Increment != nullptr &&
1644 InnerMatcher.matches(*Increment, Finder, Builder));
1647 /// \brief Matches the initialization statement of a for loop.
1650 /// forStmt(hasLoopInit(declStmt()))
1651 /// matches 'int x = 0' in
1653 /// for (int x = 0; x < N; ++x) { }
1655 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1657 const Stmt *const Init = Node.getInit();
1658 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1661 /// \brief Matches range-based for statements.
1663 /// cxxForRangeStmt() matches 'for (auto a : i)'
1665 /// int i[] = {1, 2, 3}; for (auto a : i);
1666 /// for(int j = 0; j < 5; ++j);
1668 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1671 /// \brief Matches the initialization statement of a for loop.
1674 /// forStmt(hasLoopVariable(anything()))
1675 /// matches 'int x' in
1677 /// for (int x : a) { }
1679 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1681 const VarDecl *const Var = Node.getLoopVariable();
1682 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1685 /// \brief Matches the range initialization statement of a for loop.
1688 /// forStmt(hasRangeInit(anything()))
1691 /// for (int x : a) { }
1693 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1695 const Expr *const Init = Node.getRangeInit();
1696 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1699 /// \brief Matches while statements.
1706 /// matches 'while (true) {}'.
1707 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1709 /// \brief Matches do statements.
1713 /// do {} while (true);
1716 /// matches 'do {} while(true)'
1717 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1719 /// \brief Matches break statements.
1723 /// while (true) { break; }
1727 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1729 /// \brief Matches continue statements.
1733 /// while (true) { continue; }
1736 /// matches 'continue'
1737 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1740 /// \brief Matches return statements.
1747 /// matches 'return 1'
1748 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1750 /// \brief Matches goto statements.
1758 /// matches 'goto FOO'
1759 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1761 /// \brief Matches label statements.
1770 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1772 /// \brief Matches address of label statements (GNU extension).
1777 /// void *ptr = &&FOO;
1782 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
1785 /// \brief Matches switch statements.
1789 /// switch(a) { case 42: break; default: break; }
1792 /// matches 'switch(a)'.
1793 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1795 /// \brief Matches case and default statements inside switch statements.
1799 /// switch(a) { case 42: break; default: break; }
1802 /// matches 'case 42: break;' and 'default: break;'.
1803 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1805 /// \brief Matches case statements inside switch statements.
1809 /// switch(a) { case 42: break; default: break; }
1812 /// matches 'case 42: break;'.
1813 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1815 /// \brief Matches default statements inside switch statements.
1819 /// switch(a) { case 42: break; default: break; }
1822 /// matches 'default: break;'.
1823 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
1826 /// \brief Matches compound statements.
1828 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1832 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
1835 /// \brief Matches catch statements.
1838 /// try {} catch(int i) {}
1841 /// matches 'catch(int i)'
1842 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
1845 /// \brief Matches try statements.
1848 /// try {} catch(int i) {}
1851 /// matches 'try {}'
1852 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1854 /// \brief Matches throw expressions.
1857 /// try { throw 5; } catch(int i) {}
1860 /// matches 'throw 5'
1861 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
1864 /// \brief Matches null statements.
1870 /// matches the second ';'
1871 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1873 /// \brief Matches asm statements.
1877 /// __asm("mov al, 2");
1880 /// matches '__asm("mov al, 2")'
1881 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1883 /// \brief Matches bool literals.
1885 /// Example matches true
1889 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
1892 /// \brief Matches string literals (also matches wide string literals).
1894 /// Example matches "abcd", L"abcd"
1896 /// char *s = "abcd";
1897 /// wchar_t *ws = L"abcd";
1899 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
1902 /// \brief Matches character literals (also matches wchar_t).
1904 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1907 /// Example matches 'a', L'a'
1910 /// wchar_t chw = L'a';
1912 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
1915 /// \brief Matches integer literals of all sizes / encodings, e.g.
1916 /// 1, 1L, 0x1 and 1U.
1918 /// Does not match character-encoded integers such as L'a'.
1919 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
1922 /// \brief Matches float literals of all sizes / encodings, e.g.
1923 /// 1.0, 1.0f, 1.0L and 1e10.
1925 /// Does not match implicit conversions such as
1929 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
1932 /// \brief Matches user defined literal operator call.
1934 /// Example match: "foo"_suffix
1935 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
1938 /// \brief Matches compound (i.e. non-scalar) literals
1940 /// Example match: {1}, (1, 2)
1942 /// int array[4] = {1};
1943 /// vector int myvec = (vector int)(1, 2);
1945 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
1946 compoundLiteralExpr;
1948 /// \brief Matches nullptr literal.
1949 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
1950 cxxNullPtrLiteralExpr;
1952 /// \brief Matches GNU __null expression.
1953 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
1956 /// \brief Matches atomic builtins.
1957 /// Example matches __atomic_load_n(ptr, 1)
1959 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
1961 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
1963 /// \brief Matches statement expression (GNU extension).
1965 /// Example match: ({ int X = 4; X; })
1967 /// int C = ({ int X = 4; X; });
1969 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
1971 /// \brief Matches binary operator expressions.
1973 /// Example matches a || b
1977 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
1980 /// \brief Matches unary operator expressions.
1982 /// Example matches !a
1986 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
1989 /// \brief Matches conditional operator expressions.
1991 /// Example matches a ? b : c
1993 /// (a ? b : c) + 42
1995 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
1996 conditionalOperator;
1998 /// \brief Matches binary conditional operator expressions (GNU extension).
2000 /// Example matches a ?: b
2004 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2005 BinaryConditionalOperator>
2006 binaryConditionalOperator;
2008 /// \brief Matches opaque value expressions. They are used as helpers
2009 /// to reference another expressions and can be met
2010 /// in BinaryConditionalOperators, for example.
2012 /// Example matches 'a'
2016 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2019 /// \brief Matches a C++ static_assert declaration.
2022 /// staticAssertExpr()
2024 /// static_assert(sizeof(S) == sizeof(int))
2030 /// static_assert(sizeof(S) == sizeof(int));
2032 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2035 /// \brief Matches a reinterpret_cast expression.
2037 /// Either the source expression or the destination type can be matched
2038 /// using has(), but hasDestinationType() is more specific and can be
2041 /// Example matches reinterpret_cast<char*>(&p) in
2043 /// void* p = reinterpret_cast<char*>(&p);
2045 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2046 cxxReinterpretCastExpr;
2048 /// \brief Matches a C++ static_cast expression.
2050 /// \see hasDestinationType
2051 /// \see reinterpretCast
2054 /// cxxStaticCastExpr()
2056 /// static_cast<long>(8)
2059 /// long eight(static_cast<long>(8));
2061 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2064 /// \brief Matches a dynamic_cast expression.
2067 /// cxxDynamicCastExpr()
2069 /// dynamic_cast<D*>(&b);
2072 /// struct B { virtual ~B() {} }; struct D : B {};
2074 /// D* p = dynamic_cast<D*>(&b);
2076 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2079 /// \brief Matches a const_cast expression.
2081 /// Example: Matches const_cast<int*>(&r) in
2084 /// const int &r(n);
2085 /// int* p = const_cast<int*>(&r);
2087 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2090 /// \brief Matches a C-style cast expression.
2092 /// Example: Matches (int) 2.2f in
2094 /// int i = (int) 2.2f;
2096 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2099 /// \brief Matches explicit cast expressions.
2101 /// Matches any cast expression written in user code, whether it be a
2102 /// C-style cast, a functional-style cast, or a keyword cast.
2104 /// Does not match implicit conversions.
2106 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2107 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2108 /// actual cast expressions.
2110 /// \see hasDestinationType.
2112 /// Example: matches all five of the casts in
2114 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2116 /// but does not match the implicit conversion in
2120 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2123 /// \brief Matches the implicit cast nodes of Clang's AST.
2125 /// This matches many different places, including function call return value
2126 /// eliding, as well as any type conversions.
2127 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2130 /// \brief Matches any cast nodes of Clang's AST.
2132 /// Example: castExpr() matches each of the following:
2135 /// const_cast<Expr *>(SubExpr);
2138 /// but does not match
2143 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2145 /// \brief Matches functional cast expressions
2147 /// Example: Matches Foo(bar);
2150 /// Foo g = (Foo) bar;
2151 /// Foo h = Foo(bar);
2153 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2154 cxxFunctionalCastExpr;
2156 /// \brief Matches functional cast expressions having N != 1 arguments
2158 /// Example: Matches Foo(bar, bar)
2160 /// Foo h = Foo(bar, bar);
2162 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2163 cxxTemporaryObjectExpr;
2165 /// \brief Matches predefined identifier expressions [C99 6.4.2.2].
2167 /// Example: Matches __func__
2169 /// printf("%s", __func__);
2171 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2174 /// \brief Matches C99 designated initializer expressions [C99 6.7.8].
2176 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2178 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2180 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2183 /// \brief Matches designated initializer expressions that contain
2184 /// a specific number of designators.
2188 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2189 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2191 /// designatorCountIs(2)
2192 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2193 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2194 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2195 return Node.size() == N;
2198 /// \brief Matches \c QualTypes in the clang AST.
2199 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2201 /// \brief Matches \c Types in the clang AST.
2202 extern const internal::VariadicAllOfMatcher<Type> type;
2204 /// \brief Matches \c TypeLocs in the clang AST.
2205 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2207 /// \brief Matches if any of the given matchers matches.
2209 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2210 /// matching submatcher.
2212 /// For example, in:
2214 /// class A { int a; int b; };
2218 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2219 /// has(fieldDecl(hasName("b")).bind("v"))))
2221 /// will generate two results binding "v", the first of which binds
2222 /// the field declaration of \c a, the second the field declaration of
2225 /// Usable as: Any Matcher
2226 extern const internal::VariadicOperatorMatcherFunc<
2227 2, std::numeric_limits<unsigned>::max()>
2230 /// \brief Matches if any of the given matchers matches.
2232 /// Usable as: Any Matcher
2233 extern const internal::VariadicOperatorMatcherFunc<
2234 2, std::numeric_limits<unsigned>::max()>
2237 /// \brief Matches if all given matchers match.
2239 /// Usable as: Any Matcher
2240 extern const internal::VariadicOperatorMatcherFunc<
2241 2, std::numeric_limits<unsigned>::max()>
2244 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2249 /// int y = sizeof(x) + alignof(x);
2251 /// unaryExprOrTypeTraitExpr()
2252 /// matches \c sizeof(x) and \c alignof(x)
2253 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2254 UnaryExprOrTypeTraitExpr>
2255 unaryExprOrTypeTraitExpr;
2257 /// \brief Matches unary expressions that have a specific type of argument.
2261 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2263 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2264 /// matches \c sizeof(a) and \c alignof(c)
2265 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2266 internal::Matcher<QualType>, InnerMatcher) {
2267 const QualType ArgumentType = Node.getTypeOfArgument();
2268 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2271 /// \brief Matches unary expressions of a certain kind.
2276 /// int s = sizeof(x) + alignof(x)
2278 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2279 /// matches \c sizeof(x)
2280 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2281 return Node.getKind() == Kind;
2284 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2286 inline internal::Matcher<Stmt> alignOfExpr(
2287 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2288 return stmt(unaryExprOrTypeTraitExpr(allOf(
2289 ofKind(UETT_AlignOf), InnerMatcher)));
2292 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2294 inline internal::Matcher<Stmt> sizeOfExpr(
2295 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2296 return stmt(unaryExprOrTypeTraitExpr(
2297 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2300 /// \brief Matches NamedDecl nodes that have the specified name.
2302 /// Supports specifying enclosing namespaces or classes by prefixing the name
2303 /// with '<enclosing>::'.
2304 /// Does not match typedefs of an underlying type with the given name.
2306 /// Example matches X (Name == "X")
2311 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2313 /// namespace a { namespace b { class X; } }
2315 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2316 std::vector<std::string> Names;
2317 Names.push_back(Name);
2318 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
2321 /// \brief Matches NamedDecl nodes that have any of the specified names.
2323 /// This matcher is only provided as a performance optimization of hasName.
2325 /// hasAnyName(a, b, c)
2327 /// is equivalent to, but faster than
2329 /// anyOf(hasName(a), hasName(b), hasName(c))
2331 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2332 internal::hasAnyNameFunc>
2335 /// \brief Matches NamedDecl nodes whose fully qualified names contain
2336 /// a substring matched by the given RegExp.
2338 /// Supports specifying enclosing namespaces or classes by
2339 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2340 /// of an underlying type with the given name.
2342 /// Example matches X (regexp == "::X")
2347 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2349 /// namespace foo { namespace bar { class X; } }
2351 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2352 assert(!RegExp.empty());
2353 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2354 llvm::Regex RE(RegExp);
2355 return RE.match(FullNameString);
2358 /// \brief Matches overloaded operator names.
2360 /// Matches overloaded operator names specified in strings without the
2361 /// "operator" prefix: e.g. "<<".
2365 /// class A { int operator*(); };
2366 /// const A &operator<<(const A &a, const A &b);
2368 /// a << a; // <-- This matches
2371 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2372 /// specified line and
2373 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2374 /// matches the declaration of \c A.
2376 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2377 inline internal::PolymorphicMatcherWithParam1<
2378 internal::HasOverloadedOperatorNameMatcher, StringRef,
2379 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2380 hasOverloadedOperatorName(StringRef Name) {
2381 return internal::PolymorphicMatcherWithParam1<
2382 internal::HasOverloadedOperatorNameMatcher, StringRef,
2383 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2386 /// \brief Matches C++ classes that are directly or indirectly derived from
2387 /// a class matching \c Base.
2389 /// Note that a class is not considered to be derived from itself.
2391 /// Example matches Y, Z, C (Base == hasName("X"))
2394 /// class Y : public X {}; // directly derived
2395 /// class Z : public Y {}; // indirectly derived
2398 /// class C : public B {}; // derived from a typedef of X
2401 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2405 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2407 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2408 internal::Matcher<NamedDecl>, Base) {
2409 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2412 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2413 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2414 assert(!BaseName.empty());
2415 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2418 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
2420 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2421 internal::Matcher<NamedDecl>, Base, 0) {
2422 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2423 .matches(Node, Finder, Builder);
2426 /// \brief Overloaded method as shortcut for
2427 /// \c isSameOrDerivedFrom(hasName(...)).
2428 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2430 assert(!BaseName.empty());
2431 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2434 /// \brief Matches the first method of a class or struct that satisfies \c
2439 /// class A { void func(); };
2440 /// class B { void member(); };
2443 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2444 /// \c A but not \c B.
2445 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2447 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2448 Node.method_end(), Finder, Builder);
2451 /// \brief Matches the generated class of lambda expressions.
2458 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2460 AST_MATCHER(CXXRecordDecl, isLambda) {
2461 return Node.isLambda();
2464 /// \brief Matches AST nodes that have child AST nodes that match the
2465 /// provided matcher.
2467 /// Example matches X, Y
2468 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2470 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2471 /// class Y { class X {}; };
2472 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2475 /// ChildT must be an AST base type.
2477 /// Usable as: Any Matcher
2478 /// Note that has is direct matcher, so it also matches things like implicit
2479 /// casts and paren casts. If you are matching with expr then you should
2480 /// probably consider using ignoringParenImpCasts like:
2481 /// has(ignoringParenImpCasts(expr())).
2482 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2484 /// \brief Matches AST nodes that have descendant AST nodes that match the
2485 /// provided matcher.
2487 /// Example matches X, Y, Z
2488 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2490 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2491 /// class Y { class X {}; };
2492 /// class Z { class Y { class X {}; }; };
2495 /// DescendantT must be an AST base type.
2497 /// Usable as: Any Matcher
2498 extern const internal::ArgumentAdaptingMatcherFunc<
2499 internal::HasDescendantMatcher>
2502 /// \brief Matches AST nodes that have child AST nodes that match the
2503 /// provided matcher.
2505 /// Example matches X, Y
2506 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2508 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2509 /// class Y { class X {}; };
2510 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2513 /// ChildT must be an AST base type.
2515 /// As opposed to 'has', 'forEach' will cause a match for each result that
2516 /// matches instead of only on the first one.
2518 /// Usable as: Any Matcher
2519 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2522 /// \brief Matches AST nodes that have descendant AST nodes that match the
2523 /// provided matcher.
2525 /// Example matches X, A, B, C
2526 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2528 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2529 /// class A { class X {}; };
2530 /// class B { class C { class X {}; }; };
2533 /// DescendantT must be an AST base type.
2535 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2536 /// each result that matches instead of only on the first one.
2538 /// Note: Recursively combined ForEachDescendant can cause many matches:
2539 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2540 /// forEachDescendant(cxxRecordDecl())
2542 /// will match 10 times (plus injected class name matches) on:
2544 /// class A { class B { class C { class D { class E {}; }; }; }; };
2547 /// Usable as: Any Matcher
2548 extern const internal::ArgumentAdaptingMatcherFunc<
2549 internal::ForEachDescendantMatcher>
2552 /// \brief Matches if the node or any descendant matches.
2554 /// Generates results for each match.
2556 /// For example, in:
2558 /// class A { class B {}; class C {}; };
2562 /// cxxRecordDecl(hasName("::A"),
2563 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2565 /// will generate results for \c A, \c B and \c C.
2567 /// Usable as: Any Matcher
2568 template <typename T>
2569 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2570 return eachOf(Matcher, forEachDescendant(Matcher));
2573 /// \brief Matches AST nodes that have a parent that matches the provided
2578 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2580 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2582 /// Usable as: Any Matcher
2583 extern const internal::ArgumentAdaptingMatcherFunc<
2584 internal::HasParentMatcher,
2585 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2586 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2589 /// \brief Matches AST nodes that have an ancestor that matches the provided
2594 /// void f() { if (true) { int x = 42; } }
2595 /// void g() { for (;;) { int x = 43; } }
2597 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2599 /// Usable as: Any Matcher
2600 extern const internal::ArgumentAdaptingMatcherFunc<
2601 internal::HasAncestorMatcher,
2602 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2603 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2606 /// \brief Matches if the provided matcher does not match.
2608 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2614 /// Usable as: Any Matcher
2615 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2617 /// \brief Matches a node if the declaration associated with that node
2618 /// matches the given matcher.
2620 /// The associated declaration is:
2621 /// - for type nodes, the declaration of the underlying type
2622 /// - for CallExpr, the declaration of the callee
2623 /// - for MemberExpr, the declaration of the referenced member
2624 /// - for CXXConstructExpr, the declaration of the constructor
2625 /// - for CXXNewExpr, the declaration of the operator new
2627 /// For type nodes, hasDeclaration will generally match the declaration of the
2628 /// sugared type. Given
2634 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2635 /// typedefDecl. A common use case is to match the underlying, desugared type.
2636 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2638 /// varDecl(hasType(hasUnqualifiedDesugaredType(
2639 /// recordType(hasDeclaration(decl())))))
2641 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2643 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2644 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2645 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2646 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2647 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2648 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2649 /// Matcher<UnresolvedUsingType>
2650 inline internal::PolymorphicMatcherWithParam1<
2651 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2652 void(internal::HasDeclarationSupportedTypes)>
2653 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2654 return internal::PolymorphicMatcherWithParam1<
2655 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2656 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2659 /// \brief Matches a \c NamedDecl whose underlying declaration matches the given
2664 /// namespace N { template<class T> void f(T t); }
2665 /// template <class T> void g() { using N::f; f(T()); }
2667 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2668 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2669 /// matches the use of \c f in \c g() .
2670 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2672 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2674 return UnderlyingDecl != nullptr &&
2675 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2678 /// \brief Matches on the implicit object argument of a member call expression.
2680 /// Example matches y.x()
2681 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2683 /// class Y { public: void x(); };
2684 /// void z() { Y y; y.x(); }",
2687 /// FIXME: Overload to allow directly matching types?
2688 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2690 const Expr *ExprNode = Node.getImplicitObjectArgument()
2691 ->IgnoreParenImpCasts();
2692 return (ExprNode != nullptr &&
2693 InnerMatcher.matches(*ExprNode, Finder, Builder));
2697 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2700 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2701 /// matches the [webView ...] message invocation.
2703 /// NSString *webViewJavaScript = ...
2704 /// UIWebView *webView = ...
2705 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2707 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2709 const QualType TypeDecl = Node.getReceiverType();
2710 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2713 /// \brief Matches when BaseName == Selector.getAsString()
2715 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2716 /// matches the outer message expr in the code below, but NOT the message
2717 /// invocation for self.bodyView.
2719 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2721 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2722 Selector Sel = Node.getSelector();
2723 return BaseName.compare(Sel.getAsString()) == 0;
2727 /// \brief Matches ObjC selectors whose name contains
2728 /// a substring matched by the given RegExp.
2729 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2730 /// matches the outer message expr in the code below, but NOT the message
2731 /// invocation for self.bodyView.
2733 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2735 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2736 assert(!RegExp.empty());
2737 std::string SelectorString = Node.getSelector().getAsString();
2738 llvm::Regex RE(RegExp);
2739 return RE.match(SelectorString);
2742 /// \brief Matches when the selector is the empty selector
2744 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2745 /// represent an error condition in the tree!
2746 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2747 return Node.getSelector().isNull();
2750 /// \brief Matches when the selector is a Unary Selector
2752 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2753 /// matches self.bodyView in the code below, but NOT the outer message
2754 /// invocation of "loadHTMLString:baseURL:".
2756 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2758 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2759 return Node.getSelector().isUnarySelector();
2762 /// \brief Matches when the selector is a keyword selector
2764 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2765 /// message expression in
2768 /// UIWebView *webView = ...;
2769 /// CGRect bodyFrame = webView.frame;
2770 /// bodyFrame.size.height = self.bodyContentHeight;
2771 /// webView.frame = bodyFrame;
2772 /// // ^---- matches here
2774 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2775 return Node.getSelector().isKeywordSelector();
2778 /// \brief Matches when the selector has the specified number of arguments
2780 /// matcher = objCMessageExpr(numSelectorArgs(0));
2781 /// matches self.bodyView in the code below
2783 /// matcher = objCMessageExpr(numSelectorArgs(2));
2784 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2785 /// of self.bodyView
2787 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2789 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2790 return Node.getSelector().getNumArgs() == N;
2793 /// \brief Matches if the call expression's callee expression matches.
2797 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2798 /// void f() { f(); }
2800 /// callExpr(callee(expr()))
2801 /// matches this->x(), x(), y.x(), f()
2802 /// with callee(...)
2803 /// matching this->x, x, y.x, f respectively
2805 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2806 /// because this introduces ambiguous overloads with calls to Callee taking a
2807 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2808 /// implemented in terms of implicit casts.
2809 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2811 const Expr *ExprNode = Node.getCallee();
2812 return (ExprNode != nullptr &&
2813 InnerMatcher.matches(*ExprNode, Finder, Builder));
2816 /// \brief Matches if the call expression's callee's declaration matches the
2819 /// Example matches y.x() (matcher = callExpr(callee(
2820 /// cxxMethodDecl(hasName("x")))))
2822 /// class Y { public: void x(); };
2823 /// void z() { Y y; y.x(); }
2825 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2827 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2830 /// \brief Matches if the expression's or declaration's type matches a type
2833 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2834 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2835 /// and U (matcher = typedefDecl(hasType(asString("int")))
2838 /// void y(X &x) { x; X z; }
2841 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2842 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefNameDecl, ValueDecl),
2843 internal::Matcher<QualType>, InnerMatcher, 0) {
2844 return InnerMatcher.matches(internal::getUnderlyingType(Node),
2848 /// \brief Overloaded to match the declaration of the expression's or value
2849 /// declaration's type.
2851 /// In case of a value declaration (for example a variable declaration),
2852 /// this resolves one layer of indirection. For example, in the value
2853 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2854 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2855 /// declaration of x.
2857 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2858 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2861 /// void y(X &x) { x; X z; }
2864 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2865 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2866 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2868 internal::Matcher<Decl>, InnerMatcher, 1) {
2869 return qualType(hasDeclaration(InnerMatcher))
2870 .matches(Node.getType(), Finder, Builder);
2873 /// \brief Matches if the type location of the declarator decl's type matches
2874 /// the inner matcher.
2880 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2882 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2883 if (!Node.getTypeSourceInfo())
2884 // This happens for example for implicit destructors.
2886 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2889 /// \brief Matches if the matched type is represented by the given string.
2893 /// class Y { public: void x(); };
2894 /// void z() { Y* y; y->x(); }
2896 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2898 AST_MATCHER_P(QualType, asString, std::string, Name) {
2899 return Name == Node.getAsString();
2902 /// \brief Matches if the matched type is a pointer type and the pointee type
2903 /// matches the specified matcher.
2905 /// Example matches y->x()
2906 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2907 /// cxxRecordDecl(hasName("Y")))))))
2909 /// class Y { public: void x(); };
2910 /// void z() { Y *y; y->x(); }
2913 QualType, pointsTo, internal::Matcher<QualType>,
2915 return (!Node.isNull() && Node->isAnyPointerType() &&
2916 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2919 /// \brief Overloaded to match the pointee type's declaration.
2920 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2922 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2923 .matches(Node, Finder, Builder);
2926 /// \brief Matches if the matched type matches the unqualified desugared
2927 /// type of the matched node.
2929 /// For example, in:
2934 /// The matcher type(hasUnqualifeidDesugaredType(recordType())) matches
2936 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
2938 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
2942 /// \brief Matches if the matched type is a reference type and the referenced
2943 /// type matches the specified matcher.
2945 /// Example matches X &x and const X &y
2946 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2955 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2957 return (!Node.isNull() && Node->isReferenceType() &&
2958 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2961 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2965 /// typedef int &int_ref;
2970 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2971 /// declaration of b but \c
2972 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2973 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2977 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2980 /// \brief Overloaded to match the referenced type's declaration.
2981 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2983 return references(qualType(hasDeclaration(InnerMatcher)))
2984 .matches(Node, Finder, Builder);
2987 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2988 internal::Matcher<Expr>, InnerMatcher) {
2989 const Expr *ExprNode = Node.getImplicitObjectArgument();
2990 return (ExprNode != nullptr &&
2991 InnerMatcher.matches(*ExprNode, Finder, Builder));
2994 /// \brief Matches if the expression's type either matches the specified
2995 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2996 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2997 internal::Matcher<QualType>, InnerMatcher, 0) {
2998 return onImplicitObjectArgument(
2999 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3000 .matches(Node, Finder, Builder);
3003 /// \brief Overloaded to match the type's declaration.
3004 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3005 internal::Matcher<Decl>, InnerMatcher, 1) {
3006 return onImplicitObjectArgument(
3007 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3008 .matches(Node, Finder, Builder);
3011 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
3012 /// specified matcher.
3014 /// Example matches x in if(x)
3015 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3020 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3022 const Decl *DeclNode = Node.getDecl();
3023 return (DeclNode != nullptr &&
3024 InnerMatcher.matches(*DeclNode, Finder, Builder));
3027 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
3028 /// specific using shadow declaration.
3032 /// namespace a { void f() {} }
3035 /// f(); // Matches this ..
3036 /// a::f(); // .. but not this.
3039 /// declRefExpr(throughUsingDecl(anything()))
3041 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3042 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3043 const NamedDecl *FoundDecl = Node.getFoundDecl();
3044 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3045 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3049 /// \brief Matches an \c OverloadExpr if any of the declarations in the set of
3050 /// overloads matches the given matcher.
3054 /// template <typename T> void foo(T);
3055 /// template <typename T> void bar(T);
3056 /// template <typename T> void baz(T t) {
3061 /// unresolvedLookupExpr(hasAnyDeclaration(
3062 /// functionTemplateDecl(hasName("foo"))))
3063 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3064 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3066 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3067 Node.decls_end(), Finder, Builder);
3070 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
3077 /// declStmt(hasSingleDecl(anything()))
3078 /// matches 'int c;' but not 'int a, b;'.
3079 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3080 if (Node.isSingleDecl()) {
3081 const Decl *FoundDecl = Node.getSingleDecl();
3082 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3087 /// \brief Matches a variable declaration that has an initializer expression
3088 /// that matches the given matcher.
3090 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3092 /// bool y() { return true; }
3096 VarDecl, hasInitializer, internal::Matcher<Expr>,
3098 const Expr *Initializer = Node.getAnyInitializer();
3099 return (Initializer != nullptr &&
3100 InnerMatcher.matches(*Initializer, Finder, Builder));
3103 /// \brief Matches a variable declaration that has function scope and is a
3104 /// non-static local variable.
3106 /// Example matches x (matcher = varDecl(hasLocalStorage())
3114 AST_MATCHER(VarDecl, hasLocalStorage) {
3115 return Node.hasLocalStorage();
3118 /// \brief Matches a variable declaration that does not have local storage.
3120 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3128 AST_MATCHER(VarDecl, hasGlobalStorage) {
3129 return Node.hasGlobalStorage();
3132 /// \brief Matches a variable declaration that has automatic storage duration.
3134 /// Example matches x, but not y, z, or a.
3135 /// (matcher = varDecl(hasAutomaticStorageDuration())
3140 /// thread_local int z;
3144 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3145 return Node.getStorageDuration() == SD_Automatic;
3148 /// \brief Matches a variable declaration that has static storage duration.
3149 /// It includes the variable declared at namespace scope and those declared
3150 /// with "static" and "extern" storage class specifiers.
3156 /// thread_local int z;
3161 /// varDecl(hasStaticStorageDuration())
3162 /// matches the function declaration y, a, b and c.
3164 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3165 return Node.getStorageDuration() == SD_Static;
3168 /// \brief Matches a variable declaration that has thread storage duration.
3170 /// Example matches z, but not x, z, or a.
3171 /// (matcher = varDecl(hasThreadStorageDuration())
3176 /// thread_local int z;
3180 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3181 return Node.getStorageDuration() == SD_Thread;
3184 /// \brief Matches a variable declaration that is an exception variable from
3185 /// a C++ catch block, or an Objective-C \@catch statement.
3187 /// Example matches x (matcher = varDecl(isExceptionVariable())
3191 /// } catch (int x) {
3195 AST_MATCHER(VarDecl, isExceptionVariable) {
3196 return Node.isExceptionVariable();
3199 /// \brief Checks that a call expression or a constructor call expression has
3200 /// a specific number of arguments (including absent default arguments).
3202 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3204 /// void f(int x, int y);
3207 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3208 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3212 return Node.getNumArgs() == N;
3215 /// \brief Matches the n'th argument of a call expression or a constructor
3216 /// call expression.
3218 /// Example matches y in x(y)
3219 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3221 /// void x(int) { int y; x(y); }
3223 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3224 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3227 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3228 return (N < Node.getNumArgs() &&
3229 InnerMatcher.matches(
3230 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3233 /// \brief Matches declaration statements that contain a specific number of
3243 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3244 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3245 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3248 /// \brief Matches the n'th declaration of a declaration statement.
3250 /// Note that this does not work for global declarations because the AST
3251 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3253 /// Example: Given non-global declarations
3259 /// declStmt(containsDeclaration(
3260 /// 0, varDecl(hasInitializer(anything()))))
3261 /// matches only 'int d = 2, e;', and
3262 /// declStmt(containsDeclaration(1, varDecl()))
3264 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3265 /// but 'int c;' is not matched.
3267 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3268 internal::Matcher<Decl>, InnerMatcher) {
3269 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3272 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3273 std::advance(Iterator, N);
3274 return InnerMatcher.matches(**Iterator, Finder, Builder);
3277 /// \brief Matches a C++ catch statement that has a catch-all handler.
3289 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3290 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3291 return Node.getExceptionDecl() == nullptr;
3294 /// \brief Matches a constructor initializer.
3299 /// Foo() : foo_(1) { }
3303 /// cxxRecordDecl(has(cxxConstructorDecl(
3304 /// hasAnyConstructorInitializer(anything())
3306 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3307 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3308 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3309 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3310 Node.init_end(), Finder, Builder);
3313 /// \brief Matches the field declaration of a constructor initializer.
3318 /// Foo() : foo_(1) { }
3322 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3323 /// forField(hasName("foo_"))))))
3325 /// with forField matching foo_
3326 AST_MATCHER_P(CXXCtorInitializer, forField,
3327 internal::Matcher<FieldDecl>, InnerMatcher) {
3328 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3329 return (NodeAsDecl != nullptr &&
3330 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3333 /// \brief Matches the initializer expression of a constructor initializer.
3338 /// Foo() : foo_(1) { }
3342 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3343 /// withInitializer(integerLiteral(equals(1)))))))
3345 /// with withInitializer matching (1)
3346 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3347 internal::Matcher<Expr>, InnerMatcher) {
3348 const Expr* NodeAsExpr = Node.getInit();
3349 return (NodeAsExpr != nullptr &&
3350 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3353 /// \brief Matches a constructor initializer if it is explicitly written in
3354 /// code (as opposed to implicitly added by the compiler).
3360 /// Foo(int) : foo_("A") { }
3364 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3365 /// will match Foo(int), but not Foo()
3366 AST_MATCHER(CXXCtorInitializer, isWritten) {
3367 return Node.isWritten();
3370 /// \brief Matches a constructor initializer if it is initializing a base, as
3371 /// opposed to a member.
3378 /// D(int i) : I(i) {}
3384 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3385 /// will match E(), but not match D(int).
3386 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3387 return Node.isBaseInitializer();
3390 /// \brief Matches a constructor initializer if it is initializing a member, as
3391 /// opposed to a base.
3398 /// D(int i) : I(i) {}
3404 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3405 /// will match D(int), but not match E().
3406 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3407 return Node.isMemberInitializer();
3410 /// \brief Matches any argument of a call expression or a constructor call
3415 /// void x(int, int, int) { int y; x(1, y, 42); }
3417 /// callExpr(hasAnyArgument(declRefExpr()))
3418 /// matches x(1, y, 42)
3419 /// with hasAnyArgument(...)
3421 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3422 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3424 internal::Matcher<Expr>, InnerMatcher) {
3425 for (const Expr *Arg : Node.arguments()) {
3426 BoundNodesTreeBuilder Result(*Builder);
3427 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3428 *Builder = std::move(Result);
3435 /// \brief Matches a constructor call expression which uses list initialization.
3436 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3437 return Node.isListInitialization();
3440 /// \brief Matches a constructor call expression which requires
3441 /// zero initialization.
3446 /// struct point { double x; double y; };
3447 /// point pt[2] = { { 1.0, 2.0 } };
3450 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3451 /// will match the implicit array filler for pt[1].
3452 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3453 return Node.requiresZeroInitialization();
3456 /// \brief Matches the n'th parameter of a function declaration.
3460 /// class X { void f(int x) {} };
3462 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3463 /// matches f(int x) {}
3464 /// with hasParameter(...)
3466 AST_MATCHER_P2(FunctionDecl, hasParameter,
3467 unsigned, N, internal::Matcher<ParmVarDecl>,
3469 return (N < Node.getNumParams() &&
3470 InnerMatcher.matches(
3471 *Node.getParamDecl(N), Finder, Builder));
3474 /// \brief Matches all arguments and their respective ParmVarDecl.
3483 /// forEachArgumentWithParam(
3484 /// declRefExpr(to(varDecl(hasName("y")))),
3485 /// parmVarDecl(hasType(isInteger()))
3488 /// with declRefExpr(...)
3490 /// and parmVarDecl(...)
3492 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3493 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3495 internal::Matcher<Expr>, ArgMatcher,
3496 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3497 BoundNodesTreeBuilder Result;
3498 // The first argument of an overloaded member operator is the implicit object
3499 // argument of the method which should not be matched against a parameter, so
3500 // we skip over it here.
3501 BoundNodesTreeBuilder Matches;
3502 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3503 .matches(Node, Finder, &Matches)
3507 bool Matched = false;
3508 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3509 BoundNodesTreeBuilder ArgMatches(*Builder);
3510 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3511 Finder, &ArgMatches)) {
3512 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3513 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3514 hasParameter(ParamIndex, ParamMatcher)))),
3515 callExpr(callee(functionDecl(
3516 hasParameter(ParamIndex, ParamMatcher))))))
3517 .matches(Node, Finder, &ParamMatches)) {
3518 Result.addMatch(ParamMatches);
3524 *Builder = std::move(Result);
3528 /// \brief Matches any parameter of a function declaration.
3530 /// Does not match the 'this' parameter of a method.
3534 /// class X { void f(int x, int y, int z) {} };
3536 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3537 /// matches f(int x, int y, int z) {}
3538 /// with hasAnyParameter(...)
3540 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
3541 internal::Matcher<ParmVarDecl>, InnerMatcher) {
3542 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3543 Node.param_end(), Finder, Builder);
3546 /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3547 /// specific parameter count.
3551 /// void f(int i) {}
3552 /// void g(int i, int j) {}
3553 /// void h(int i, int j);
3555 /// void k(int x, int y, int z, ...);
3557 /// functionDecl(parameterCountIs(2))
3558 /// matches void g(int i, int j) {}
3559 /// functionProtoType(parameterCountIs(2))
3560 /// matches void h(int i, int j)
3561 /// functionProtoType(parameterCountIs(3))
3562 /// matches void k(int x, int y, int z, ...);
3563 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3564 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3567 return Node.getNumParams() == N;
3570 /// \brief Matches the return type of a function declaration.
3574 /// class X { int f() { return 1; } };
3576 /// cxxMethodDecl(returns(asString("int")))
3577 /// matches int f() { return 1; }
3578 AST_MATCHER_P(FunctionDecl, returns,
3579 internal::Matcher<QualType>, InnerMatcher) {
3580 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3583 /// \brief Matches extern "C" function or variable declarations.
3587 /// extern "C" void f() {}
3588 /// extern "C" { void g() {} }
3590 /// extern "C" int x = 1;
3591 /// extern "C" int y = 2;
3594 /// functionDecl(isExternC())
3595 /// matches the declaration of f and g, but not the declaration of h.
3596 /// varDecl(isExternC())
3597 /// matches the declaration of x and y, but not the declaration of z.
3598 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3600 return Node.isExternC();
3603 /// \brief Matches variable/function declarations that have "static" storage
3604 /// class specifier ("static" keyword) written in the source.
3608 /// static void f() {}
3609 /// static int i = 0;
3613 /// functionDecl(isStaticStorageClass())
3614 /// matches the function declaration f.
3615 /// varDecl(isStaticStorageClass())
3616 /// matches the variable declaration i.
3617 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
3618 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3620 return Node.getStorageClass() == SC_Static;
3623 /// \brief Matches deleted function declarations.
3628 /// void DeletedFunc() = delete;
3630 /// functionDecl(isDeleted())
3631 /// matches the declaration of DeletedFunc, but not Func.
3632 AST_MATCHER(FunctionDecl, isDeleted) {
3633 return Node.isDeleted();
3636 /// \brief Matches defaulted function declarations.
3640 /// class A { ~A(); };
3641 /// class B { ~B() = default; };
3643 /// functionDecl(isDefaulted())
3644 /// matches the declaration of ~B, but not ~A.
3645 AST_MATCHER(FunctionDecl, isDefaulted) {
3646 return Node.isDefaulted();
3649 /// \brief Matches functions that have a dynamic exception specification.
3654 /// void g() noexcept;
3655 /// void h() noexcept(true);
3656 /// void i() noexcept(false);
3657 /// void j() throw();
3658 /// void k() throw(int);
3659 /// void l() throw(...);
3661 /// functionDecl(hasDynamicExceptionSpec()) and
3662 /// functionProtoType(hasDynamicExceptionSpec())
3663 /// match the declarations of j, k, and l, but not f, g, h, or i.
3664 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
3665 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3666 FunctionProtoType)) {
3667 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
3668 return FnTy->hasDynamicExceptionSpec();
3672 /// \brief Matches functions that have a non-throwing exception specification.
3677 /// void g() noexcept;
3678 /// void h() throw();
3679 /// void i() throw(int);
3680 /// void j() noexcept(false);
3682 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
3683 /// match the declarations of g, and h, but not f, i or j.
3684 AST_POLYMORPHIC_MATCHER(isNoThrow,
3685 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3686 FunctionProtoType)) {
3687 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
3689 // If the function does not have a prototype, then it is assumed to be a
3690 // throwing function (as it would if the function did not have any exception
3695 // Assume the best for any unresolved exception specification.
3696 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3699 return FnTy->isNothrow(Finder->getASTContext());
3702 /// \brief Matches constexpr variable and function declarations.
3706 /// constexpr int foo = 42;
3707 /// constexpr int bar();
3709 /// varDecl(isConstexpr())
3710 /// matches the declaration of foo.
3711 /// functionDecl(isConstexpr())
3712 /// matches the declaration of bar.
3713 AST_POLYMORPHIC_MATCHER(isConstexpr,
3714 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3716 return Node.isConstexpr();
3719 /// \brief Matches the condition expression of an if statement, for loop,
3720 /// switch statement or conditional operator.
3722 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3726 AST_POLYMORPHIC_MATCHER_P(
3728 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3729 SwitchStmt, AbstractConditionalOperator),
3730 internal::Matcher<Expr>, InnerMatcher) {
3731 const Expr *const Condition = Node.getCond();
3732 return (Condition != nullptr &&
3733 InnerMatcher.matches(*Condition, Finder, Builder));
3736 /// \brief Matches the then-statement of an if statement.
3738 /// Examples matches the if statement
3739 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3741 /// if (false) true; else false;
3743 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3744 const Stmt *const Then = Node.getThen();
3745 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3748 /// \brief Matches the else-statement of an if statement.
3750 /// Examples matches the if statement
3751 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3753 /// if (false) false; else true;
3755 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3756 const Stmt *const Else = Node.getElse();
3757 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3760 /// \brief Matches if a node equals a previously bound node.
3762 /// Matches a node if it equals the node previously bound to \p ID.
3766 /// class X { int a; int b; };
3769 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3770 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3771 /// matches the class \c X, as \c a and \c b have the same type.
3773 /// Note that when multiple matches are involved via \c forEach* matchers,
3774 /// \c equalsBoundNodes acts as a filter.
3777 /// forEachDescendant(varDecl().bind("d")),
3778 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3779 /// will trigger a match for each combination of variable declaration
3780 /// and reference to that variable declaration within a compound statement.
3781 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3782 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3785 // FIXME: Figure out whether it makes sense to allow this
3786 // on any other node types.
3787 // For *Loc it probably does not make sense, as those seem
3788 // unique. For NestedNameSepcifier it might make sense, as
3789 // those also have pointer identity, but I'm not sure whether
3790 // they're ever reused.
3791 internal::NotEqualsBoundNodePredicate Predicate;
3793 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3794 return Builder->removeBindings(Predicate);
3797 /// \brief Matches the condition variable statement in an if statement.
3801 /// if (A* a = GetAPointer()) {}
3803 /// hasConditionVariableStatement(...)
3804 /// matches 'A* a = GetAPointer()'.
3805 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3806 internal::Matcher<DeclStmt>, InnerMatcher) {
3807 const DeclStmt* const DeclarationStatement =
3808 Node.getConditionVariableDeclStmt();
3809 return DeclarationStatement != nullptr &&
3810 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3813 /// \brief Matches the index expression of an array subscript expression.
3818 /// void f() { i[1] = 42; }
3820 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3821 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3822 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3823 internal::Matcher<Expr>, InnerMatcher) {
3824 if (const Expr* Expression = Node.getIdx())
3825 return InnerMatcher.matches(*Expression, Finder, Builder);
3829 /// \brief Matches the base expression of an array subscript expression.
3834 /// void f() { i[1] = 42; }
3836 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3837 /// hasSourceExpression(declRefExpr()))))
3838 /// matches \c i[1] with the \c declRefExpr() matching \c i
3839 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3840 internal::Matcher<Expr>, InnerMatcher) {
3841 if (const Expr* Expression = Node.getBase())
3842 return InnerMatcher.matches(*Expression, Finder, Builder);
3846 /// \brief Matches a 'for', 'while', 'do while' statement or a function
3847 /// definition that has a given body.
3853 /// hasBody(compoundStmt())
3854 /// matches 'for (;;) {}'
3855 /// with compoundStmt()
3857 AST_POLYMORPHIC_MATCHER_P(hasBody,
3858 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3862 internal::Matcher<Stmt>, InnerMatcher) {
3863 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
3864 return (Statement != nullptr &&
3865 InnerMatcher.matches(*Statement, Finder, Builder));
3868 /// \brief Matches compound statements where at least one substatement matches
3869 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
3875 /// hasAnySubstatement(compoundStmt())
3876 /// matches '{ {}; 1+2; }'
3877 /// with compoundStmt()
3879 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
3880 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
3882 internal::Matcher<Stmt>, InnerMatcher) {
3883 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
3884 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
3885 CS->body_end(), Finder, Builder);
3888 /// \brief Checks that a compound statement contains a specific number of
3889 /// child statements.
3895 /// compoundStmt(statementCountIs(0)))
3897 /// but does not match the outer compound statement.
3898 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3899 return Node.size() == N;
3902 /// \brief Matches literals that are equal to the given value of type ValueT.
3906 /// f('\0', false, 3.14, 42);
3908 /// characterLiteral(equals(0))
3910 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
3912 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
3914 /// integerLiteral(equals(42))
3917 /// Note that you cannot directly match a negative numeric literal because the
3918 /// minus sign is not part of the literal: It is a unary operator whose operand
3919 /// is the positive numeric literal. Instead, you must use a unaryOperator()
3920 /// matcher to match the minus sign:
3922 /// unaryOperator(hasOperatorName("-"),
3923 /// hasUnaryOperand(integerLiteral(equals(13))))
3925 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
3926 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3927 template <typename ValueT>
3928 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3929 equals(const ValueT &Value) {
3930 return internal::PolymorphicMatcherWithParam1<
3931 internal::ValueEqualsMatcher,
3935 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
3936 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
3940 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
3944 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
3945 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
3948 unsigned, Value, 1) {
3949 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
3953 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
3954 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
3959 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
3963 /// \brief Matches the operator Name of operator expressions (binary or
3966 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3970 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3971 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3973 std::string, Name) {
3974 return Name == Node.getOpcodeStr(Node.getOpcode());
3977 /// \brief Matches the left hand side of binary operator expressions.
3979 /// Example matches a (matcher = binaryOperator(hasLHS()))
3983 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3984 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3985 ArraySubscriptExpr),
3986 internal::Matcher<Expr>, InnerMatcher) {
3987 const Expr *LeftHandSide = Node.getLHS();
3988 return (LeftHandSide != nullptr &&
3989 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3992 /// \brief Matches the right hand side of binary operator expressions.
3994 /// Example matches b (matcher = binaryOperator(hasRHS()))
3998 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3999 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4000 ArraySubscriptExpr),
4001 internal::Matcher<Expr>, InnerMatcher) {
4002 const Expr *RightHandSide = Node.getRHS();
4003 return (RightHandSide != nullptr &&
4004 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4007 /// \brief Matches if either the left hand side or the right hand side of a
4008 /// binary operator matches.
4009 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4010 const internal::Matcher<Expr> &InnerMatcher) {
4011 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4014 /// \brief Matches if the operand of a unary operator matches.
4016 /// Example matches true (matcher = hasUnaryOperand(
4017 /// cxxBoolLiteral(equals(true))))
4021 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4022 internal::Matcher<Expr>, InnerMatcher) {
4023 const Expr * const Operand = Node.getSubExpr();
4024 return (Operand != nullptr &&
4025 InnerMatcher.matches(*Operand, Finder, Builder));
4028 /// \brief Matches if the cast's source expression
4029 /// or opaque value's source expression matches the given matcher.
4031 /// Example 1: matches "a string"
4032 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4034 /// class URL { URL(string); };
4035 /// URL url = "a string";
4038 /// Example 2: matches 'b' (matcher =
4039 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4043 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4044 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4046 internal::Matcher<Expr>, InnerMatcher) {
4047 const Expr *const SubExpression =
4048 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4049 return (SubExpression != nullptr &&
4050 InnerMatcher.matches(*SubExpression, Finder, Builder));
4053 /// \brief Matches casts that has a given cast kind.
4055 /// Example: matches the implicit cast around \c 0
4056 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4060 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4061 return Node.getCastKind() == Kind;
4064 /// \brief Matches casts whose destination type matches a given matcher.
4066 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4067 /// actual casts "explicit" casts.)
4068 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4069 internal::Matcher<QualType>, InnerMatcher) {
4070 const QualType NodeType = Node.getTypeAsWritten();
4071 return InnerMatcher.matches(NodeType, Finder, Builder);
4074 /// \brief Matches implicit casts whose destination type matches a given
4077 /// FIXME: Unit test this matcher
4078 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4079 internal::Matcher<QualType>, InnerMatcher) {
4080 return InnerMatcher.matches(Node.getType(), Finder, Builder);
4083 /// \brief Matches RecordDecl object that are spelled with "struct."
4085 /// Example matches S, but not C or U.
4091 AST_MATCHER(RecordDecl, isStruct) {
4092 return Node.isStruct();
4095 /// \brief Matches RecordDecl object that are spelled with "union."
4097 /// Example matches U, but not C or S.
4103 AST_MATCHER(RecordDecl, isUnion) {
4104 return Node.isUnion();
4107 /// \brief Matches RecordDecl object that are spelled with "class."
4109 /// Example matches C, but not S or U.
4115 AST_MATCHER(RecordDecl, isClass) {
4116 return Node.isClass();
4119 /// \brief Matches the true branch expression of a conditional operator.
4121 /// Example 1 (conditional ternary operator): matches a
4123 /// condition ? a : b
4126 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4130 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4131 internal::Matcher<Expr>, InnerMatcher) {
4132 const Expr *Expression = Node.getTrueExpr();
4133 return (Expression != nullptr &&
4134 InnerMatcher.matches(*Expression, Finder, Builder));
4137 /// \brief Matches the false branch expression of a conditional operator
4138 /// (binary or ternary).
4140 /// Example matches b
4142 /// condition ? a : b
4145 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4146 internal::Matcher<Expr>, InnerMatcher) {
4147 const Expr *Expression = Node.getFalseExpr();
4148 return (Expression != nullptr &&
4149 InnerMatcher.matches(*Expression, Finder, Builder));
4152 /// \brief Matches if a declaration has a body attached.
4154 /// Example matches A, va, fa
4157 /// class B; // Doesn't match, as it has no body.
4159 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4161 /// void fb(); // Doesn't match, as it has no body.
4163 /// - (void)ma; // Doesn't match, interface is declaration.
4165 /// @implementation X
4170 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4171 /// Matcher<ObjCMethodDecl>
4172 AST_POLYMORPHIC_MATCHER(isDefinition,
4173 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4176 return Node.isThisDeclarationADefinition();
4179 /// \brief Matches if a function declaration is variadic.
4181 /// Example matches f, but not g or h. The function i will not match, even when
4182 /// compiled in C mode.
4186 /// template <typename... Ts> void h(Ts...);
4189 AST_MATCHER(FunctionDecl, isVariadic) {
4190 return Node.isVariadic();
4193 /// \brief Matches the class declaration that the given method declaration
4196 /// FIXME: Generalize this for other kinds of declarations.
4197 /// FIXME: What other kind of declarations would we need to generalize
4200 /// Example matches A() in the last line
4201 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4202 /// ofClass(hasName("A"))))))
4210 AST_MATCHER_P(CXXMethodDecl, ofClass,
4211 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4212 const CXXRecordDecl *Parent = Node.getParent();
4213 return (Parent != nullptr &&
4214 InnerMatcher.matches(*Parent, Finder, Builder));
4217 /// \brief Matches each method overriden by the given method. This matcher may
4218 /// produce multiple matches.
4222 /// class A { virtual void f(); };
4223 /// class B : public A { void f(); };
4224 /// class C : public B { void f(); };
4226 /// cxxMethodDecl(ofClass(hasName("C")),
4227 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4228 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4229 /// that B::f is not overridden by C::f).
4231 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4233 /// class A1 { virtual void f(); };
4234 /// class A2 { virtual void f(); };
4235 /// class C : public A1, public A2 { void f(); };
4237 /// cxxMethodDecl(ofClass(hasName("C")),
4238 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4239 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4240 /// once with "b" binding "A2::f" and "d" binding "C::f".
4241 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4242 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4243 BoundNodesTreeBuilder Result;
4244 bool Matched = false;
4245 for (const auto *Overridden : Node.overridden_methods()) {
4246 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4247 const bool OverriddenMatched =
4248 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4249 if (OverriddenMatched) {
4251 Result.addMatch(OverriddenBuilder);
4254 *Builder = std::move(Result);
4258 /// \brief Matches if the given method declaration is virtual.
4264 /// virtual void x();
4268 AST_MATCHER(CXXMethodDecl, isVirtual) {
4269 return Node.isVirtual();
4272 /// \brief Matches if the given method declaration has an explicit "virtual".
4278 /// virtual void x();
4280 /// class B : public A {
4285 /// matches A::x but not B::x
4286 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4287 return Node.isVirtualAsWritten();
4290 /// \brief Matches if the given method or class declaration is final.
4294 /// class A final {};
4297 /// virtual void f();
4304 /// matches A and C::f, but not B, C, or B::f
4305 AST_POLYMORPHIC_MATCHER(isFinal,
4306 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4308 return Node.template hasAttr<FinalAttr>();
4311 /// \brief Matches if the given method declaration is pure.
4317 /// virtual void x() = 0;
4321 AST_MATCHER(CXXMethodDecl, isPure) {
4322 return Node.isPure();
4325 /// \brief Matches if the given method declaration is const.
4330 /// void foo() const;
4335 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4336 AST_MATCHER(CXXMethodDecl, isConst) {
4337 return Node.isConst();
4340 /// \brief Matches if the given method declaration declares a copy assignment
4346 /// A &operator=(const A &);
4347 /// A &operator=(A &&);
4351 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4353 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4354 return Node.isCopyAssignmentOperator();
4357 /// \brief Matches if the given method declaration declares a move assignment
4363 /// A &operator=(const A &);
4364 /// A &operator=(A &&);
4368 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4370 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4371 return Node.isMoveAssignmentOperator();
4374 /// \brief Matches if the given method declaration overrides another method.
4380 /// virtual void x();
4382 /// class B : public A {
4384 /// virtual void x();
4388 AST_MATCHER(CXXMethodDecl, isOverride) {
4389 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4392 /// \brief Matches method declarations that are user-provided.
4398 /// S(const S &) = default; // #2
4399 /// S(S &&) = delete; // #3
4402 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4403 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4404 return Node.isUserProvided();
4407 /// \brief Matches member expressions that are called with '->' as opposed
4410 /// Member calls on the implicit this pointer match as called with '->'.
4415 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4420 /// memberExpr(isArrow())
4421 /// matches this->x, x, y.x, a, this->b
4422 AST_MATCHER(MemberExpr, isArrow) {
4423 return Node.isArrow();
4426 /// \brief Matches QualType nodes that are of integer type.
4434 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4435 /// matches "a(int)", "b(long)", but not "c(double)".
4436 AST_MATCHER(QualType, isInteger) {
4437 return Node->isIntegerType();
4440 /// \brief Matches QualType nodes that are of unsigned integer type.
4445 /// void b(unsigned long);
4448 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4449 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4450 AST_MATCHER(QualType, isUnsignedInteger) {
4451 return Node->isUnsignedIntegerType();
4454 /// \brief Matches QualType nodes that are of signed integer type.
4459 /// void b(unsigned long);
4462 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4463 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4464 AST_MATCHER(QualType, isSignedInteger) {
4465 return Node->isSignedIntegerType();
4468 /// \brief Matches QualType nodes that are of character type.
4473 /// void b(wchar_t);
4476 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4477 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4478 AST_MATCHER(QualType, isAnyCharacter) {
4479 return Node->isAnyCharacterType();
4482 /// \brief Matches QualType nodes that are of any pointer type; this includes
4483 /// the Objective-C object pointer type, which is different despite being
4484 /// syntactically similar.
4488 /// int *i = nullptr;
4496 /// varDecl(hasType(isAnyPointer()))
4497 /// matches "int *i" and "Foo *f", but not "int j".
4498 AST_MATCHER(QualType, isAnyPointer) {
4499 return Node->isAnyPointerType();
4502 /// \brief Matches QualType nodes that are const-qualified, i.e., that
4503 /// include "top-level" const.
4508 /// void b(int const);
4509 /// void c(const int);
4510 /// void d(const int*);
4511 /// void e(int const) {};
4513 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4514 /// matches "void b(int const)", "void c(const int)" and
4515 /// "void e(int const) {}". It does not match d as there
4516 /// is no top-level const on the parameter type "const int *".
4517 AST_MATCHER(QualType, isConstQualified) {
4518 return Node.isConstQualified();
4521 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
4522 /// include "top-level" volatile.
4527 /// void b(int volatile);
4528 /// void c(volatile int);
4529 /// void d(volatile int*);
4530 /// void e(int volatile) {};
4532 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4533 /// matches "void b(int volatile)", "void c(volatile int)" and
4534 /// "void e(int volatile) {}". It does not match d as there
4535 /// is no top-level volatile on the parameter type "volatile int *".
4536 AST_MATCHER(QualType, isVolatileQualified) {
4537 return Node.isVolatileQualified();
4540 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
4541 /// the node, not hidden within a typedef.
4545 /// typedef const int const_int;
4548 /// int *volatile k;
4551 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4552 /// \c i is const-qualified but the qualifier is not local.
4553 AST_MATCHER(QualType, hasLocalQualifiers) {
4554 return Node.hasLocalQualifiers();
4557 /// \brief Matches a member expression where the member is matched by a
4562 /// struct { int first, second; } first, second;
4563 /// int i(second.first);
4564 /// int j(first.second);
4566 /// memberExpr(member(hasName("first")))
4567 /// matches second.first
4568 /// but not first.second (because the member name there is "second").
4569 AST_MATCHER_P(MemberExpr, member,
4570 internal::Matcher<ValueDecl>, InnerMatcher) {
4571 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4574 /// \brief Matches a member expression where the object expression is
4575 /// matched by a given matcher.
4579 /// struct X { int m; };
4580 /// void f(X x) { x.m; m; }
4582 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4583 /// matches "x.m" and "m"
4584 /// with hasObjectExpression(...)
4585 /// matching "x" and the implicit object expression of "m" which has type X*.
4586 AST_MATCHER_P(MemberExpr, hasObjectExpression,
4587 internal::Matcher<Expr>, InnerMatcher) {
4588 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4591 /// \brief Matches any using shadow declaration.
4595 /// namespace X { void b(); }
4598 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
4599 /// matches \code using X::b \endcode
4600 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
4601 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4602 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
4603 Node.shadow_end(), Finder, Builder);
4606 /// \brief Matches a using shadow declaration where the target declaration is
4607 /// matched by the given matcher.
4611 /// namespace X { int a; void b(); }
4615 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
4616 /// matches \code using X::b \endcode
4617 /// but not \code using X::a \endcode
4618 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
4619 internal::Matcher<NamedDecl>, InnerMatcher) {
4620 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
4623 /// \brief Matches template instantiations of function, class, or static
4624 /// member variable template instantiations.
4628 /// template <typename T> class X {}; class A {}; X<A> x;
4632 /// template <typename T> class X {}; class A {}; template class X<A>;
4634 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4635 /// matches the template instantiation of X<A>.
4639 /// template <typename T> class X {}; class A {};
4640 /// template <> class X<A> {}; X<A> x;
4642 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4643 /// does not match, as X<A> is an explicit template specialization.
4645 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4646 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4647 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4649 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4650 Node.getTemplateSpecializationKind() ==
4651 TSK_ExplicitInstantiationDefinition);
4654 /// \brief Matches declarations that are template instantiations or are inside
4655 /// template instantiations.
4659 /// template<typename T> void A(T t) { T i; }
4663 /// functionDecl(isInstantiated())
4664 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
4665 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4666 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4667 functionDecl(isTemplateInstantiation())));
4668 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4671 /// \brief Matches statements inside of a template instantiation.
4676 /// template<typename T> void A(T t) { T i; j += 42;}
4680 /// declStmt(isInTemplateInstantiation())
4681 /// matches 'int i;' and 'unsigned i'.
4682 /// unless(stmt(isInTemplateInstantiation()))
4683 /// will NOT match j += 42; as it's shared between the template definition and
4685 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4687 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4688 functionDecl(isTemplateInstantiation())))));
4691 /// \brief Matches explicit template specializations of function, class, or
4692 /// static member variable template instantiations.
4696 /// template<typename T> void A(T t) { }
4697 /// template<> void A(int N) { }
4699 /// functionDecl(isExplicitTemplateSpecialization())
4700 /// matches the specialization A<int>().
4702 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4703 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4704 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4706 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4709 /// \brief Matches \c TypeLocs for which the given inner
4710 /// QualType-matcher matches.
4711 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4712 internal::Matcher<QualType>, InnerMatcher, 0) {
4713 return internal::BindableMatcher<TypeLoc>(
4714 new internal::TypeLocTypeMatcher(InnerMatcher));
4717 /// \brief Matches type \c bool.
4721 /// struct S { bool func(); };
4723 /// functionDecl(returns(booleanType()))
4724 /// matches "bool func();"
4725 AST_MATCHER(Type, booleanType) {
4726 return Node.isBooleanType();
4729 /// \brief Matches type \c void.
4733 /// struct S { void func(); };
4735 /// functionDecl(returns(voidType()))
4736 /// matches "void func();"
4737 AST_MATCHER(Type, voidType) {
4738 return Node.isVoidType();
4741 template <typename NodeType>
4742 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
4744 /// \brief Matches builtin Types.
4755 /// matches "int b", "float c" and "bool d"
4756 extern const AstTypeMatcher<BuiltinType> builtinType;
4758 /// \brief Matches all kinds of arrays.
4762 /// int a[] = { 2, 3 };
4764 /// void f() { int c[a[0]]; }
4767 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4768 extern const AstTypeMatcher<ArrayType> arrayType;
4770 /// \brief Matches C99 complex types.
4774 /// _Complex float f;
4777 /// matches "_Complex float f"
4778 extern const AstTypeMatcher<ComplexType> complexType;
4780 /// \brief Matches any real floating-point type (float, double, long double).
4787 /// realFloatingPointType()
4788 /// matches "float f" but not "int i"
4789 AST_MATCHER(Type, realFloatingPointType) {
4790 return Node.isRealFloatingType();
4793 /// \brief Matches arrays and C99 complex types that have a specific element
4802 /// arrayType(hasElementType(builtinType()))
4803 /// matches "int b[7]"
4805 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
4806 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
4807 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
4810 /// \brief Matches C arrays with a specified constant size.
4816 /// int b[] = { 2, 3 };
4820 /// constantArrayType()
4821 /// matches "int a[2]"
4822 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
4824 /// \brief Matches nodes that have the specified size.
4830 /// int c[41], d[43];
4831 /// char *s = "abcd";
4832 /// wchar_t *ws = L"abcd";
4835 /// constantArrayType(hasSize(42))
4836 /// matches "int a[42]" and "int b[2 * 21]"
4837 /// stringLiteral(hasSize(4))
4838 /// matches "abcd", L"abcd"
4839 AST_POLYMORPHIC_MATCHER_P(hasSize,
4840 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
4843 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
4846 /// \brief Matches C++ arrays whose size is a value-dependent expression.
4850 /// template<typename T, int Size>
4855 /// dependentSizedArrayType
4856 /// matches "T data[Size]"
4857 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
4859 /// \brief Matches C arrays with unspecified size.
4863 /// int a[] = { 2, 3 };
4865 /// void f(int c[]) { int d[a[0]]; };
4867 /// incompleteArrayType()
4868 /// matches "int a[]" and "int c[]"
4869 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
4871 /// \brief Matches C arrays with a specified size that is not an
4872 /// integer-constant-expression.
4877 /// int a[] = { 2, 3 }
4882 /// variableArrayType()
4883 /// matches "int c[a[0]]"
4884 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
4886 /// \brief Matches \c VariableArrayType nodes that have a specific size
4895 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4896 /// varDecl(hasName("b")))))))
4897 /// matches "int a[b]"
4898 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
4899 internal::Matcher<Expr>, InnerMatcher) {
4900 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
4903 /// \brief Matches atomic types.
4910 /// matches "_Atomic(int) i"
4911 extern const AstTypeMatcher<AtomicType> atomicType;
4913 /// \brief Matches atomic types with a specific value type.
4918 /// _Atomic(float) f;
4920 /// atomicType(hasValueType(isInteger()))
4921 /// matches "_Atomic(int) i"
4923 /// Usable as: Matcher<AtomicType>
4924 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
4925 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
4927 /// \brief Matches types nodes representing C++11 auto types.
4932 /// int v[] = { 2, 3 }
4933 /// for (auto i : v) { }
4936 /// matches "auto n" and "auto i"
4937 extern const AstTypeMatcher<AutoType> autoType;
4939 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
4941 /// Note: There is no \c TypeLoc for the deduced type and thus no
4942 /// \c getDeducedLoc() matcher.
4949 /// autoType(hasDeducedType(isInteger()))
4950 /// matches "auto a"
4952 /// Usable as: Matcher<AutoType>
4953 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
4954 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
4956 /// \brief Matches \c FunctionType nodes.
4964 /// matches "int (*f)(int)" and the type of "g".
4965 extern const AstTypeMatcher<FunctionType> functionType;
4967 /// \brief Matches \c FunctionProtoType nodes.
4974 /// functionProtoType()
4975 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
4976 /// In C mode, "g" is not matched because it does not contain a prototype.
4977 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
4979 /// \brief Matches \c ParenType nodes.
4983 /// int (*ptr_to_array)[4];
4984 /// int *array_of_ptrs[4];
4987 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4988 /// \c array_of_ptrs.
4989 extern const AstTypeMatcher<ParenType> parenType;
4991 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4995 /// int (*ptr_to_array)[4];
4996 /// int (*ptr_to_func)(int);
4999 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5000 /// \c ptr_to_func but not \c ptr_to_array.
5002 /// Usable as: Matcher<ParenType>
5003 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5004 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5006 /// \brief Matches block pointer types, i.e. types syntactically represented as
5007 /// "void (^)(int)".
5009 /// The \c pointee is always required to be a \c FunctionType.
5010 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5012 /// \brief Matches member pointer types.
5015 /// struct A { int i; }
5016 /// A::* ptr = A::i;
5018 /// memberPointerType()
5019 /// matches "A::* ptr"
5020 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5022 /// \brief Matches pointer types, but does not match Objective-C object pointer
5036 /// matches "int *a", but does not match "Foo *f".
5037 extern const AstTypeMatcher<PointerType> pointerType;
5039 /// \brief Matches an Objective-C object pointer type, which is different from
5040 /// a pointer type, despite being syntactically similar.
5051 /// matches "Foo *f", but does not match "int *a".
5052 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5054 /// \brief Matches both lvalue and rvalue reference types.
5067 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5068 extern const AstTypeMatcher<ReferenceType> referenceType;
5070 /// \brief Matches lvalue reference types.
5083 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5084 /// matched since the type is deduced as int& by reference collapsing rules.
5085 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5087 /// \brief Matches rvalue reference types.
5100 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5101 /// matched as it is deduced to int& by reference collapsing rules.
5102 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5104 /// \brief Narrows PointerType (and similar) matchers to those where the
5105 /// \c pointee matches a given matcher.
5113 /// pointerType(pointee(isConstQualified(), isInteger()))
5114 /// matches "int const *b"
5116 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5117 /// Matcher<PointerType>, Matcher<ReferenceType>
5118 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5119 pointee, getPointee,
5120 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5121 PointerType, ReferenceType));
5123 /// \brief Matches typedef types.
5130 /// matches "typedef int X"
5131 extern const AstTypeMatcher<TypedefType> typedefType;
5133 /// \brief Matches enum types.
5137 /// enum C { Green };
5138 /// enum class S { Red };
5144 /// \c enumType() matches the type of the variable declarations of both \c c and
5146 extern const AstTypeMatcher<EnumType> enumType;
5148 /// \brief Matches template specialization types.
5152 /// template <typename T>
5155 /// template class C<int>; // A
5156 /// C<char> var; // B
5159 /// \c templateSpecializationType() matches the type of the explicit
5160 /// instantiation in \c A and the type of the variable declaration in \c B.
5161 extern const AstTypeMatcher<TemplateSpecializationType>
5162 templateSpecializationType;
5164 /// \brief Matches types nodes representing unary type transformations.
5168 /// typedef __underlying_type(T) type;
5170 /// unaryTransformType()
5171 /// matches "__underlying_type(T)"
5172 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5174 /// \brief Matches record types (e.g. structs, classes).
5185 /// \c recordType() matches the type of the variable declarations of both \c c
5187 extern const AstTypeMatcher<RecordType> recordType;
5189 /// \brief Matches tag types (record and enum types).
5200 /// \c tagType() matches the type of the variable declarations of both \c e
5202 extern const AstTypeMatcher<TagType> tagType;
5204 /// \brief Matches types specified with an elaborated type keyword or with a
5220 /// \c elaboratedType() matches the type of the variable declarations of both
5222 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5224 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5225 /// matches \c InnerMatcher if the qualifier exists.
5237 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5238 /// matches the type of the variable declaration of \c d.
5239 AST_MATCHER_P(ElaboratedType, hasQualifier,
5240 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5241 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5242 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5247 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5259 /// \c elaboratedType(namesType(recordType(
5260 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5261 /// declaration of \c d.
5262 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5264 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5267 /// \brief Matches types that represent the result of substituting a type for a
5268 /// template type parameter.
5272 /// template <typename T>
5278 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5279 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5280 substTemplateTypeParmType;
5282 /// \brief Matches template type parameter substitutions that have a replacement
5283 /// type that matches the provided matcher.
5287 /// template <typename T>
5290 /// double j = F(i);
5293 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5294 AST_TYPE_TRAVERSE_MATCHER(
5295 hasReplacementType, getReplacementType,
5296 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5298 /// \brief Matches template type parameter types.
5300 /// Example matches T, but not int.
5301 /// (matcher = templateTypeParmType())
5303 /// template <typename T> void f(int i);
5305 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5307 /// \brief Matches injected class name types.
5309 /// Example matches S s, but not S<T> s.
5310 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5312 /// template <typename T> struct S {
5317 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5319 /// \brief Matches decayed type
5320 /// Example matches i[] in declaration of f.
5321 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5322 /// Example matches i[1].
5323 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5325 /// void f(int i[]) {
5329 extern const AstTypeMatcher<DecayedType> decayedType;
5331 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
5332 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5334 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5337 /// \brief Matches declarations whose declaration context, interpreted as a
5338 /// Decl, matches \c InnerMatcher.
5349 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5350 /// declaration of \c class \c D.
5351 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5352 const DeclContext *DC = Node.getDeclContext();
5353 if (!DC) return false;
5354 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5357 /// \brief Matches nested name specifiers.
5362 /// struct A { static void f(); };
5364 /// void g() { A::f(); }
5368 /// nestedNameSpecifier()
5369 /// matches "ns::" and both "A::"
5370 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
5371 nestedNameSpecifier;
5373 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5374 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
5375 nestedNameSpecifierLoc;
5377 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
5378 /// NestedNameSpecifier-matcher matches.
5379 AST_MATCHER_FUNCTION_P_OVERLOAD(
5380 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5381 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5382 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5383 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5387 /// \brief Matches nested name specifiers that specify a type matching the
5388 /// given \c QualType matcher without qualifiers.
5392 /// struct A { struct B { struct C {}; }; };
5395 /// nestedNameSpecifier(specifiesType(
5396 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5399 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5400 internal::Matcher<QualType>, InnerMatcher) {
5401 if (!Node.getAsType())
5403 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5406 /// \brief Matches nested name specifier locs that specify a type matching the
5407 /// given \c TypeLoc.
5411 /// struct A { struct B { struct C {}; }; };
5414 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5415 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5417 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5418 internal::Matcher<TypeLoc>, InnerMatcher) {
5419 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5422 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
5426 /// struct A { struct B { struct C {}; }; };
5429 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5431 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5432 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5434 const NestedNameSpecifier *NextNode = Node.getPrefix();
5437 return InnerMatcher.matches(*NextNode, Finder, Builder);
5440 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
5444 /// struct A { struct B { struct C {}; }; };
5447 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5449 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5450 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5452 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5455 return InnerMatcher.matches(NextNode, Finder, Builder);
5458 /// \brief Matches nested name specifiers that specify a namespace matching the
5459 /// given namespace matcher.
5463 /// namespace ns { struct A {}; }
5466 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5468 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5469 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5470 if (!Node.getAsNamespace())
5472 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5475 /// \brief Overloads for the \c equalsNode matcher.
5476 /// FIXME: Implement for other node types.
5479 /// \brief Matches if a node equals another node.
5481 /// \c Decl has pointer identity in the AST.
5482 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5483 return &Node == Other;
5485 /// \brief Matches if a node equals another node.
5487 /// \c Stmt has pointer identity in the AST.
5488 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5489 return &Node == Other;
5491 /// \brief Matches if a node equals another node.
5493 /// \c Type has pointer identity in the AST.
5494 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5495 return &Node == Other;
5500 /// \brief Matches each case or default statement belonging to the given switch
5501 /// statement. This matcher may produce multiple matches.
5505 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5507 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5508 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5509 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5510 /// "switch (1)", "switch (2)" and "switch (2)".
5511 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5513 BoundNodesTreeBuilder Result;
5514 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5515 // iteration order. We should use the more general iterating matchers once
5516 // they are capable of expressing this matcher (for example, it should ignore
5517 // case statements belonging to nested switch statements).
5518 bool Matched = false;
5519 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5520 SC = SC->getNextSwitchCase()) {
5521 BoundNodesTreeBuilder CaseBuilder(*Builder);
5522 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5525 Result.addMatch(CaseBuilder);
5528 *Builder = std::move(Result);
5532 /// \brief Matches each constructor initializer in a constructor definition.
5536 /// class A { A() : i(42), j(42) {} int i; int j; };
5538 /// cxxConstructorDecl(forEachConstructorInitializer(
5539 /// forField(decl().bind("x"))
5541 /// will trigger two matches, binding for 'i' and 'j' respectively.
5542 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5543 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5544 BoundNodesTreeBuilder Result;
5545 bool Matched = false;
5546 for (const auto *I : Node.inits()) {
5547 BoundNodesTreeBuilder InitBuilder(*Builder);
5548 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5550 Result.addMatch(InitBuilder);
5553 *Builder = std::move(Result);
5557 /// \brief Matches constructor declarations that are copy constructors.
5563 /// S(const S &); // #2
5567 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
5568 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
5569 return Node.isCopyConstructor();
5572 /// \brief Matches constructor declarations that are move constructors.
5578 /// S(const S &); // #2
5582 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
5583 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
5584 return Node.isMoveConstructor();
5587 /// \brief Matches constructor declarations that are default constructors.
5593 /// S(const S &); // #2
5597 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
5598 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
5599 return Node.isDefaultConstructor();
5602 /// \brief Matches constructors that delegate to another constructor.
5609 /// S(S &&) : S() {} // #3
5611 /// S::S() : S(0) {} // #4
5613 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
5615 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
5616 return Node.isDelegatingConstructor();
5619 /// \brief Matches constructor and conversion declarations that are marked with
5620 /// the explicit keyword.
5626 /// explicit S(double); // #2
5627 /// operator int(); // #3
5628 /// explicit operator bool(); // #4
5631 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
5632 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
5633 AST_POLYMORPHIC_MATCHER(isExplicit,
5634 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
5635 CXXConversionDecl)) {
5636 return Node.isExplicit();
5639 /// \brief Matches function and namespace declarations that are marked with
5640 /// the inline keyword.
5644 /// inline void f();
5647 /// inline namespace m {}
5650 /// functionDecl(isInline()) will match ::f().
5651 /// namespaceDecl(isInline()) will match n::m.
5652 AST_POLYMORPHIC_MATCHER(isInline,
5653 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
5655 // This is required because the spelling of the function used to determine
5656 // whether inline is specified or not differs between the polymorphic types.
5657 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
5658 return FD->isInlineSpecified();
5659 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
5660 return NSD->isInline();
5661 llvm_unreachable("Not a valid polymorphic type");
5664 /// \brief Matches anonymous namespace declarations.
5669 /// namespace {} // #1
5672 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
5673 AST_MATCHER(NamespaceDecl, isAnonymous) {
5674 return Node.isAnonymousNamespace();
5677 /// \brief If the given case statement does not use the GNU case range
5678 /// extension, matches the constant given in the statement.
5682 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
5684 /// caseStmt(hasCaseConstant(integerLiteral()))
5685 /// matches "case 1:"
5686 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
5691 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
5694 /// \brief Matches declaration that has a given attribute.
5698 /// __attribute__((device)) void f() { ... }
5700 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
5701 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
5702 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
5703 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
5704 for (const auto *Attr : Node.attrs()) {
5705 if (Attr->getKind() == AttrKind)
5711 /// \brief Matches the return value expression of a return statement
5717 /// hasReturnValue(binaryOperator())
5718 /// matches 'return a + b'
5719 /// with binaryOperator()
5720 /// matching 'a + b'
5721 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5723 if (const auto *RetValue = Node.getRetValue())
5724 return InnerMatcher.matches(*RetValue, Finder, Builder);
5728 /// \brief Matches CUDA kernel call expression.
5730 /// Example matches,
5732 /// kernel<<<i,j>>>();
5734 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
5737 /// \brief Matches expressions that resolve to a null pointer constant, such as
5738 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5742 /// void *v1 = NULL;
5743 /// void *v2 = nullptr;
5744 /// void *v3 = __null; // GNU extension
5745 /// char *cp = (char *)0;
5749 /// expr(nullPointerConstant())
5750 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5751 /// initializer for i.
5752 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5754 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5755 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5758 /// \brief Matches declaration of the function the statement belongs to
5762 /// F& operator=(const F& o) {
5763 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
5767 /// returnStmt(forFunction(hasName("operator=")))
5768 /// matches 'return *this'
5769 /// but does match 'return > 0'
5770 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
5772 const auto &Parents = Finder->getASTContext().getParents(Node);
5774 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
5776 while(!Stack.empty()) {
5777 const auto &CurNode = Stack.back();
5779 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
5780 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
5783 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
5784 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
5789 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
5790 Stack.push_back(Parent);
5796 /// \brief Matches a declaration that has external formal linkage.
5798 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
5807 /// Example matches f() because it has external formal linkage despite being
5808 /// unique to the translation unit as though it has internal likage
5809 /// (matcher = functionDecl(hasExternalFormalLinkage()))
5816 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
5817 return Node.hasExternalFormalLinkage();
5820 /// \brief Matches a declaration that has default arguments.
5822 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
5824 /// void x(int val) {}
5825 /// void y(int val = 0) {}
5827 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
5828 return Node.hasDefaultArg();
5831 /// \brief Matches array new expressions.
5835 /// MyClass *p1 = new MyClass[10];
5837 /// cxxNewExpr(isArray())
5838 /// matches the expression 'new MyClass[10]'.
5839 AST_MATCHER(CXXNewExpr, isArray) {
5840 return Node.isArray();
5843 /// \brief Matches array new expressions with a given array size.
5847 /// MyClass *p1 = new MyClass[10];
5849 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
5850 /// matches the expression 'new MyClass[10]'.
5851 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
5852 return Node.isArray() &&
5853 InnerMatcher.matches(*Node.getArraySize(), Finder, Builder);
5856 /// \brief Matches a class declaration that is defined.
5858 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
5863 AST_MATCHER(CXXRecordDecl, hasDefinition) {
5864 return Node.hasDefinition();
5867 } // namespace ast_matchers
5868 } // namespace clang
5870 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H