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 AST nodes that were expanded within the main-file.
185 /// Example matches X but not Y
186 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
196 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
197 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
198 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
199 auto &SourceManager = Finder->getASTContext().getSourceManager();
200 return SourceManager.isInMainFile(
201 SourceManager.getExpansionLoc(Node.getLocStart()));
204 /// \brief Matches AST nodes that were expanded within system-header-files.
206 /// Example matches Y but not X
207 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
209 /// #include <SystemHeader.h>
217 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
218 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
219 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
220 auto &SourceManager = Finder->getASTContext().getSourceManager();
221 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
222 if (ExpansionLoc.isInvalid()) {
225 return SourceManager.isInSystemHeader(ExpansionLoc);
228 /// \brief Matches AST nodes that were expanded within files whose name is
229 /// partially matching a given regex.
231 /// Example matches Y but not X
232 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
234 /// #include "ASTMatcher.h"
242 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
243 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
244 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
245 std::string, RegExp) {
246 auto &SourceManager = Finder->getASTContext().getSourceManager();
247 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
248 if (ExpansionLoc.isInvalid()) {
252 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
257 auto Filename = FileEntry->getName();
258 llvm::Regex RE(RegExp);
259 return RE.match(Filename);
262 /// \brief Matches declarations.
264 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
271 const internal::VariadicAllOfMatcher<Decl> decl;
273 /// \brief Matches a declaration of a linkage specification.
279 /// linkageSpecDecl()
280 /// matches "extern "C" {}"
281 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
284 /// \brief Matches a declaration of anything that could have a name.
286 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
295 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
297 /// \brief Matches a declaration of label.
306 const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
308 /// \brief Matches a declaration of a namespace.
313 /// namespace test {}
316 /// matches "namespace {}" and "namespace test {}"
317 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
319 /// \brief Matches a declaration of a namespace alias.
323 /// namespace test {}
324 /// namespace alias = ::test;
326 /// namespaceAliasDecl()
327 /// matches "namespace alias" but not "namespace test"
328 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
331 /// \brief Matches class, struct, and union declarations.
333 /// Example matches \c X, \c Z, \c U, and \c S
336 /// template<class T> class Z {};
340 const internal::VariadicDynCastAllOfMatcher<
342 RecordDecl> recordDecl;
344 /// \brief Matches C++ class declarations.
346 /// Example matches \c X, \c Z
349 /// template<class T> class Z {};
351 const internal::VariadicDynCastAllOfMatcher<
353 CXXRecordDecl> cxxRecordDecl;
355 /// \brief Matches C++ class template declarations.
357 /// Example matches \c Z
359 /// template<class T> class Z {};
361 const internal::VariadicDynCastAllOfMatcher<
363 ClassTemplateDecl> classTemplateDecl;
365 /// \brief Matches C++ class template specializations.
369 /// template<typename T> class A {};
370 /// template<> class A<double> {};
373 /// classTemplateSpecializationDecl()
374 /// matches the specializations \c A<int> and \c A<double>
375 const internal::VariadicDynCastAllOfMatcher<
377 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
379 /// \brief Matches declarator declarations (field, variable, function
380 /// and non-type template parameter declarations).
384 /// class X { int y; };
387 /// matches \c int y.
388 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
391 /// \brief Matches parameter variable declarations.
398 /// matches \c int x.
399 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
401 /// \brief Matches C++ access specifier declarations.
411 /// matches 'public:'
412 const internal::VariadicDynCastAllOfMatcher<
414 AccessSpecDecl> accessSpecDecl;
416 /// \brief Matches constructor initializers.
418 /// Examples matches \c i(42).
425 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
427 /// \brief Matches template arguments.
431 /// template <typename T> struct C {};
434 /// templateArgument()
435 /// matches 'int' in C<int>.
436 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
438 /// \brief Matches template name.
442 /// template <typename T> class X { };
446 /// matches 'X' in X<int>.
447 const internal::VariadicAllOfMatcher<TemplateName> templateName;
449 /// \brief Matches non-type template parameter declarations.
453 /// template <typename T, int N> struct C {};
455 /// nonTypeTemplateParmDecl()
456 /// matches 'N', but not 'T'.
457 const internal::VariadicDynCastAllOfMatcher<
459 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
461 /// \brief Matches template type parameter declarations.
465 /// template <typename T, int N> struct C {};
467 /// templateTypeParmDecl()
468 /// matches 'T', but not 'N'.
469 const internal::VariadicDynCastAllOfMatcher<
471 TemplateTypeParmDecl> templateTypeParmDecl;
473 /// \brief Matches public C++ declarations.
479 /// protected: int b;
483 /// fieldDecl(isPublic())
485 AST_MATCHER(Decl, isPublic) {
486 return Node.getAccess() == AS_public;
489 /// \brief Matches protected C++ declarations.
495 /// protected: int b;
499 /// fieldDecl(isProtected())
501 AST_MATCHER(Decl, isProtected) {
502 return Node.getAccess() == AS_protected;
505 /// \brief Matches private C++ declarations.
511 /// protected: int b;
515 /// fieldDecl(isPrivate())
517 AST_MATCHER(Decl, isPrivate) {
518 return Node.getAccess() == AS_private;
521 /// \brief Matches non-static data members that are bit-fields.
530 /// fieldDecl(isBitField())
531 /// matches 'int a;' but not 'int b;'.
532 AST_MATCHER(FieldDecl, isBitField) {
533 return Node.isBitField();
536 /// \brief Matches non-static data members that are bit-fields of the specified
547 /// fieldDecl(hasBitWidth(2))
548 /// matches 'int a;' and 'int c;' but not 'int b;'.
549 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
550 return Node.isBitField() &&
551 Node.getBitWidthValue(Finder->getASTContext()) == Width;
554 /// \brief Matches non-static data members that have an in-class initializer.
564 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
565 /// matches 'int a;' but not 'int b;'.
566 /// fieldDecl(hasInClassInitializer(anything()))
567 /// matches 'int a;' and 'int b;' but not 'int c;'.
568 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
570 const Expr *Initializer = Node.getInClassInitializer();
571 return (Initializer != nullptr &&
572 InnerMatcher.matches(*Initializer, Finder, Builder));
575 /// \brief Matches a declaration that has been implicitly added
576 /// by the compiler (eg. implicit default/copy constructors).
577 AST_MATCHER(Decl, isImplicit) {
578 return Node.isImplicit();
581 /// \brief Matches classTemplateSpecializations, templateSpecializationType and
582 /// functionDecl that have at least one TemplateArgument matching the given
587 /// template<typename T> class A {};
588 /// template<> class A<double> {};
591 /// template<typename T> f() {};
592 /// void func() { f<int>(); };
596 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
597 /// refersToType(asString("int"))))
598 /// matches the specialization \c A<int>
600 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
601 /// matches the specialization \c f<int>
602 AST_POLYMORPHIC_MATCHER_P(
603 hasAnyTemplateArgument,
604 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
605 TemplateSpecializationType,
607 internal::Matcher<TemplateArgument>, InnerMatcher) {
608 ArrayRef<TemplateArgument> List =
609 internal::getTemplateSpecializationArgs(Node);
610 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
614 /// \brief Matches expressions that match InnerMatcher after any implicit AST
615 /// nodes are stripped off.
617 /// Parentheses and explicit casts are not discarded.
627 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
629 /// would match the declarations for a, b, and c.
632 /// varDecl(hasInitializer(cxxConstructExpr()))
634 /// only match the declarations for b and c.
635 AST_MATCHER_P(Expr, ignoringImplicit, ast_matchers::internal::Matcher<Expr>,
637 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
640 /// \brief Matches expressions that match InnerMatcher after any implicit casts
641 /// are stripped off.
643 /// Parentheses and explicit casts are not discarded.
651 /// long e = (long) 0l;
655 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
656 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
658 /// would match the declarations for a, b, c, and d, but not e.
661 /// varDecl(hasInitializer(integerLiteral()))
662 /// varDecl(hasInitializer(declRefExpr()))
664 /// only match the declarations for b, c, and d.
665 AST_MATCHER_P(Expr, ignoringImpCasts,
666 internal::Matcher<Expr>, InnerMatcher) {
667 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
670 /// \brief Matches expressions that match InnerMatcher after parentheses and
671 /// casts are stripped off.
673 /// Implicit and non-C Style casts are also discarded.
678 /// void* c = reinterpret_cast<char*>(0);
679 /// char d = char(0);
682 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
683 /// would match the declarations for a, b, c, and d.
685 /// varDecl(hasInitializer(integerLiteral()))
686 /// only match the declaration for a.
687 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
688 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
691 /// \brief Matches expressions that match InnerMatcher after implicit casts and
692 /// parentheses are stripped off.
694 /// Explicit casts are not discarded.
702 /// long e = ((long) 0l);
705 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
706 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
707 /// would match the declarations for a, b, c, and d, but not e.
709 /// varDecl(hasInitializer(integerLiteral()))
710 /// varDecl(hasInitializer(declRefExpr()))
711 /// would only match the declaration for a.
712 AST_MATCHER_P(Expr, ignoringParenImpCasts,
713 internal::Matcher<Expr>, InnerMatcher) {
714 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
717 /// \brief Matches types that match InnerMatcher after any parens are stripped.
721 /// void (*fp)(void);
725 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
727 /// would match the declaration for fp.
728 AST_MATCHER_P(QualType, ignoringParens,
729 internal::Matcher<QualType>, InnerMatcher) {
730 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
733 /// \brief Matches classTemplateSpecializations, templateSpecializationType and
734 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
738 /// template<typename T, typename U> class A {};
742 /// template<typename T> f() {};
743 /// void func() { f<int>(); };
745 /// classTemplateSpecializationDecl(hasTemplateArgument(
746 /// 1, refersToType(asString("int"))))
747 /// matches the specialization \c A<bool, int>
749 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
750 /// matches the specialization \c f<int>
751 AST_POLYMORPHIC_MATCHER_P2(
753 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
754 TemplateSpecializationType,
756 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
757 ArrayRef<TemplateArgument> List =
758 internal::getTemplateSpecializationArgs(Node);
759 if (List.size() <= N)
761 return InnerMatcher.matches(List[N], Finder, Builder);
764 /// \brief Matches if the number of template arguments equals \p N.
768 /// template<typename T> struct C {};
771 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
773 AST_POLYMORPHIC_MATCHER_P(
774 templateArgumentCountIs,
775 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
776 TemplateSpecializationType),
778 return internal::getTemplateSpecializationArgs(Node).size() == N;
781 /// \brief Matches a TemplateArgument that refers to a certain type.
786 /// template<typename T> struct A {};
789 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
790 /// refersToType(class(hasName("X")))))
791 /// matches the specialization \c A<X>
792 AST_MATCHER_P(TemplateArgument, refersToType,
793 internal::Matcher<QualType>, InnerMatcher) {
794 if (Node.getKind() != TemplateArgument::Type)
796 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
799 /// \brief Matches a TemplateArgument that refers to a certain template.
803 /// template<template <typename> class S> class X {};
804 /// template<typename T> class Y {};"
807 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
808 /// refersToTemplate(templateName())))
809 /// matches the specialization \c X<Y>
810 AST_MATCHER_P(TemplateArgument, refersToTemplate,
811 internal::Matcher<TemplateName>, InnerMatcher) {
812 if (Node.getKind() != TemplateArgument::Template)
814 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
817 /// \brief Matches a canonical TemplateArgument that refers to a certain
822 /// template<typename T> struct A {};
823 /// struct B { B* next; };
826 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
827 /// refersToDeclaration(fieldDecl(hasName("next"))))
828 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
830 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
831 internal::Matcher<Decl>, InnerMatcher) {
832 if (Node.getKind() == TemplateArgument::Declaration)
833 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
837 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
841 /// template<typename T> struct A {};
842 /// struct B { B* next; };
845 /// templateSpecializationType(hasAnyTemplateArgument(
846 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
847 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
849 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
850 if (Node.getKind() == TemplateArgument::Expression)
851 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
855 /// \brief Matches a TemplateArgument that is an integral value.
859 /// template<int T> struct A {};
862 /// classTemplateSpecializationDecl(
863 /// hasAnyTemplateArgument(isIntegral()))
864 /// matches the implicit instantiation of C in C<42>
865 /// with isIntegral() matching 42.
866 AST_MATCHER(TemplateArgument, isIntegral) {
867 return Node.getKind() == TemplateArgument::Integral;
870 /// \brief Matches a TemplateArgument that referes to an integral type.
874 /// template<int T> struct A {};
877 /// classTemplateSpecializationDecl(
878 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
879 /// matches the implicit instantiation of C in C<42>.
880 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
881 internal::Matcher<QualType>, InnerMatcher) {
882 if (Node.getKind() != TemplateArgument::Integral)
884 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
887 /// \brief Matches a TemplateArgument of integral type with a given value.
889 /// Note that 'Value' is a string as the template argument's value is
890 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
891 /// representation of that integral value in base 10.
895 /// template<int T> struct A {};
898 /// classTemplateSpecializationDecl(
899 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
900 /// matches the implicit instantiation of C in C<42>.
901 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
902 std::string, Value) {
903 if (Node.getKind() != TemplateArgument::Integral)
905 return Node.getAsIntegral().toString(10) == Value;
908 /// \brief Matches any value declaration.
910 /// Example matches A, B, C and F
912 /// enum X { A, B, C };
915 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
917 /// \brief Matches C++ constructor declarations.
919 /// Example matches Foo::Foo() and Foo::Foo(int)
925 /// int DoSomething();
928 const internal::VariadicDynCastAllOfMatcher<
930 CXXConstructorDecl> cxxConstructorDecl;
932 /// \brief Matches explicit C++ destructor declarations.
934 /// Example matches Foo::~Foo()
941 const internal::VariadicDynCastAllOfMatcher<
943 CXXDestructorDecl> cxxDestructorDecl;
945 /// \brief Matches enum declarations.
947 /// Example matches X
953 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
955 /// \brief Matches enum constants.
957 /// Example matches A, B, C
963 const internal::VariadicDynCastAllOfMatcher<
965 EnumConstantDecl> enumConstantDecl;
967 /// \brief Matches method declarations.
969 /// Example matches y
971 /// class X { void y(); };
973 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
975 /// \brief Matches conversion operator declarations.
977 /// Example matches the operator.
979 /// class X { operator int() const; };
981 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
984 /// \brief Matches variable declarations.
986 /// Note: this does not match declarations of member variables, which are
987 /// "field" declarations in Clang parlance.
989 /// Example matches a
993 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
995 /// \brief Matches field declarations.
999 /// class X { int m; };
1003 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1005 /// \brief Matches function declarations.
1007 /// Example matches f
1011 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
1013 /// \brief Matches C++ function template declarations.
1015 /// Example matches f
1017 /// template<class T> void f(T t) {}
1019 const internal::VariadicDynCastAllOfMatcher<
1021 FunctionTemplateDecl> functionTemplateDecl;
1023 /// \brief Matches friend declarations.
1027 /// class X { friend void foo(); };
1030 /// matches 'friend void foo()'.
1031 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1033 /// \brief Matches statements.
1040 /// matches both the compound statement '{ ++a; }' and '++a'.
1041 const internal::VariadicAllOfMatcher<Stmt> stmt;
1043 /// \brief Matches declaration statements.
1050 /// matches 'int a'.
1051 const internal::VariadicDynCastAllOfMatcher<
1055 /// \brief Matches member expressions.
1060 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1061 /// int a; static int b;
1065 /// matches this->x, x, y.x, a, this->b
1066 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1068 /// \brief Matches call expressions.
1070 /// Example matches x.y() and y()
1076 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1078 /// \brief Matches lambda expressions.
1080 /// Example matches [&](){return 5;}
1082 /// [&](){return 5;}
1084 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1086 /// \brief Matches member call expressions.
1088 /// Example matches x.y()
1093 const internal::VariadicDynCastAllOfMatcher<
1095 CXXMemberCallExpr> cxxMemberCallExpr;
1097 /// \brief Matches ObjectiveC Message invocation expressions.
1099 /// The innermost message send invokes the "alloc" class method on the
1100 /// NSString class, while the outermost message send invokes the
1101 /// "initWithString" instance method on the object returned from
1102 /// NSString's "alloc". This matcher should match both message sends.
1104 /// [[NSString alloc] initWithString:@"Hello"]
1106 const internal::VariadicDynCastAllOfMatcher<
1108 ObjCMessageExpr> objcMessageExpr;
1110 /// \brief Matches Objective-C interface declarations.
1112 /// Example matches Foo
1117 const internal::VariadicDynCastAllOfMatcher<
1119 ObjCInterfaceDecl> objcInterfaceDecl;
1121 /// \brief Matches expressions that introduce cleanups to be run at the end
1122 /// of the sub-expression's evaluation.
1124 /// Example matches std::string()
1126 /// const std::string str = std::string();
1128 const internal::VariadicDynCastAllOfMatcher<
1130 ExprWithCleanups> exprWithCleanups;
1132 /// \brief Matches init list expressions.
1136 /// int a[] = { 1, 2 };
1137 /// struct B { int x, y; };
1141 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1142 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
1144 /// \brief Matches the syntactic form of init list expressions
1145 /// (if expression have it).
1146 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1147 internal::Matcher<Expr>, InnerMatcher) {
1148 const Expr *SyntForm = Node.getSyntacticForm();
1149 return (SyntForm != nullptr &&
1150 InnerMatcher.matches(*SyntForm, Finder, Builder));
1153 /// \brief Matches implicit initializers of init list expressions.
1157 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1159 /// implicitValueInitExpr()
1160 /// matches "[0].y" (implicitly)
1161 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1162 implicitValueInitExpr;
1164 /// \brief Matches paren list expressions.
1165 /// ParenListExprs don't have a predefined type and are used for late parsing.
1166 /// In the final AST, they can be met in template declarations.
1170 /// template<typename T> class X {
1173 /// int a = 0, b = 1; int i = (a, b);
1177 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1178 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1179 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr;
1181 /// \brief Matches substitutions of non-type template parameters.
1185 /// template <int N>
1186 /// struct A { static const int n = N; };
1187 /// struct B : public A<42> {};
1189 /// substNonTypeTemplateParmExpr()
1190 /// matches "N" in the right-hand side of "static const int n = N;"
1191 const internal::VariadicDynCastAllOfMatcher<
1193 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
1195 /// \brief Matches using declarations.
1199 /// namespace X { int x; }
1203 /// matches \code using X::x \endcode
1204 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1206 /// \brief Matches using namespace declarations.
1210 /// namespace X { int x; }
1211 /// using namespace X;
1213 /// usingDirectiveDecl()
1214 /// matches \code using namespace X \endcode
1215 const internal::VariadicDynCastAllOfMatcher<
1217 UsingDirectiveDecl> usingDirectiveDecl;
1219 /// \brief Matches reference to a name that can be looked up during parsing
1220 /// but could not be resolved to a specific declaration.
1224 /// template<typename T>
1225 /// T foo() { T a; return a; }
1226 /// template<typename T>
1231 /// unresolvedLookupExpr()
1232 /// matches \code foo<T>() \endcode
1233 const internal::VariadicDynCastAllOfMatcher<
1235 UnresolvedLookupExpr> unresolvedLookupExpr;
1237 /// \brief Matches unresolved using value declarations.
1241 /// template<typename X>
1242 /// class C : private X {
1246 /// unresolvedUsingValueDecl()
1247 /// matches \code using X::x \endcode
1248 const internal::VariadicDynCastAllOfMatcher<
1250 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1252 /// \brief Matches unresolved using value declarations that involve the
1257 /// template <typename T>
1258 /// struct Base { typedef T Foo; };
1260 /// template<typename T>
1261 /// struct S : private Base<T> {
1262 /// using typename Base<T>::Foo;
1265 /// unresolvedUsingTypenameDecl()
1266 /// matches \code using Base<T>::Foo \endcode
1267 const internal::VariadicDynCastAllOfMatcher<
1269 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1271 /// \brief Matches parentheses used in expressions.
1273 /// Example matches (foo() + 1)
1275 /// int foo() { return 1; }
1276 /// int a = (foo() + 1);
1278 const internal::VariadicDynCastAllOfMatcher<
1280 ParenExpr> parenExpr;
1282 /// \brief Matches constructor call expressions (including implicit ones).
1284 /// Example matches string(ptr, n) and ptr within arguments of f
1285 /// (matcher = cxxConstructExpr())
1287 /// void f(const string &a, const string &b);
1290 /// f(string(ptr, n), ptr);
1292 const internal::VariadicDynCastAllOfMatcher<
1294 CXXConstructExpr> cxxConstructExpr;
1296 /// \brief Matches unresolved constructor call expressions.
1298 /// Example matches T(t) in return statement of f
1299 /// (matcher = cxxUnresolvedConstructExpr())
1301 /// template <typename T>
1302 /// void f(const T& t) { return T(t); }
1304 const internal::VariadicDynCastAllOfMatcher<
1306 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1308 /// \brief Matches implicit and explicit this expressions.
1310 /// Example matches the implicit this expression in "return i".
1311 /// (matcher = cxxThisExpr())
1315 /// int f() { return i; }
1318 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1320 /// \brief Matches nodes where temporaries are created.
1322 /// Example matches FunctionTakesString(GetStringByValue())
1323 /// (matcher = cxxBindTemporaryExpr())
1325 /// FunctionTakesString(GetStringByValue());
1326 /// FunctionTakesStringByPointer(GetStringPointer());
1328 const internal::VariadicDynCastAllOfMatcher<
1330 CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1332 /// \brief Matches nodes where temporaries are materialized.
1336 /// struct T {void func()};
1340 /// materializeTemporaryExpr() matches 'f()' in these statements
1345 /// but does not match
1350 const internal::VariadicDynCastAllOfMatcher<
1352 MaterializeTemporaryExpr> materializeTemporaryExpr;
1354 /// \brief Matches new expressions.
1361 /// matches 'new X'.
1362 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1364 /// \brief Matches delete expressions.
1371 /// matches 'delete X'.
1372 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1374 /// \brief Matches array subscript expressions.
1380 /// arraySubscriptExpr()
1382 const internal::VariadicDynCastAllOfMatcher<
1384 ArraySubscriptExpr> arraySubscriptExpr;
1386 /// \brief Matches the value of a default argument at the call site.
1388 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1389 /// default value of the second parameter in the call expression f(42)
1390 /// (matcher = cxxDefaultArgExpr())
1392 /// void f(int x, int y = 0);
1395 const internal::VariadicDynCastAllOfMatcher<
1397 CXXDefaultArgExpr> cxxDefaultArgExpr;
1399 /// \brief Matches overloaded operator calls.
1401 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1402 /// binaryOperator matcher.
1403 /// Currently it does not match operators such as new delete.
1404 /// FIXME: figure out why these do not match?
1406 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1407 /// (matcher = cxxOperatorCallExpr())
1409 /// ostream &operator<< (ostream &out, int i) { };
1410 /// ostream &o; int b = 1, c = 1;
1413 const internal::VariadicDynCastAllOfMatcher<
1415 CXXOperatorCallExpr> cxxOperatorCallExpr;
1417 /// \brief Matches expressions.
1419 /// Example matches x()
1421 /// void f() { x(); }
1423 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1425 /// \brief Matches expressions that refer to declarations.
1427 /// Example matches x in if (x)
1432 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1434 /// \brief Matches if statements.
1436 /// Example matches 'if (x) {}'
1440 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1442 /// \brief Matches for statements.
1444 /// Example matches 'for (;;) {}'
1447 /// int i[] = {1, 2, 3}; for (auto a : i);
1449 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1451 /// \brief Matches the increment statement of a for loop.
1454 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1455 /// matches '++x' in
1457 /// for (x; x < N; ++x) { }
1459 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1461 const Stmt *const Increment = Node.getInc();
1462 return (Increment != nullptr &&
1463 InnerMatcher.matches(*Increment, Finder, Builder));
1466 /// \brief Matches the initialization statement of a for loop.
1469 /// forStmt(hasLoopInit(declStmt()))
1470 /// matches 'int x = 0' in
1472 /// for (int x = 0; x < N; ++x) { }
1474 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1476 const Stmt *const Init = Node.getInit();
1477 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1480 /// \brief Matches range-based for statements.
1482 /// cxxForRangeStmt() matches 'for (auto a : i)'
1484 /// int i[] = {1, 2, 3}; for (auto a : i);
1485 /// for(int j = 0; j < 5; ++j);
1487 const internal::VariadicDynCastAllOfMatcher<
1489 CXXForRangeStmt> cxxForRangeStmt;
1491 /// \brief Matches the initialization statement of a for loop.
1494 /// forStmt(hasLoopVariable(anything()))
1495 /// matches 'int x' in
1497 /// for (int x : a) { }
1499 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1501 const VarDecl *const Var = Node.getLoopVariable();
1502 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1505 /// \brief Matches the range initialization statement of a for loop.
1508 /// forStmt(hasRangeInit(anything()))
1511 /// for (int x : a) { }
1513 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1515 const Expr *const Init = Node.getRangeInit();
1516 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1519 /// \brief Matches while statements.
1526 /// matches 'while (true) {}'.
1527 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1529 /// \brief Matches do statements.
1533 /// do {} while (true);
1536 /// matches 'do {} while(true)'
1537 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1539 /// \brief Matches break statements.
1543 /// while (true) { break; }
1547 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1549 /// \brief Matches continue statements.
1553 /// while (true) { continue; }
1556 /// matches 'continue'
1557 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1559 /// \brief Matches return statements.
1566 /// matches 'return 1'
1567 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1569 /// \brief Matches goto statements.
1577 /// matches 'goto FOO'
1578 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1580 /// \brief Matches label statements.
1589 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1591 /// \brief Matches address of label statements (GNU extension).
1596 /// void *ptr = &&FOO;
1601 const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr;
1603 /// \brief Matches switch statements.
1607 /// switch(a) { case 42: break; default: break; }
1610 /// matches 'switch(a)'.
1611 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1613 /// \brief Matches case and default statements inside switch statements.
1617 /// switch(a) { case 42: break; default: break; }
1620 /// matches 'case 42: break;' and 'default: break;'.
1621 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1623 /// \brief Matches case statements inside switch statements.
1627 /// switch(a) { case 42: break; default: break; }
1630 /// matches 'case 42: break;'.
1631 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1633 /// \brief Matches default statements inside switch statements.
1637 /// switch(a) { case 42: break; default: break; }
1640 /// matches 'default: break;'.
1641 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1643 /// \brief Matches compound statements.
1645 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1649 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1651 /// \brief Matches catch statements.
1654 /// try {} catch(int i) {}
1657 /// matches 'catch(int i)'
1658 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1660 /// \brief Matches try statements.
1663 /// try {} catch(int i) {}
1666 /// matches 'try {}'
1667 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1669 /// \brief Matches throw expressions.
1672 /// try { throw 5; } catch(int i) {}
1675 /// matches 'throw 5'
1676 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1678 /// \brief Matches null statements.
1684 /// matches the second ';'
1685 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1687 /// \brief Matches asm statements.
1691 /// __asm("mov al, 2");
1694 /// matches '__asm("mov al, 2")'
1695 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1697 /// \brief Matches bool literals.
1699 /// Example matches true
1703 const internal::VariadicDynCastAllOfMatcher<
1705 CXXBoolLiteralExpr> cxxBoolLiteral;
1707 /// \brief Matches string literals (also matches wide string literals).
1709 /// Example matches "abcd", L"abcd"
1711 /// char *s = "abcd";
1712 /// wchar_t *ws = L"abcd";
1714 const internal::VariadicDynCastAllOfMatcher<
1716 StringLiteral> stringLiteral;
1718 /// \brief Matches character literals (also matches wchar_t).
1720 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1723 /// Example matches 'a', L'a'
1726 /// wchar_t chw = L'a';
1728 const internal::VariadicDynCastAllOfMatcher<
1730 CharacterLiteral> characterLiteral;
1732 /// \brief Matches integer literals of all sizes / encodings, e.g.
1733 /// 1, 1L, 0x1 and 1U.
1735 /// Does not match character-encoded integers such as L'a'.
1736 const internal::VariadicDynCastAllOfMatcher<
1738 IntegerLiteral> integerLiteral;
1740 /// \brief Matches float literals of all sizes / encodings, e.g.
1741 /// 1.0, 1.0f, 1.0L and 1e10.
1743 /// Does not match implicit conversions such as
1747 const internal::VariadicDynCastAllOfMatcher<
1749 FloatingLiteral> floatLiteral;
1751 /// \brief Matches user defined literal operator call.
1753 /// Example match: "foo"_suffix
1754 const internal::VariadicDynCastAllOfMatcher<
1756 UserDefinedLiteral> userDefinedLiteral;
1758 /// \brief Matches compound (i.e. non-scalar) literals
1760 /// Example match: {1}, (1, 2)
1762 /// int array[4] = {1};
1763 /// vector int myvec = (vector int)(1, 2);
1765 const internal::VariadicDynCastAllOfMatcher<
1767 CompoundLiteralExpr> compoundLiteralExpr;
1769 /// \brief Matches nullptr literal.
1770 const internal::VariadicDynCastAllOfMatcher<
1772 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1774 /// \brief Matches GNU __null expression.
1775 const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr;
1777 /// \brief Matches atomic builtins.
1778 /// Example matches __atomic_load_n(ptr, 1)
1780 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
1782 const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
1784 /// \brief Matches statement expression (GNU extension).
1786 /// Example match: ({ int X = 4; X; })
1788 /// int C = ({ int X = 4; X; });
1790 const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
1792 /// \brief Matches binary operator expressions.
1794 /// Example matches a || b
1798 const internal::VariadicDynCastAllOfMatcher<
1800 BinaryOperator> binaryOperator;
1802 /// \brief Matches unary operator expressions.
1804 /// Example matches !a
1808 const internal::VariadicDynCastAllOfMatcher<
1810 UnaryOperator> unaryOperator;
1812 /// \brief Matches conditional operator expressions.
1814 /// Example matches a ? b : c
1816 /// (a ? b : c) + 42
1818 const internal::VariadicDynCastAllOfMatcher<
1820 ConditionalOperator> conditionalOperator;
1822 /// \brief Matches binary conditional operator expressions (GNU extension).
1824 /// Example matches a ?: b
1828 const internal::VariadicDynCastAllOfMatcher<
1830 BinaryConditionalOperator> binaryConditionalOperator;
1832 /// \brief Matches opaque value expressions. They are used as helpers
1833 /// to reference another expressions and can be met
1834 /// in BinaryConditionalOperators, for example.
1836 /// Example matches 'a'
1840 const internal::VariadicDynCastAllOfMatcher<
1842 OpaqueValueExpr> opaqueValueExpr;
1844 /// \brief Matches a C++ static_assert declaration.
1847 /// staticAssertExpr()
1849 /// static_assert(sizeof(S) == sizeof(int))
1855 /// static_assert(sizeof(S) == sizeof(int));
1857 const internal::VariadicDynCastAllOfMatcher<
1859 StaticAssertDecl> staticAssertDecl;
1861 /// \brief Matches a reinterpret_cast expression.
1863 /// Either the source expression or the destination type can be matched
1864 /// using has(), but hasDestinationType() is more specific and can be
1867 /// Example matches reinterpret_cast<char*>(&p) in
1869 /// void* p = reinterpret_cast<char*>(&p);
1871 const internal::VariadicDynCastAllOfMatcher<
1873 CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1875 /// \brief Matches a C++ static_cast expression.
1877 /// \see hasDestinationType
1878 /// \see reinterpretCast
1881 /// cxxStaticCastExpr()
1883 /// static_cast<long>(8)
1886 /// long eight(static_cast<long>(8));
1888 const internal::VariadicDynCastAllOfMatcher<
1890 CXXStaticCastExpr> cxxStaticCastExpr;
1892 /// \brief Matches a dynamic_cast expression.
1895 /// cxxDynamicCastExpr()
1897 /// dynamic_cast<D*>(&b);
1900 /// struct B { virtual ~B() {} }; struct D : B {};
1902 /// D* p = dynamic_cast<D*>(&b);
1904 const internal::VariadicDynCastAllOfMatcher<
1906 CXXDynamicCastExpr> cxxDynamicCastExpr;
1908 /// \brief Matches a const_cast expression.
1910 /// Example: Matches const_cast<int*>(&r) in
1913 /// const int &r(n);
1914 /// int* p = const_cast<int*>(&r);
1916 const internal::VariadicDynCastAllOfMatcher<
1918 CXXConstCastExpr> cxxConstCastExpr;
1920 /// \brief Matches a C-style cast expression.
1922 /// Example: Matches (int) 2.2f in
1924 /// int i = (int) 2.2f;
1926 const internal::VariadicDynCastAllOfMatcher<
1928 CStyleCastExpr> cStyleCastExpr;
1930 /// \brief Matches explicit cast expressions.
1932 /// Matches any cast expression written in user code, whether it be a
1933 /// C-style cast, a functional-style cast, or a keyword cast.
1935 /// Does not match implicit conversions.
1937 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1938 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1939 /// actual cast expressions.
1941 /// \see hasDestinationType.
1943 /// Example: matches all five of the casts in
1945 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1947 /// but does not match the implicit conversion in
1951 const internal::VariadicDynCastAllOfMatcher<
1953 ExplicitCastExpr> explicitCastExpr;
1955 /// \brief Matches the implicit cast nodes of Clang's AST.
1957 /// This matches many different places, including function call return value
1958 /// eliding, as well as any type conversions.
1959 const internal::VariadicDynCastAllOfMatcher<
1961 ImplicitCastExpr> implicitCastExpr;
1963 /// \brief Matches any cast nodes of Clang's AST.
1965 /// Example: castExpr() matches each of the following:
1968 /// const_cast<Expr *>(SubExpr);
1971 /// but does not match
1976 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1978 /// \brief Matches functional cast expressions
1980 /// Example: Matches Foo(bar);
1983 /// Foo g = (Foo) bar;
1984 /// Foo h = Foo(bar);
1986 const internal::VariadicDynCastAllOfMatcher<
1988 CXXFunctionalCastExpr> cxxFunctionalCastExpr;
1990 /// \brief Matches functional cast expressions having N != 1 arguments
1992 /// Example: Matches Foo(bar, bar)
1994 /// Foo h = Foo(bar, bar);
1996 const internal::VariadicDynCastAllOfMatcher<
1998 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
2000 /// \brief Matches predefined identifier expressions [C99 6.4.2.2].
2002 /// Example: Matches __func__
2004 /// printf("%s", __func__);
2006 const internal::VariadicDynCastAllOfMatcher<
2008 PredefinedExpr> predefinedExpr;
2010 /// \brief Matches C99 designated initializer expressions [C99 6.7.8].
2012 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2014 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2016 const internal::VariadicDynCastAllOfMatcher<
2018 DesignatedInitExpr> designatedInitExpr;
2020 /// \brief Matches designated initializer expressions that contain
2021 /// a specific number of designators.
2025 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2026 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2028 /// designatorCountIs(2)
2029 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2030 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2031 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2032 return Node.size() == N;
2035 /// \brief Matches \c QualTypes in the clang AST.
2036 const internal::VariadicAllOfMatcher<QualType> qualType;
2038 /// \brief Matches \c Types in the clang AST.
2039 const internal::VariadicAllOfMatcher<Type> type;
2041 /// \brief Matches \c TypeLocs in the clang AST.
2042 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2044 /// \brief Matches if any of the given matchers matches.
2046 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2047 /// matching submatcher.
2049 /// For example, in:
2051 /// class A { int a; int b; };
2055 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2056 /// has(fieldDecl(hasName("b")).bind("v"))))
2058 /// will generate two results binding "v", the first of which binds
2059 /// the field declaration of \c a, the second the field declaration of
2062 /// Usable as: Any Matcher
2063 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
2064 internal::DynTypedMatcher::VO_EachOf
2067 /// \brief Matches if any of the given matchers matches.
2069 /// Usable as: Any Matcher
2070 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
2071 internal::DynTypedMatcher::VO_AnyOf
2074 /// \brief Matches if all given matchers match.
2076 /// Usable as: Any Matcher
2077 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
2078 internal::DynTypedMatcher::VO_AllOf
2081 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2086 /// int y = sizeof(x) + alignof(x);
2088 /// unaryExprOrTypeTraitExpr()
2089 /// matches \c sizeof(x) and \c alignof(x)
2090 const internal::VariadicDynCastAllOfMatcher<
2092 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
2094 /// \brief Matches unary expressions that have a specific type of argument.
2098 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2100 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2101 /// matches \c sizeof(a) and \c alignof(c)
2102 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2103 internal::Matcher<QualType>, InnerMatcher) {
2104 const QualType ArgumentType = Node.getTypeOfArgument();
2105 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2108 /// \brief Matches unary expressions of a certain kind.
2113 /// int s = sizeof(x) + alignof(x)
2115 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2116 /// matches \c sizeof(x)
2117 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2118 return Node.getKind() == Kind;
2121 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2123 inline internal::Matcher<Stmt> alignOfExpr(
2124 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2125 return stmt(unaryExprOrTypeTraitExpr(allOf(
2126 ofKind(UETT_AlignOf), InnerMatcher)));
2129 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
2131 inline internal::Matcher<Stmt> sizeOfExpr(
2132 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2133 return stmt(unaryExprOrTypeTraitExpr(
2134 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2137 /// \brief Matches NamedDecl nodes that have the specified name.
2139 /// Supports specifying enclosing namespaces or classes by prefixing the name
2140 /// with '<enclosing>::'.
2141 /// Does not match typedefs of an underlying type with the given name.
2143 /// Example matches X (Name == "X")
2148 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2150 /// namespace a { namespace b { class X; } }
2152 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2153 std::vector<std::string> Names;
2154 Names.push_back(Name);
2155 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
2158 /// \brief Matches NamedDecl nodes that have any of the specified names.
2160 /// This matcher is only provided as a performance optimization of hasName.
2162 /// hasAnyName(a, b, c)
2164 /// is equivalent to, but faster than
2166 /// anyOf(hasName(a), hasName(b), hasName(c))
2168 const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2169 internal::hasAnyNameFunc>
2172 /// \brief Matches NamedDecl nodes whose fully qualified names contain
2173 /// a substring matched by the given RegExp.
2175 /// Supports specifying enclosing namespaces or classes by
2176 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2177 /// of an underlying type with the given name.
2179 /// Example matches X (regexp == "::X")
2184 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2186 /// namespace foo { namespace bar { class X; } }
2188 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2189 assert(!RegExp.empty());
2190 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2191 llvm::Regex RE(RegExp);
2192 return RE.match(FullNameString);
2195 /// \brief Matches overloaded operator names.
2197 /// Matches overloaded operator names specified in strings without the
2198 /// "operator" prefix: e.g. "<<".
2202 /// class A { int operator*(); };
2203 /// const A &operator<<(const A &a, const A &b);
2205 /// a << a; // <-- This matches
2208 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2209 /// specified line and
2210 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2211 /// matches the declaration of \c A.
2213 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2214 inline internal::PolymorphicMatcherWithParam1<
2215 internal::HasOverloadedOperatorNameMatcher, StringRef,
2216 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2217 hasOverloadedOperatorName(StringRef Name) {
2218 return internal::PolymorphicMatcherWithParam1<
2219 internal::HasOverloadedOperatorNameMatcher, StringRef,
2220 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2223 /// \brief Matches C++ classes that are directly or indirectly derived from
2224 /// a class matching \c Base.
2226 /// Note that a class is not considered to be derived from itself.
2228 /// Example matches Y, Z, C (Base == hasName("X"))
2231 /// class Y : public X {}; // directly derived
2232 /// class Z : public Y {}; // indirectly derived
2235 /// class C : public B {}; // derived from a typedef of X
2238 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2242 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2244 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2245 internal::Matcher<NamedDecl>, Base) {
2246 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2249 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2250 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2251 assert(!BaseName.empty());
2252 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2255 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
2257 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2258 internal::Matcher<NamedDecl>, Base, 0) {
2259 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2260 .matches(Node, Finder, Builder);
2263 /// \brief Overloaded method as shortcut for
2264 /// \c isSameOrDerivedFrom(hasName(...)).
2265 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2267 assert(!BaseName.empty());
2268 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2271 /// \brief Matches the first method of a class or struct that satisfies \c
2276 /// class A { void func(); };
2277 /// class B { void member(); };
2280 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2281 /// \c A but not \c B.
2282 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2284 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2285 Node.method_end(), Finder, Builder);
2288 /// \brief Matches the generated class of lambda expressions.
2295 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2297 AST_MATCHER(CXXRecordDecl, isLambda) {
2298 return Node.isLambda();
2301 /// \brief Matches AST nodes that have child AST nodes that match the
2302 /// provided matcher.
2304 /// Example matches X, Y
2305 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2307 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2308 /// class Y { class X {}; };
2309 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2312 /// ChildT must be an AST base type.
2314 /// Usable as: Any Matcher
2315 /// Note that has is direct matcher, so it also matches things like implicit
2316 /// casts and paren casts. If you are matching with expr then you should
2317 /// probably consider using ignoringParenImpCasts like:
2318 /// has(ignoringParenImpCasts(expr())).
2319 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
2320 LLVM_ATTRIBUTE_UNUSED has = {};
2322 /// \brief Matches AST nodes that have descendant AST nodes that match the
2323 /// provided matcher.
2325 /// Example matches X, Y, Z
2326 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2328 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2329 /// class Y { class X {}; };
2330 /// class Z { class Y { class X {}; }; };
2333 /// DescendantT must be an AST base type.
2335 /// Usable as: Any Matcher
2336 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
2337 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
2339 /// \brief Matches AST nodes that have child AST nodes that match the
2340 /// provided matcher.
2342 /// Example matches X, Y
2343 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2345 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2346 /// class Y { class X {}; };
2347 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2350 /// ChildT must be an AST base type.
2352 /// As opposed to 'has', 'forEach' will cause a match for each result that
2353 /// matches instead of only on the first one.
2355 /// Usable as: Any Matcher
2356 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2357 LLVM_ATTRIBUTE_UNUSED forEach = {};
2359 /// \brief Matches AST nodes that have descendant AST nodes that match the
2360 /// provided matcher.
2362 /// Example matches X, A, B, C
2363 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2365 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2366 /// class A { class X {}; };
2367 /// class B { class C { class X {}; }; };
2370 /// DescendantT must be an AST base type.
2372 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2373 /// each result that matches instead of only on the first one.
2375 /// Note: Recursively combined ForEachDescendant can cause many matches:
2376 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2377 /// forEachDescendant(cxxRecordDecl())
2379 /// will match 10 times (plus injected class name matches) on:
2381 /// class A { class B { class C { class D { class E {}; }; }; }; };
2384 /// Usable as: Any Matcher
2385 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2386 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2388 /// \brief Matches if the node or any descendant matches.
2390 /// Generates results for each match.
2392 /// For example, in:
2394 /// class A { class B {}; class C {}; };
2398 /// cxxRecordDecl(hasName("::A"),
2399 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2401 /// will generate results for \c A, \c B and \c C.
2403 /// Usable as: Any Matcher
2404 template <typename T>
2405 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2406 return eachOf(Matcher, forEachDescendant(Matcher));
2409 /// \brief Matches AST nodes that have a parent that matches the provided
2414 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2416 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2418 /// Usable as: Any Matcher
2419 const internal::ArgumentAdaptingMatcherFunc<
2420 internal::HasParentMatcher,
2421 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2422 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2423 LLVM_ATTRIBUTE_UNUSED hasParent = {};
2425 /// \brief Matches AST nodes that have an ancestor that matches the provided
2430 /// void f() { if (true) { int x = 42; } }
2431 /// void g() { for (;;) { int x = 43; } }
2433 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2435 /// Usable as: Any Matcher
2436 const internal::ArgumentAdaptingMatcherFunc<
2437 internal::HasAncestorMatcher,
2438 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2439 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2440 LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2442 /// \brief Matches if the provided matcher does not match.
2444 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2450 /// Usable as: Any Matcher
2451 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2452 internal::DynTypedMatcher::VO_UnaryNot
2455 /// \brief Matches a node if the declaration associated with that node
2456 /// matches the given matcher.
2458 /// The associated declaration is:
2459 /// - for type nodes, the declaration of the underlying type
2460 /// - for CallExpr, the declaration of the callee
2461 /// - for MemberExpr, the declaration of the referenced member
2462 /// - for CXXConstructExpr, the declaration of the constructor
2463 /// - for CXXNewExpr, the declaration of the operator new
2465 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2466 /// function. e.g. various subtypes of clang::Type and various expressions.
2468 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2469 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2470 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2471 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2472 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2473 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2474 /// Matcher<UnresolvedUsingType>
2475 inline internal::PolymorphicMatcherWithParam1<
2476 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2477 void(internal::HasDeclarationSupportedTypes)>
2478 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2479 return internal::PolymorphicMatcherWithParam1<
2480 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2481 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2484 /// \brief Matches a \c NamedDecl whose underlying declaration matches the given
2489 /// namespace N { template<class T> void f(T t); }
2490 /// template <class T> void g() { using N::f; f(T()); }
2492 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2493 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2494 /// matches the use of \c f in \c g() .
2495 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2497 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2499 return UnderlyingDecl != nullptr &&
2500 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2503 /// \brief Matches on the implicit object argument of a member call expression.
2505 /// Example matches y.x()
2506 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2508 /// class Y { public: void x(); };
2509 /// void z() { Y y; y.x(); }",
2512 /// FIXME: Overload to allow directly matching types?
2513 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2515 const Expr *ExprNode = Node.getImplicitObjectArgument()
2516 ->IgnoreParenImpCasts();
2517 return (ExprNode != nullptr &&
2518 InnerMatcher.matches(*ExprNode, Finder, Builder));
2522 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2525 /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *")));
2526 /// matches the [webView ...] message invocation.
2528 /// NSString *webViewJavaScript = ...
2529 /// UIWebView *webView = ...
2530 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2532 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2534 const QualType TypeDecl = Node.getReceiverType();
2535 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2538 /// \brief Matches when BaseName == Selector.getAsString()
2540 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2541 /// matches the outer message expr in the code below, but NOT the message
2542 /// invocation for self.bodyView.
2544 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2546 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2547 Selector Sel = Node.getSelector();
2548 return BaseName.compare(Sel.getAsString()) == 0;
2552 /// \brief Matches ObjC selectors whose name contains
2553 /// a substring matched by the given RegExp.
2554 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2555 /// matches the outer message expr in the code below, but NOT the message
2556 /// invocation for self.bodyView.
2558 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2560 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2561 assert(!RegExp.empty());
2562 std::string SelectorString = Node.getSelector().getAsString();
2563 llvm::Regex RE(RegExp);
2564 return RE.match(SelectorString);
2567 /// \brief Matches when the selector is the empty selector
2569 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2570 /// represent an error condition in the tree!
2571 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2572 return Node.getSelector().isNull();
2575 /// \brief Matches when the selector is a Unary Selector
2577 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2578 /// matches self.bodyView in the code below, but NOT the outer message
2579 /// invocation of "loadHTMLString:baseURL:".
2581 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2583 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2584 return Node.getSelector().isUnarySelector();
2587 /// \brief Matches when the selector is a keyword selector
2589 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2590 /// message expression in
2593 /// UIWebView *webView = ...;
2594 /// CGRect bodyFrame = webView.frame;
2595 /// bodyFrame.size.height = self.bodyContentHeight;
2596 /// webView.frame = bodyFrame;
2597 /// // ^---- matches here
2599 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2600 return Node.getSelector().isKeywordSelector();
2603 /// \brief Matches when the selector has the specified number of arguments
2605 /// matcher = objCMessageExpr(numSelectorArgs(0));
2606 /// matches self.bodyView in the code below
2608 /// matcher = objCMessageExpr(numSelectorArgs(2));
2609 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2610 /// of self.bodyView
2612 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2614 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2615 return Node.getSelector().getNumArgs() == N;
2618 /// \brief Matches if the call expression's callee expression matches.
2622 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2623 /// void f() { f(); }
2625 /// callExpr(callee(expr()))
2626 /// matches this->x(), x(), y.x(), f()
2627 /// with callee(...)
2628 /// matching this->x, x, y.x, f respectively
2630 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2631 /// because this introduces ambiguous overloads with calls to Callee taking a
2632 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2633 /// implemented in terms of implicit casts.
2634 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2636 const Expr *ExprNode = Node.getCallee();
2637 return (ExprNode != nullptr &&
2638 InnerMatcher.matches(*ExprNode, Finder, Builder));
2641 /// \brief Matches if the call expression's callee's declaration matches the
2644 /// Example matches y.x() (matcher = callExpr(callee(
2645 /// cxxMethodDecl(hasName("x")))))
2647 /// class Y { public: void x(); };
2648 /// void z() { Y y; y.x(); }
2650 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2652 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2655 /// \brief Matches if the expression's or declaration's type matches a type
2658 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2659 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2660 /// and U (matcher = typedefDecl(hasType(asString("int")))
2663 /// void y(X &x) { x; X z; }
2666 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2667 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefNameDecl, ValueDecl),
2668 internal::Matcher<QualType>, InnerMatcher, 0) {
2669 return InnerMatcher.matches(internal::getUnderlyingType(Node),
2673 /// \brief Overloaded to match the declaration of the expression's or value
2674 /// declaration's type.
2676 /// In case of a value declaration (for example a variable declaration),
2677 /// this resolves one layer of indirection. For example, in the value
2678 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2679 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2680 /// declaration of x.
2682 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2683 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2686 /// void y(X &x) { x; X z; }
2689 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2690 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2691 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2693 internal::Matcher<Decl>, InnerMatcher, 1) {
2694 return qualType(hasDeclaration(InnerMatcher))
2695 .matches(Node.getType(), Finder, Builder);
2698 /// \brief Matches if the type location of the declarator decl's type matches
2699 /// the inner matcher.
2705 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2707 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2708 if (!Node.getTypeSourceInfo())
2709 // This happens for example for implicit destructors.
2711 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2714 /// \brief Matches if the matched type is represented by the given string.
2718 /// class Y { public: void x(); };
2719 /// void z() { Y* y; y->x(); }
2721 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2723 AST_MATCHER_P(QualType, asString, std::string, Name) {
2724 return Name == Node.getAsString();
2727 /// \brief Matches if the matched type is a pointer type and the pointee type
2728 /// matches the specified matcher.
2730 /// Example matches y->x()
2731 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2732 /// cxxRecordDecl(hasName("Y")))))))
2734 /// class Y { public: void x(); };
2735 /// void z() { Y *y; y->x(); }
2738 QualType, pointsTo, internal::Matcher<QualType>,
2740 return (!Node.isNull() && Node->isAnyPointerType() &&
2741 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2744 /// \brief Overloaded to match the pointee type's declaration.
2745 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2747 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2748 .matches(Node, Finder, Builder);
2751 /// \brief Matches if the matched type matches the unqualified desugared
2752 /// type of the matched node.
2754 /// For example, in:
2759 /// The matcher type(hasUniqualifeidDesugaredType(recordType())) matches
2761 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
2763 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
2767 /// \brief Matches if the matched type is a reference type and the referenced
2768 /// type matches the specified matcher.
2770 /// Example matches X &x and const X &y
2771 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2780 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2782 return (!Node.isNull() && Node->isReferenceType() &&
2783 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2786 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2790 /// typedef int &int_ref;
2795 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2796 /// declaration of b but \c
2797 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
2798 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2802 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2805 /// \brief Overloaded to match the referenced type's declaration.
2806 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2808 return references(qualType(hasDeclaration(InnerMatcher)))
2809 .matches(Node, Finder, Builder);
2812 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2813 internal::Matcher<Expr>, InnerMatcher) {
2814 const Expr *ExprNode = Node.getImplicitObjectArgument();
2815 return (ExprNode != nullptr &&
2816 InnerMatcher.matches(*ExprNode, Finder, Builder));
2819 /// \brief Matches if the expression's type either matches the specified
2820 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2821 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2822 internal::Matcher<QualType>, InnerMatcher, 0) {
2823 return onImplicitObjectArgument(
2824 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2825 .matches(Node, Finder, Builder);
2828 /// \brief Overloaded to match the type's declaration.
2829 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2830 internal::Matcher<Decl>, InnerMatcher, 1) {
2831 return onImplicitObjectArgument(
2832 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2833 .matches(Node, Finder, Builder);
2836 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2837 /// specified matcher.
2839 /// Example matches x in if(x)
2840 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2845 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2847 const Decl *DeclNode = Node.getDecl();
2848 return (DeclNode != nullptr &&
2849 InnerMatcher.matches(*DeclNode, Finder, Builder));
2852 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2853 /// specific using shadow declaration.
2857 /// namespace a { void f() {} }
2860 /// f(); // Matches this ..
2861 /// a::f(); // .. but not this.
2864 /// declRefExpr(throughUsingDecl(anything()))
2866 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2867 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2868 const NamedDecl *FoundDecl = Node.getFoundDecl();
2869 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2870 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2874 /// \brief Matches an \c OverloadExpr if any of the declarations in the set of
2875 /// overloads matches the given matcher.
2879 /// template <typename T> void foo(T);
2880 /// template <typename T> void bar(T);
2881 /// template <typename T> void baz(T t) {
2886 /// unresolvedLookupExpr(hasAnyDeclaration(
2887 /// functionTemplateDecl(hasName("foo"))))
2888 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
2889 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
2891 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
2892 Node.decls_end(), Finder, Builder);
2895 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2902 /// declStmt(hasSingleDecl(anything()))
2903 /// matches 'int c;' but not 'int a, b;'.
2904 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2905 if (Node.isSingleDecl()) {
2906 const Decl *FoundDecl = Node.getSingleDecl();
2907 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2912 /// \brief Matches a variable declaration that has an initializer expression
2913 /// that matches the given matcher.
2915 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2917 /// bool y() { return true; }
2921 VarDecl, hasInitializer, internal::Matcher<Expr>,
2923 const Expr *Initializer = Node.getAnyInitializer();
2924 return (Initializer != nullptr &&
2925 InnerMatcher.matches(*Initializer, Finder, Builder));
2928 /// \brief Matches a variable declaration that has function scope and is a
2929 /// non-static local variable.
2931 /// Example matches x (matcher = varDecl(hasLocalStorage())
2939 AST_MATCHER(VarDecl, hasLocalStorage) {
2940 return Node.hasLocalStorage();
2943 /// \brief Matches a variable declaration that does not have local storage.
2945 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2953 AST_MATCHER(VarDecl, hasGlobalStorage) {
2954 return Node.hasGlobalStorage();
2957 /// \brief Matches a variable declaration that has automatic storage duration.
2959 /// Example matches x, but not y, z, or a.
2960 /// (matcher = varDecl(hasAutomaticStorageDuration())
2965 /// thread_local int z;
2969 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
2970 return Node.getStorageDuration() == SD_Automatic;
2973 /// \brief Matches a variable declaration that has static storage duration.
2974 /// It includes the variable declared at namespace scope and those declared
2975 /// with "static" and "extern" storage class specifiers.
2981 /// thread_local int z;
2986 /// varDecl(hasStaticStorageDuration())
2987 /// matches the function declaration y, a, b and c.
2989 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
2990 return Node.getStorageDuration() == SD_Static;
2993 /// \brief Matches a variable declaration that has thread storage duration.
2995 /// Example matches z, but not x, z, or a.
2996 /// (matcher = varDecl(hasThreadStorageDuration())
3001 /// thread_local int z;
3005 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3006 return Node.getStorageDuration() == SD_Thread;
3009 /// \brief Matches a variable declaration that is an exception variable from
3010 /// a C++ catch block, or an Objective-C \@catch statement.
3012 /// Example matches x (matcher = varDecl(isExceptionVariable())
3016 /// } catch (int x) {
3020 AST_MATCHER(VarDecl, isExceptionVariable) {
3021 return Node.isExceptionVariable();
3024 /// \brief Checks that a call expression or a constructor call expression has
3025 /// a specific number of arguments (including absent default arguments).
3027 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3029 /// void f(int x, int y);
3032 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3033 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3037 return Node.getNumArgs() == N;
3040 /// \brief Matches the n'th argument of a call expression or a constructor
3041 /// call expression.
3043 /// Example matches y in x(y)
3044 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3046 /// void x(int) { int y; x(y); }
3048 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3049 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3052 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3053 return (N < Node.getNumArgs() &&
3054 InnerMatcher.matches(
3055 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3058 /// \brief Matches declaration statements that contain a specific number of
3068 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3069 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3070 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3073 /// \brief Matches the n'th declaration of a declaration statement.
3075 /// Note that this does not work for global declarations because the AST
3076 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3078 /// Example: Given non-global declarations
3084 /// declStmt(containsDeclaration(
3085 /// 0, varDecl(hasInitializer(anything()))))
3086 /// matches only 'int d = 2, e;', and
3087 /// declStmt(containsDeclaration(1, varDecl()))
3089 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3090 /// but 'int c;' is not matched.
3092 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3093 internal::Matcher<Decl>, InnerMatcher) {
3094 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3097 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3098 std::advance(Iterator, N);
3099 return InnerMatcher.matches(**Iterator, Finder, Builder);
3102 /// \brief Matches a C++ catch statement that has a catch-all handler.
3114 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3115 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3116 return Node.getExceptionDecl() == nullptr;
3119 /// \brief Matches a constructor initializer.
3124 /// Foo() : foo_(1) { }
3128 /// cxxRecordDecl(has(cxxConstructorDecl(
3129 /// hasAnyConstructorInitializer(anything())
3131 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3132 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3133 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3134 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3135 Node.init_end(), Finder, Builder);
3138 /// \brief Matches the field declaration of a constructor initializer.
3143 /// Foo() : foo_(1) { }
3147 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3148 /// forField(hasName("foo_"))))))
3150 /// with forField matching foo_
3151 AST_MATCHER_P(CXXCtorInitializer, forField,
3152 internal::Matcher<FieldDecl>, InnerMatcher) {
3153 const FieldDecl *NodeAsDecl = Node.getMember();
3154 return (NodeAsDecl != nullptr &&
3155 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3158 /// \brief Matches the initializer expression of a constructor initializer.
3163 /// Foo() : foo_(1) { }
3167 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3168 /// withInitializer(integerLiteral(equals(1)))))))
3170 /// with withInitializer matching (1)
3171 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3172 internal::Matcher<Expr>, InnerMatcher) {
3173 const Expr* NodeAsExpr = Node.getInit();
3174 return (NodeAsExpr != nullptr &&
3175 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3178 /// \brief Matches a constructor initializer if it is explicitly written in
3179 /// code (as opposed to implicitly added by the compiler).
3185 /// Foo(int) : foo_("A") { }
3189 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3190 /// will match Foo(int), but not Foo()
3191 AST_MATCHER(CXXCtorInitializer, isWritten) {
3192 return Node.isWritten();
3195 /// \brief Matches a constructor initializer if it is initializing a base, as
3196 /// opposed to a member.
3203 /// D(int i) : I(i) {}
3209 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3210 /// will match E(), but not match D(int).
3211 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3212 return Node.isBaseInitializer();
3215 /// \brief Matches a constructor initializer if it is initializing a member, as
3216 /// opposed to a base.
3223 /// D(int i) : I(i) {}
3229 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3230 /// will match D(int), but not match E().
3231 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3232 return Node.isMemberInitializer();
3235 /// \brief Matches any argument of a call expression or a constructor call
3240 /// void x(int, int, int) { int y; x(1, y, 42); }
3242 /// callExpr(hasAnyArgument(declRefExpr()))
3243 /// matches x(1, y, 42)
3244 /// with hasAnyArgument(...)
3246 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3247 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3249 internal::Matcher<Expr>, InnerMatcher) {
3250 for (const Expr *Arg : Node.arguments()) {
3251 BoundNodesTreeBuilder Result(*Builder);
3252 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3253 *Builder = std::move(Result);
3260 /// \brief Matches a constructor call expression which uses list initialization.
3261 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3262 return Node.isListInitialization();
3265 /// \brief Matches a constructor call expression which requires
3266 /// zero initialization.
3271 /// struct point { double x; double y; };
3272 /// point pt[2] = { { 1.0, 2.0 } };
3275 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3276 /// will match the implicit array filler for pt[1].
3277 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3278 return Node.requiresZeroInitialization();
3281 /// \brief Matches the n'th parameter of a function declaration.
3285 /// class X { void f(int x) {} };
3287 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3288 /// matches f(int x) {}
3289 /// with hasParameter(...)
3291 AST_MATCHER_P2(FunctionDecl, hasParameter,
3292 unsigned, N, internal::Matcher<ParmVarDecl>,
3294 return (N < Node.getNumParams() &&
3295 InnerMatcher.matches(
3296 *Node.getParamDecl(N), Finder, Builder));
3299 /// \brief Matches all arguments and their respective ParmVarDecl.
3308 /// forEachArgumentWithParam(
3309 /// declRefExpr(to(varDecl(hasName("y")))),
3310 /// parmVarDecl(hasType(isInteger()))
3313 /// with declRefExpr(...)
3315 /// and parmVarDecl(...)
3317 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3318 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3320 internal::Matcher<Expr>, ArgMatcher,
3321 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3322 BoundNodesTreeBuilder Result;
3323 // The first argument of an overloaded member operator is the implicit object
3324 // argument of the method which should not be matched against a parameter, so
3325 // we skip over it here.
3326 BoundNodesTreeBuilder Matches;
3327 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3328 .matches(Node, Finder, &Matches)
3332 bool Matched = false;
3333 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3334 BoundNodesTreeBuilder ArgMatches(*Builder);
3335 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3336 Finder, &ArgMatches)) {
3337 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3338 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3339 hasParameter(ParamIndex, ParamMatcher)))),
3340 callExpr(callee(functionDecl(
3341 hasParameter(ParamIndex, ParamMatcher))))))
3342 .matches(Node, Finder, &ParamMatches)) {
3343 Result.addMatch(ParamMatches);
3349 *Builder = std::move(Result);
3353 /// \brief Matches any parameter of a function declaration.
3355 /// Does not match the 'this' parameter of a method.
3359 /// class X { void f(int x, int y, int z) {} };
3361 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3362 /// matches f(int x, int y, int z) {}
3363 /// with hasAnyParameter(...)
3365 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
3366 internal::Matcher<ParmVarDecl>, InnerMatcher) {
3367 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3368 Node.param_end(), Finder, Builder);
3371 /// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3372 /// specific parameter count.
3376 /// void f(int i) {}
3377 /// void g(int i, int j) {}
3378 /// void h(int i, int j);
3380 /// void k(int x, int y, int z, ...);
3382 /// functionDecl(parameterCountIs(2))
3383 /// matches void g(int i, int j) {}
3384 /// functionProtoType(parameterCountIs(2))
3385 /// matches void h(int i, int j)
3386 /// functionProtoType(parameterCountIs(3))
3387 /// matches void k(int x, int y, int z, ...);
3388 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3389 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3392 return Node.getNumParams() == N;
3395 /// \brief Matches the return type of a function declaration.
3399 /// class X { int f() { return 1; } };
3401 /// cxxMethodDecl(returns(asString("int")))
3402 /// matches int f() { return 1; }
3403 AST_MATCHER_P(FunctionDecl, returns,
3404 internal::Matcher<QualType>, InnerMatcher) {
3405 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3408 /// \brief Matches extern "C" function declarations.
3412 /// extern "C" void f() {}
3413 /// extern "C" { void g() {} }
3416 /// functionDecl(isExternC())
3417 /// matches the declaration of f and g, but not the declaration h
3418 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3420 return Node.isExternC();
3423 /// \brief Matches variable/function declarations that have "static" storage
3424 /// class specifier ("static" keyword) written in the source.
3428 /// static void f() {}
3429 /// static int i = 0;
3433 /// functionDecl(isStaticStorageClass())
3434 /// matches the function declaration f.
3435 /// varDecl(isStaticStorageClass())
3436 /// matches the variable declaration i.
3437 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
3438 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3440 return Node.getStorageClass() == SC_Static;
3443 /// \brief Matches deleted function declarations.
3448 /// void DeletedFunc() = delete;
3450 /// functionDecl(isDeleted())
3451 /// matches the declaration of DeletedFunc, but not Func.
3452 AST_MATCHER(FunctionDecl, isDeleted) {
3453 return Node.isDeleted();
3456 /// \brief Matches defaulted function declarations.
3460 /// class A { ~A(); };
3461 /// class B { ~B() = default; };
3463 /// functionDecl(isDefaulted())
3464 /// matches the declaration of ~B, but not ~A.
3465 AST_MATCHER(FunctionDecl, isDefaulted) {
3466 return Node.isDefaulted();
3469 /// \brief Matches functions that have a dynamic exception specification.
3474 /// void g() noexcept;
3475 /// void h() noexcept(true);
3476 /// void i() noexcept(false);
3477 /// void j() throw();
3478 /// void k() throw(int);
3479 /// void l() throw(...);
3481 /// functionDecl(hasDynamicExceptionSpec()) and
3482 /// functionProtoType(hasDynamicExceptionSpec())
3483 /// match the declarations of j, k, and l, but not f, g, h, or i.
3484 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
3485 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3486 FunctionProtoType)) {
3487 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
3488 return FnTy->hasDynamicExceptionSpec();
3492 /// \brief Matches functions that have a non-throwing exception specification.
3497 /// void g() noexcept;
3498 /// void h() throw();
3499 /// void i() throw(int);
3500 /// void j() noexcept(false);
3502 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
3503 /// match the declarations of g, and h, but not f, i or j.
3504 AST_POLYMORPHIC_MATCHER(isNoThrow,
3505 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3506 FunctionProtoType)) {
3507 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
3509 // If the function does not have a prototype, then it is assumed to be a
3510 // throwing function (as it would if the function did not have any exception
3515 // Assume the best for any unresolved exception specification.
3516 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3519 return FnTy->isNothrow(Finder->getASTContext());
3522 /// \brief Matches constexpr variable and function declarations.
3526 /// constexpr int foo = 42;
3527 /// constexpr int bar();
3529 /// varDecl(isConstexpr())
3530 /// matches the declaration of foo.
3531 /// functionDecl(isConstexpr())
3532 /// matches the declaration of bar.
3533 AST_POLYMORPHIC_MATCHER(isConstexpr,
3534 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3536 return Node.isConstexpr();
3539 /// \brief Matches the condition expression of an if statement, for loop,
3540 /// switch statement or conditional operator.
3542 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3546 AST_POLYMORPHIC_MATCHER_P(
3548 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3549 SwitchStmt, AbstractConditionalOperator),
3550 internal::Matcher<Expr>, InnerMatcher) {
3551 const Expr *const Condition = Node.getCond();
3552 return (Condition != nullptr &&
3553 InnerMatcher.matches(*Condition, Finder, Builder));
3556 /// \brief Matches the then-statement of an if statement.
3558 /// Examples matches the if statement
3559 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3561 /// if (false) true; else false;
3563 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3564 const Stmt *const Then = Node.getThen();
3565 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3568 /// \brief Matches the else-statement of an if statement.
3570 /// Examples matches the if statement
3571 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3573 /// if (false) false; else true;
3575 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3576 const Stmt *const Else = Node.getElse();
3577 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3580 /// \brief Matches if a node equals a previously bound node.
3582 /// Matches a node if it equals the node previously bound to \p ID.
3586 /// class X { int a; int b; };
3589 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3590 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3591 /// matches the class \c X, as \c a and \c b have the same type.
3593 /// Note that when multiple matches are involved via \c forEach* matchers,
3594 /// \c equalsBoundNodes acts as a filter.
3597 /// forEachDescendant(varDecl().bind("d")),
3598 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3599 /// will trigger a match for each combination of variable declaration
3600 /// and reference to that variable declaration within a compound statement.
3601 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3602 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3605 // FIXME: Figure out whether it makes sense to allow this
3606 // on any other node types.
3607 // For *Loc it probably does not make sense, as those seem
3608 // unique. For NestedNameSepcifier it might make sense, as
3609 // those also have pointer identity, but I'm not sure whether
3610 // they're ever reused.
3611 internal::NotEqualsBoundNodePredicate Predicate;
3613 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3614 return Builder->removeBindings(Predicate);
3617 /// \brief Matches the condition variable statement in an if statement.
3621 /// if (A* a = GetAPointer()) {}
3623 /// hasConditionVariableStatement(...)
3624 /// matches 'A* a = GetAPointer()'.
3625 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3626 internal::Matcher<DeclStmt>, InnerMatcher) {
3627 const DeclStmt* const DeclarationStatement =
3628 Node.getConditionVariableDeclStmt();
3629 return DeclarationStatement != nullptr &&
3630 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3633 /// \brief Matches the index expression of an array subscript expression.
3638 /// void f() { i[1] = 42; }
3640 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3641 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3642 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3643 internal::Matcher<Expr>, InnerMatcher) {
3644 if (const Expr* Expression = Node.getIdx())
3645 return InnerMatcher.matches(*Expression, Finder, Builder);
3649 /// \brief Matches the base expression of an array subscript expression.
3654 /// void f() { i[1] = 42; }
3656 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3657 /// hasSourceExpression(declRefExpr()))))
3658 /// matches \c i[1] with the \c declRefExpr() matching \c i
3659 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3660 internal::Matcher<Expr>, InnerMatcher) {
3661 if (const Expr* Expression = Node.getBase())
3662 return InnerMatcher.matches(*Expression, Finder, Builder);
3666 /// \brief Matches a 'for', 'while', 'do while' statement or a function
3667 /// definition that has a given body.
3673 /// hasBody(compoundStmt())
3674 /// matches 'for (;;) {}'
3675 /// with compoundStmt()
3677 AST_POLYMORPHIC_MATCHER_P(hasBody,
3678 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3682 internal::Matcher<Stmt>, InnerMatcher) {
3683 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
3684 return (Statement != nullptr &&
3685 InnerMatcher.matches(*Statement, Finder, Builder));
3688 /// \brief Matches compound statements where at least one substatement matches
3689 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
3695 /// hasAnySubstatement(compoundStmt())
3696 /// matches '{ {}; 1+2; }'
3697 /// with compoundStmt()
3699 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
3700 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
3702 internal::Matcher<Stmt>, InnerMatcher) {
3703 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
3704 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
3705 CS->body_end(), Finder, Builder);
3708 /// \brief Checks that a compound statement contains a specific number of
3709 /// child statements.
3715 /// compoundStmt(statementCountIs(0)))
3717 /// but does not match the outer compound statement.
3718 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3719 return Node.size() == N;
3722 /// \brief Matches literals that are equal to the given value.
3724 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3729 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3730 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3731 template <typename ValueT>
3732 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
3733 equals(const ValueT &Value) {
3734 return internal::PolymorphicMatcherWithParam1<
3735 internal::ValueEqualsMatcher,
3739 /// \brief Matches the operator Name of operator expressions (binary or
3742 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3746 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3747 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3749 std::string, Name) {
3750 return Name == Node.getOpcodeStr(Node.getOpcode());
3753 /// \brief Matches the left hand side of binary operator expressions.
3755 /// Example matches a (matcher = binaryOperator(hasLHS()))
3759 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3760 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3761 ArraySubscriptExpr),
3762 internal::Matcher<Expr>, InnerMatcher) {
3763 const Expr *LeftHandSide = Node.getLHS();
3764 return (LeftHandSide != nullptr &&
3765 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3768 /// \brief Matches the right hand side of binary operator expressions.
3770 /// Example matches b (matcher = binaryOperator(hasRHS()))
3774 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3775 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3776 ArraySubscriptExpr),
3777 internal::Matcher<Expr>, InnerMatcher) {
3778 const Expr *RightHandSide = Node.getRHS();
3779 return (RightHandSide != nullptr &&
3780 InnerMatcher.matches(*RightHandSide, Finder, Builder));
3783 /// \brief Matches if either the left hand side or the right hand side of a
3784 /// binary operator matches.
3785 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3786 const internal::Matcher<Expr> &InnerMatcher) {
3787 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3790 /// \brief Matches if the operand of a unary operator matches.
3792 /// Example matches true (matcher = hasUnaryOperand(
3793 /// cxxBoolLiteral(equals(true))))
3797 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3798 internal::Matcher<Expr>, InnerMatcher) {
3799 const Expr * const Operand = Node.getSubExpr();
3800 return (Operand != nullptr &&
3801 InnerMatcher.matches(*Operand, Finder, Builder));
3804 /// \brief Matches if the cast's source expression
3805 /// or opaque value's source expression matches the given matcher.
3807 /// Example 1: matches "a string"
3808 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
3810 /// class URL { URL(string); };
3811 /// URL url = "a string";
3814 /// Example 2: matches 'b' (matcher =
3815 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
3820 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
3821 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
3823 internal::Matcher<Expr>, InnerMatcher) {
3824 const Expr *const SubExpression =
3825 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
3826 return (SubExpression != nullptr &&
3827 InnerMatcher.matches(*SubExpression, Finder, Builder));
3830 /// \brief Matches casts that has a given cast kind.
3832 /// Example: matches the implicit cast around \c 0
3833 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
3837 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
3838 return Node.getCastKind() == Kind;
3841 /// \brief Matches casts whose destination type matches a given matcher.
3843 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3844 /// actual casts "explicit" casts.)
3845 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3846 internal::Matcher<QualType>, InnerMatcher) {
3847 const QualType NodeType = Node.getTypeAsWritten();
3848 return InnerMatcher.matches(NodeType, Finder, Builder);
3851 /// \brief Matches implicit casts whose destination type matches a given
3854 /// FIXME: Unit test this matcher
3855 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3856 internal::Matcher<QualType>, InnerMatcher) {
3857 return InnerMatcher.matches(Node.getType(), Finder, Builder);
3860 /// \brief Matches RecordDecl object that are spelled with "struct."
3862 /// Example matches S, but not C or U.
3868 AST_MATCHER(RecordDecl, isStruct) {
3869 return Node.isStruct();
3872 /// \brief Matches RecordDecl object that are spelled with "union."
3874 /// Example matches U, but not C or S.
3880 AST_MATCHER(RecordDecl, isUnion) {
3881 return Node.isUnion();
3884 /// \brief Matches RecordDecl object that are spelled with "class."
3886 /// Example matches C, but not S or U.
3892 AST_MATCHER(RecordDecl, isClass) {
3893 return Node.isClass();
3896 /// \brief Matches the true branch expression of a conditional operator.
3898 /// Example 1 (conditional ternary operator): matches a
3900 /// condition ? a : b
3903 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
3907 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
3908 internal::Matcher<Expr>, InnerMatcher) {
3909 const Expr *Expression = Node.getTrueExpr();
3910 return (Expression != nullptr &&
3911 InnerMatcher.matches(*Expression, Finder, Builder));
3914 /// \brief Matches the false branch expression of a conditional operator
3915 /// (binary or ternary).
3917 /// Example matches b
3919 /// condition ? a : b
3922 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
3923 internal::Matcher<Expr>, InnerMatcher) {
3924 const Expr *Expression = Node.getFalseExpr();
3925 return (Expression != nullptr &&
3926 InnerMatcher.matches(*Expression, Finder, Builder));
3929 /// \brief Matches if a declaration has a body attached.
3931 /// Example matches A, va, fa
3934 /// class B; // Doesn't match, as it has no body.
3936 /// extern int vb; // Doesn't match, as it doesn't define the variable.
3938 /// void fb(); // Doesn't match, as it has no body.
3941 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
3942 AST_POLYMORPHIC_MATCHER(isDefinition,
3943 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
3945 return Node.isThisDeclarationADefinition();
3948 /// \brief Matches if a function declaration is variadic.
3950 /// Example matches f, but not g or h. The function i will not match, even when
3951 /// compiled in C mode.
3955 /// template <typename... Ts> void h(Ts...);
3958 AST_MATCHER(FunctionDecl, isVariadic) {
3959 return Node.isVariadic();
3962 /// \brief Matches the class declaration that the given method declaration
3965 /// FIXME: Generalize this for other kinds of declarations.
3966 /// FIXME: What other kind of declarations would we need to generalize
3969 /// Example matches A() in the last line
3970 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
3971 /// ofClass(hasName("A"))))))
3979 AST_MATCHER_P(CXXMethodDecl, ofClass,
3980 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
3981 const CXXRecordDecl *Parent = Node.getParent();
3982 return (Parent != nullptr &&
3983 InnerMatcher.matches(*Parent, Finder, Builder));
3986 /// \brief Matches each method overriden by the given method. This matcher may
3987 /// produce multiple matches.
3991 /// class A { virtual void f(); };
3992 /// class B : public A { void f(); };
3993 /// class C : public B { void f(); };
3995 /// cxxMethodDecl(ofClass(hasName("C")),
3996 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
3997 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
3998 /// that B::f is not overridden by C::f).
4000 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4002 /// class A1 { virtual void f(); };
4003 /// class A2 { virtual void f(); };
4004 /// class C : public A1, public A2 { void f(); };
4006 /// cxxMethodDecl(ofClass(hasName("C")),
4007 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4008 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4009 /// once with "b" binding "A2::f" and "d" binding "C::f".
4010 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4011 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4012 BoundNodesTreeBuilder Result;
4013 bool Matched = false;
4014 for (const auto *Overridden : Node.overridden_methods()) {
4015 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4016 const bool OverriddenMatched =
4017 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4018 if (OverriddenMatched) {
4020 Result.addMatch(OverriddenBuilder);
4023 *Builder = std::move(Result);
4027 /// \brief Matches if the given method declaration is virtual.
4033 /// virtual void x();
4037 AST_MATCHER(CXXMethodDecl, isVirtual) {
4038 return Node.isVirtual();
4041 /// \brief Matches if the given method declaration has an explicit "virtual".
4047 /// virtual void x();
4049 /// class B : public A {
4054 /// matches A::x but not B::x
4055 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4056 return Node.isVirtualAsWritten();
4059 /// \brief Matches if the given method or class declaration is final.
4063 /// class A final {};
4066 /// virtual void f();
4073 /// matches A and C::f, but not B, C, or B::f
4074 AST_POLYMORPHIC_MATCHER(isFinal,
4075 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4077 return Node.template hasAttr<FinalAttr>();
4080 /// \brief Matches if the given method declaration is pure.
4086 /// virtual void x() = 0;
4090 AST_MATCHER(CXXMethodDecl, isPure) {
4091 return Node.isPure();
4094 /// \brief Matches if the given method declaration is const.
4099 /// void foo() const;
4104 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4105 AST_MATCHER(CXXMethodDecl, isConst) {
4106 return Node.isConst();
4109 /// \brief Matches if the given method declaration declares a copy assignment
4115 /// A &operator=(const A &);
4116 /// A &operator=(A &&);
4120 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4122 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4123 return Node.isCopyAssignmentOperator();
4126 /// \brief Matches if the given method declaration declares a move assignment
4132 /// A &operator=(const A &);
4133 /// A &operator=(A &&);
4137 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4139 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4140 return Node.isMoveAssignmentOperator();
4143 /// \brief Matches if the given method declaration overrides another method.
4149 /// virtual void x();
4151 /// class B : public A {
4153 /// virtual void x();
4157 AST_MATCHER(CXXMethodDecl, isOverride) {
4158 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4161 /// \brief Matches method declarations that are user-provided.
4167 /// S(const S &) = default; // #2
4168 /// S(S &&) = delete; // #3
4171 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4172 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4173 return Node.isUserProvided();
4176 /// \brief Matches member expressions that are called with '->' as opposed
4179 /// Member calls on the implicit this pointer match as called with '->'.
4184 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4189 /// memberExpr(isArrow())
4190 /// matches this->x, x, y.x, a, this->b
4191 AST_MATCHER(MemberExpr, isArrow) {
4192 return Node.isArrow();
4195 /// \brief Matches QualType nodes that are of integer type.
4203 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4204 /// matches "a(int)", "b(long)", but not "c(double)".
4205 AST_MATCHER(QualType, isInteger) {
4206 return Node->isIntegerType();
4209 /// \brief Matches QualType nodes that are of unsigned integer type.
4214 /// void b(unsigned long);
4217 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4218 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4219 AST_MATCHER(QualType, isUnsignedInteger) {
4220 return Node->isUnsignedIntegerType();
4223 /// \brief Matches QualType nodes that are of signed integer type.
4228 /// void b(unsigned long);
4231 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4232 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4233 AST_MATCHER(QualType, isSignedInteger) {
4234 return Node->isSignedIntegerType();
4237 /// \brief Matches QualType nodes that are of character type.
4242 /// void b(wchar_t);
4245 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4246 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4247 AST_MATCHER(QualType, isAnyCharacter) {
4248 return Node->isAnyCharacterType();
4251 /// \brief Matches QualType nodes that are of any pointer type; this includes
4252 /// the Objective-C object pointer type, which is different despite being
4253 /// syntactically similar.
4257 /// int *i = nullptr;
4265 /// varDecl(hasType(isAnyPointer()))
4266 /// matches "int *i" and "Foo *f", but not "int j".
4267 AST_MATCHER(QualType, isAnyPointer) {
4268 return Node->isAnyPointerType();
4271 /// \brief Matches QualType nodes that are const-qualified, i.e., that
4272 /// include "top-level" const.
4277 /// void b(int const);
4278 /// void c(const int);
4279 /// void d(const int*);
4280 /// void e(int const) {};
4282 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4283 /// matches "void b(int const)", "void c(const int)" and
4284 /// "void e(int const) {}". It does not match d as there
4285 /// is no top-level const on the parameter type "const int *".
4286 AST_MATCHER(QualType, isConstQualified) {
4287 return Node.isConstQualified();
4290 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
4291 /// include "top-level" volatile.
4296 /// void b(int volatile);
4297 /// void c(volatile int);
4298 /// void d(volatile int*);
4299 /// void e(int volatile) {};
4301 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4302 /// matches "void b(int volatile)", "void c(volatile int)" and
4303 /// "void e(int volatile) {}". It does not match d as there
4304 /// is no top-level volatile on the parameter type "volatile int *".
4305 AST_MATCHER(QualType, isVolatileQualified) {
4306 return Node.isVolatileQualified();
4309 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
4310 /// the node, not hidden within a typedef.
4314 /// typedef const int const_int;
4317 /// int *volatile k;
4320 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4321 /// \c i is const-qualified but the qualifier is not local.
4322 AST_MATCHER(QualType, hasLocalQualifiers) {
4323 return Node.hasLocalQualifiers();
4326 /// \brief Matches a member expression where the member is matched by a
4331 /// struct { int first, second; } first, second;
4332 /// int i(second.first);
4333 /// int j(first.second);
4335 /// memberExpr(member(hasName("first")))
4336 /// matches second.first
4337 /// but not first.second (because the member name there is "second").
4338 AST_MATCHER_P(MemberExpr, member,
4339 internal::Matcher<ValueDecl>, InnerMatcher) {
4340 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4343 /// \brief Matches a member expression where the object expression is
4344 /// matched by a given matcher.
4348 /// struct X { int m; };
4349 /// void f(X x) { x.m; m; }
4351 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4352 /// matches "x.m" and "m"
4353 /// with hasObjectExpression(...)
4354 /// matching "x" and the implicit object expression of "m" which has type X*.
4355 AST_MATCHER_P(MemberExpr, hasObjectExpression,
4356 internal::Matcher<Expr>, InnerMatcher) {
4357 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4360 /// \brief Matches any using shadow declaration.
4364 /// namespace X { void b(); }
4367 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
4368 /// matches \code using X::b \endcode
4369 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
4370 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4371 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
4372 Node.shadow_end(), Finder, Builder);
4375 /// \brief Matches a using shadow declaration where the target declaration is
4376 /// matched by the given matcher.
4380 /// namespace X { int a; void b(); }
4384 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
4385 /// matches \code using X::b \endcode
4386 /// but not \code using X::a \endcode
4387 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
4388 internal::Matcher<NamedDecl>, InnerMatcher) {
4389 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
4392 /// \brief Matches template instantiations of function, class, or static
4393 /// member variable template instantiations.
4397 /// template <typename T> class X {}; class A {}; X<A> x;
4401 /// template <typename T> class X {}; class A {}; template class X<A>;
4403 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4404 /// matches the template instantiation of X<A>.
4408 /// template <typename T> class X {}; class A {};
4409 /// template <> class X<A> {}; X<A> x;
4411 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4412 /// does not match, as X<A> is an explicit template specialization.
4414 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4415 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4416 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4418 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4419 Node.getTemplateSpecializationKind() ==
4420 TSK_ExplicitInstantiationDefinition);
4423 /// \brief Matches declarations that are template instantiations or are inside
4424 /// template instantiations.
4428 /// template<typename T> void A(T t) { T i; }
4432 /// functionDecl(isInstantiated())
4433 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
4434 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4435 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4436 functionDecl(isTemplateInstantiation())));
4437 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4440 /// \brief Matches statements inside of a template instantiation.
4445 /// template<typename T> void A(T t) { T i; j += 42;}
4449 /// declStmt(isInTemplateInstantiation())
4450 /// matches 'int i;' and 'unsigned i'.
4451 /// unless(stmt(isInTemplateInstantiation()))
4452 /// will NOT match j += 42; as it's shared between the template definition and
4454 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4456 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4457 functionDecl(isTemplateInstantiation())))));
4460 /// \brief Matches explicit template specializations of function, class, or
4461 /// static member variable template instantiations.
4465 /// template<typename T> void A(T t) { }
4466 /// template<> void A(int N) { }
4468 /// functionDecl(isExplicitTemplateSpecialization())
4469 /// matches the specialization A<int>().
4471 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4472 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4473 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4475 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4478 /// \brief Matches \c TypeLocs for which the given inner
4479 /// QualType-matcher matches.
4480 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4481 internal::Matcher<QualType>, InnerMatcher, 0) {
4482 return internal::BindableMatcher<TypeLoc>(
4483 new internal::TypeLocTypeMatcher(InnerMatcher));
4486 /// \brief Matches type \c bool.
4490 /// struct S { bool func(); };
4492 /// functionDecl(returns(booleanType()))
4493 /// matches "bool func();"
4494 AST_MATCHER(Type, booleanType) {
4495 return Node.isBooleanType();
4498 /// \brief Matches type \c void.
4502 /// struct S { void func(); };
4504 /// functionDecl(returns(voidType()))
4505 /// matches "void func();"
4506 AST_MATCHER(Type, voidType) {
4507 return Node.isVoidType();
4510 /// \brief Matches builtin Types.
4521 /// matches "int b", "float c" and "bool d"
4522 AST_TYPE_MATCHER(BuiltinType, builtinType);
4524 /// \brief Matches all kinds of arrays.
4528 /// int a[] = { 2, 3 };
4530 /// void f() { int c[a[0]]; }
4533 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4534 AST_TYPE_MATCHER(ArrayType, arrayType);
4536 /// \brief Matches C99 complex types.
4540 /// _Complex float f;
4543 /// matches "_Complex float f"
4544 AST_TYPE_MATCHER(ComplexType, complexType);
4546 /// \brief Matches any real floating-point type (float, double, long double).
4553 /// realFloatingPointType()
4554 /// matches "float f" but not "int i"
4555 AST_MATCHER(Type, realFloatingPointType) {
4556 return Node.isRealFloatingType();
4559 /// \brief Matches arrays and C99 complex types that have a specific element
4568 /// arrayType(hasElementType(builtinType()))
4569 /// matches "int b[7]"
4571 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
4572 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
4573 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
4576 /// \brief Matches C arrays with a specified constant size.
4582 /// int b[] = { 2, 3 };
4586 /// constantArrayType()
4587 /// matches "int a[2]"
4588 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
4590 /// \brief Matches nodes that have the specified size.
4596 /// int c[41], d[43];
4597 /// char *s = "abcd";
4598 /// wchar_t *ws = L"abcd";
4601 /// constantArrayType(hasSize(42))
4602 /// matches "int a[42]" and "int b[2 * 21]"
4603 /// stringLiteral(hasSize(4))
4604 /// matches "abcd", L"abcd"
4605 AST_POLYMORPHIC_MATCHER_P(hasSize,
4606 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
4609 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
4612 /// \brief Matches C++ arrays whose size is a value-dependent expression.
4616 /// template<typename T, int Size>
4621 /// dependentSizedArrayType
4622 /// matches "T data[Size]"
4623 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
4625 /// \brief Matches C arrays with unspecified size.
4629 /// int a[] = { 2, 3 };
4631 /// void f(int c[]) { int d[a[0]]; };
4633 /// incompleteArrayType()
4634 /// matches "int a[]" and "int c[]"
4635 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
4637 /// \brief Matches C arrays with a specified size that is not an
4638 /// integer-constant-expression.
4643 /// int a[] = { 2, 3 }
4648 /// variableArrayType()
4649 /// matches "int c[a[0]]"
4650 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
4652 /// \brief Matches \c VariableArrayType nodes that have a specific size
4661 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
4662 /// varDecl(hasName("b")))))))
4663 /// matches "int a[b]"
4664 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
4665 internal::Matcher<Expr>, InnerMatcher) {
4666 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
4669 /// \brief Matches atomic types.
4676 /// matches "_Atomic(int) i"
4677 AST_TYPE_MATCHER(AtomicType, atomicType);
4679 /// \brief Matches atomic types with a specific value type.
4684 /// _Atomic(float) f;
4686 /// atomicType(hasValueType(isInteger()))
4687 /// matches "_Atomic(int) i"
4689 /// Usable as: Matcher<AtomicType>
4690 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
4691 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
4693 /// \brief Matches types nodes representing C++11 auto types.
4698 /// int v[] = { 2, 3 }
4699 /// for (auto i : v) { }
4702 /// matches "auto n" and "auto i"
4703 AST_TYPE_MATCHER(AutoType, autoType);
4705 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
4707 /// Note: There is no \c TypeLoc for the deduced type and thus no
4708 /// \c getDeducedLoc() matcher.
4715 /// autoType(hasDeducedType(isInteger()))
4716 /// matches "auto a"
4718 /// Usable as: Matcher<AutoType>
4719 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
4720 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
4722 /// \brief Matches \c FunctionType nodes.
4730 /// matches "int (*f)(int)" and the type of "g".
4731 AST_TYPE_MATCHER(FunctionType, functionType);
4733 /// \brief Matches \c FunctionProtoType nodes.
4740 /// functionProtoType()
4741 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
4742 /// In C mode, "g" is not matched because it does not contain a prototype.
4743 AST_TYPE_MATCHER(FunctionProtoType, functionProtoType);
4745 /// \brief Matches \c ParenType nodes.
4749 /// int (*ptr_to_array)[4];
4750 /// int *array_of_ptrs[4];
4753 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
4754 /// \c array_of_ptrs.
4755 AST_TYPE_MATCHER(ParenType, parenType);
4757 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
4761 /// int (*ptr_to_array)[4];
4762 /// int (*ptr_to_func)(int);
4765 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4766 /// \c ptr_to_func but not \c ptr_to_array.
4768 /// Usable as: Matcher<ParenType>
4769 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4770 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4772 /// \brief Matches block pointer types, i.e. types syntactically represented as
4773 /// "void (^)(int)".
4775 /// The \c pointee is always required to be a \c FunctionType.
4776 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4778 /// \brief Matches member pointer types.
4781 /// struct A { int i; }
4782 /// A::* ptr = A::i;
4784 /// memberPointerType()
4785 /// matches "A::* ptr"
4786 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4788 /// \brief Matches pointer types, but does not match Objective-C object pointer
4802 /// matches "int *a", but does not match "Foo *f".
4803 AST_TYPE_MATCHER(PointerType, pointerType);
4805 /// \brief Matches an Objective-C object pointer type, which is different from
4806 /// a pointer type, despite being syntactically similar.
4817 /// matches "Foo *f", but does not match "int *a".
4818 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4820 /// \brief Matches both lvalue and rvalue reference types.
4833 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4834 AST_TYPE_MATCHER(ReferenceType, referenceType);
4836 /// \brief Matches lvalue reference types.
4849 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4850 /// matched since the type is deduced as int& by reference collapsing rules.
4851 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4853 /// \brief Matches rvalue reference types.
4866 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4867 /// matched as it is deduced to int& by reference collapsing rules.
4868 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4870 /// \brief Narrows PointerType (and similar) matchers to those where the
4871 /// \c pointee matches a given matcher.
4879 /// pointerType(pointee(isConstQualified(), isInteger()))
4880 /// matches "int const *b"
4882 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4883 /// Matcher<PointerType>, Matcher<ReferenceType>
4884 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4885 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4890 /// \brief Matches typedef types.
4897 /// matches "typedef int X"
4898 AST_TYPE_MATCHER(TypedefType, typedefType);
4900 /// \brief Matches enum types.
4904 /// enum C { Green };
4905 /// enum class S { Red };
4911 /// \c enumType() matches the type of the variable declarations of both \c c and
4913 AST_TYPE_MATCHER(EnumType, enumType);
4915 /// \brief Matches template specialization types.
4919 /// template <typename T>
4922 /// template class C<int>; // A
4923 /// C<char> var; // B
4926 /// \c templateSpecializationType() matches the type of the explicit
4927 /// instantiation in \c A and the type of the variable declaration in \c B.
4928 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
4930 /// \brief Matches types nodes representing unary type transformations.
4934 /// typedef __underlying_type(T) type;
4936 /// unaryTransformType()
4937 /// matches "__underlying_type(T)"
4938 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
4940 /// \brief Matches record types (e.g. structs, classes).
4951 /// \c recordType() matches the type of the variable declarations of both \c c
4953 AST_TYPE_MATCHER(RecordType, recordType);
4955 /// \brief Matches types specified with an elaborated type keyword or with a
4971 /// \c elaboratedType() matches the type of the variable declarations of both
4973 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
4975 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
4976 /// matches \c InnerMatcher if the qualifier exists.
4988 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
4989 /// matches the type of the variable declaration of \c d.
4990 AST_MATCHER_P(ElaboratedType, hasQualifier,
4991 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
4992 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
4993 return InnerMatcher.matches(*Qualifier, Finder, Builder);
4998 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5010 /// \c elaboratedType(namesType(recordType(
5011 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5012 /// declaration of \c d.
5013 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5015 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5018 /// \brief Matches types that represent the result of substituting a type for a
5019 /// template type parameter.
5023 /// template <typename T>
5029 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5030 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
5032 /// \brief Matches template type parameter substitutions that have a replacement
5033 /// type that matches the provided matcher.
5037 /// template <typename T>
5040 /// double j = F(i);
5043 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5044 AST_TYPE_TRAVERSE_MATCHER(
5045 hasReplacementType, getReplacementType,
5046 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5048 /// \brief Matches template type parameter types.
5050 /// Example matches T, but not int.
5051 /// (matcher = templateTypeParmType())
5053 /// template <typename T> void f(int i);
5055 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
5057 /// \brief Matches injected class name types.
5059 /// Example matches S s, but not S<T> s.
5060 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5062 /// template <typename T> struct S {
5067 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
5069 /// \brief Matches decayed type
5070 /// Example matches i[] in declaration of f.
5071 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5072 /// Example matches i[1].
5073 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5075 /// void f(int i[]) {
5079 AST_TYPE_MATCHER(DecayedType, decayedType);
5081 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
5082 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5084 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5087 /// \brief Matches declarations whose declaration context, interpreted as a
5088 /// Decl, matches \c InnerMatcher.
5099 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5100 /// declaration of \c class \c D.
5101 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5102 const DeclContext *DC = Node.getDeclContext();
5103 if (!DC) return false;
5104 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5107 /// \brief Matches nested name specifiers.
5112 /// struct A { static void f(); };
5114 /// void g() { A::f(); }
5118 /// nestedNameSpecifier()
5119 /// matches "ns::" and both "A::"
5120 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
5122 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5123 const internal::VariadicAllOfMatcher<
5124 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
5126 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
5127 /// NestedNameSpecifier-matcher matches.
5128 AST_MATCHER_FUNCTION_P_OVERLOAD(
5129 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5130 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5131 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5132 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5136 /// \brief Matches nested name specifiers that specify a type matching the
5137 /// given \c QualType matcher without qualifiers.
5141 /// struct A { struct B { struct C {}; }; };
5144 /// nestedNameSpecifier(specifiesType(
5145 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5148 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5149 internal::Matcher<QualType>, InnerMatcher) {
5150 if (!Node.getAsType())
5152 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5155 /// \brief Matches nested name specifier locs that specify a type matching the
5156 /// given \c TypeLoc.
5160 /// struct A { struct B { struct C {}; }; };
5163 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5164 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5166 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5167 internal::Matcher<TypeLoc>, InnerMatcher) {
5168 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5171 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
5175 /// struct A { struct B { struct C {}; }; };
5178 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5180 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5181 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5183 const NestedNameSpecifier *NextNode = Node.getPrefix();
5186 return InnerMatcher.matches(*NextNode, Finder, Builder);
5189 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
5193 /// struct A { struct B { struct C {}; }; };
5196 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5198 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5199 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5201 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5204 return InnerMatcher.matches(NextNode, Finder, Builder);
5207 /// \brief Matches nested name specifiers that specify a namespace matching the
5208 /// given namespace matcher.
5212 /// namespace ns { struct A {}; }
5215 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5217 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5218 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5219 if (!Node.getAsNamespace())
5221 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5224 /// \brief Overloads for the \c equalsNode matcher.
5225 /// FIXME: Implement for other node types.
5228 /// \brief Matches if a node equals another node.
5230 /// \c Decl has pointer identity in the AST.
5231 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5232 return &Node == Other;
5234 /// \brief Matches if a node equals another node.
5236 /// \c Stmt has pointer identity in the AST.
5237 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5238 return &Node == Other;
5240 /// \brief Matches if a node equals another node.
5242 /// \c Type has pointer identity in the AST.
5243 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5244 return &Node == Other;
5249 /// \brief Matches each case or default statement belonging to the given switch
5250 /// statement. This matcher may produce multiple matches.
5254 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5256 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5257 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5258 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5259 /// "switch (1)", "switch (2)" and "switch (2)".
5260 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5262 BoundNodesTreeBuilder Result;
5263 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5264 // iteration order. We should use the more general iterating matchers once
5265 // they are capable of expressing this matcher (for example, it should ignore
5266 // case statements belonging to nested switch statements).
5267 bool Matched = false;
5268 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5269 SC = SC->getNextSwitchCase()) {
5270 BoundNodesTreeBuilder CaseBuilder(*Builder);
5271 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5274 Result.addMatch(CaseBuilder);
5277 *Builder = std::move(Result);
5281 /// \brief Matches each constructor initializer in a constructor definition.
5285 /// class A { A() : i(42), j(42) {} int i; int j; };
5287 /// cxxConstructorDecl(forEachConstructorInitializer(
5288 /// forField(decl().bind("x"))
5290 /// will trigger two matches, binding for 'i' and 'j' respectively.
5291 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5292 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5293 BoundNodesTreeBuilder Result;
5294 bool Matched = false;
5295 for (const auto *I : Node.inits()) {
5296 BoundNodesTreeBuilder InitBuilder(*Builder);
5297 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5299 Result.addMatch(InitBuilder);
5302 *Builder = std::move(Result);
5306 /// \brief Matches constructor declarations that are copy constructors.
5312 /// S(const S &); // #2
5316 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
5317 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
5318 return Node.isCopyConstructor();
5321 /// \brief Matches constructor declarations that are move constructors.
5327 /// S(const S &); // #2
5331 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
5332 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
5333 return Node.isMoveConstructor();
5336 /// \brief Matches constructor declarations that are default constructors.
5342 /// S(const S &); // #2
5346 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
5347 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
5348 return Node.isDefaultConstructor();
5351 /// \brief Matches constructors that delegate to another constructor.
5358 /// S(S &&) : S() {} // #3
5360 /// S::S() : S(0) {} // #4
5362 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
5364 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
5365 return Node.isDelegatingConstructor();
5368 /// \brief Matches constructor and conversion declarations that are marked with
5369 /// the explicit keyword.
5375 /// explicit S(double); // #2
5376 /// operator int(); // #3
5377 /// explicit operator bool(); // #4
5380 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
5381 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
5382 AST_POLYMORPHIC_MATCHER(isExplicit,
5383 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
5384 CXXConversionDecl)) {
5385 return Node.isExplicit();
5388 /// \brief Matches function and namespace declarations that are marked with
5389 /// the inline keyword.
5393 /// inline void f();
5396 /// inline namespace m {}
5399 /// functionDecl(isInline()) will match ::f().
5400 /// namespaceDecl(isInline()) will match n::m.
5401 AST_POLYMORPHIC_MATCHER(isInline,
5402 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
5404 // This is required because the spelling of the function used to determine
5405 // whether inline is specified or not differs between the polymorphic types.
5406 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
5407 return FD->isInlineSpecified();
5408 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
5409 return NSD->isInline();
5410 llvm_unreachable("Not a valid polymorphic type");
5413 /// \brief Matches anonymous namespace declarations.
5418 /// namespace {} // #1
5421 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
5422 AST_MATCHER(NamespaceDecl, isAnonymous) {
5423 return Node.isAnonymousNamespace();
5426 /// \brief If the given case statement does not use the GNU case range
5427 /// extension, matches the constant given in the statement.
5431 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
5433 /// caseStmt(hasCaseConstant(integerLiteral()))
5434 /// matches "case 1:"
5435 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
5440 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
5443 /// \brief Matches declaration that has a given attribute.
5447 /// __attribute__((device)) void f() { ... }
5449 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
5450 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
5451 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
5452 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
5453 for (const auto *Attr : Node.attrs()) {
5454 if (Attr->getKind() == AttrKind)
5460 /// \brief Matches the return value expression of a return statement
5466 /// hasReturnValue(binaryOperator())
5467 /// matches 'return a + b'
5468 /// with binaryOperator()
5469 /// matching 'a + b'
5470 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5472 if (const auto *RetValue = Node.getRetValue())
5473 return InnerMatcher.matches(*RetValue, Finder, Builder);
5478 /// \brief Matches CUDA kernel call expression.
5480 /// Example matches,
5482 /// kernel<<<i,j>>>();
5484 const internal::VariadicDynCastAllOfMatcher<
5486 CUDAKernelCallExpr> cudaKernelCallExpr;
5489 /// \brief Matches expressions that resolve to a null pointer constant, such as
5490 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5494 /// void *v1 = NULL;
5495 /// void *v2 = nullptr;
5496 /// void *v3 = __null; // GNU extension
5497 /// char *cp = (char *)0;
5501 /// expr(nullPointerConstant())
5502 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5503 /// initializer for i.
5504 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5506 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5507 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5510 /// \brief Matches declaration of the function the statemenet belongs to
5514 /// F& operator=(const F& o) {
5515 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
5519 /// returnStmt(forFunction(hasName("operator=")))
5520 /// matches 'return *this'
5521 /// but does match 'return > 0'
5522 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
5524 const auto &Parents = Finder->getASTContext().getParents(Node);
5526 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
5528 while(!Stack.empty()) {
5529 const auto &CurNode = Stack.back();
5531 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
5532 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
5535 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
5536 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
5541 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
5542 Stack.push_back(Parent);
5548 /// \brief Matches a declaration that has external formal linkage.
5550 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
5559 /// Example matches f() because it has external formal linkage despite being
5560 /// unique to the translation unit as though it has internal likage
5561 /// (matcher = functionDecl(hasExternalFormalLinkage()))
5568 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
5569 return Node.hasExternalFormalLinkage();
5572 } // end namespace ast_matchers
5573 } // end namespace clang