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"), hasChild(id("child", recordDecl())))
29 // When the match is found via the MatchFinder, a user provided callback will
30 // be called with a BoundNodes instance that contains a mapping from the
31 // strings that we provided for the id(...) calls to the nodes that were
33 // In the given example, each time our matcher finds a match we get a callback
34 // where "child" is bound to the 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/DeclFriend.h"
50 #include "clang/AST/DeclObjC.h"
51 #include "clang/AST/DeclTemplate.h"
52 #include "clang/ASTMatchers/ASTMatchersInternal.h"
53 #include "clang/ASTMatchers/ASTMatchersMacros.h"
54 #include "llvm/Support/Regex.h"
58 namespace ast_matchers {
60 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
62 /// The bound nodes are generated by calling \c bind("id") on the node matchers
63 /// of the nodes we want to access later.
65 /// The instances of BoundNodes are created by \c MatchFinder when the user's
66 /// callbacks are executed every time a match is found.
69 /// \brief Returns the AST node bound to \c ID.
71 /// Returns NULL if there was no node bound to \c ID or if there is a node but
72 /// it cannot be converted to the specified type.
74 const T *getNodeAs(StringRef ID) const {
75 return MyBoundNodes.getNodeAs<T>(ID);
78 /// \brief Type of mapping from binding identifiers to bound nodes. This type
79 /// is an associative container with a key type of \c std::string and a value
80 /// type of \c clang::ast_type_traits::DynTypedNode
81 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
83 /// \brief Retrieve mapping from binding identifiers to bound nodes.
84 const IDToNodeMap &getMap() const {
85 return MyBoundNodes.getMap();
89 /// \brief Create BoundNodes from a pre-filled map of bindings.
90 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
91 : MyBoundNodes(MyBoundNodes) {}
93 internal::BoundNodesMap MyBoundNodes;
95 friend class internal::BoundNodesTreeBuilder;
98 /// \brief If the provided matcher matches a node, binds the node to \c ID.
100 /// FIXME: Do we want to support this now that we have bind()?
101 template <typename T>
102 internal::Matcher<T> id(StringRef ID,
103 const internal::BindableMatcher<T> &InnerMatcher) {
104 return InnerMatcher.bind(ID);
107 /// \brief Types of matchers for the top-level classes in the AST class
110 typedef internal::Matcher<Decl> DeclarationMatcher;
111 typedef internal::Matcher<Stmt> StatementMatcher;
112 typedef internal::Matcher<QualType> TypeMatcher;
113 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
114 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
115 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
116 typedef internal::Matcher<CXXCtorInitializer> CXXCtorInitializerMatcher;
119 /// \brief Matches any node.
121 /// Useful when another matcher requires a child matcher, but there's no
122 /// additional constraint. This will often be used with an explicit conversion
123 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
125 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
127 /// "int* p" and "void f()" in
132 /// Usable as: Any Matcher
133 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
135 /// \brief Matches the top declaration context.
142 /// } // namespace NS
144 /// decl(hasDeclContext(translationUnitDecl()))
145 /// matches "int X", but not "int Y".
146 const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
149 /// \brief Matches typedef declarations.
157 /// matches "typedef int X", but not "using Y = int"
158 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
160 /// \brief Matches typedef name declarations.
167 /// typedefNameDecl()
168 /// matches "typedef int X" and "using Y = int"
169 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
172 /// \brief Matches type alias declarations.
180 /// matches "using Y = int", but not "typedef int X"
181 const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl> typeAliasDecl;
183 /// \brief Matches type alias template declarations.
185 /// typeAliasTemplateDecl() matches
187 /// template <typename T>
190 const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
191 typeAliasTemplateDecl;
193 /// \brief Matches AST nodes that were expanded within the main-file.
195 /// Example matches X but not Y
196 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
206 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
207 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
208 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
209 auto &SourceManager = Finder->getASTContext().getSourceManager();
210 return SourceManager.isInMainFile(
211 SourceManager.getExpansionLoc(Node.getLocStart()));
214 /// \brief Matches AST nodes that were expanded within system-header-files.
216 /// Example matches Y but not X
217 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
219 /// #include <SystemHeader.h>
227 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
228 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
229 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
230 auto &SourceManager = Finder->getASTContext().getSourceManager();
231 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
232 if (ExpansionLoc.isInvalid()) {
235 return SourceManager.isInSystemHeader(ExpansionLoc);
238 /// \brief Matches AST nodes that were expanded within files whose name is
239 /// partially matching a given regex.
241 /// Example matches Y but not X
242 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
244 /// #include "ASTMatcher.h"
252 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
253 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
254 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
255 std::string, RegExp) {
256 auto &SourceManager = Finder->getASTContext().getSourceManager();
257 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
258 if (ExpansionLoc.isInvalid()) {
262 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
267 auto Filename = FileEntry->getName();
268 llvm::Regex RE(RegExp);
269 return RE.match(Filename);
272 /// \brief Matches declarations.
274 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
281 const internal::VariadicAllOfMatcher<Decl> decl;
283 /// \brief Matches a declaration of a linkage specification.
289 /// linkageSpecDecl()
290 /// matches "extern "C" {}"
291 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
294 /// \brief Matches a declaration of anything that could have a name.
296 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
305 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
307 /// \brief Matches a declaration of label.
316 const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
318 /// \brief Matches a declaration of a namespace.
323 /// namespace test {}
326 /// matches "namespace {}" and "namespace test {}"
327 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
329 /// \brief Matches a declaration of a namespace alias.
333 /// namespace test {}
334 /// namespace alias = ::test;
336 /// namespaceAliasDecl()
337 /// matches "namespace alias" but not "namespace test"
338 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
341 /// \brief Matches class, struct, and union declarations.
343 /// Example matches \c X, \c Z, \c U, and \c S
346 /// template<class T> class Z {};
350 const internal::VariadicDynCastAllOfMatcher<
352 RecordDecl> recordDecl;
354 /// \brief Matches C++ class declarations.
356 /// Example matches \c X, \c Z
359 /// template<class T> class Z {};
361 const internal::VariadicDynCastAllOfMatcher<
363 CXXRecordDecl> cxxRecordDecl;
365 /// \brief Matches C++ class template declarations.
367 /// Example matches \c Z
369 /// template<class T> class Z {};
371 const internal::VariadicDynCastAllOfMatcher<
373 ClassTemplateDecl> classTemplateDecl;
375 /// \brief Matches C++ class template specializations.
379 /// template<typename T> class A {};
380 /// template<> class A<double> {};
383 /// classTemplateSpecializationDecl()
384 /// matches the specializations \c A<int> and \c A<double>
385 const internal::VariadicDynCastAllOfMatcher<
387 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
389 /// \brief Matches declarator declarations (field, variable, function
390 /// and non-type template parameter declarations).
394 /// class X { int y; };
397 /// matches \c int y.
398 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
401 /// \brief Matches parameter variable declarations.
408 /// matches \c int x.
409 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
411 /// \brief Matches C++ access specifier declarations.
421 /// matches 'public:'
422 const internal::VariadicDynCastAllOfMatcher<
424 AccessSpecDecl> accessSpecDecl;
426 /// \brief Matches constructor initializers.
428 /// Examples matches \c i(42).
435 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
437 /// \brief Matches template arguments.
441 /// template <typename T> struct C {};
444 /// templateArgument()
445 /// matches 'int' in C<int>.
446 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
448 /// \brief Matches template name.
452 /// template <typename T> class X { };
456 /// matches 'X' in X<int>.
457 const internal::VariadicAllOfMatcher<TemplateName> templateName;
459 /// \brief Matches non-type template parameter declarations.
463 /// template <typename T, int N> struct C {};
465 /// nonTypeTemplateParmDecl()
466 /// matches 'N', but not 'T'.
467 const internal::VariadicDynCastAllOfMatcher<
469 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
471 /// \brief Matches template type parameter declarations.
475 /// template <typename T, int N> struct C {};
477 /// templateTypeParmDecl()
478 /// matches 'T', but not 'N'.
479 const internal::VariadicDynCastAllOfMatcher<
481 TemplateTypeParmDecl> templateTypeParmDecl;
483 /// \brief Matches public C++ declarations.
489 /// protected: int b;
493 /// fieldDecl(isPublic())
495 AST_MATCHER(Decl, isPublic) {
496 return Node.getAccess() == AS_public;
499 /// \brief Matches protected C++ declarations.
505 /// protected: int b;
509 /// fieldDecl(isProtected())
511 AST_MATCHER(Decl, isProtected) {
512 return Node.getAccess() == AS_protected;
515 /// \brief Matches private C++ declarations.
521 /// protected: int b;
525 /// fieldDecl(isPrivate())
527 AST_MATCHER(Decl, isPrivate) {
528 return Node.getAccess() == AS_private;
531 /// \brief Matches non-static data members that are bit-fields.
540 /// fieldDecl(isBitField())
541 /// matches 'int a;' but not 'int b;'.
542 AST_MATCHER(FieldDecl, isBitField) {
543 return Node.isBitField();
546 /// \brief Matches non-static data members that are bit-fields of the specified
557 /// fieldDecl(hasBitWidth(2))
558 /// matches 'int a;' and 'int c;' but not 'int b;'.
559 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
560 return Node.isBitField() &&
561 Node.getBitWidthValue(Finder->getASTContext()) == Width;
564 /// \brief Matches non-static data members that have an in-class initializer.
574 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
575 /// matches 'int a;' but not 'int b;'.
576 /// fieldDecl(hasInClassInitializer(anything()))
577 /// matches 'int a;' and 'int b;' but not 'int c;'.
578 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
580 const Expr *Initializer = Node.getInClassInitializer();
581 return (Initializer != nullptr &&
582 InnerMatcher.matches(*Initializer, Finder, Builder));
585 /// \brief Matches a declaration that has been implicitly added
586 /// by the compiler (eg. implicit default/copy constructors).
587 AST_MATCHER(Decl, isImplicit) {
588 return Node.isImplicit();
591 /// \brief Matches classTemplateSpecializations, templateSpecializationType and
592 /// functionDecl that have at least one TemplateArgument matching the given
597 /// template<typename T> class A {};
598 /// template<> class A<double> {};
601 /// template<typename T> f() {};
602 /// void func() { f<int>(); };
606 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
607 /// refersToType(asString("int"))))
608 /// matches the specialization \c A<int>
610 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
611 /// matches the specialization \c f<int>
612 AST_POLYMORPHIC_MATCHER_P(
613 hasAnyTemplateArgument,
614 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
615 TemplateSpecializationType,
617 internal::Matcher<TemplateArgument>, InnerMatcher) {
618 ArrayRef<TemplateArgument> List =
619 internal::getTemplateSpecializationArgs(Node);
620 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
624 /// \brief Matches expressions that match InnerMatcher after any implicit AST
625 /// nodes are stripped off.
627 /// Parentheses and explicit casts are not discarded.
637 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
639 /// would match the declarations for a, b, and c.
642 /// varDecl(hasInitializer(cxxConstructExpr()))
644 /// only match the declarations for b and c.
645 AST_MATCHER_P(Expr, ignoringImplicit, ast_matchers::internal::Matcher<Expr>,
647 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
650 /// \brief Matches expressions that match InnerMatcher after any implicit casts
651 /// are stripped off.
653 /// Parentheses and explicit casts are not discarded.
661 /// long e = (long) 0l;
665 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
666 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
668 /// would match the declarations for a, b, c, and d, but not e.
671 /// varDecl(hasInitializer(integerLiteral()))
672 /// varDecl(hasInitializer(declRefExpr()))
674 /// only match the declarations for b, c, and d.
675 AST_MATCHER_P(Expr, ignoringImpCasts,
676 internal::Matcher<Expr>, InnerMatcher) {
677 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
680 /// \brief Matches expressions that match InnerMatcher after parentheses and
681 /// casts are stripped off.
683 /// Implicit and non-C Style casts are also discarded.
688 /// void* c = reinterpret_cast<char*>(0);
689 /// char d = char(0);
692 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
693 /// would match the declarations for a, b, c, and d.
695 /// varDecl(hasInitializer(integerLiteral()))
696 /// only match the declaration for a.
697 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
698 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
701 /// \brief Matches expressions that match InnerMatcher after implicit casts and
702 /// parentheses are stripped off.
704 /// Explicit casts are not discarded.
712 /// long e = ((long) 0l);
715 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
716 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
717 /// would match the declarations for a, b, c, and d, but not e.
719 /// varDecl(hasInitializer(integerLiteral()))
720 /// varDecl(hasInitializer(declRefExpr()))
721 /// would only match the declaration for a.
722 AST_MATCHER_P(Expr, ignoringParenImpCasts,
723 internal::Matcher<Expr>, InnerMatcher) {
724 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
727 /// \brief Matches types that match InnerMatcher after any parens are stripped.
731 /// void (*fp)(void);
735 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
737 /// would match the declaration for fp.
738 AST_MATCHER_P(QualType, ignoringParens,
739 internal::Matcher<QualType>, InnerMatcher) {
740 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
743 /// \brief Matches classTemplateSpecializations, templateSpecializationType and
744 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
748 /// template<typename T, typename U> class A {};
752 /// template<typename T> f() {};
753 /// void func() { f<int>(); };
755 /// classTemplateSpecializationDecl(hasTemplateArgument(
756 /// 1, refersToType(asString("int"))))
757 /// matches the specialization \c A<bool, int>
759 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
760 /// matches the specialization \c f<int>
761 AST_POLYMORPHIC_MATCHER_P2(
763 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
764 TemplateSpecializationType,
766 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
767 ArrayRef<TemplateArgument> List =
768 internal::getTemplateSpecializationArgs(Node);
769 if (List.size() <= N)
771 return InnerMatcher.matches(List[N], Finder, Builder);
774 /// \brief Matches if the number of template arguments equals \p N.
778 /// template<typename T> struct C {};
781 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
783 AST_POLYMORPHIC_MATCHER_P(
784 templateArgumentCountIs,
785 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
786 TemplateSpecializationType),
788 return internal::getTemplateSpecializationArgs(Node).size() == N;
791 /// \brief Matches a TemplateArgument that refers to a certain type.
796 /// template<typename T> struct A {};
799 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
800 /// refersToType(class(hasName("X")))))
801 /// matches the specialization \c A<X>
802 AST_MATCHER_P(TemplateArgument, refersToType,
803 internal::Matcher<QualType>, InnerMatcher) {
804 if (Node.getKind() != TemplateArgument::Type)
806 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
809 /// \brief Matches a TemplateArgument that refers to a certain template.
813 /// template<template <typename> class S> class X {};
814 /// template<typename T> class Y {};"
817 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
818 /// refersToTemplate(templateName())))
819 /// matches the specialization \c X<Y>
820 AST_MATCHER_P(TemplateArgument, refersToTemplate,
821 internal::Matcher<TemplateName>, InnerMatcher) {
822 if (Node.getKind() != TemplateArgument::Template)
824 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
827 /// \brief Matches a canonical TemplateArgument that refers to a certain
832 /// template<typename T> struct A {};
833 /// struct B { B* next; };
836 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
837 /// refersToDeclaration(fieldDecl(hasName("next"))))
838 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
840 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
841 internal::Matcher<Decl>, InnerMatcher) {
842 if (Node.getKind() == TemplateArgument::Declaration)
843 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
847 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
851 /// template<typename T> struct A {};
852 /// struct B { B* next; };
855 /// templateSpecializationType(hasAnyTemplateArgument(
856 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
857 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
859 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
860 if (Node.getKind() == TemplateArgument::Expression)
861 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
865 /// \brief Matches a TemplateArgument that is an integral value.
869 /// template<int T> struct A {};
872 /// classTemplateSpecializationDecl(
873 /// hasAnyTemplateArgument(isIntegral()))
874 /// matches the implicit instantiation of C in C<42>
875 /// with isIntegral() matching 42.
876 AST_MATCHER(TemplateArgument, isIntegral) {
877 return Node.getKind() == TemplateArgument::Integral;
880 /// \brief Matches a TemplateArgument that referes to an integral type.
884 /// template<int T> struct A {};
887 /// classTemplateSpecializationDecl(
888 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
889 /// matches the implicit instantiation of C in C<42>.
890 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
891 internal::Matcher<QualType>, InnerMatcher) {
892 if (Node.getKind() != TemplateArgument::Integral)
894 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
897 /// \brief Matches a TemplateArgument of integral type with a given value.
899 /// Note that 'Value' is a string as the template argument's value is
900 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
901 /// representation of that integral value in base 10.
905 /// template<int T> struct A {};
908 /// classTemplateSpecializationDecl(
909 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
910 /// matches the implicit instantiation of C in C<42>.
911 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
912 std::string, Value) {
913 if (Node.getKind() != TemplateArgument::Integral)
915 return Node.getAsIntegral().toString(10) == Value;
918 /// \brief Matches any value declaration.
920 /// Example matches A, B, C and F
922 /// enum X { A, B, C };
925 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
927 /// \brief Matches C++ constructor declarations.
929 /// Example matches Foo::Foo() and Foo::Foo(int)
935 /// int DoSomething();
938 const internal::VariadicDynCastAllOfMatcher<
940 CXXConstructorDecl> cxxConstructorDecl;
942 /// \brief Matches explicit C++ destructor declarations.
944 /// Example matches Foo::~Foo()
951 const internal::VariadicDynCastAllOfMatcher<
953 CXXDestructorDecl> cxxDestructorDecl;
955 /// \brief Matches enum declarations.
957 /// Example matches X
963 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
965 /// \brief Matches enum constants.
967 /// Example matches A, B, C
973 const internal::VariadicDynCastAllOfMatcher<
975 EnumConstantDecl> enumConstantDecl;
977 /// \brief Matches method declarations.
979 /// Example matches y
981 /// class X { void y(); };
983 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
985 /// \brief Matches conversion operator declarations.
987 /// Example matches the operator.
989 /// class X { operator int() const; };
991 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
994 /// \brief Matches variable declarations.
996 /// Note: this does not match declarations of member variables, which are
997 /// "field" declarations in Clang parlance.
999 /// Example matches a
1003 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1005 /// \brief Matches field declarations.
1009 /// class X { int m; };
1013 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1015 /// \brief Matches function declarations.
1017 /// Example matches f
1021 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
1023 /// \brief Matches C++ function template declarations.
1025 /// Example matches f
1027 /// template<class T> void f(T t) {}
1029 const internal::VariadicDynCastAllOfMatcher<
1031 FunctionTemplateDecl> functionTemplateDecl;
1033 /// \brief Matches friend declarations.
1037 /// class X { friend void foo(); };
1040 /// matches 'friend void foo()'.
1041 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1043 /// \brief Matches statements.
1050 /// matches both the compound statement '{ ++a; }' and '++a'.
1051 const internal::VariadicAllOfMatcher<Stmt> stmt;
1053 /// \brief Matches declaration statements.
1060 /// matches 'int a'.
1061 const internal::VariadicDynCastAllOfMatcher<
1065 /// \brief Matches member expressions.
1070 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1071 /// int a; static int b;
1075 /// matches this->x, x, y.x, a, this->b
1076 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1078 /// \brief Matches call expressions.
1080 /// Example matches x.y() and y()
1086 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1088 /// \brief Matches lambda expressions.
1090 /// Example matches [&](){return 5;}
1092 /// [&](){return 5;}
1094 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1096 /// \brief Matches member call expressions.
1098 /// Example matches x.y()
1103 const internal::VariadicDynCastAllOfMatcher<
1105 CXXMemberCallExpr> cxxMemberCallExpr;
1107 /// \brief Matches ObjectiveC Message invocation expressions.
1109 /// The innermost message send invokes the "alloc" class method on the
1110 /// NSString class, while the outermost message send invokes the
1111 /// "initWithString" instance method on the object returned from
1112 /// NSString's "alloc". This matcher should match both message sends.
1114 /// [[NSString alloc] initWithString:@"Hello"]
1116 const internal::VariadicDynCastAllOfMatcher<
1118 ObjCMessageExpr> objcMessageExpr;
1120 /// \brief Matches Objective-C interface declarations.
1122 /// Example matches Foo
1127 const internal::VariadicDynCastAllOfMatcher<
1129 ObjCInterfaceDecl> objcInterfaceDecl;
1131 /// \brief Matches Objective-C protocol declarations.
1133 /// Example matches FooDelegate
1135 /// @protocol FooDelegate
1138 const internal::VariadicDynCastAllOfMatcher<
1140 ObjCProtocolDecl> objcProtocolDecl;
1142 /// \brief Matches Objective-C category declarations.
1144 /// Example matches Foo (Additions)
1146 /// @interface Foo (Additions)
1149 const internal::VariadicDynCastAllOfMatcher<
1151 ObjCCategoryDecl> objcCategoryDecl;
1153 /// \brief Matches Objective-C method declarations.
1155 /// Example matches both declaration and definition of -[Foo method]
1161 /// @implementation Foo
1162 /// - (void)method {}
1165 const internal::VariadicDynCastAllOfMatcher<
1167 ObjCMethodDecl> objcMethodDecl;
1169 /// \brief Matches Objective-C instance variable declarations.
1171 /// Example matches _enabled
1173 /// @implementation Foo {
1178 const internal::VariadicDynCastAllOfMatcher<
1180 ObjCIvarDecl> objcIvarDecl;
1182 /// \brief Matches Objective-C property declarations.
1184 /// Example matches enabled
1187 /// @property BOOL enabled;
1190 const internal::VariadicDynCastAllOfMatcher<
1192 ObjCPropertyDecl> objcPropertyDecl;
1194 /// \brief Matches expressions that introduce cleanups to be run at the end
1195 /// of the sub-expression's evaluation.
1197 /// Example matches std::string()
1199 /// const std::string str = std::string();
1201 const internal::VariadicDynCastAllOfMatcher<
1203 ExprWithCleanups> exprWithCleanups;
1205 /// \brief Matches init list expressions.
1209 /// int a[] = { 1, 2 };
1210 /// struct B { int x, y; };
1214 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1215 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
1217 /// \brief Matches the syntactic form of init list expressions
1218 /// (if expression have it).
1219 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1220 internal::Matcher<Expr>, InnerMatcher) {
1221 const Expr *SyntForm = Node.getSyntacticForm();
1222 return (SyntForm != nullptr &&
1223 InnerMatcher.matches(*SyntForm, Finder, Builder));
1226 /// \brief Matches implicit initializers of init list expressions.
1230 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1232 /// implicitValueInitExpr()
1233 /// matches "[0].y" (implicitly)
1234 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1235 implicitValueInitExpr;
1237 /// \brief Matches paren list expressions.
1238 /// ParenListExprs don't have a predefined type and are used for late parsing.
1239 /// In the final AST, they can be met in template declarations.
1243 /// template<typename T> class X {
1246 /// int a = 0, b = 1; int i = (a, b);
1250 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1251 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1252 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr;
1254 /// \brief Matches substitutions of non-type template parameters.
1258 /// template <int N>
1259 /// struct A { static const int n = N; };
1260 /// struct B : public A<42> {};
1262 /// substNonTypeTemplateParmExpr()
1263 /// matches "N" in the right-hand side of "static const int n = N;"
1264 const internal::VariadicDynCastAllOfMatcher<
1266 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
1268 /// \brief Matches using declarations.
1272 /// namespace X { int x; }
1276 /// matches \code using X::x \endcode
1277 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1279 /// \brief Matches using namespace declarations.
1283 /// namespace X { int x; }
1284 /// using namespace X;
1286 /// usingDirectiveDecl()
1287 /// matches \code using namespace X \endcode
1288 const internal::VariadicDynCastAllOfMatcher<
1290 UsingDirectiveDecl> usingDirectiveDecl;
1292 /// \brief Matches reference to a name that can be looked up during parsing
1293 /// but could not be resolved to a specific declaration.
1297 /// template<typename T>
1298 /// T foo() { T a; return a; }
1299 /// template<typename T>
1304 /// unresolvedLookupExpr()
1305 /// matches \code foo<T>() \endcode
1306 const internal::VariadicDynCastAllOfMatcher<
1308 UnresolvedLookupExpr> unresolvedLookupExpr;
1310 /// \brief Matches unresolved using value declarations.
1314 /// template<typename X>
1315 /// class C : private X {
1319 /// unresolvedUsingValueDecl()
1320 /// matches \code using X::x \endcode
1321 const internal::VariadicDynCastAllOfMatcher<
1323 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1325 /// \brief Matches unresolved using value declarations that involve the
1330 /// template <typename T>
1331 /// struct Base { typedef T Foo; };
1333 /// template<typename T>
1334 /// struct S : private Base<T> {
1335 /// using typename Base<T>::Foo;
1338 /// unresolvedUsingTypenameDecl()
1339 /// matches \code using Base<T>::Foo \endcode
1340 const internal::VariadicDynCastAllOfMatcher<
1342 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1344 /// \brief Matches parentheses used in expressions.
1346 /// Example matches (foo() + 1)
1348 /// int foo() { return 1; }
1349 /// int a = (foo() + 1);
1351 const internal::VariadicDynCastAllOfMatcher<
1353 ParenExpr> parenExpr;
1355 /// \brief Matches constructor call expressions (including implicit ones).
1357 /// Example matches string(ptr, n) and ptr within arguments of f
1358 /// (matcher = cxxConstructExpr())
1360 /// void f(const string &a, const string &b);
1363 /// f(string(ptr, n), ptr);
1365 const internal::VariadicDynCastAllOfMatcher<
1367 CXXConstructExpr> cxxConstructExpr;
1369 /// \brief Matches unresolved constructor call expressions.
1371 /// Example matches T(t) in return statement of f
1372 /// (matcher = cxxUnresolvedConstructExpr())
1374 /// template <typename T>
1375 /// void f(const T& t) { return T(t); }
1377 const internal::VariadicDynCastAllOfMatcher<
1379 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1381 /// \brief Matches implicit and explicit this expressions.
1383 /// Example matches the implicit this expression in "return i".
1384 /// (matcher = cxxThisExpr())
1388 /// int f() { return i; }
1391 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1393 /// \brief Matches nodes where temporaries are created.
1395 /// Example matches FunctionTakesString(GetStringByValue())
1396 /// (matcher = cxxBindTemporaryExpr())
1398 /// FunctionTakesString(GetStringByValue());
1399 /// FunctionTakesStringByPointer(GetStringPointer());
1401 const internal::VariadicDynCastAllOfMatcher<
1403 CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1405 /// \brief Matches nodes where temporaries are materialized.
1409 /// struct T {void func()};
1413 /// materializeTemporaryExpr() matches 'f()' in these statements
1418 /// but does not match
1423 const internal::VariadicDynCastAllOfMatcher<
1425 MaterializeTemporaryExpr> materializeTemporaryExpr;
1427 /// \brief Matches new expressions.
1434 /// matches 'new X'.
1435 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1437 /// \brief Matches delete expressions.
1444 /// matches 'delete X'.
1445 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1447 /// \brief Matches array subscript expressions.
1453 /// arraySubscriptExpr()
1455 const internal::VariadicDynCastAllOfMatcher<
1457 ArraySubscriptExpr> arraySubscriptExpr;
1459 /// \brief Matches the value of a default argument at the call site.
1461 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1462 /// default value of the second parameter in the call expression f(42)
1463 /// (matcher = cxxDefaultArgExpr())
1465 /// void f(int x, int y = 0);
1468 const internal::VariadicDynCastAllOfMatcher<
1470 CXXDefaultArgExpr> cxxDefaultArgExpr;
1472 /// \brief Matches overloaded operator calls.
1474 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1475 /// binaryOperator matcher.
1476 /// Currently it does not match operators such as new delete.
1477 /// FIXME: figure out why these do not match?
1479 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1480 /// (matcher = cxxOperatorCallExpr())
1482 /// ostream &operator<< (ostream &out, int i) { };
1483 /// ostream &o; int b = 1, c = 1;
1486 const internal::VariadicDynCastAllOfMatcher<
1488 CXXOperatorCallExpr> cxxOperatorCallExpr;
1490 /// \brief Matches expressions.
1492 /// Example matches x()
1494 /// void f() { x(); }
1496 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1498 /// \brief Matches expressions that refer to declarations.
1500 /// Example matches x in if (x)
1505 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1507 /// \brief Matches if statements.
1509 /// Example matches 'if (x) {}'
1513 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1515 /// \brief Matches for statements.
1517 /// Example matches 'for (;;) {}'
1520 /// int i[] = {1, 2, 3}; for (auto a : i);
1522 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1524 /// \brief Matches the increment statement of a for loop.
1527 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1528 /// matches '++x' in
1530 /// for (x; x < N; ++x) { }
1532 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1534 const Stmt *const Increment = Node.getInc();
1535 return (Increment != nullptr &&
1536 InnerMatcher.matches(*Increment, Finder, Builder));
1539 /// \brief Matches the initialization statement of a for loop.
1542 /// forStmt(hasLoopInit(declStmt()))
1543 /// matches 'int x = 0' in
1545 /// for (int x = 0; x < N; ++x) { }
1547 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1549 const Stmt *const Init = Node.getInit();
1550 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1553 /// \brief Matches range-based for statements.
1555 /// cxxForRangeStmt() matches 'for (auto a : i)'
1557 /// int i[] = {1, 2, 3}; for (auto a : i);
1558 /// for(int j = 0; j < 5; ++j);
1560 const internal::VariadicDynCastAllOfMatcher<
1562 CXXForRangeStmt> cxxForRangeStmt;
1564 /// \brief Matches the initialization statement of a for loop.
1567 /// forStmt(hasLoopVariable(anything()))
1568 /// matches 'int x' in
1570 /// for (int x : a) { }
1572 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1574 const VarDecl *const Var = Node.getLoopVariable();
1575 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1578 /// \brief Matches the range initialization statement of a for loop.
1581 /// forStmt(hasRangeInit(anything()))
1584 /// for (int x : a) { }
1586 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1588 const Expr *const Init = Node.getRangeInit();
1589 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1592 /// \brief Matches while statements.
1599 /// matches 'while (true) {}'.
1600 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1602 /// \brief Matches do statements.
1606 /// do {} while (true);
1609 /// matches 'do {} while(true)'
1610 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1612 /// \brief Matches break statements.
1616 /// while (true) { break; }
1620 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1622 /// \brief Matches continue statements.
1626 /// while (true) { continue; }
1629 /// matches 'continue'
1630 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1632 /// \brief Matches return statements.
1639 /// matches 'return 1'
1640 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1642 /// \brief Matches goto statements.
1650 /// matches 'goto FOO'
1651 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1653 /// \brief Matches label statements.
1662 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1664 /// \brief Matches address of label statements (GNU extension).
1669 /// void *ptr = &&FOO;
1674 const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr;
1676 /// \brief Matches switch statements.
1680 /// switch(a) { case 42: break; default: break; }
1683 /// matches 'switch(a)'.
1684 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1686 /// \brief Matches case and default statements inside switch statements.
1690 /// switch(a) { case 42: break; default: break; }
1693 /// matches 'case 42: break;' and 'default: break;'.
1694 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1696 /// \brief Matches case statements inside switch statements.
1700 /// switch(a) { case 42: break; default: break; }
1703 /// matches 'case 42: break;'.
1704 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1706 /// \brief Matches default statements inside switch statements.
1710 /// switch(a) { case 42: break; default: break; }
1713 /// matches 'default: break;'.
1714 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1716 /// \brief Matches compound statements.
1718 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1722 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1724 /// \brief Matches catch statements.
1727 /// try {} catch(int i) {}
1730 /// matches 'catch(int i)'
1731 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1733 /// \brief Matches try statements.
1736 /// try {} catch(int i) {}
1739 /// matches 'try {}'
1740 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1742 /// \brief Matches throw expressions.
1745 /// try { throw 5; } catch(int i) {}
1748 /// matches 'throw 5'
1749 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1751 /// \brief Matches null statements.
1757 /// matches the second ';'
1758 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1760 /// \brief Matches asm statements.
1764 /// __asm("mov al, 2");
1767 /// matches '__asm("mov al, 2")'
1768 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1770 /// \brief Matches bool literals.
1772 /// Example matches true
1776 const internal::VariadicDynCastAllOfMatcher<
1778 CXXBoolLiteralExpr> cxxBoolLiteral;
1780 /// \brief Matches string literals (also matches wide string literals).
1782 /// Example matches "abcd", L"abcd"
1784 /// char *s = "abcd";
1785 /// wchar_t *ws = L"abcd";
1787 const internal::VariadicDynCastAllOfMatcher<
1789 StringLiteral> stringLiteral;
1791 /// \brief Matches character literals (also matches wchar_t).
1793 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1796 /// Example matches 'a', L'a'
1799 /// wchar_t chw = L'a';
1801 const internal::VariadicDynCastAllOfMatcher<
1803 CharacterLiteral> characterLiteral;
1805 /// \brief Matches integer literals of all sizes / encodings, e.g.
1806 /// 1, 1L, 0x1 and 1U.
1808 /// Does not match character-encoded integers such as L'a'.
1809 const internal::VariadicDynCastAllOfMatcher<
1811 IntegerLiteral> integerLiteral;
1813 /// \brief Matches float literals of all sizes / encodings, e.g.
1814 /// 1.0, 1.0f, 1.0L and 1e10.
1816 /// Does not match implicit conversions such as
1820 const internal::VariadicDynCastAllOfMatcher<
1822 FloatingLiteral> floatLiteral;
1824 /// \brief Matches user defined literal operator call.
1826 /// Example match: "foo"_suffix
1827 const internal::VariadicDynCastAllOfMatcher<
1829 UserDefinedLiteral> userDefinedLiteral;
1831 /// \brief Matches compound (i.e. non-scalar) literals
1833 /// Example match: {1}, (1, 2)
1835 /// int array[4] = {1};
1836 /// vector int myvec = (vector int)(1, 2);
1838 const internal::VariadicDynCastAllOfMatcher<
1840 CompoundLiteralExpr> compoundLiteralExpr;
1842 /// \brief Matches nullptr literal.
1843 const internal::VariadicDynCastAllOfMatcher<
1845 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1847 /// \brief Matches GNU __null expression.
1848 const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr;
1850 /// \brief Matches atomic builtins.
1851 /// Example matches __atomic_load_n(ptr, 1)
1853 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
1855 const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
1857 /// \brief Matches statement expression (GNU extension).
1859 /// Example match: ({ int X = 4; X; })
1861 /// int C = ({ int X = 4; X; });
1863 const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
1865 /// \brief Matches binary operator expressions.
1867 /// Example matches a || b
1871 const internal::VariadicDynCastAllOfMatcher<
1873 BinaryOperator> binaryOperator;
1875 /// \brief Matches unary operator expressions.
1877 /// Example matches !a
1881 const internal::VariadicDynCastAllOfMatcher<
1883 UnaryOperator> unaryOperator;
1885 /// \brief Matches conditional operator expressions.
1887 /// Example matches a ? b : c
1889 /// (a ? b : c) + 42
1891 const internal::VariadicDynCastAllOfMatcher<
1893 ConditionalOperator> conditionalOperator;
1895 /// \brief Matches binary conditional operator expressions (GNU extension).
1897 /// Example matches a ?: b
1901 const internal::VariadicDynCastAllOfMatcher<
1903 BinaryConditionalOperator> binaryConditionalOperator;
1905 /// \brief Matches opaque value expressions. They are used as helpers
1906 /// to reference another expressions and can be met
1907 /// in BinaryConditionalOperators, for example.
1909 /// Example matches 'a'
1913 const internal::VariadicDynCastAllOfMatcher<
1915 OpaqueValueExpr> opaqueValueExpr;
1917 /// \brief Matches a C++ static_assert declaration.
1920 /// staticAssertExpr()
1922 /// static_assert(sizeof(S) == sizeof(int))
1928 /// static_assert(sizeof(S) == sizeof(int));
1930 const internal::VariadicDynCastAllOfMatcher<
1932 StaticAssertDecl> staticAssertDecl;
1934 /// \brief Matches a reinterpret_cast expression.
1936 /// Either the source expression or the destination type can be matched
1937 /// using has(), but hasDestinationType() is more specific and can be
1940 /// Example matches reinterpret_cast<char*>(&p) in
1942 /// void* p = reinterpret_cast<char*>(&p);
1944 const internal::VariadicDynCastAllOfMatcher<
1946 CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1948 /// \brief Matches a C++ static_cast expression.
1950 /// \see hasDestinationType
1951 /// \see reinterpretCast
1954 /// cxxStaticCastExpr()
1956 /// static_cast<long>(8)
1959 /// long eight(static_cast<long>(8));
1961 const internal::VariadicDynCastAllOfMatcher<
1963 CXXStaticCastExpr> cxxStaticCastExpr;
1965 /// \brief Matches a dynamic_cast expression.
1968 /// cxxDynamicCastExpr()
1970 /// dynamic_cast<D*>(&b);
1973 /// struct B { virtual ~B() {} }; struct D : B {};
1975 /// D* p = dynamic_cast<D*>(&b);
1977 const internal::VariadicDynCastAllOfMatcher<
1979 CXXDynamicCastExpr> cxxDynamicCastExpr;
1981 /// \brief Matches a const_cast expression.
1983 /// Example: Matches const_cast<int*>(&r) in
1986 /// const int &r(n);
1987 /// int* p = const_cast<int*>(&r);
1989 const internal::VariadicDynCastAllOfMatcher<
1991 CXXConstCastExpr> cxxConstCastExpr;
1993 /// \brief Matches a C-style cast expression.
1995 /// Example: Matches (int) 2.2f in
1997 /// int i = (int) 2.2f;
1999 const internal::VariadicDynCastAllOfMatcher<
2001 CStyleCastExpr> cStyleCastExpr;
2003 /// \brief Matches explicit cast expressions.
2005 /// Matches any cast expression written in user code, whether it be a
2006 /// C-style cast, a functional-style cast, or a keyword cast.
2008 /// Does not match implicit conversions.
2010 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2011 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2012 /// actual cast expressions.
2014 /// \see hasDestinationType.
2016 /// Example: matches all five of the casts in
2018 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2020 /// but does not match the implicit conversion in
2024 const internal::VariadicDynCastAllOfMatcher<
2026 ExplicitCastExpr> explicitCastExpr;
2028 /// \brief Matches the implicit cast nodes of Clang's AST.
2030 /// This matches many different places, including function call return value
2031 /// eliding, as well as any type conversions.
2032 const internal::VariadicDynCastAllOfMatcher<
2034 ImplicitCastExpr> implicitCastExpr;
2036 /// \brief Matches any cast nodes of Clang's AST.
2038 /// Example: castExpr() matches each of the following:
2041 /// const_cast<Expr *>(SubExpr);
2044 /// but does not match
2049 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2051 /// \brief Matches functional cast expressions
2053 /// Example: Matches Foo(bar);
2056 /// Foo g = (Foo) bar;
2057 /// Foo h = Foo(bar);
2059 const internal::VariadicDynCastAllOfMatcher<
2061 CXXFunctionalCastExpr> cxxFunctionalCastExpr;
2063 /// \brief Matches functional cast expressions having N != 1 arguments
2065 /// Example: Matches Foo(bar, bar)
2067 /// Foo h = Foo(bar, bar);
2069 const internal::VariadicDynCastAllOfMatcher<
2071 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
2073 /// \brief Matches predefined identifier expressions [C99 6.4.2.2].
2075 /// Example: Matches __func__
2077 /// printf("%s", __func__);
2079 const internal::VariadicDynCastAllOfMatcher<
2081 PredefinedExpr> predefinedExpr;
2083 /// \brief Matches C99 designated initializer expressions [C99 6.7.8].
2085 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2087 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2089 const internal::VariadicDynCastAllOfMatcher<
2091 DesignatedInitExpr> designatedInitExpr;
2093 /// \brief Matches designated initializer expressions that contain
2094 /// a specific number of designators.
2098 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2099 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2101 /// designatorCountIs(2)
2102 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2103 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2104 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2105 return Node.size() == N;
2108 /// \brief Matches \c QualTypes in the clang AST.
2109 const internal::VariadicAllOfMatcher<QualType> qualType;
2111 /// \brief Matches \c Types in the clang AST.
2112 const internal::VariadicAllOfMatcher<Type> type;
2114 /// \brief Matches \c TypeLocs in the clang AST.
2115 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2117 /// \brief Matches if any of the given matchers matches.
2119 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2120 /// matching submatcher.
2122 /// For example, in:
2124 /// class A { int a; int b; };
2128 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2129 /// has(fieldDecl(hasName("b")).bind("v"))))
2131 /// will generate two results binding "v", the first of which binds
2132 /// the field declaration of \c a, the second the field declaration of
2135 /// Usable as: Any Matcher
2136 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
2137 internal::DynTypedMatcher::VO_EachOf
2140 /// \brief Matches if any of the given matchers matches.
2142 /// Usable as: Any Matcher
2143 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
2144 internal::DynTypedMatcher::VO_AnyOf
2147 /// \brief Matches if all given matchers match.
2149 /// Usable as: Any Matcher
2150 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
2151 internal::DynTypedMatcher::VO_AllOf
2154 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2159 /// int y = sizeof(x) + alignof(x);
2161 /// unaryExprOrTypeTraitExpr()
2162 /// matches \c sizeof(x) and \c alignof(x)
2163 const internal::VariadicDynCastAllOfMatcher<
2165 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
2167 /// \brief Matches unary expressions that have a specific type of argument.
2171 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2173 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2174 /// matches \c sizeof(a) and \c alignof(c)
2175 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2176 internal::Matcher<QualType>, InnerMatcher) {
2177 const QualType ArgumentType = Node.getTypeOfArgument();
2178 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2181 /// \brief Matches unary expressions of a certain kind.
2186 /// int s = sizeof(x) + alignof(x)
2188 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2189 /// matches \c sizeof(x)
2190 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2191 return Node.getKind() == Kind;
2194 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2196 inline internal::Matcher<Stmt> alignOfExpr(
2197 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2198 return stmt(unaryExprOrTypeTraitExpr(allOf(
2199 ofKind(UETT_AlignOf), InnerMatcher)));
2202 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2204 inline internal::Matcher<Stmt> sizeOfExpr(
2205 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2206 return stmt(unaryExprOrTypeTraitExpr(
2207 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2210 /// \brief Matches NamedDecl nodes that have the specified name.
2212 /// Supports specifying enclosing namespaces or classes by prefixing the name
2213 /// with '<enclosing>::'.
2214 /// Does not match typedefs of an underlying type with the given name.
2216 /// Example matches X (Name == "X")
2221 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2223 /// namespace a { namespace b { class X; } }
2225 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2226 std::vector<std::string> Names;
2227 Names.push_back(Name);
2228 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
2231 /// \brief Matches NamedDecl nodes that have any of the specified names.
2233 /// This matcher is only provided as a performance optimization of hasName.
2235 /// hasAnyName(a, b, c)
2237 /// is equivalent to, but faster than
2239 /// anyOf(hasName(a), hasName(b), hasName(c))
2241 const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2242 internal::hasAnyNameFunc>
2245 /// \brief Matches NamedDecl nodes whose fully qualified names contain
2246 /// a substring matched by the given RegExp.
2248 /// Supports specifying enclosing namespaces or classes by
2249 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2250 /// of an underlying type with the given name.
2252 /// Example matches X (regexp == "::X")
2257 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2259 /// namespace foo { namespace bar { class X; } }
2261 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2262 assert(!RegExp.empty());
2263 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2264 llvm::Regex RE(RegExp);
2265 return RE.match(FullNameString);
2268 /// \brief Matches overloaded operator names.
2270 /// Matches overloaded operator names specified in strings without the
2271 /// "operator" prefix: e.g. "<<".
2275 /// class A { int operator*(); };
2276 /// const A &operator<<(const A &a, const A &b);
2278 /// a << a; // <-- This matches
2281 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2282 /// specified line and
2283 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2284 /// matches the declaration of \c A.
2286 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2287 inline internal::PolymorphicMatcherWithParam1<
2288 internal::HasOverloadedOperatorNameMatcher, StringRef,
2289 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2290 hasOverloadedOperatorName(StringRef Name) {
2291 return internal::PolymorphicMatcherWithParam1<
2292 internal::HasOverloadedOperatorNameMatcher, StringRef,
2293 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2296 /// \brief Matches C++ classes that are directly or indirectly derived from
2297 /// a class matching \c Base.
2299 /// Note that a class is not considered to be derived from itself.
2301 /// Example matches Y, Z, C (Base == hasName("X"))
2304 /// class Y : public X {}; // directly derived
2305 /// class Z : public Y {}; // indirectly derived
2308 /// class C : public B {}; // derived from a typedef of X
2311 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2315 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2317 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2318 internal::Matcher<NamedDecl>, Base) {
2319 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2322 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2323 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2324 assert(!BaseName.empty());
2325 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2328 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
2330 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2331 internal::Matcher<NamedDecl>, Base, 0) {
2332 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2333 .matches(Node, Finder, Builder);
2336 /// \brief Overloaded method as shortcut for
2337 /// \c isSameOrDerivedFrom(hasName(...)).
2338 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2340 assert(!BaseName.empty());
2341 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2344 /// \brief Matches the first method of a class or struct that satisfies \c
2349 /// class A { void func(); };
2350 /// class B { void member(); };
2353 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2354 /// \c A but not \c B.
2355 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2357 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2358 Node.method_end(), Finder, Builder);
2361 /// \brief Matches the generated class of lambda expressions.
2368 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2370 AST_MATCHER(CXXRecordDecl, isLambda) {
2371 return Node.isLambda();
2374 /// \brief Matches AST nodes that have child AST nodes that match the
2375 /// provided matcher.
2377 /// Example matches X, Y
2378 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2380 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2381 /// class Y { class X {}; };
2382 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2385 /// ChildT must be an AST base type.
2387 /// Usable as: Any Matcher
2388 /// Note that has is direct matcher, so it also matches things like implicit
2389 /// casts and paren casts. If you are matching with expr then you should
2390 /// probably consider using ignoringParenImpCasts like:
2391 /// has(ignoringParenImpCasts(expr())).
2392 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
2393 LLVM_ATTRIBUTE_UNUSED has = {};
2395 /// \brief Matches AST nodes that have descendant AST nodes that match the
2396 /// provided matcher.
2398 /// Example matches X, Y, Z
2399 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2401 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2402 /// class Y { class X {}; };
2403 /// class Z { class Y { class X {}; }; };
2406 /// DescendantT must be an AST base type.
2408 /// Usable as: Any Matcher
2409 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
2410 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
2412 /// \brief Matches AST nodes that have child AST nodes that match the
2413 /// provided matcher.
2415 /// Example matches X, Y
2416 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2418 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2419 /// class Y { class X {}; };
2420 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2423 /// ChildT must be an AST base type.
2425 /// As opposed to 'has', 'forEach' will cause a match for each result that
2426 /// matches instead of only on the first one.
2428 /// Usable as: Any Matcher
2429 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2430 LLVM_ATTRIBUTE_UNUSED forEach = {};
2432 /// \brief Matches AST nodes that have descendant AST nodes that match the
2433 /// provided matcher.
2435 /// Example matches X, A, B, C
2436 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2438 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2439 /// class A { class X {}; };
2440 /// class B { class C { class X {}; }; };
2443 /// DescendantT must be an AST base type.
2445 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2446 /// each result that matches instead of only on the first one.
2448 /// Note: Recursively combined ForEachDescendant can cause many matches:
2449 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2450 /// forEachDescendant(cxxRecordDecl())
2452 /// will match 10 times (plus injected class name matches) on:
2454 /// class A { class B { class C { class D { class E {}; }; }; }; };
2457 /// Usable as: Any Matcher
2458 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2459 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2461 /// \brief Matches if the node or any descendant matches.
2463 /// Generates results for each match.
2465 /// For example, in:
2467 /// class A { class B {}; class C {}; };
2471 /// cxxRecordDecl(hasName("::A"),
2472 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2474 /// will generate results for \c A, \c B and \c C.
2476 /// Usable as: Any Matcher
2477 template <typename T>
2478 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2479 return eachOf(Matcher, forEachDescendant(Matcher));
2482 /// \brief Matches AST nodes that have a parent that matches the provided
2487 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2489 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2491 /// Usable as: Any Matcher
2492 const internal::ArgumentAdaptingMatcherFunc<
2493 internal::HasParentMatcher,
2494 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2495 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2496 LLVM_ATTRIBUTE_UNUSED hasParent = {};
2498 /// \brief Matches AST nodes that have an ancestor that matches the provided
2503 /// void f() { if (true) { int x = 42; } }
2504 /// void g() { for (;;) { int x = 43; } }
2506 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2508 /// Usable as: Any Matcher
2509 const internal::ArgumentAdaptingMatcherFunc<
2510 internal::HasAncestorMatcher,
2511 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2512 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2513 LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2515 /// \brief Matches if the provided matcher does not match.
2517 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2523 /// Usable as: Any Matcher
2524 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2525 internal::DynTypedMatcher::VO_UnaryNot
2528 /// \brief Matches a node if the declaration associated with that node
2529 /// matches the given matcher.
2531 /// The associated declaration is:
2532 /// - for type nodes, the declaration of the underlying type
2533 /// - for CallExpr, the declaration of the callee
2534 /// - for MemberExpr, the declaration of the referenced member
2535 /// - for CXXConstructExpr, the declaration of the constructor
2536 /// - for CXXNewExpr, the declaration of the operator new
2538 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2539 /// function. e.g. various subtypes of clang::Type and various expressions.
2541 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2542 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2543 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2544 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2545 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2546 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2547 /// Matcher<UnresolvedUsingType>
2548 inline internal::PolymorphicMatcherWithParam1<
2549 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2550 void(internal::HasDeclarationSupportedTypes)>
2551 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2552 return internal::PolymorphicMatcherWithParam1<
2553 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2554 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2557 /// \brief Matches a \c NamedDecl whose underlying declaration matches the given
2562 /// namespace N { template<class T> void f(T t); }
2563 /// template <class T> void g() { using N::f; f(T()); }
2565 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2566 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2567 /// matches the use of \c f in \c g() .
2568 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2570 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2572 return UnderlyingDecl != nullptr &&
2573 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2576 /// \brief Matches on the implicit object argument of a member call expression.
2578 /// Example matches y.x()
2579 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2581 /// class Y { public: void x(); };
2582 /// void z() { Y y; y.x(); }",
2585 /// FIXME: Overload to allow directly matching types?
2586 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2588 const Expr *ExprNode = Node.getImplicitObjectArgument()
2589 ->IgnoreParenImpCasts();
2590 return (ExprNode != nullptr &&
2591 InnerMatcher.matches(*ExprNode, Finder, Builder));
2595 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2598 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2599 /// matches the [webView ...] message invocation.
2601 /// NSString *webViewJavaScript = ...
2602 /// UIWebView *webView = ...
2603 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2605 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2607 const QualType TypeDecl = Node.getReceiverType();
2608 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2611 /// \brief Matches when BaseName == Selector.getAsString()
2613 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2614 /// matches the outer message expr in the code below, but NOT the message
2615 /// invocation for self.bodyView.
2617 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2619 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2620 Selector Sel = Node.getSelector();
2621 return BaseName.compare(Sel.getAsString()) == 0;
2625 /// \brief Matches ObjC selectors whose name contains
2626 /// a substring matched by the given RegExp.
2627 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2628 /// matches the outer message expr in the code below, but NOT the message
2629 /// invocation for self.bodyView.
2631 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2633 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2634 assert(!RegExp.empty());
2635 std::string SelectorString = Node.getSelector().getAsString();
2636 llvm::Regex RE(RegExp);
2637 return RE.match(SelectorString);
2640 /// \brief Matches when the selector is the empty selector
2642 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2643 /// represent an error condition in the tree!
2644 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2645 return Node.getSelector().isNull();
2648 /// \brief Matches when the selector is a Unary Selector
2650 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2651 /// matches self.bodyView in the code below, but NOT the outer message
2652 /// invocation of "loadHTMLString:baseURL:".
2654 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2656 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2657 return Node.getSelector().isUnarySelector();
2660 /// \brief Matches when the selector is a keyword selector
2662 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2663 /// message expression in
2666 /// UIWebView *webView = ...;
2667 /// CGRect bodyFrame = webView.frame;
2668 /// bodyFrame.size.height = self.bodyContentHeight;
2669 /// webView.frame = bodyFrame;
2670 /// // ^---- matches here
2672 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2673 return Node.getSelector().isKeywordSelector();
2676 /// \brief Matches when the selector has the specified number of arguments
2678 /// matcher = objCMessageExpr(numSelectorArgs(0));
2679 /// matches self.bodyView in the code below
2681 /// matcher = objCMessageExpr(numSelectorArgs(2));
2682 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2683 /// of self.bodyView
2685 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2687 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2688 return Node.getSelector().getNumArgs() == N;
2691 /// \brief Matches if the call expression's callee expression matches.
2695 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2696 /// void f() { f(); }
2698 /// callExpr(callee(expr()))
2699 /// matches this->x(), x(), y.x(), f()
2700 /// with callee(...)
2701 /// matching this->x, x, y.x, f respectively
2703 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2704 /// because this introduces ambiguous overloads with calls to Callee taking a
2705 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2706 /// implemented in terms of implicit casts.
2707 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2709 const Expr *ExprNode = Node.getCallee();
2710 return (ExprNode != nullptr &&
2711 InnerMatcher.matches(*ExprNode, Finder, Builder));
2714 /// \brief Matches if the call expression's callee's declaration matches the
2717 /// Example matches y.x() (matcher = callExpr(callee(
2718 /// cxxMethodDecl(hasName("x")))))
2720 /// class Y { public: void x(); };
2721 /// void z() { Y y; y.x(); }
2723 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2725 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2728 /// \brief Matches if the expression's or declaration's type matches a type
2731 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2732 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2733 /// and U (matcher = typedefDecl(hasType(asString("int")))
2736 /// void y(X &x) { x; X z; }
2739 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2740 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefNameDecl, ValueDecl),
2741 internal::Matcher<QualType>, InnerMatcher, 0) {
2742 return InnerMatcher.matches(internal::getUnderlyingType(Node),
2746 /// \brief Overloaded to match the declaration of the expression's or value
2747 /// declaration's type.
2749 /// In case of a value declaration (for example a variable declaration),
2750 /// this resolves one layer of indirection. For example, in the value
2751 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2752 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2753 /// declaration of x.
2755 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2756 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2759 /// void y(X &x) { x; X z; }
2762 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2763 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2764 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2766 internal::Matcher<Decl>, InnerMatcher, 1) {
2767 return qualType(hasDeclaration(InnerMatcher))
2768 .matches(Node.getType(), Finder, Builder);
2771 /// \brief Matches if the type location of the declarator decl's type matches
2772 /// the inner matcher.
2778 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2780 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2781 if (!Node.getTypeSourceInfo())
2782 // This happens for example for implicit destructors.
2784 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2787 /// \brief Matches if the matched type is represented by the given string.
2791 /// class Y { public: void x(); };
2792 /// void z() { Y* y; y->x(); }
2794 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2796 AST_MATCHER_P(QualType, asString, std::string, Name) {
2797 return Name == Node.getAsString();
2800 /// \brief Matches if the matched type is a pointer type and the pointee type
2801 /// matches the specified matcher.
2803 /// Example matches y->x()
2804 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2805 /// cxxRecordDecl(hasName("Y")))))))
2807 /// class Y { public: void x(); };
2808 /// void z() { Y *y; y->x(); }
2811 QualType, pointsTo, internal::Matcher<QualType>,
2813 return (!Node.isNull() && Node->isAnyPointerType() &&
2814 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2817 /// \brief Overloaded to match the pointee type's declaration.
2818 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2820 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2821 .matches(Node, Finder, Builder);
2824 /// \brief Matches if the matched type matches the unqualified desugared
2825 /// type of the matched node.
2827 /// For example, in:
2832 /// The matcher type(hasUniqualifeidDesugaredType(recordType())) matches
2834 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
2836 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
2840 /// \brief Matches if the matched type is a reference type and the referenced
2841 /// type matches the specified matcher.
2843 /// Example matches X &x and const X &y
2844 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2853 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2855 return (!Node.isNull() && Node->isReferenceType() &&
2856 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2859 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2863 /// typedef int &int_ref;
2868 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2869 /// declaration of b but \c
2870 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2871 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2875 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2878 /// \brief Overloaded to match the referenced type's declaration.
2879 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2881 return references(qualType(hasDeclaration(InnerMatcher)))
2882 .matches(Node, Finder, Builder);
2885 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2886 internal::Matcher<Expr>, InnerMatcher) {
2887 const Expr *ExprNode = Node.getImplicitObjectArgument();
2888 return (ExprNode != nullptr &&
2889 InnerMatcher.matches(*ExprNode, Finder, Builder));
2892 /// \brief Matches if the expression's type either matches the specified
2893 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2894 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2895 internal::Matcher<QualType>, InnerMatcher, 0) {
2896 return onImplicitObjectArgument(
2897 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2898 .matches(Node, Finder, Builder);
2901 /// \brief Overloaded to match the type's declaration.
2902 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2903 internal::Matcher<Decl>, InnerMatcher, 1) {
2904 return onImplicitObjectArgument(
2905 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2906 .matches(Node, Finder, Builder);
2909 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2910 /// specified matcher.
2912 /// Example matches x in if(x)
2913 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2918 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2920 const Decl *DeclNode = Node.getDecl();
2921 return (DeclNode != nullptr &&
2922 InnerMatcher.matches(*DeclNode, Finder, Builder));
2925 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2926 /// specific using shadow declaration.
2930 /// namespace a { void f() {} }
2933 /// f(); // Matches this ..
2934 /// a::f(); // .. but not this.
2937 /// declRefExpr(throughUsingDecl(anything()))
2939 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2940 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2941 const NamedDecl *FoundDecl = Node.getFoundDecl();
2942 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2943 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2947 /// \brief Matches an \c OverloadExpr if any of the declarations in the set of
2948 /// overloads matches the given matcher.
2952 /// template <typename T> void foo(T);
2953 /// template <typename T> void bar(T);
2954 /// template <typename T> void baz(T t) {
2959 /// unresolvedLookupExpr(hasAnyDeclaration(
2960 /// functionTemplateDecl(hasName("foo"))))
2961 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
2962 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
2964 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
2965 Node.decls_end(), Finder, Builder);
2968 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2975 /// declStmt(hasSingleDecl(anything()))
2976 /// matches 'int c;' but not 'int a, b;'.
2977 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2978 if (Node.isSingleDecl()) {
2979 const Decl *FoundDecl = Node.getSingleDecl();
2980 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2985 /// \brief Matches a variable declaration that has an initializer expression
2986 /// that matches the given matcher.
2988 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2990 /// bool y() { return true; }
2994 VarDecl, hasInitializer, internal::Matcher<Expr>,
2996 const Expr *Initializer = Node.getAnyInitializer();
2997 return (Initializer != nullptr &&
2998 InnerMatcher.matches(*Initializer, Finder, Builder));
3001 /// \brief Matches a variable declaration that has function scope and is a
3002 /// non-static local variable.
3004 /// Example matches x (matcher = varDecl(hasLocalStorage())
3012 AST_MATCHER(VarDecl, hasLocalStorage) {
3013 return Node.hasLocalStorage();
3016 /// \brief Matches a variable declaration that does not have local storage.
3018 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3026 AST_MATCHER(VarDecl, hasGlobalStorage) {
3027 return Node.hasGlobalStorage();
3030 /// \brief Matches a variable declaration that has automatic storage duration.
3032 /// Example matches x, but not y, z, or a.
3033 /// (matcher = varDecl(hasAutomaticStorageDuration())
3038 /// thread_local int z;
3042 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3043 return Node.getStorageDuration() == SD_Automatic;
3046 /// \brief Matches a variable declaration that has static storage duration.
3047 /// It includes the variable declared at namespace scope and those declared
3048 /// with "static" and "extern" storage class specifiers.
3054 /// thread_local int z;
3059 /// varDecl(hasStaticStorageDuration())
3060 /// matches the function declaration y, a, b and c.
3062 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3063 return Node.getStorageDuration() == SD_Static;
3066 /// \brief Matches a variable declaration that has thread storage duration.
3068 /// Example matches z, but not x, z, or a.
3069 /// (matcher = varDecl(hasThreadStorageDuration())
3074 /// thread_local int z;
3078 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3079 return Node.getStorageDuration() == SD_Thread;
3082 /// \brief Matches a variable declaration that is an exception variable from
3083 /// a C++ catch block, or an Objective-C \@catch statement.
3085 /// Example matches x (matcher = varDecl(isExceptionVariable())
3089 /// } catch (int x) {
3093 AST_MATCHER(VarDecl, isExceptionVariable) {
3094 return Node.isExceptionVariable();
3097 /// \brief Checks that a call expression or a constructor call expression has
3098 /// a specific number of arguments (including absent default arguments).
3100 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3102 /// void f(int x, int y);
3105 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3106 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3110 return Node.getNumArgs() == N;
3113 /// \brief Matches the n'th argument of a call expression or a constructor
3114 /// call expression.
3116 /// Example matches y in x(y)
3117 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3119 /// void x(int) { int y; x(y); }
3121 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3122 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3125 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3126 return (N < Node.getNumArgs() &&
3127 InnerMatcher.matches(
3128 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3131 /// \brief Matches declaration statements that contain a specific number of
3141 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3142 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3143 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3146 /// \brief Matches the n'th declaration of a declaration statement.
3148 /// Note that this does not work for global declarations because the AST
3149 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3151 /// Example: Given non-global declarations
3157 /// declStmt(containsDeclaration(
3158 /// 0, varDecl(hasInitializer(anything()))))
3159 /// matches only 'int d = 2, e;', and
3160 /// declStmt(containsDeclaration(1, varDecl()))
3162 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3163 /// but 'int c;' is not matched.
3165 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3166 internal::Matcher<Decl>, InnerMatcher) {
3167 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3170 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3171 std::advance(Iterator, N);
3172 return InnerMatcher.matches(**Iterator, Finder, Builder);
3175 /// \brief Matches a C++ catch statement that has a catch-all handler.
3187 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3188 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3189 return Node.getExceptionDecl() == nullptr;
3192 /// \brief Matches a constructor initializer.
3197 /// Foo() : foo_(1) { }
3201 /// cxxRecordDecl(has(cxxConstructorDecl(
3202 /// hasAnyConstructorInitializer(anything())
3204 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3205 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3206 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3207 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3208 Node.init_end(), Finder, Builder);
3211 /// \brief Matches the field declaration of a constructor initializer.
3216 /// Foo() : foo_(1) { }
3220 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3221 /// forField(hasName("foo_"))))))
3223 /// with forField matching foo_
3224 AST_MATCHER_P(CXXCtorInitializer, forField,
3225 internal::Matcher<FieldDecl>, InnerMatcher) {
3226 const FieldDecl *NodeAsDecl = Node.getMember();
3227 return (NodeAsDecl != nullptr &&
3228 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3231 /// \brief Matches the initializer expression of a constructor initializer.
3236 /// Foo() : foo_(1) { }
3240 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3241 /// withInitializer(integerLiteral(equals(1)))))))
3243 /// with withInitializer matching (1)
3244 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3245 internal::Matcher<Expr>, InnerMatcher) {
3246 const Expr* NodeAsExpr = Node.getInit();
3247 return (NodeAsExpr != nullptr &&
3248 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3251 /// \brief Matches a constructor initializer if it is explicitly written in
3252 /// code (as opposed to implicitly added by the compiler).
3258 /// Foo(int) : foo_("A") { }
3262 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3263 /// will match Foo(int), but not Foo()
3264 AST_MATCHER(CXXCtorInitializer, isWritten) {
3265 return Node.isWritten();
3268 /// \brief Matches a constructor initializer if it is initializing a base, as
3269 /// opposed to a member.
3276 /// D(int i) : I(i) {}
3282 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3283 /// will match E(), but not match D(int).
3284 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3285 return Node.isBaseInitializer();
3288 /// \brief Matches a constructor initializer if it is initializing a member, as
3289 /// opposed to a base.
3296 /// D(int i) : I(i) {}
3302 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3303 /// will match D(int), but not match E().
3304 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3305 return Node.isMemberInitializer();
3308 /// \brief Matches any argument of a call expression or a constructor call
3313 /// void x(int, int, int) { int y; x(1, y, 42); }
3315 /// callExpr(hasAnyArgument(declRefExpr()))
3316 /// matches x(1, y, 42)
3317 /// with hasAnyArgument(...)
3319 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3320 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3322 internal::Matcher<Expr>, InnerMatcher) {
3323 for (const Expr *Arg : Node.arguments()) {
3324 BoundNodesTreeBuilder Result(*Builder);
3325 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3326 *Builder = std::move(Result);
3333 /// \brief Matches a constructor call expression which uses list initialization.
3334 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3335 return Node.isListInitialization();
3338 /// \brief Matches a constructor call expression which requires
3339 /// zero initialization.
3344 /// struct point { double x; double y; };
3345 /// point pt[2] = { { 1.0, 2.0 } };
3348 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3349 /// will match the implicit array filler for pt[1].
3350 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3351 return Node.requiresZeroInitialization();
3354 /// \brief Matches the n'th parameter of a function declaration.
3358 /// class X { void f(int x) {} };
3360 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3361 /// matches f(int x) {}
3362 /// with hasParameter(...)
3364 AST_MATCHER_P2(FunctionDecl, hasParameter,
3365 unsigned, N, internal::Matcher<ParmVarDecl>,
3367 return (N < Node.getNumParams() &&
3368 InnerMatcher.matches(
3369 *Node.getParamDecl(N), Finder, Builder));
3372 /// \brief Matches all arguments and their respective ParmVarDecl.
3381 /// forEachArgumentWithParam(
3382 /// declRefExpr(to(varDecl(hasName("y")))),
3383 /// parmVarDecl(hasType(isInteger()))
3386 /// with declRefExpr(...)
3388 /// and parmVarDecl(...)
3390 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3391 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3393 internal::Matcher<Expr>, ArgMatcher,
3394 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3395 BoundNodesTreeBuilder Result;
3396 // The first argument of an overloaded member operator is the implicit object
3397 // argument of the method which should not be matched against a parameter, so
3398 // we skip over it here.
3399 BoundNodesTreeBuilder Matches;
3400 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3401 .matches(Node, Finder, &Matches)
3405 bool Matched = false;
3406 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3407 BoundNodesTreeBuilder ArgMatches(*Builder);
3408 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3409 Finder, &ArgMatches)) {
3410 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3411 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3412 hasParameter(ParamIndex, ParamMatcher)))),
3413 callExpr(callee(functionDecl(
3414 hasParameter(ParamIndex, ParamMatcher))))))
3415 .matches(Node, Finder, &ParamMatches)) {
3416 Result.addMatch(ParamMatches);
3422 *Builder = std::move(Result);
3426 /// \brief Matches any parameter of a function declaration.
3428 /// Does not match the 'this' parameter of a method.
3432 /// class X { void f(int x, int y, int z) {} };
3434 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3435 /// matches f(int x, int y, int z) {}
3436 /// with hasAnyParameter(...)
3438 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
3439 internal::Matcher<ParmVarDecl>, InnerMatcher) {
3440 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3441 Node.param_end(), Finder, Builder);
3444 /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3445 /// specific parameter count.
3449 /// void f(int i) {}
3450 /// void g(int i, int j) {}
3451 /// void h(int i, int j);
3453 /// void k(int x, int y, int z, ...);
3455 /// functionDecl(parameterCountIs(2))
3456 /// matches void g(int i, int j) {}
3457 /// functionProtoType(parameterCountIs(2))
3458 /// matches void h(int i, int j)
3459 /// functionProtoType(parameterCountIs(3))
3460 /// matches void k(int x, int y, int z, ...);
3461 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3462 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3465 return Node.getNumParams() == N;
3468 /// \brief Matches the return type of a function declaration.
3472 /// class X { int f() { return 1; } };
3474 /// cxxMethodDecl(returns(asString("int")))
3475 /// matches int f() { return 1; }
3476 AST_MATCHER_P(FunctionDecl, returns,
3477 internal::Matcher<QualType>, InnerMatcher) {
3478 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3481 /// \brief Matches extern "C" function declarations.
3485 /// extern "C" void f() {}
3486 /// extern "C" { void g() {} }
3489 /// functionDecl(isExternC())
3490 /// matches the declaration of f and g, but not the declaration h
3491 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3493 return Node.isExternC();
3496 /// \brief Matches variable/function declarations that have "static" storage
3497 /// class specifier ("static" keyword) written in the source.
3501 /// static void f() {}
3502 /// static int i = 0;
3506 /// functionDecl(isStaticStorageClass())
3507 /// matches the function declaration f.
3508 /// varDecl(isStaticStorageClass())
3509 /// matches the variable declaration i.
3510 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
3511 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3513 return Node.getStorageClass() == SC_Static;
3516 /// \brief Matches deleted function declarations.
3521 /// void DeletedFunc() = delete;
3523 /// functionDecl(isDeleted())
3524 /// matches the declaration of DeletedFunc, but not Func.
3525 AST_MATCHER(FunctionDecl, isDeleted) {
3526 return Node.isDeleted();
3529 /// \brief Matches defaulted function declarations.
3533 /// class A { ~A(); };
3534 /// class B { ~B() = default; };
3536 /// functionDecl(isDefaulted())
3537 /// matches the declaration of ~B, but not ~A.
3538 AST_MATCHER(FunctionDecl, isDefaulted) {
3539 return Node.isDefaulted();
3542 /// \brief Matches functions that have a dynamic exception specification.
3547 /// void g() noexcept;
3548 /// void h() noexcept(true);
3549 /// void i() noexcept(false);
3550 /// void j() throw();
3551 /// void k() throw(int);
3552 /// void l() throw(...);
3554 /// functionDecl(hasDynamicExceptionSpec()) and
3555 /// functionProtoType(hasDynamicExceptionSpec())
3556 /// match the declarations of j, k, and l, but not f, g, h, or i.
3557 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
3558 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3559 FunctionProtoType)) {
3560 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
3561 return FnTy->hasDynamicExceptionSpec();
3565 /// \brief Matches functions that have a non-throwing exception specification.
3570 /// void g() noexcept;
3571 /// void h() throw();
3572 /// void i() throw(int);
3573 /// void j() noexcept(false);
3575 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
3576 /// match the declarations of g, and h, but not f, i or j.
3577 AST_POLYMORPHIC_MATCHER(isNoThrow,
3578 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3579 FunctionProtoType)) {
3580 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
3582 // If the function does not have a prototype, then it is assumed to be a
3583 // throwing function (as it would if the function did not have any exception
3588 // Assume the best for any unresolved exception specification.
3589 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3592 return FnTy->isNothrow(Finder->getASTContext());
3595 /// \brief Matches constexpr variable and function declarations.
3599 /// constexpr int foo = 42;
3600 /// constexpr int bar();
3602 /// varDecl(isConstexpr())
3603 /// matches the declaration of foo.
3604 /// functionDecl(isConstexpr())
3605 /// matches the declaration of bar.
3606 AST_POLYMORPHIC_MATCHER(isConstexpr,
3607 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3609 return Node.isConstexpr();
3612 /// \brief Matches the condition expression of an if statement, for loop,
3613 /// switch statement or conditional operator.
3615 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3619 AST_POLYMORPHIC_MATCHER_P(
3621 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3622 SwitchStmt, AbstractConditionalOperator),
3623 internal::Matcher<Expr>, InnerMatcher) {
3624 const Expr *const Condition = Node.getCond();
3625 return (Condition != nullptr &&
3626 InnerMatcher.matches(*Condition, Finder, Builder));
3629 /// \brief Matches the then-statement of an if statement.
3631 /// Examples matches the if statement
3632 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3634 /// if (false) true; else false;
3636 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3637 const Stmt *const Then = Node.getThen();
3638 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3641 /// \brief Matches the else-statement of an if statement.
3643 /// Examples matches the if statement
3644 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3646 /// if (false) false; else true;
3648 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3649 const Stmt *const Else = Node.getElse();
3650 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3653 /// \brief Matches if a node equals a previously bound node.
3655 /// Matches a node if it equals the node previously bound to \p ID.
3659 /// class X { int a; int b; };
3662 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3663 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3664 /// matches the class \c X, as \c a and \c b have the same type.
3666 /// Note that when multiple matches are involved via \c forEach* matchers,
3667 /// \c equalsBoundNodes acts as a filter.
3670 /// forEachDescendant(varDecl().bind("d")),
3671 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3672 /// will trigger a match for each combination of variable declaration
3673 /// and reference to that variable declaration within a compound statement.
3674 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3675 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3678 // FIXME: Figure out whether it makes sense to allow this
3679 // on any other node types.
3680 // For *Loc it probably does not make sense, as those seem
3681 // unique. For NestedNameSepcifier it might make sense, as
3682 // those also have pointer identity, but I'm not sure whether
3683 // they're ever reused.
3684 internal::NotEqualsBoundNodePredicate Predicate;
3686 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3687 return Builder->removeBindings(Predicate);
3690 /// \brief Matches the condition variable statement in an if statement.
3694 /// if (A* a = GetAPointer()) {}
3696 /// hasConditionVariableStatement(...)
3697 /// matches 'A* a = GetAPointer()'.
3698 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3699 internal::Matcher<DeclStmt>, InnerMatcher) {
3700 const DeclStmt* const DeclarationStatement =
3701 Node.getConditionVariableDeclStmt();
3702 return DeclarationStatement != nullptr &&
3703 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3706 /// \brief Matches the index expression of an array subscript expression.
3711 /// void f() { i[1] = 42; }
3713 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3714 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3715 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3716 internal::Matcher<Expr>, InnerMatcher) {
3717 if (const Expr* Expression = Node.getIdx())
3718 return InnerMatcher.matches(*Expression, Finder, Builder);
3722 /// \brief Matches the base expression of an array subscript expression.
3727 /// void f() { i[1] = 42; }
3729 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3730 /// hasSourceExpression(declRefExpr()))))
3731 /// matches \c i[1] with the \c declRefExpr() matching \c i
3732 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3733 internal::Matcher<Expr>, InnerMatcher) {
3734 if (const Expr* Expression = Node.getBase())
3735 return InnerMatcher.matches(*Expression, Finder, Builder);
3739 /// \brief Matches a 'for', 'while', 'do while' statement or a function
3740 /// definition that has a given body.
3746 /// hasBody(compoundStmt())
3747 /// matches 'for (;;) {}'
3748 /// with compoundStmt()
3750 AST_POLYMORPHIC_MATCHER_P(hasBody,
3751 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3755 internal::Matcher<Stmt>, InnerMatcher) {
3756 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
3757 return (Statement != nullptr &&
3758 InnerMatcher.matches(*Statement, Finder, Builder));
3761 /// \brief Matches compound statements where at least one substatement matches
3762 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
3768 /// hasAnySubstatement(compoundStmt())
3769 /// matches '{ {}; 1+2; }'
3770 /// with compoundStmt()
3772 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
3773 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
3775 internal::Matcher<Stmt>, InnerMatcher) {
3776 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
3777 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
3778 CS->body_end(), Finder, Builder);
3781 /// \brief Checks that a compound statement contains a specific number of
3782 /// child statements.
3788 /// compoundStmt(statementCountIs(0)))
3790 /// but does not match the outer compound statement.
3791 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3792 return Node.size() == N;
3795 /// \brief Matches literals that are equal to the given value.
3797 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3802 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3803 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3804 template <typename ValueT>
3805 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3806 equals(const ValueT &Value) {
3807 return internal::PolymorphicMatcherWithParam1<
3808 internal::ValueEqualsMatcher,
3812 /// \brief Matches the operator Name of operator expressions (binary or
3815 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3819 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3820 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3822 std::string, Name) {
3823 return Name == Node.getOpcodeStr(Node.getOpcode());
3826 /// \brief Matches the left hand side of binary operator expressions.
3828 /// Example matches a (matcher = binaryOperator(hasLHS()))
3832 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3833 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3834 ArraySubscriptExpr),
3835 internal::Matcher<Expr>, InnerMatcher) {
3836 const Expr *LeftHandSide = Node.getLHS();
3837 return (LeftHandSide != nullptr &&
3838 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3841 /// \brief Matches the right hand side of binary operator expressions.
3843 /// Example matches b (matcher = binaryOperator(hasRHS()))
3847 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3848 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3849 ArraySubscriptExpr),
3850 internal::Matcher<Expr>, InnerMatcher) {
3851 const Expr *RightHandSide = Node.getRHS();
3852 return (RightHandSide != nullptr &&
3853 InnerMatcher.matches(*RightHandSide, Finder, Builder));
3856 /// \brief Matches if either the left hand side or the right hand side of a
3857 /// binary operator matches.
3858 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3859 const internal::Matcher<Expr> &InnerMatcher) {
3860 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3863 /// \brief Matches if the operand of a unary operator matches.
3865 /// Example matches true (matcher = hasUnaryOperand(
3866 /// cxxBoolLiteral(equals(true))))
3870 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3871 internal::Matcher<Expr>, InnerMatcher) {
3872 const Expr * const Operand = Node.getSubExpr();
3873 return (Operand != nullptr &&
3874 InnerMatcher.matches(*Operand, Finder, Builder));
3877 /// \brief Matches if the cast's source expression
3878 /// or opaque value's source expression matches the given matcher.
3880 /// Example 1: matches "a string"
3881 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
3883 /// class URL { URL(string); };
3884 /// URL url = "a string";
3887 /// Example 2: matches 'b' (matcher =
3888 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
3893 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
3894 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
3896 internal::Matcher<Expr>, InnerMatcher) {
3897 const Expr *const SubExpression =
3898 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
3899 return (SubExpression != nullptr &&
3900 InnerMatcher.matches(*SubExpression, Finder, Builder));
3903 /// \brief Matches casts that has a given cast kind.
3905 /// Example: matches the implicit cast around \c 0
3906 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
3910 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
3911 return Node.getCastKind() == Kind;
3914 /// \brief Matches casts whose destination type matches a given matcher.
3916 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3917 /// actual casts "explicit" casts.)
3918 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3919 internal::Matcher<QualType>, InnerMatcher) {
3920 const QualType NodeType = Node.getTypeAsWritten();
3921 return InnerMatcher.matches(NodeType, Finder, Builder);
3924 /// \brief Matches implicit casts whose destination type matches a given
3927 /// FIXME: Unit test this matcher
3928 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3929 internal::Matcher<QualType>, InnerMatcher) {
3930 return InnerMatcher.matches(Node.getType(), Finder, Builder);
3933 /// \brief Matches RecordDecl object that are spelled with "struct."
3935 /// Example matches S, but not C or U.
3941 AST_MATCHER(RecordDecl, isStruct) {
3942 return Node.isStruct();
3945 /// \brief Matches RecordDecl object that are spelled with "union."
3947 /// Example matches U, but not C or S.
3953 AST_MATCHER(RecordDecl, isUnion) {
3954 return Node.isUnion();
3957 /// \brief Matches RecordDecl object that are spelled with "class."
3959 /// Example matches C, but not S or U.
3965 AST_MATCHER(RecordDecl, isClass) {
3966 return Node.isClass();
3969 /// \brief Matches the true branch expression of a conditional operator.
3971 /// Example 1 (conditional ternary operator): matches a
3973 /// condition ? a : b
3976 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
3980 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
3981 internal::Matcher<Expr>, InnerMatcher) {
3982 const Expr *Expression = Node.getTrueExpr();
3983 return (Expression != nullptr &&
3984 InnerMatcher.matches(*Expression, Finder, Builder));
3987 /// \brief Matches the false branch expression of a conditional operator
3988 /// (binary or ternary).
3990 /// Example matches b
3992 /// condition ? a : b
3995 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
3996 internal::Matcher<Expr>, InnerMatcher) {
3997 const Expr *Expression = Node.getFalseExpr();
3998 return (Expression != nullptr &&
3999 InnerMatcher.matches(*Expression, Finder, Builder));
4002 /// \brief Matches if a declaration has a body attached.
4004 /// Example matches A, va, fa
4007 /// class B; // Doesn't match, as it has no body.
4009 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4011 /// void fb(); // Doesn't match, as it has no body.
4014 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
4015 AST_POLYMORPHIC_MATCHER(isDefinition,
4016 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4018 return Node.isThisDeclarationADefinition();
4021 /// \brief Matches if a function declaration is variadic.
4023 /// Example matches f, but not g or h. The function i will not match, even when
4024 /// compiled in C mode.
4028 /// template <typename... Ts> void h(Ts...);
4031 AST_MATCHER(FunctionDecl, isVariadic) {
4032 return Node.isVariadic();
4035 /// \brief Matches the class declaration that the given method declaration
4038 /// FIXME: Generalize this for other kinds of declarations.
4039 /// FIXME: What other kind of declarations would we need to generalize
4042 /// Example matches A() in the last line
4043 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4044 /// ofClass(hasName("A"))))))
4052 AST_MATCHER_P(CXXMethodDecl, ofClass,
4053 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4054 const CXXRecordDecl *Parent = Node.getParent();
4055 return (Parent != nullptr &&
4056 InnerMatcher.matches(*Parent, Finder, Builder));
4059 /// \brief Matches each method overriden by the given method. This matcher may
4060 /// produce multiple matches.
4064 /// class A { virtual void f(); };
4065 /// class B : public A { void f(); };
4066 /// class C : public B { void f(); };
4068 /// cxxMethodDecl(ofClass(hasName("C")),
4069 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4070 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4071 /// that B::f is not overridden by C::f).
4073 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4075 /// class A1 { virtual void f(); };
4076 /// class A2 { virtual void f(); };
4077 /// class C : public A1, public A2 { void f(); };
4079 /// cxxMethodDecl(ofClass(hasName("C")),
4080 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4081 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4082 /// once with "b" binding "A2::f" and "d" binding "C::f".
4083 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4084 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4085 BoundNodesTreeBuilder Result;
4086 bool Matched = false;
4087 for (const auto *Overridden : Node.overridden_methods()) {
4088 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4089 const bool OverriddenMatched =
4090 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4091 if (OverriddenMatched) {
4093 Result.addMatch(OverriddenBuilder);
4096 *Builder = std::move(Result);
4100 /// \brief Matches if the given method declaration is virtual.
4106 /// virtual void x();
4110 AST_MATCHER(CXXMethodDecl, isVirtual) {
4111 return Node.isVirtual();
4114 /// \brief Matches if the given method declaration has an explicit "virtual".
4120 /// virtual void x();
4122 /// class B : public A {
4127 /// matches A::x but not B::x
4128 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4129 return Node.isVirtualAsWritten();
4132 /// \brief Matches if the given method or class declaration is final.
4136 /// class A final {};
4139 /// virtual void f();
4146 /// matches A and C::f, but not B, C, or B::f
4147 AST_POLYMORPHIC_MATCHER(isFinal,
4148 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4150 return Node.template hasAttr<FinalAttr>();
4153 /// \brief Matches if the given method declaration is pure.
4159 /// virtual void x() = 0;
4163 AST_MATCHER(CXXMethodDecl, isPure) {
4164 return Node.isPure();
4167 /// \brief Matches if the given method declaration is const.
4172 /// void foo() const;
4177 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4178 AST_MATCHER(CXXMethodDecl, isConst) {
4179 return Node.isConst();
4182 /// \brief Matches if the given method declaration declares a copy assignment
4188 /// A &operator=(const A &);
4189 /// A &operator=(A &&);
4193 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4195 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4196 return Node.isCopyAssignmentOperator();
4199 /// \brief Matches if the given method declaration declares a move assignment
4205 /// A &operator=(const A &);
4206 /// A &operator=(A &&);
4210 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4212 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4213 return Node.isMoveAssignmentOperator();
4216 /// \brief Matches if the given method declaration overrides another method.
4222 /// virtual void x();
4224 /// class B : public A {
4226 /// virtual void x();
4230 AST_MATCHER(CXXMethodDecl, isOverride) {
4231 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4234 /// \brief Matches method declarations that are user-provided.
4240 /// S(const S &) = default; // #2
4241 /// S(S &&) = delete; // #3
4244 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4245 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4246 return Node.isUserProvided();
4249 /// \brief Matches member expressions that are called with '->' as opposed
4252 /// Member calls on the implicit this pointer match as called with '->'.
4257 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4262 /// memberExpr(isArrow())
4263 /// matches this->x, x, y.x, a, this->b
4264 AST_MATCHER(MemberExpr, isArrow) {
4265 return Node.isArrow();
4268 /// \brief Matches QualType nodes that are of integer type.
4276 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4277 /// matches "a(int)", "b(long)", but not "c(double)".
4278 AST_MATCHER(QualType, isInteger) {
4279 return Node->isIntegerType();
4282 /// \brief Matches QualType nodes that are of unsigned integer type.
4287 /// void b(unsigned long);
4290 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4291 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4292 AST_MATCHER(QualType, isUnsignedInteger) {
4293 return Node->isUnsignedIntegerType();
4296 /// \brief Matches QualType nodes that are of signed integer type.
4301 /// void b(unsigned long);
4304 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4305 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4306 AST_MATCHER(QualType, isSignedInteger) {
4307 return Node->isSignedIntegerType();
4310 /// \brief Matches QualType nodes that are of character type.
4315 /// void b(wchar_t);
4318 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4319 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4320 AST_MATCHER(QualType, isAnyCharacter) {
4321 return Node->isAnyCharacterType();
4324 /// \brief Matches QualType nodes that are of any pointer type; this includes
4325 /// the Objective-C object pointer type, which is different despite being
4326 /// syntactically similar.
4330 /// int *i = nullptr;
4338 /// varDecl(hasType(isAnyPointer()))
4339 /// matches "int *i" and "Foo *f", but not "int j".
4340 AST_MATCHER(QualType, isAnyPointer) {
4341 return Node->isAnyPointerType();
4344 /// \brief Matches QualType nodes that are const-qualified, i.e., that
4345 /// include "top-level" const.
4350 /// void b(int const);
4351 /// void c(const int);
4352 /// void d(const int*);
4353 /// void e(int const) {};
4355 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4356 /// matches "void b(int const)", "void c(const int)" and
4357 /// "void e(int const) {}". It does not match d as there
4358 /// is no top-level const on the parameter type "const int *".
4359 AST_MATCHER(QualType, isConstQualified) {
4360 return Node.isConstQualified();
4363 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
4364 /// include "top-level" volatile.
4369 /// void b(int volatile);
4370 /// void c(volatile int);
4371 /// void d(volatile int*);
4372 /// void e(int volatile) {};
4374 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4375 /// matches "void b(int volatile)", "void c(volatile int)" and
4376 /// "void e(int volatile) {}". It does not match d as there
4377 /// is no top-level volatile on the parameter type "volatile int *".
4378 AST_MATCHER(QualType, isVolatileQualified) {
4379 return Node.isVolatileQualified();
4382 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
4383 /// the node, not hidden within a typedef.
4387 /// typedef const int const_int;
4390 /// int *volatile k;
4393 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4394 /// \c i is const-qualified but the qualifier is not local.
4395 AST_MATCHER(QualType, hasLocalQualifiers) {
4396 return Node.hasLocalQualifiers();
4399 /// \brief Matches a member expression where the member is matched by a
4404 /// struct { int first, second; } first, second;
4405 /// int i(second.first);
4406 /// int j(first.second);
4408 /// memberExpr(member(hasName("first")))
4409 /// matches second.first
4410 /// but not first.second (because the member name there is "second").
4411 AST_MATCHER_P(MemberExpr, member,
4412 internal::Matcher<ValueDecl>, InnerMatcher) {
4413 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4416 /// \brief Matches a member expression where the object expression is
4417 /// matched by a given matcher.
4421 /// struct X { int m; };
4422 /// void f(X x) { x.m; m; }
4424 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4425 /// matches "x.m" and "m"
4426 /// with hasObjectExpression(...)
4427 /// matching "x" and the implicit object expression of "m" which has type X*.
4428 AST_MATCHER_P(MemberExpr, hasObjectExpression,
4429 internal::Matcher<Expr>, InnerMatcher) {
4430 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4433 /// \brief Matches any using shadow declaration.
4437 /// namespace X { void b(); }
4440 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
4441 /// matches \code using X::b \endcode
4442 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
4443 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4444 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
4445 Node.shadow_end(), Finder, Builder);
4448 /// \brief Matches a using shadow declaration where the target declaration is
4449 /// matched by the given matcher.
4453 /// namespace X { int a; void b(); }
4457 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
4458 /// matches \code using X::b \endcode
4459 /// but not \code using X::a \endcode
4460 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
4461 internal::Matcher<NamedDecl>, InnerMatcher) {
4462 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
4465 /// \brief Matches template instantiations of function, class, or static
4466 /// member variable template instantiations.
4470 /// template <typename T> class X {}; class A {}; X<A> x;
4474 /// template <typename T> class X {}; class A {}; template class X<A>;
4476 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4477 /// matches the template instantiation of X<A>.
4481 /// template <typename T> class X {}; class A {};
4482 /// template <> class X<A> {}; X<A> x;
4484 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4485 /// does not match, as X<A> is an explicit template specialization.
4487 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4488 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4489 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4491 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4492 Node.getTemplateSpecializationKind() ==
4493 TSK_ExplicitInstantiationDefinition);
4496 /// \brief Matches declarations that are template instantiations or are inside
4497 /// template instantiations.
4501 /// template<typename T> void A(T t) { T i; }
4505 /// functionDecl(isInstantiated())
4506 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
4507 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4508 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4509 functionDecl(isTemplateInstantiation())));
4510 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4513 /// \brief Matches statements inside of a template instantiation.
4518 /// template<typename T> void A(T t) { T i; j += 42;}
4522 /// declStmt(isInTemplateInstantiation())
4523 /// matches 'int i;' and 'unsigned i'.
4524 /// unless(stmt(isInTemplateInstantiation()))
4525 /// will NOT match j += 42; as it's shared between the template definition and
4527 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4529 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4530 functionDecl(isTemplateInstantiation())))));
4533 /// \brief Matches explicit template specializations of function, class, or
4534 /// static member variable template instantiations.
4538 /// template<typename T> void A(T t) { }
4539 /// template<> void A(int N) { }
4541 /// functionDecl(isExplicitTemplateSpecialization())
4542 /// matches the specialization A<int>().
4544 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4545 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4546 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4548 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4551 /// \brief Matches \c TypeLocs for which the given inner
4552 /// QualType-matcher matches.
4553 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4554 internal::Matcher<QualType>, InnerMatcher, 0) {
4555 return internal::BindableMatcher<TypeLoc>(
4556 new internal::TypeLocTypeMatcher(InnerMatcher));
4559 /// \brief Matches type \c bool.
4563 /// struct S { bool func(); };
4565 /// functionDecl(returns(booleanType()))
4566 /// matches "bool func();"
4567 AST_MATCHER(Type, booleanType) {
4568 return Node.isBooleanType();
4571 /// \brief Matches type \c void.
4575 /// struct S { void func(); };
4577 /// functionDecl(returns(voidType()))
4578 /// matches "void func();"
4579 AST_MATCHER(Type, voidType) {
4580 return Node.isVoidType();
4583 /// \brief Matches builtin Types.
4594 /// matches "int b", "float c" and "bool d"
4595 AST_TYPE_MATCHER(BuiltinType, builtinType);
4597 /// \brief Matches all kinds of arrays.
4601 /// int a[] = { 2, 3 };
4603 /// void f() { int c[a[0]]; }
4606 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4607 AST_TYPE_MATCHER(ArrayType, arrayType);
4609 /// \brief Matches C99 complex types.
4613 /// _Complex float f;
4616 /// matches "_Complex float f"
4617 AST_TYPE_MATCHER(ComplexType, complexType);
4619 /// \brief Matches any real floating-point type (float, double, long double).
4626 /// realFloatingPointType()
4627 /// matches "float f" but not "int i"
4628 AST_MATCHER(Type, realFloatingPointType) {
4629 return Node.isRealFloatingType();
4632 /// \brief Matches arrays and C99 complex types that have a specific element
4641 /// arrayType(hasElementType(builtinType()))
4642 /// matches "int b[7]"
4644 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
4645 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
4646 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
4649 /// \brief Matches C arrays with a specified constant size.
4655 /// int b[] = { 2, 3 };
4659 /// constantArrayType()
4660 /// matches "int a[2]"
4661 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
4663 /// \brief Matches nodes that have the specified size.
4669 /// int c[41], d[43];
4670 /// char *s = "abcd";
4671 /// wchar_t *ws = L"abcd";
4674 /// constantArrayType(hasSize(42))
4675 /// matches "int a[42]" and "int b[2 * 21]"
4676 /// stringLiteral(hasSize(4))
4677 /// matches "abcd", L"abcd"
4678 AST_POLYMORPHIC_MATCHER_P(hasSize,
4679 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
4682 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
4685 /// \brief Matches C++ arrays whose size is a value-dependent expression.
4689 /// template<typename T, int Size>
4694 /// dependentSizedArrayType
4695 /// matches "T data[Size]"
4696 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
4698 /// \brief Matches C arrays with unspecified size.
4702 /// int a[] = { 2, 3 };
4704 /// void f(int c[]) { int d[a[0]]; };
4706 /// incompleteArrayType()
4707 /// matches "int a[]" and "int c[]"
4708 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
4710 /// \brief Matches C arrays with a specified size that is not an
4711 /// integer-constant-expression.
4716 /// int a[] = { 2, 3 }
4721 /// variableArrayType()
4722 /// matches "int c[a[0]]"
4723 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
4725 /// \brief Matches \c VariableArrayType nodes that have a specific size
4734 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4735 /// varDecl(hasName("b")))))))
4736 /// matches "int a[b]"
4737 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
4738 internal::Matcher<Expr>, InnerMatcher) {
4739 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
4742 /// \brief Matches atomic types.
4749 /// matches "_Atomic(int) i"
4750 AST_TYPE_MATCHER(AtomicType, atomicType);
4752 /// \brief Matches atomic types with a specific value type.
4757 /// _Atomic(float) f;
4759 /// atomicType(hasValueType(isInteger()))
4760 /// matches "_Atomic(int) i"
4762 /// Usable as: Matcher<AtomicType>
4763 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
4764 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
4766 /// \brief Matches types nodes representing C++11 auto types.
4771 /// int v[] = { 2, 3 }
4772 /// for (auto i : v) { }
4775 /// matches "auto n" and "auto i"
4776 AST_TYPE_MATCHER(AutoType, autoType);
4778 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
4780 /// Note: There is no \c TypeLoc for the deduced type and thus no
4781 /// \c getDeducedLoc() matcher.
4788 /// autoType(hasDeducedType(isInteger()))
4789 /// matches "auto a"
4791 /// Usable as: Matcher<AutoType>
4792 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
4793 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
4795 /// \brief Matches \c FunctionType nodes.
4803 /// matches "int (*f)(int)" and the type of "g".
4804 AST_TYPE_MATCHER(FunctionType, functionType);
4806 /// \brief Matches \c FunctionProtoType nodes.
4813 /// functionProtoType()
4814 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
4815 /// In C mode, "g" is not matched because it does not contain a prototype.
4816 AST_TYPE_MATCHER(FunctionProtoType, functionProtoType);
4818 /// \brief Matches \c ParenType nodes.
4822 /// int (*ptr_to_array)[4];
4823 /// int *array_of_ptrs[4];
4826 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4827 /// \c array_of_ptrs.
4828 AST_TYPE_MATCHER(ParenType, parenType);
4830 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4834 /// int (*ptr_to_array)[4];
4835 /// int (*ptr_to_func)(int);
4838 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4839 /// \c ptr_to_func but not \c ptr_to_array.
4841 /// Usable as: Matcher<ParenType>
4842 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4843 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4845 /// \brief Matches block pointer types, i.e. types syntactically represented as
4846 /// "void (^)(int)".
4848 /// The \c pointee is always required to be a \c FunctionType.
4849 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4851 /// \brief Matches member pointer types.
4854 /// struct A { int i; }
4855 /// A::* ptr = A::i;
4857 /// memberPointerType()
4858 /// matches "A::* ptr"
4859 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4861 /// \brief Matches pointer types, but does not match Objective-C object pointer
4875 /// matches "int *a", but does not match "Foo *f".
4876 AST_TYPE_MATCHER(PointerType, pointerType);
4878 /// \brief Matches an Objective-C object pointer type, which is different from
4879 /// a pointer type, despite being syntactically similar.
4890 /// matches "Foo *f", but does not match "int *a".
4891 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4893 /// \brief Matches both lvalue and rvalue reference types.
4906 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4907 AST_TYPE_MATCHER(ReferenceType, referenceType);
4909 /// \brief Matches lvalue reference types.
4922 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4923 /// matched since the type is deduced as int& by reference collapsing rules.
4924 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4926 /// \brief Matches rvalue reference types.
4939 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4940 /// matched as it is deduced to int& by reference collapsing rules.
4941 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4943 /// \brief Narrows PointerType (and similar) matchers to those where the
4944 /// \c pointee matches a given matcher.
4952 /// pointerType(pointee(isConstQualified(), isInteger()))
4953 /// matches "int const *b"
4955 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4956 /// Matcher<PointerType>, Matcher<ReferenceType>
4957 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4958 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4963 /// \brief Matches typedef types.
4970 /// matches "typedef int X"
4971 AST_TYPE_MATCHER(TypedefType, typedefType);
4973 /// \brief Matches enum types.
4977 /// enum C { Green };
4978 /// enum class S { Red };
4984 /// \c enumType() matches the type of the variable declarations of both \c c and
4986 AST_TYPE_MATCHER(EnumType, enumType);
4988 /// \brief Matches template specialization types.
4992 /// template <typename T>
4995 /// template class C<int>; // A
4996 /// C<char> var; // B
4999 /// \c templateSpecializationType() matches the type of the explicit
5000 /// instantiation in \c A and the type of the variable declaration in \c B.
5001 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
5003 /// \brief Matches types nodes representing unary type transformations.
5007 /// typedef __underlying_type(T) type;
5009 /// unaryTransformType()
5010 /// matches "__underlying_type(T)"
5011 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
5013 /// \brief Matches record types (e.g. structs, classes).
5024 /// \c recordType() matches the type of the variable declarations of both \c c
5026 AST_TYPE_MATCHER(RecordType, recordType);
5028 /// \brief Matches types specified with an elaborated type keyword or with a
5044 /// \c elaboratedType() matches the type of the variable declarations of both
5046 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
5048 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5049 /// matches \c InnerMatcher if the qualifier exists.
5061 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5062 /// matches the type of the variable declaration of \c d.
5063 AST_MATCHER_P(ElaboratedType, hasQualifier,
5064 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5065 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5066 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5071 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5083 /// \c elaboratedType(namesType(recordType(
5084 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5085 /// declaration of \c d.
5086 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5088 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5091 /// \brief Matches types that represent the result of substituting a type for a
5092 /// template type parameter.
5096 /// template <typename T>
5102 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5103 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
5105 /// \brief Matches template type parameter substitutions that have a replacement
5106 /// type that matches the provided matcher.
5110 /// template <typename T>
5113 /// double j = F(i);
5116 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5117 AST_TYPE_TRAVERSE_MATCHER(
5118 hasReplacementType, getReplacementType,
5119 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5121 /// \brief Matches template type parameter types.
5123 /// Example matches T, but not int.
5124 /// (matcher = templateTypeParmType())
5126 /// template <typename T> void f(int i);
5128 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
5130 /// \brief Matches injected class name types.
5132 /// Example matches S s, but not S<T> s.
5133 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5135 /// template <typename T> struct S {
5140 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
5142 /// \brief Matches decayed type
5143 /// Example matches i[] in declaration of f.
5144 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5145 /// Example matches i[1].
5146 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5148 /// void f(int i[]) {
5152 AST_TYPE_MATCHER(DecayedType, decayedType);
5154 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
5155 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5157 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5160 /// \brief Matches declarations whose declaration context, interpreted as a
5161 /// Decl, matches \c InnerMatcher.
5172 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5173 /// declaration of \c class \c D.
5174 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5175 const DeclContext *DC = Node.getDeclContext();
5176 if (!DC) return false;
5177 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5180 /// \brief Matches nested name specifiers.
5185 /// struct A { static void f(); };
5187 /// void g() { A::f(); }
5191 /// nestedNameSpecifier()
5192 /// matches "ns::" and both "A::"
5193 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
5195 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5196 const internal::VariadicAllOfMatcher<
5197 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
5199 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
5200 /// NestedNameSpecifier-matcher matches.
5201 AST_MATCHER_FUNCTION_P_OVERLOAD(
5202 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5203 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5204 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5205 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5209 /// \brief Matches nested name specifiers that specify a type matching the
5210 /// given \c QualType matcher without qualifiers.
5214 /// struct A { struct B { struct C {}; }; };
5217 /// nestedNameSpecifier(specifiesType(
5218 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5221 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5222 internal::Matcher<QualType>, InnerMatcher) {
5223 if (!Node.getAsType())
5225 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5228 /// \brief Matches nested name specifier locs that specify a type matching the
5229 /// given \c TypeLoc.
5233 /// struct A { struct B { struct C {}; }; };
5236 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5237 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5239 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5240 internal::Matcher<TypeLoc>, InnerMatcher) {
5241 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5244 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
5248 /// struct A { struct B { struct C {}; }; };
5251 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5253 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5254 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5256 const NestedNameSpecifier *NextNode = Node.getPrefix();
5259 return InnerMatcher.matches(*NextNode, Finder, Builder);
5262 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
5266 /// struct A { struct B { struct C {}; }; };
5269 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5271 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5272 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5274 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5277 return InnerMatcher.matches(NextNode, Finder, Builder);
5280 /// \brief Matches nested name specifiers that specify a namespace matching the
5281 /// given namespace matcher.
5285 /// namespace ns { struct A {}; }
5288 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5290 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5291 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5292 if (!Node.getAsNamespace())
5294 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5297 /// \brief Overloads for the \c equalsNode matcher.
5298 /// FIXME: Implement for other node types.
5301 /// \brief Matches if a node equals another node.
5303 /// \c Decl has pointer identity in the AST.
5304 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5305 return &Node == Other;
5307 /// \brief Matches if a node equals another node.
5309 /// \c Stmt has pointer identity in the AST.
5310 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5311 return &Node == Other;
5313 /// \brief Matches if a node equals another node.
5315 /// \c Type has pointer identity in the AST.
5316 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5317 return &Node == Other;
5322 /// \brief Matches each case or default statement belonging to the given switch
5323 /// statement. This matcher may produce multiple matches.
5327 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5329 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5330 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5331 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5332 /// "switch (1)", "switch (2)" and "switch (2)".
5333 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5335 BoundNodesTreeBuilder Result;
5336 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5337 // iteration order. We should use the more general iterating matchers once
5338 // they are capable of expressing this matcher (for example, it should ignore
5339 // case statements belonging to nested switch statements).
5340 bool Matched = false;
5341 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5342 SC = SC->getNextSwitchCase()) {
5343 BoundNodesTreeBuilder CaseBuilder(*Builder);
5344 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5347 Result.addMatch(CaseBuilder);
5350 *Builder = std::move(Result);
5354 /// \brief Matches each constructor initializer in a constructor definition.
5358 /// class A { A() : i(42), j(42) {} int i; int j; };
5360 /// cxxConstructorDecl(forEachConstructorInitializer(
5361 /// forField(decl().bind("x"))
5363 /// will trigger two matches, binding for 'i' and 'j' respectively.
5364 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5365 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5366 BoundNodesTreeBuilder Result;
5367 bool Matched = false;
5368 for (const auto *I : Node.inits()) {
5369 BoundNodesTreeBuilder InitBuilder(*Builder);
5370 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5372 Result.addMatch(InitBuilder);
5375 *Builder = std::move(Result);
5379 /// \brief Matches constructor declarations that are copy constructors.
5385 /// S(const S &); // #2
5389 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
5390 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
5391 return Node.isCopyConstructor();
5394 /// \brief Matches constructor declarations that are move constructors.
5400 /// S(const S &); // #2
5404 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
5405 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
5406 return Node.isMoveConstructor();
5409 /// \brief Matches constructor declarations that are default constructors.
5415 /// S(const S &); // #2
5419 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
5420 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
5421 return Node.isDefaultConstructor();
5424 /// \brief Matches constructors that delegate to another constructor.
5431 /// S(S &&) : S() {} // #3
5433 /// S::S() : S(0) {} // #4
5435 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
5437 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
5438 return Node.isDelegatingConstructor();
5441 /// \brief Matches constructor and conversion declarations that are marked with
5442 /// the explicit keyword.
5448 /// explicit S(double); // #2
5449 /// operator int(); // #3
5450 /// explicit operator bool(); // #4
5453 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
5454 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
5455 AST_POLYMORPHIC_MATCHER(isExplicit,
5456 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
5457 CXXConversionDecl)) {
5458 return Node.isExplicit();
5461 /// \brief Matches function and namespace declarations that are marked with
5462 /// the inline keyword.
5466 /// inline void f();
5469 /// inline namespace m {}
5472 /// functionDecl(isInline()) will match ::f().
5473 /// namespaceDecl(isInline()) will match n::m.
5474 AST_POLYMORPHIC_MATCHER(isInline,
5475 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
5477 // This is required because the spelling of the function used to determine
5478 // whether inline is specified or not differs between the polymorphic types.
5479 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
5480 return FD->isInlineSpecified();
5481 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
5482 return NSD->isInline();
5483 llvm_unreachable("Not a valid polymorphic type");
5486 /// \brief Matches anonymous namespace declarations.
5491 /// namespace {} // #1
5494 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
5495 AST_MATCHER(NamespaceDecl, isAnonymous) {
5496 return Node.isAnonymousNamespace();
5499 /// \brief If the given case statement does not use the GNU case range
5500 /// extension, matches the constant given in the statement.
5504 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
5506 /// caseStmt(hasCaseConstant(integerLiteral()))
5507 /// matches "case 1:"
5508 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
5513 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
5516 /// \brief Matches declaration that has a given attribute.
5520 /// __attribute__((device)) void f() { ... }
5522 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
5523 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
5524 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
5525 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
5526 for (const auto *Attr : Node.attrs()) {
5527 if (Attr->getKind() == AttrKind)
5533 /// \brief Matches the return value expression of a return statement
5539 /// hasReturnValue(binaryOperator())
5540 /// matches 'return a + b'
5541 /// with binaryOperator()
5542 /// matching 'a + b'
5543 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5545 if (const auto *RetValue = Node.getRetValue())
5546 return InnerMatcher.matches(*RetValue, Finder, Builder);
5551 /// \brief Matches CUDA kernel call expression.
5553 /// Example matches,
5555 /// kernel<<<i,j>>>();
5557 const internal::VariadicDynCastAllOfMatcher<
5559 CUDAKernelCallExpr> cudaKernelCallExpr;
5562 /// \brief Matches expressions that resolve to a null pointer constant, such as
5563 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5567 /// void *v1 = NULL;
5568 /// void *v2 = nullptr;
5569 /// void *v3 = __null; // GNU extension
5570 /// char *cp = (char *)0;
5574 /// expr(nullPointerConstant())
5575 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5576 /// initializer for i.
5577 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5579 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5580 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5583 /// \brief Matches declaration of the function the statement belongs to
5587 /// F& operator=(const F& o) {
5588 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
5592 /// returnStmt(forFunction(hasName("operator=")))
5593 /// matches 'return *this'
5594 /// but does match 'return > 0'
5595 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
5597 const auto &Parents = Finder->getASTContext().getParents(Node);
5599 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
5601 while(!Stack.empty()) {
5602 const auto &CurNode = Stack.back();
5604 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
5605 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
5608 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
5609 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
5614 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
5615 Stack.push_back(Parent);
5621 /// \brief Matches a declaration that has external formal linkage.
5623 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
5632 /// Example matches f() because it has external formal linkage despite being
5633 /// unique to the translation unit as though it has internal likage
5634 /// (matcher = functionDecl(hasExternalFormalLinkage()))
5641 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
5642 return Node.hasExternalFormalLinkage();
5645 } // end namespace ast_matchers
5646 } // end namespace clang