1 //===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements matchers to be used together with the MatchFinder to
12 // Matchers are created by generator functions, which can be combined in
13 // a functional in-language DSL to express queries over the C++ AST.
15 // For example, to match a class with a certain name, one would call:
16 // cxxRecordDecl(hasName("MyClass"))
17 // which returns a matcher that can be used to find all AST nodes that declare
18 // a class named 'MyClass'.
20 // For more complicated match expressions we're often interested in accessing
21 // multiple parts of the matched AST nodes once a match is found. In that case,
22 // use the id(...) matcher around the match expressions that match the nodes
23 // you want to access.
25 // For example, when we're interested in child classes of a certain class, we
27 // cxxRecordDecl(hasName("MyClass"), has(id("child", recordDecl())))
28 // When the match is found via the MatchFinder, a user provided callback will
29 // be called with a BoundNodes instance that contains a mapping from the
30 // strings that we provided for the id(...) calls to the nodes that were
32 // In the given example, each time our matcher finds a match we get a callback
33 // where "child" is bound to the RecordDecl node of the matching child
36 // See ASTMatchersInternal.h for a more in-depth explanation of the
37 // implementation details of the matcher framework.
39 // See ASTMatchFinder.h for how to use the generated matchers to run over
42 //===----------------------------------------------------------------------===//
44 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
45 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
47 #include "clang/AST/ASTContext.h"
48 #include "clang/AST/ASTTypeTraits.h"
49 #include "clang/AST/Attr.h"
50 #include "clang/AST/Decl.h"
51 #include "clang/AST/DeclCXX.h"
52 #include "clang/AST/DeclFriend.h"
53 #include "clang/AST/DeclObjC.h"
54 #include "clang/AST/DeclTemplate.h"
55 #include "clang/AST/Expr.h"
56 #include "clang/AST/ExprCXX.h"
57 #include "clang/AST/ExprObjC.h"
58 #include "clang/AST/NestedNameSpecifier.h"
59 #include "clang/AST/OpenMPClause.h"
60 #include "clang/AST/OperationKinds.h"
61 #include "clang/AST/Stmt.h"
62 #include "clang/AST/StmtCXX.h"
63 #include "clang/AST/StmtObjC.h"
64 #include "clang/AST/StmtOpenMP.h"
65 #include "clang/AST/TemplateBase.h"
66 #include "clang/AST/TemplateName.h"
67 #include "clang/AST/Type.h"
68 #include "clang/AST/TypeLoc.h"
69 #include "clang/ASTMatchers/ASTMatchersInternal.h"
70 #include "clang/ASTMatchers/ASTMatchersMacros.h"
71 #include "clang/Basic/AttrKinds.h"
72 #include "clang/Basic/ExceptionSpecificationType.h"
73 #include "clang/Basic/IdentifierTable.h"
74 #include "clang/Basic/LLVM.h"
75 #include "clang/Basic/SourceManager.h"
76 #include "clang/Basic/Specifiers.h"
77 #include "clang/Basic/TypeTraits.h"
78 #include "llvm/ADT/ArrayRef.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringRef.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Regex.h"
94 namespace ast_matchers {
96 /// Maps string IDs to AST nodes matched by parts of a matcher.
98 /// The bound nodes are generated by calling \c bind("id") on the node matchers
99 /// of the nodes we want to access later.
101 /// The instances of BoundNodes are created by \c MatchFinder when the user's
102 /// callbacks are executed every time a match is found.
105 /// Returns the AST node bound to \c ID.
107 /// Returns NULL if there was no node bound to \c ID or if there is a node but
108 /// it cannot be converted to the specified type.
109 template <typename T>
110 const T *getNodeAs(StringRef ID) const {
111 return MyBoundNodes.getNodeAs<T>(ID);
114 /// Type of mapping from binding identifiers to bound nodes. This type
115 /// is an associative container with a key type of \c std::string and a value
116 /// type of \c clang::ast_type_traits::DynTypedNode
117 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
119 /// Retrieve mapping from binding identifiers to bound nodes.
120 const IDToNodeMap &getMap() const {
121 return MyBoundNodes.getMap();
125 friend class internal::BoundNodesTreeBuilder;
127 /// Create BoundNodes from a pre-filled map of bindings.
128 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
129 : MyBoundNodes(MyBoundNodes) {}
131 internal::BoundNodesMap MyBoundNodes;
134 /// If the provided matcher matches a node, binds the node to \c ID.
136 /// FIXME: Do we want to support this now that we have bind()?
137 template <typename T>
138 internal::Matcher<T> id(StringRef ID,
139 const internal::BindableMatcher<T> &InnerMatcher) {
140 return InnerMatcher.bind(ID);
143 /// Types of matchers for the top-level classes in the AST class
146 using DeclarationMatcher = internal::Matcher<Decl>;
147 using StatementMatcher = internal::Matcher<Stmt>;
148 using TypeMatcher = internal::Matcher<QualType>;
149 using TypeLocMatcher = internal::Matcher<TypeLoc>;
150 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
151 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
152 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
155 /// Matches any node.
157 /// Useful when another matcher requires a child matcher, but there's no
158 /// additional constraint. This will often be used with an explicit conversion
159 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
161 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
163 /// "int* p" and "void f()" in
168 /// Usable as: Any Matcher
169 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
171 /// Matches the top declaration context.
178 /// } // namespace NS
180 /// decl(hasDeclContext(translationUnitDecl()))
181 /// matches "int X", but not "int Y".
182 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
185 /// Matches typedef declarations.
193 /// matches "typedef int X", but not "using Y = int"
194 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
197 /// Matches typedef name declarations.
204 /// typedefNameDecl()
205 /// matches "typedef int X" and "using Y = int"
206 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
209 /// Matches type alias declarations.
217 /// matches "using Y = int", but not "typedef int X"
218 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
221 /// Matches type alias template declarations.
223 /// typeAliasTemplateDecl() matches
225 /// template <typename T>
228 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
229 typeAliasTemplateDecl;
231 /// Matches AST nodes that were expanded within the main-file.
233 /// Example matches X but not Y
234 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
244 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
245 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
246 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
247 auto &SourceManager = Finder->getASTContext().getSourceManager();
248 return SourceManager.isInMainFile(
249 SourceManager.getExpansionLoc(Node.getBeginLoc()));
252 /// Matches AST nodes that were expanded within system-header-files.
254 /// Example matches Y but not X
255 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
257 /// #include <SystemHeader.h>
265 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
266 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
267 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
268 auto &SourceManager = Finder->getASTContext().getSourceManager();
269 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
270 if (ExpansionLoc.isInvalid()) {
273 return SourceManager.isInSystemHeader(ExpansionLoc);
276 /// Matches AST nodes that were expanded within files whose name is
277 /// partially matching a given regex.
279 /// Example matches Y but not X
280 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
282 /// #include "ASTMatcher.h"
290 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
291 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
292 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
293 std::string, RegExp) {
294 auto &SourceManager = Finder->getASTContext().getSourceManager();
295 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
296 if (ExpansionLoc.isInvalid()) {
300 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
305 auto Filename = FileEntry->getName();
306 llvm::Regex RE(RegExp);
307 return RE.match(Filename);
310 /// Matches declarations.
312 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
319 extern const internal::VariadicAllOfMatcher<Decl> decl;
321 /// Matches a declaration of a linkage specification.
327 /// linkageSpecDecl()
328 /// matches "extern "C" {}"
329 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
332 /// Matches a declaration of anything that could have a name.
334 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
343 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
345 /// Matches a declaration of label.
354 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
356 /// Matches a declaration of a namespace.
361 /// namespace test {}
364 /// matches "namespace {}" and "namespace test {}"
365 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
368 /// Matches a declaration of a namespace alias.
372 /// namespace test {}
373 /// namespace alias = ::test;
375 /// namespaceAliasDecl()
376 /// matches "namespace alias" but not "namespace test"
377 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
380 /// Matches class, struct, and union declarations.
382 /// Example matches \c X, \c Z, \c U, and \c S
385 /// template<class T> class Z {};
389 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
391 /// Matches C++ class declarations.
393 /// Example matches \c X, \c Z
396 /// template<class T> class Z {};
398 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
401 /// Matches C++ class template declarations.
403 /// Example matches \c Z
405 /// template<class T> class Z {};
407 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
410 /// Matches C++ class template specializations.
414 /// template<typename T> class A {};
415 /// template<> class A<double> {};
418 /// classTemplateSpecializationDecl()
419 /// matches the specializations \c A<int> and \c A<double>
420 extern const internal::VariadicDynCastAllOfMatcher<
421 Decl, ClassTemplateSpecializationDecl>
422 classTemplateSpecializationDecl;
424 /// Matches C++ class template partial specializations.
428 /// template<class T1, class T2, int I>
431 /// template<class T, int I>
432 /// class A<T, T*, I> {};
435 /// class A<int, int, 1> {};
437 /// classTemplatePartialSpecializationDecl()
438 /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
439 extern const internal::VariadicDynCastAllOfMatcher<
440 Decl, ClassTemplatePartialSpecializationDecl>
441 classTemplatePartialSpecializationDecl;
443 /// Matches declarator declarations (field, variable, function
444 /// and non-type template parameter declarations).
448 /// class X { int y; };
451 /// matches \c int y.
452 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
455 /// Matches parameter variable declarations.
462 /// matches \c int x.
463 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
466 /// Matches C++ access specifier declarations.
476 /// matches 'public:'
477 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
480 /// Matches constructor initializers.
482 /// Examples matches \c i(42).
489 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
492 /// Matches template arguments.
496 /// template <typename T> struct C {};
499 /// templateArgument()
500 /// matches 'int' in C<int>.
501 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
503 /// Matches template name.
507 /// template <typename T> class X { };
511 /// matches 'X' in X<int>.
512 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
514 /// Matches non-type template parameter declarations.
518 /// template <typename T, int N> struct C {};
520 /// nonTypeTemplateParmDecl()
521 /// matches 'N', but not 'T'.
522 extern const internal::VariadicDynCastAllOfMatcher<Decl,
523 NonTypeTemplateParmDecl>
524 nonTypeTemplateParmDecl;
526 /// Matches template type parameter declarations.
530 /// template <typename T, int N> struct C {};
532 /// templateTypeParmDecl()
533 /// matches 'T', but not 'N'.
534 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
535 templateTypeParmDecl;
537 /// Matches public C++ declarations.
543 /// protected: int b;
547 /// fieldDecl(isPublic())
549 AST_MATCHER(Decl, isPublic) {
550 return Node.getAccess() == AS_public;
553 /// Matches protected C++ declarations.
559 /// protected: int b;
563 /// fieldDecl(isProtected())
565 AST_MATCHER(Decl, isProtected) {
566 return Node.getAccess() == AS_protected;
569 /// Matches private C++ declarations.
575 /// protected: int b;
579 /// fieldDecl(isPrivate())
581 AST_MATCHER(Decl, isPrivate) {
582 return Node.getAccess() == AS_private;
585 /// Matches non-static data members that are bit-fields.
594 /// fieldDecl(isBitField())
595 /// matches 'int a;' but not 'int b;'.
596 AST_MATCHER(FieldDecl, isBitField) {
597 return Node.isBitField();
600 /// Matches non-static data members that are bit-fields of the specified
611 /// fieldDecl(hasBitWidth(2))
612 /// matches 'int a;' and 'int c;' but not 'int b;'.
613 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
614 return Node.isBitField() &&
615 Node.getBitWidthValue(Finder->getASTContext()) == Width;
618 /// Matches non-static data members that have an in-class initializer.
628 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
629 /// matches 'int a;' but not 'int b;'.
630 /// fieldDecl(hasInClassInitializer(anything()))
631 /// matches 'int a;' and 'int b;' but not 'int c;'.
632 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
634 const Expr *Initializer = Node.getInClassInitializer();
635 return (Initializer != nullptr &&
636 InnerMatcher.matches(*Initializer, Finder, Builder));
639 /// Determines whether the function is "main", which is the entry point
640 /// into an executable program.
641 AST_MATCHER(FunctionDecl, isMain) {
642 return Node.isMain();
645 /// Matches the specialized template of a specialization declaration.
649 /// template<typename T> class A {}; #1
650 /// template<> class A<int> {}; #2
652 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
653 /// matches '#2' with classTemplateDecl() matching the class template
654 /// declaration of 'A' at #1.
655 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
656 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
657 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
658 return (Decl != nullptr &&
659 InnerMatcher.matches(*Decl, Finder, Builder));
662 /// Matches a declaration that has been implicitly added
663 /// by the compiler (eg. implicit default/copy constructors).
664 AST_MATCHER(Decl, isImplicit) {
665 return Node.isImplicit();
668 /// Matches classTemplateSpecializations, templateSpecializationType and
669 /// functionDecl that have at least one TemplateArgument matching the given
674 /// template<typename T> class A {};
675 /// template<> class A<double> {};
678 /// template<typename T> f() {};
679 /// void func() { f<int>(); };
683 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
684 /// refersToType(asString("int"))))
685 /// matches the specialization \c A<int>
687 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
688 /// matches the specialization \c f<int>
689 AST_POLYMORPHIC_MATCHER_P(
690 hasAnyTemplateArgument,
691 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
692 TemplateSpecializationType,
694 internal::Matcher<TemplateArgument>, InnerMatcher) {
695 ArrayRef<TemplateArgument> List =
696 internal::getTemplateSpecializationArgs(Node);
697 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
701 /// Matches expressions that match InnerMatcher after any implicit AST
702 /// nodes are stripped off.
704 /// Parentheses and explicit casts are not discarded.
714 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
716 /// would match the declarations for a, b, and c.
719 /// varDecl(hasInitializer(cxxConstructExpr()))
721 /// only match the declarations for b and c.
722 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
724 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
727 /// Matches expressions that match InnerMatcher after any implicit casts
728 /// are stripped off.
730 /// Parentheses and explicit casts are not discarded.
738 /// long e = (long) 0l;
742 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
743 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
745 /// would match the declarations for a, b, c, and d, but not e.
748 /// varDecl(hasInitializer(integerLiteral()))
749 /// varDecl(hasInitializer(declRefExpr()))
751 /// only match the declarations for b, c, and d.
752 AST_MATCHER_P(Expr, ignoringImpCasts,
753 internal::Matcher<Expr>, InnerMatcher) {
754 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
757 /// Matches expressions that match InnerMatcher after parentheses and
758 /// casts are stripped off.
760 /// Implicit and non-C Style casts are also discarded.
765 /// void* c = reinterpret_cast<char*>(0);
766 /// char d = char(0);
769 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
770 /// would match the declarations for a, b, c, and d.
772 /// varDecl(hasInitializer(integerLiteral()))
773 /// only match the declaration for a.
774 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
775 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
778 /// Matches expressions that match InnerMatcher after implicit casts and
779 /// parentheses are stripped off.
781 /// Explicit casts are not discarded.
789 /// long e = ((long) 0l);
792 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
793 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
794 /// would match the declarations for a, b, c, and d, but not e.
796 /// varDecl(hasInitializer(integerLiteral()))
797 /// varDecl(hasInitializer(declRefExpr()))
798 /// would only match the declaration for a.
799 AST_MATCHER_P(Expr, ignoringParenImpCasts,
800 internal::Matcher<Expr>, InnerMatcher) {
801 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
804 /// Matches types that match InnerMatcher after any parens are stripped.
808 /// void (*fp)(void);
812 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
814 /// would match the declaration for fp.
815 AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
817 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
820 /// Overload \c ignoringParens for \c Expr.
824 /// const char* str = ("my-string");
828 /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
830 /// would match the implicit cast resulting from the assignment.
831 AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
833 const Expr *E = Node.IgnoreParens();
834 return InnerMatcher.matches(*E, Finder, Builder);
837 /// Matches expressions that are instantiation-dependent even if it is
838 /// neither type- nor value-dependent.
840 /// In the following example, the expression sizeof(sizeof(T() + T()))
841 /// is instantiation-dependent (since it involves a template parameter T),
842 /// but is neither type- nor value-dependent, since the type of the inner
843 /// sizeof is known (std::size_t) and therefore the size of the outer
846 /// template<typename T>
847 /// void f(T x, T y) { sizeof(sizeof(T() + T()); }
849 /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
850 AST_MATCHER(Expr, isInstantiationDependent) {
851 return Node.isInstantiationDependent();
854 /// Matches expressions that are type-dependent because the template type
855 /// is not yet instantiated.
857 /// For example, the expressions "x" and "x + y" are type-dependent in
858 /// the following code, but "y" is not type-dependent:
860 /// template<typename T>
861 /// void add(T x, int y) {
865 /// expr(isTypeDependent()) matches x + y
866 AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
868 /// Matches expression that are value-dependent because they contain a
869 /// non-type template parameter.
871 /// For example, the array bound of "Chars" in the following example is
874 /// template<int Size> int f() { return Size; }
876 /// expr(isValueDependent()) matches return Size
877 AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
879 /// Matches classTemplateSpecializations, templateSpecializationType and
880 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
884 /// template<typename T, typename U> class A {};
888 /// template<typename T> void f() {}
889 /// void func() { f<int>(); };
891 /// classTemplateSpecializationDecl(hasTemplateArgument(
892 /// 1, refersToType(asString("int"))))
893 /// matches the specialization \c A<bool, int>
895 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
896 /// matches the specialization \c f<int>
897 AST_POLYMORPHIC_MATCHER_P2(
899 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
900 TemplateSpecializationType,
902 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
903 ArrayRef<TemplateArgument> List =
904 internal::getTemplateSpecializationArgs(Node);
905 if (List.size() <= N)
907 return InnerMatcher.matches(List[N], Finder, Builder);
910 /// Matches if the number of template arguments equals \p N.
914 /// template<typename T> struct C {};
917 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
919 AST_POLYMORPHIC_MATCHER_P(
920 templateArgumentCountIs,
921 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
922 TemplateSpecializationType),
924 return internal::getTemplateSpecializationArgs(Node).size() == N;
927 /// Matches a TemplateArgument that refers to a certain type.
932 /// template<typename T> struct A {};
935 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
936 /// refersToType(class(hasName("X")))))
937 /// matches the specialization \c A<X>
938 AST_MATCHER_P(TemplateArgument, refersToType,
939 internal::Matcher<QualType>, InnerMatcher) {
940 if (Node.getKind() != TemplateArgument::Type)
942 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
945 /// Matches a TemplateArgument that refers to a certain template.
949 /// template<template <typename> class S> class X {};
950 /// template<typename T> class Y {};
953 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
954 /// refersToTemplate(templateName())))
955 /// matches the specialization \c X<Y>
956 AST_MATCHER_P(TemplateArgument, refersToTemplate,
957 internal::Matcher<TemplateName>, InnerMatcher) {
958 if (Node.getKind() != TemplateArgument::Template)
960 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
963 /// Matches a canonical TemplateArgument that refers to a certain
968 /// struct B { int next; };
969 /// template<int(B::*next_ptr)> struct A {};
972 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
973 /// refersToDeclaration(fieldDecl(hasName("next")))))
974 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
976 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
977 internal::Matcher<Decl>, InnerMatcher) {
978 if (Node.getKind() == TemplateArgument::Declaration)
979 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
983 /// Matches a sugar TemplateArgument that refers to a certain expression.
987 /// struct B { int next; };
988 /// template<int(B::*next_ptr)> struct A {};
991 /// templateSpecializationType(hasAnyTemplateArgument(
992 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
993 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
995 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
996 if (Node.getKind() == TemplateArgument::Expression)
997 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1001 /// Matches a TemplateArgument that is an integral value.
1005 /// template<int T> struct C {};
1008 /// classTemplateSpecializationDecl(
1009 /// hasAnyTemplateArgument(isIntegral()))
1010 /// matches the implicit instantiation of C in C<42>
1011 /// with isIntegral() matching 42.
1012 AST_MATCHER(TemplateArgument, isIntegral) {
1013 return Node.getKind() == TemplateArgument::Integral;
1016 /// Matches a TemplateArgument that referes to an integral type.
1020 /// template<int T> struct C {};
1023 /// classTemplateSpecializationDecl(
1024 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1025 /// matches the implicit instantiation of C in C<42>.
1026 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1027 internal::Matcher<QualType>, InnerMatcher) {
1028 if (Node.getKind() != TemplateArgument::Integral)
1030 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1033 /// Matches a TemplateArgument of integral type with a given value.
1035 /// Note that 'Value' is a string as the template argument's value is
1036 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
1037 /// representation of that integral value in base 10.
1041 /// template<int T> struct C {};
1044 /// classTemplateSpecializationDecl(
1045 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
1046 /// matches the implicit instantiation of C in C<42>.
1047 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1048 std::string, Value) {
1049 if (Node.getKind() != TemplateArgument::Integral)
1051 return Node.getAsIntegral().toString(10) == Value;
1054 /// Matches an Objective-C autorelease pool statement.
1058 /// @autoreleasepool {
1062 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1063 /// inside the autorelease pool.
1064 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1065 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1067 /// Matches any value declaration.
1069 /// Example matches A, B, C and F
1071 /// enum X { A, B, C };
1074 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1076 /// Matches C++ constructor declarations.
1078 /// Example matches Foo::Foo() and Foo::Foo(int)
1084 /// int DoSomething();
1087 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1090 /// Matches explicit C++ destructor declarations.
1092 /// Example matches Foo::~Foo()
1099 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1102 /// Matches enum declarations.
1104 /// Example matches X
1110 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1112 /// Matches enum constants.
1114 /// Example matches A, B, C
1120 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1123 /// Matches method declarations.
1125 /// Example matches y
1127 /// class X { void y(); };
1129 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1132 /// Matches conversion operator declarations.
1134 /// Example matches the operator.
1136 /// class X { operator int() const; };
1138 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1141 /// Matches user-defined and implicitly generated deduction guide.
1143 /// Example matches the deduction guide.
1145 /// template<typename T>
1146 /// class X { X(int) };
1147 /// X(int) -> X<int>;
1149 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1150 cxxDeductionGuideDecl;
1152 /// Matches variable declarations.
1154 /// Note: this does not match declarations of member variables, which are
1155 /// "field" declarations in Clang parlance.
1157 /// Example matches a
1161 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1163 /// Matches field declarations.
1167 /// class X { int m; };
1171 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1173 /// Matches indirect field declarations.
1177 /// struct X { struct { int a; }; };
1179 /// indirectFieldDecl()
1181 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1184 /// Matches function declarations.
1186 /// Example matches f
1190 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1193 /// Matches C++ function template declarations.
1195 /// Example matches f
1197 /// template<class T> void f(T t) {}
1199 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1200 functionTemplateDecl;
1202 /// Matches friend declarations.
1206 /// class X { friend void foo(); };
1209 /// matches 'friend void foo()'.
1210 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1212 /// Matches statements.
1219 /// matches both the compound statement '{ ++a; }' and '++a'.
1220 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1222 /// Matches declaration statements.
1229 /// matches 'int a'.
1230 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1232 /// Matches member expressions.
1237 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1238 /// int a; static int b;
1242 /// matches this->x, x, y.x, a, this->b
1243 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1245 /// Matches unresolved member expressions.
1250 /// template <class T> void f();
1253 /// template <class T> void h() { X x; x.f<T>(); x.g(); }
1255 /// unresolvedMemberExpr()
1257 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1258 unresolvedMemberExpr;
1260 /// Matches member expressions where the actual member referenced could not be
1261 /// resolved because the base expression or the member name was dependent.
1265 /// template <class T> void f() { T t; t.g(); }
1267 /// cxxDependentScopeMemberExpr()
1269 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1270 CXXDependentScopeMemberExpr>
1271 cxxDependentScopeMemberExpr;
1273 /// Matches call expressions.
1275 /// Example matches x.y() and y()
1281 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1283 /// Matches call expressions which were resolved using ADL.
1285 /// Example matches y(x) but not y(42) or NS::y(x).
1296 /// y(x); // Matches
1297 /// NS::y(x); // Doesn't match
1298 /// y(42); // Doesn't match
1300 /// y(x); // Found by both unqualified lookup and ADL, doesn't match
1303 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1305 /// Matches lambda expressions.
1307 /// Example matches [&](){return 5;}
1309 /// [&](){return 5;}
1311 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1313 /// Matches member call expressions.
1315 /// Example matches x.y()
1320 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1323 /// Matches ObjectiveC Message invocation expressions.
1325 /// The innermost message send invokes the "alloc" class method on the
1326 /// NSString class, while the outermost message send invokes the
1327 /// "initWithString" instance method on the object returned from
1328 /// NSString's "alloc". This matcher should match both message sends.
1330 /// [[NSString alloc] initWithString:@"Hello"]
1332 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1335 /// Matches Objective-C interface declarations.
1337 /// Example matches Foo
1342 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1345 /// Matches Objective-C implementation declarations.
1347 /// Example matches Foo
1349 /// @implementation Foo
1352 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1353 objcImplementationDecl;
1355 /// Matches Objective-C protocol declarations.
1357 /// Example matches FooDelegate
1359 /// @protocol FooDelegate
1362 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1365 /// Matches Objective-C category declarations.
1367 /// Example matches Foo (Additions)
1369 /// @interface Foo (Additions)
1372 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1375 /// Matches Objective-C category definitions.
1377 /// Example matches Foo (Additions)
1379 /// @implementation Foo (Additions)
1382 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1383 objcCategoryImplDecl;
1385 /// Matches Objective-C method declarations.
1387 /// Example matches both declaration and definition of -[Foo method]
1393 /// @implementation Foo
1394 /// - (void)method {}
1397 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1400 /// Matches block declarations.
1402 /// Example matches the declaration of the nameless block printing an input
1406 /// myFunc(^(int p) {
1407 /// printf("%d", p);
1410 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1413 /// Matches Objective-C instance variable declarations.
1415 /// Example matches _enabled
1417 /// @implementation Foo {
1422 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1425 /// Matches Objective-C property declarations.
1427 /// Example matches enabled
1430 /// @property BOOL enabled;
1433 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1436 /// Matches Objective-C \@throw statements.
1438 /// Example matches \@throw
1442 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1445 /// Matches Objective-C @try statements.
1447 /// Example matches @try
1452 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1455 /// Matches Objective-C @catch statements.
1457 /// Example matches @catch
1462 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1465 /// Matches Objective-C @finally statements.
1467 /// Example matches @finally
1472 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1475 /// Matches expressions that introduce cleanups to be run at the end
1476 /// of the sub-expression's evaluation.
1478 /// Example matches std::string()
1480 /// const std::string str = std::string();
1482 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1485 /// Matches init list expressions.
1489 /// int a[] = { 1, 2 };
1490 /// struct B { int x, y; };
1494 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1495 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1498 /// Matches the syntactic form of init list expressions
1499 /// (if expression have it).
1500 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1501 internal::Matcher<Expr>, InnerMatcher) {
1502 const Expr *SyntForm = Node.getSyntacticForm();
1503 return (SyntForm != nullptr &&
1504 InnerMatcher.matches(*SyntForm, Finder, Builder));
1507 /// Matches C++ initializer list expressions.
1511 /// std::vector<int> a({ 1, 2, 3 });
1512 /// std::vector<int> b = { 4, 5 };
1513 /// int c[] = { 6, 7 };
1514 /// std::pair<int, int> d = { 8, 9 };
1516 /// cxxStdInitializerListExpr()
1517 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1518 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1519 CXXStdInitializerListExpr>
1520 cxxStdInitializerListExpr;
1522 /// Matches implicit initializers of init list expressions.
1526 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1528 /// implicitValueInitExpr()
1529 /// matches "[0].y" (implicitly)
1530 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1531 implicitValueInitExpr;
1533 /// Matches paren list expressions.
1534 /// ParenListExprs don't have a predefined type and are used for late parsing.
1535 /// In the final AST, they can be met in template declarations.
1539 /// template<typename T> class X {
1542 /// int a = 0, b = 1; int i = (a, b);
1546 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1547 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1548 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1551 /// Matches substitutions of non-type template parameters.
1555 /// template <int N>
1556 /// struct A { static const int n = N; };
1557 /// struct B : public A<42> {};
1559 /// substNonTypeTemplateParmExpr()
1560 /// matches "N" in the right-hand side of "static const int n = N;"
1561 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1562 SubstNonTypeTemplateParmExpr>
1563 substNonTypeTemplateParmExpr;
1565 /// Matches using declarations.
1569 /// namespace X { int x; }
1573 /// matches \code using X::x \endcode
1574 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1576 /// Matches using namespace declarations.
1580 /// namespace X { int x; }
1581 /// using namespace X;
1583 /// usingDirectiveDecl()
1584 /// matches \code using namespace X \endcode
1585 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1588 /// Matches reference to a name that can be looked up during parsing
1589 /// but could not be resolved to a specific declaration.
1593 /// template<typename T>
1594 /// T foo() { T a; return a; }
1595 /// template<typename T>
1600 /// unresolvedLookupExpr()
1601 /// matches \code foo<T>() \endcode
1602 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1603 unresolvedLookupExpr;
1605 /// Matches unresolved using value declarations.
1609 /// template<typename X>
1610 /// class C : private X {
1614 /// unresolvedUsingValueDecl()
1615 /// matches \code using X::x \endcode
1616 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1617 UnresolvedUsingValueDecl>
1618 unresolvedUsingValueDecl;
1620 /// Matches unresolved using value declarations that involve the
1625 /// template <typename T>
1626 /// struct Base { typedef T Foo; };
1628 /// template<typename T>
1629 /// struct S : private Base<T> {
1630 /// using typename Base<T>::Foo;
1633 /// unresolvedUsingTypenameDecl()
1634 /// matches \code using Base<T>::Foo \endcode
1635 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1636 UnresolvedUsingTypenameDecl>
1637 unresolvedUsingTypenameDecl;
1639 /// Matches a constant expression wrapper.
1641 /// Example matches the constant in the case statement:
1642 /// (matcher = constantExpr())
1648 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1651 /// Matches parentheses used in expressions.
1653 /// Example matches (foo() + 1)
1655 /// int foo() { return 1; }
1656 /// int a = (foo() + 1);
1658 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1660 /// Matches constructor call expressions (including implicit ones).
1662 /// Example matches string(ptr, n) and ptr within arguments of f
1663 /// (matcher = cxxConstructExpr())
1665 /// void f(const string &a, const string &b);
1668 /// f(string(ptr, n), ptr);
1670 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1673 /// Matches unresolved constructor call expressions.
1675 /// Example matches T(t) in return statement of f
1676 /// (matcher = cxxUnresolvedConstructExpr())
1678 /// template <typename T>
1679 /// void f(const T& t) { return T(t); }
1681 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1682 CXXUnresolvedConstructExpr>
1683 cxxUnresolvedConstructExpr;
1685 /// Matches implicit and explicit this expressions.
1687 /// Example matches the implicit this expression in "return i".
1688 /// (matcher = cxxThisExpr())
1692 /// int f() { return i; }
1695 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1698 /// Matches nodes where temporaries are created.
1700 /// Example matches FunctionTakesString(GetStringByValue())
1701 /// (matcher = cxxBindTemporaryExpr())
1703 /// FunctionTakesString(GetStringByValue());
1704 /// FunctionTakesStringByPointer(GetStringPointer());
1706 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1707 cxxBindTemporaryExpr;
1709 /// Matches nodes where temporaries are materialized.
1713 /// struct T {void func();};
1717 /// materializeTemporaryExpr() matches 'f()' in these statements
1723 /// but does not match
1727 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1728 MaterializeTemporaryExpr>
1729 materializeTemporaryExpr;
1731 /// Matches new expressions.
1738 /// matches 'new X'.
1739 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1741 /// Matches delete expressions.
1748 /// matches 'delete X'.
1749 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1752 /// Matches array subscript expressions.
1758 /// arraySubscriptExpr()
1760 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1763 /// Matches the value of a default argument at the call site.
1765 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1766 /// default value of the second parameter in the call expression f(42)
1767 /// (matcher = cxxDefaultArgExpr())
1769 /// void f(int x, int y = 0);
1772 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1775 /// Matches overloaded operator calls.
1777 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1778 /// binaryOperator matcher.
1779 /// Currently it does not match operators such as new delete.
1780 /// FIXME: figure out why these do not match?
1782 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1783 /// (matcher = cxxOperatorCallExpr())
1785 /// ostream &operator<< (ostream &out, int i) { };
1786 /// ostream &o; int b = 1, c = 1;
1789 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1790 cxxOperatorCallExpr;
1792 /// Matches expressions.
1794 /// Example matches x()
1796 /// void f() { x(); }
1798 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1800 /// Matches expressions that refer to declarations.
1802 /// Example matches x in if (x)
1807 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1810 /// Matches a reference to an ObjCIvar.
1812 /// Example: matches "a" in "init" method:
1814 /// @implementation A {
1821 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1824 /// Matches a reference to a block.
1826 /// Example: matches "^{}":
1828 /// void f() { ^{}(); }
1830 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
1832 /// Matches if statements.
1834 /// Example matches 'if (x) {}'
1838 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1840 /// Matches for statements.
1842 /// Example matches 'for (;;) {}'
1845 /// int i[] = {1, 2, 3}; for (auto a : i);
1847 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1849 /// Matches the increment statement of a for loop.
1852 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1853 /// matches '++x' in
1855 /// for (x; x < N; ++x) { }
1857 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1859 const Stmt *const Increment = Node.getInc();
1860 return (Increment != nullptr &&
1861 InnerMatcher.matches(*Increment, Finder, Builder));
1864 /// Matches the initialization statement of a for loop.
1867 /// forStmt(hasLoopInit(declStmt()))
1868 /// matches 'int x = 0' in
1870 /// for (int x = 0; x < N; ++x) { }
1872 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1874 const Stmt *const Init = Node.getInit();
1875 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1878 /// Matches range-based for statements.
1880 /// cxxForRangeStmt() matches 'for (auto a : i)'
1882 /// int i[] = {1, 2, 3}; for (auto a : i);
1883 /// for(int j = 0; j < 5; ++j);
1885 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1888 /// Matches the initialization statement of a for loop.
1891 /// forStmt(hasLoopVariable(anything()))
1892 /// matches 'int x' in
1894 /// for (int x : a) { }
1896 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1898 const VarDecl *const Var = Node.getLoopVariable();
1899 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1902 /// Matches the range initialization statement of a for loop.
1905 /// forStmt(hasRangeInit(anything()))
1908 /// for (int x : a) { }
1910 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1912 const Expr *const Init = Node.getRangeInit();
1913 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1916 /// Matches while statements.
1923 /// matches 'while (true) {}'.
1924 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1926 /// Matches do statements.
1930 /// do {} while (true);
1933 /// matches 'do {} while(true)'
1934 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1936 /// Matches break statements.
1940 /// while (true) { break; }
1944 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1946 /// Matches continue statements.
1950 /// while (true) { continue; }
1953 /// matches 'continue'
1954 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1957 /// Matches return statements.
1964 /// matches 'return 1'
1965 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1967 /// Matches goto statements.
1975 /// matches 'goto FOO'
1976 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1978 /// Matches label statements.
1987 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1989 /// Matches address of label statements (GNU extension).
1994 /// void *ptr = &&FOO;
1999 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2002 /// Matches switch statements.
2006 /// switch(a) { case 42: break; default: break; }
2009 /// matches 'switch(a)'.
2010 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2012 /// Matches case and default statements inside switch statements.
2016 /// switch(a) { case 42: break; default: break; }
2019 /// matches 'case 42:' and 'default:'.
2020 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2022 /// Matches case statements inside switch statements.
2026 /// switch(a) { case 42: break; default: break; }
2029 /// matches 'case 42:'.
2030 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2032 /// Matches default statements inside switch statements.
2036 /// switch(a) { case 42: break; default: break; }
2039 /// matches 'default:'.
2040 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2043 /// Matches compound statements.
2045 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2049 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2052 /// Matches catch statements.
2055 /// try {} catch(int i) {}
2058 /// matches 'catch(int i)'
2059 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2062 /// Matches try statements.
2065 /// try {} catch(int i) {}
2068 /// matches 'try {}'
2069 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2071 /// Matches throw expressions.
2074 /// try { throw 5; } catch(int i) {}
2077 /// matches 'throw 5'
2078 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2081 /// Matches null statements.
2087 /// matches the second ';'
2088 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2090 /// Matches asm statements.
2094 /// __asm("mov al, 2");
2097 /// matches '__asm("mov al, 2")'
2098 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2100 /// Matches bool literals.
2102 /// Example matches true
2106 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2109 /// Matches string literals (also matches wide string literals).
2111 /// Example matches "abcd", L"abcd"
2113 /// char *s = "abcd";
2114 /// wchar_t *ws = L"abcd";
2116 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2119 /// Matches character literals (also matches wchar_t).
2121 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2124 /// Example matches 'a', L'a'
2127 /// wchar_t chw = L'a';
2129 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2132 /// Matches integer literals of all sizes / encodings, e.g.
2133 /// 1, 1L, 0x1 and 1U.
2135 /// Does not match character-encoded integers such as L'a'.
2136 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2139 /// Matches float literals of all sizes / encodings, e.g.
2140 /// 1.0, 1.0f, 1.0L and 1e10.
2142 /// Does not match implicit conversions such as
2146 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2149 /// Matches imaginary literals, which are based on integer and floating
2150 /// point literals e.g.: 1i, 1.0i
2151 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2154 /// Matches user defined literal operator call.
2156 /// Example match: "foo"_suffix
2157 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2160 /// Matches compound (i.e. non-scalar) literals
2162 /// Example match: {1}, (1, 2)
2164 /// int array[4] = {1};
2165 /// vector int myvec = (vector int)(1, 2);
2167 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2168 compoundLiteralExpr;
2170 /// Matches nullptr literal.
2171 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2172 cxxNullPtrLiteralExpr;
2174 /// Matches GNU __builtin_choose_expr.
2175 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2178 /// Matches GNU __null expression.
2179 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2182 /// Matches atomic builtins.
2183 /// Example matches __atomic_load_n(ptr, 1)
2185 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2187 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2189 /// Matches statement expression (GNU extension).
2191 /// Example match: ({ int X = 4; X; })
2193 /// int C = ({ int X = 4; X; });
2195 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2197 /// Matches binary operator expressions.
2199 /// Example matches a || b
2203 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2206 /// Matches unary operator expressions.
2208 /// Example matches !a
2212 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2215 /// Matches conditional operator expressions.
2217 /// Example matches a ? b : c
2219 /// (a ? b : c) + 42
2221 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2222 conditionalOperator;
2224 /// Matches binary conditional operator expressions (GNU extension).
2226 /// Example matches a ?: b
2230 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2231 BinaryConditionalOperator>
2232 binaryConditionalOperator;
2234 /// Matches opaque value expressions. They are used as helpers
2235 /// to reference another expressions and can be met
2236 /// in BinaryConditionalOperators, for example.
2238 /// Example matches 'a'
2242 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2245 /// Matches a C++ static_assert declaration.
2248 /// staticAssertExpr()
2250 /// static_assert(sizeof(S) == sizeof(int))
2256 /// static_assert(sizeof(S) == sizeof(int));
2258 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2261 /// Matches a reinterpret_cast expression.
2263 /// Either the source expression or the destination type can be matched
2264 /// using has(), but hasDestinationType() is more specific and can be
2267 /// Example matches reinterpret_cast<char*>(&p) in
2269 /// void* p = reinterpret_cast<char*>(&p);
2271 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2272 cxxReinterpretCastExpr;
2274 /// Matches a C++ static_cast expression.
2276 /// \see hasDestinationType
2277 /// \see reinterpretCast
2280 /// cxxStaticCastExpr()
2282 /// static_cast<long>(8)
2285 /// long eight(static_cast<long>(8));
2287 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2290 /// Matches a dynamic_cast expression.
2293 /// cxxDynamicCastExpr()
2295 /// dynamic_cast<D*>(&b);
2298 /// struct B { virtual ~B() {} }; struct D : B {};
2300 /// D* p = dynamic_cast<D*>(&b);
2302 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2305 /// Matches a const_cast expression.
2307 /// Example: Matches const_cast<int*>(&r) in
2310 /// const int &r(n);
2311 /// int* p = const_cast<int*>(&r);
2313 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2316 /// Matches a C-style cast expression.
2318 /// Example: Matches (int) 2.2f in
2320 /// int i = (int) 2.2f;
2322 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2325 /// Matches explicit cast expressions.
2327 /// Matches any cast expression written in user code, whether it be a
2328 /// C-style cast, a functional-style cast, or a keyword cast.
2330 /// Does not match implicit conversions.
2332 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2333 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2334 /// actual cast expressions.
2336 /// \see hasDestinationType.
2338 /// Example: matches all five of the casts in
2340 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2342 /// but does not match the implicit conversion in
2346 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2349 /// Matches the implicit cast nodes of Clang's AST.
2351 /// This matches many different places, including function call return value
2352 /// eliding, as well as any type conversions.
2353 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2356 /// Matches any cast nodes of Clang's AST.
2358 /// Example: castExpr() matches each of the following:
2361 /// const_cast<Expr *>(SubExpr);
2364 /// but does not match
2369 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2371 /// Matches functional cast expressions
2373 /// Example: Matches Foo(bar);
2376 /// Foo g = (Foo) bar;
2377 /// Foo h = Foo(bar);
2379 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2380 cxxFunctionalCastExpr;
2382 /// Matches functional cast expressions having N != 1 arguments
2384 /// Example: Matches Foo(bar, bar)
2386 /// Foo h = Foo(bar, bar);
2388 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2389 cxxTemporaryObjectExpr;
2391 /// Matches predefined identifier expressions [C99 6.4.2.2].
2393 /// Example: Matches __func__
2395 /// printf("%s", __func__);
2397 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2400 /// Matches C99 designated initializer expressions [C99 6.7.8].
2402 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2404 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2406 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2409 /// Matches designated initializer expressions that contain
2410 /// a specific number of designators.
2414 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2415 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2417 /// designatorCountIs(2)
2418 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2419 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2420 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2421 return Node.size() == N;
2424 /// Matches \c QualTypes in the clang AST.
2425 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2427 /// Matches \c Types in the clang AST.
2428 extern const internal::VariadicAllOfMatcher<Type> type;
2430 /// Matches \c TypeLocs in the clang AST.
2431 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2433 /// Matches if any of the given matchers matches.
2435 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2436 /// matching submatcher.
2438 /// For example, in:
2440 /// class A { int a; int b; };
2444 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2445 /// has(fieldDecl(hasName("b")).bind("v"))))
2447 /// will generate two results binding "v", the first of which binds
2448 /// the field declaration of \c a, the second the field declaration of
2451 /// Usable as: Any Matcher
2452 extern const internal::VariadicOperatorMatcherFunc<
2453 2, std::numeric_limits<unsigned>::max()>
2456 /// Matches if any of the given matchers matches.
2458 /// Usable as: Any Matcher
2459 extern const internal::VariadicOperatorMatcherFunc<
2460 2, std::numeric_limits<unsigned>::max()>
2463 /// Matches if all given matchers match.
2465 /// Usable as: Any Matcher
2466 extern const internal::VariadicOperatorMatcherFunc<
2467 2, std::numeric_limits<unsigned>::max()>
2470 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2475 /// int y = sizeof(x) + alignof(x);
2477 /// unaryExprOrTypeTraitExpr()
2478 /// matches \c sizeof(x) and \c alignof(x)
2479 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2480 UnaryExprOrTypeTraitExpr>
2481 unaryExprOrTypeTraitExpr;
2483 /// Matches unary expressions that have a specific type of argument.
2487 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2489 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2490 /// matches \c sizeof(a) and \c alignof(c)
2491 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2492 internal::Matcher<QualType>, InnerMatcher) {
2493 const QualType ArgumentType = Node.getTypeOfArgument();
2494 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2497 /// Matches unary expressions of a certain kind.
2502 /// int s = sizeof(x) + alignof(x)
2504 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2505 /// matches \c sizeof(x)
2507 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2508 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2509 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2510 return Node.getKind() == Kind;
2513 /// Same as unaryExprOrTypeTraitExpr, but only matching
2515 inline internal::Matcher<Stmt> alignOfExpr(
2516 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2517 return stmt(unaryExprOrTypeTraitExpr(
2518 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2522 /// Same as unaryExprOrTypeTraitExpr, but only matching
2524 inline internal::Matcher<Stmt> sizeOfExpr(
2525 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2526 return stmt(unaryExprOrTypeTraitExpr(
2527 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2530 /// Matches NamedDecl nodes that have the specified name.
2532 /// Supports specifying enclosing namespaces or classes by prefixing the name
2533 /// with '<enclosing>::'.
2534 /// Does not match typedefs of an underlying type with the given name.
2536 /// Example matches X (Name == "X")
2541 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2543 /// namespace a { namespace b { class X; } }
2545 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2546 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2549 /// Matches NamedDecl nodes that have any of the specified names.
2551 /// This matcher is only provided as a performance optimization of hasName.
2553 /// hasAnyName(a, b, c)
2555 /// is equivalent to, but faster than
2557 /// anyOf(hasName(a), hasName(b), hasName(c))
2559 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2560 internal::hasAnyNameFunc>
2563 /// Matches NamedDecl nodes whose fully qualified names contain
2564 /// a substring matched by the given RegExp.
2566 /// Supports specifying enclosing namespaces or classes by
2567 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2568 /// of an underlying type with the given name.
2570 /// Example matches X (regexp == "::X")
2575 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2577 /// namespace foo { namespace bar { class X; } }
2579 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2580 assert(!RegExp.empty());
2581 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2582 llvm::Regex RE(RegExp);
2583 return RE.match(FullNameString);
2586 /// Matches overloaded operator names.
2588 /// Matches overloaded operator names specified in strings without the
2589 /// "operator" prefix: e.g. "<<".
2593 /// class A { int operator*(); };
2594 /// const A &operator<<(const A &a, const A &b);
2596 /// a << a; // <-- This matches
2599 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2600 /// specified line and
2601 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2602 /// matches the declaration of \c A.
2604 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2605 inline internal::PolymorphicMatcherWithParam1<
2606 internal::HasOverloadedOperatorNameMatcher, StringRef,
2607 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2608 hasOverloadedOperatorName(StringRef Name) {
2609 return internal::PolymorphicMatcherWithParam1<
2610 internal::HasOverloadedOperatorNameMatcher, StringRef,
2611 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2614 /// Matches C++ classes that are directly or indirectly derived from
2615 /// a class matching \c Base.
2617 /// Note that a class is not considered to be derived from itself.
2619 /// Example matches Y, Z, C (Base == hasName("X"))
2622 /// class Y : public X {}; // directly derived
2623 /// class Z : public Y {}; // indirectly derived
2626 /// class C : public B {}; // derived from a typedef of X
2629 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2633 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2635 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2636 internal::Matcher<NamedDecl>, Base) {
2637 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2640 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2641 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2642 assert(!BaseName.empty());
2643 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2646 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2648 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2649 internal::Matcher<NamedDecl>, Base, 0) {
2650 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2651 .matches(Node, Finder, Builder);
2654 /// Overloaded method as shortcut for
2655 /// \c isSameOrDerivedFrom(hasName(...)).
2656 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2658 assert(!BaseName.empty());
2659 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2662 /// Matches the first method of a class or struct that satisfies \c
2667 /// class A { void func(); };
2668 /// class B { void member(); };
2671 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2672 /// \c A but not \c B.
2673 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2675 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2676 Node.method_end(), Finder, Builder);
2679 /// Matches the generated class of lambda expressions.
2686 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2688 AST_MATCHER(CXXRecordDecl, isLambda) {
2689 return Node.isLambda();
2692 /// Matches AST nodes that have child AST nodes that match the
2693 /// provided matcher.
2695 /// Example matches X, Y
2696 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2698 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2699 /// class Y { class X {}; };
2700 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2703 /// ChildT must be an AST base type.
2705 /// Usable as: Any Matcher
2706 /// Note that has is direct matcher, so it also matches things like implicit
2707 /// casts and paren casts. If you are matching with expr then you should
2708 /// probably consider using ignoringParenImpCasts like:
2709 /// has(ignoringParenImpCasts(expr())).
2710 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2712 /// Matches AST nodes that have descendant AST nodes that match the
2713 /// provided matcher.
2715 /// Example matches X, Y, Z
2716 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2718 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2719 /// class Y { class X {}; };
2720 /// class Z { class Y { class X {}; }; };
2723 /// DescendantT must be an AST base type.
2725 /// Usable as: Any Matcher
2726 extern const internal::ArgumentAdaptingMatcherFunc<
2727 internal::HasDescendantMatcher>
2730 /// Matches AST nodes that have child AST nodes that match the
2731 /// provided matcher.
2733 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2734 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2737 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
2739 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2742 /// ChildT must be an AST base type.
2744 /// As opposed to 'has', 'forEach' will cause a match for each result that
2745 /// matches instead of only on the first one.
2747 /// Usable as: Any Matcher
2748 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2751 /// Matches AST nodes that have descendant AST nodes that match the
2752 /// provided matcher.
2754 /// Example matches X, A, A::X, B, B::C, B::C::X
2755 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2758 /// class A { class X {}; }; // Matches A, because A::X is a class of name
2760 /// class B { class C { class X {}; }; };
2763 /// DescendantT must be an AST base type.
2765 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2766 /// each result that matches instead of only on the first one.
2768 /// Note: Recursively combined ForEachDescendant can cause many matches:
2769 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2770 /// forEachDescendant(cxxRecordDecl())
2772 /// will match 10 times (plus injected class name matches) on:
2774 /// class A { class B { class C { class D { class E {}; }; }; }; };
2777 /// Usable as: Any Matcher
2778 extern const internal::ArgumentAdaptingMatcherFunc<
2779 internal::ForEachDescendantMatcher>
2782 /// Matches if the node or any descendant matches.
2784 /// Generates results for each match.
2786 /// For example, in:
2788 /// class A { class B {}; class C {}; };
2792 /// cxxRecordDecl(hasName("::A"),
2793 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2795 /// will generate results for \c A, \c B and \c C.
2797 /// Usable as: Any Matcher
2798 template <typename T>
2799 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2800 return eachOf(Matcher, forEachDescendant(Matcher));
2803 /// Matches AST nodes that have a parent that matches the provided
2808 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2810 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2812 /// Usable as: Any Matcher
2813 extern const internal::ArgumentAdaptingMatcherFunc<
2814 internal::HasParentMatcher,
2815 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2816 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2819 /// Matches AST nodes that have an ancestor that matches the provided
2824 /// void f() { if (true) { int x = 42; } }
2825 /// void g() { for (;;) { int x = 43; } }
2827 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2829 /// Usable as: Any Matcher
2830 extern const internal::ArgumentAdaptingMatcherFunc<
2831 internal::HasAncestorMatcher,
2832 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2833 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2836 /// Matches if the provided matcher does not match.
2838 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2844 /// Usable as: Any Matcher
2845 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2847 /// Matches a node if the declaration associated with that node
2848 /// matches the given matcher.
2850 /// The associated declaration is:
2851 /// - for type nodes, the declaration of the underlying type
2852 /// - for CallExpr, the declaration of the callee
2853 /// - for MemberExpr, the declaration of the referenced member
2854 /// - for CXXConstructExpr, the declaration of the constructor
2855 /// - for CXXNewExpr, the declaration of the operator new
2856 /// - for ObjCIvarExpr, the declaration of the ivar
2858 /// For type nodes, hasDeclaration will generally match the declaration of the
2859 /// sugared type. Given
2865 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2866 /// typedefDecl. A common use case is to match the underlying, desugared type.
2867 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2869 /// varDecl(hasType(hasUnqualifiedDesugaredType(
2870 /// recordType(hasDeclaration(decl())))))
2872 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2874 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2875 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2876 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2877 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2878 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2879 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2880 /// Matcher<UnresolvedUsingType>
2881 inline internal::PolymorphicMatcherWithParam1<
2882 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2883 void(internal::HasDeclarationSupportedTypes)>
2884 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2885 return internal::PolymorphicMatcherWithParam1<
2886 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2887 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2890 /// Matches a \c NamedDecl whose underlying declaration matches the given
2895 /// namespace N { template<class T> void f(T t); }
2896 /// template <class T> void g() { using N::f; f(T()); }
2898 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2899 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2900 /// matches the use of \c f in \c g() .
2901 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2903 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2905 return UnderlyingDecl != nullptr &&
2906 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2909 /// Matches on the implicit object argument of a member call expression, after
2910 /// stripping off any parentheses or implicit casts.
2914 /// class Y { public: void m(); };
2916 /// class X : public Y {};
2917 /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
2919 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
2920 /// matches `y.m()` and `(g()).m()`.
2921 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
2922 /// matches `x.m()`.
2923 /// cxxMemberCallExpr(on(callExpr()))
2924 /// matches `(g()).m()`.
2926 /// FIXME: Overload to allow directly matching types?
2927 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2929 const Expr *ExprNode = Node.getImplicitObjectArgument()
2930 ->IgnoreParenImpCasts();
2931 return (ExprNode != nullptr &&
2932 InnerMatcher.matches(*ExprNode, Finder, Builder));
2936 /// Matches on the receiver of an ObjectiveC Message expression.
2939 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2940 /// matches the [webView ...] message invocation.
2942 /// NSString *webViewJavaScript = ...
2943 /// UIWebView *webView = ...
2944 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2946 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2948 const QualType TypeDecl = Node.getReceiverType();
2949 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2952 /// Returns true when the Objective-C method declaration is a class method.
2955 /// matcher = objcMethodDecl(isClassMethod())
2958 /// @interface I + (void)foo; @end
2962 /// @interface I - (void)bar; @end
2964 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
2965 return Node.isClassMethod();
2968 /// Returns true when the Objective-C method declaration is an instance method.
2971 /// matcher = objcMethodDecl(isInstanceMethod())
2974 /// @interface I - (void)bar; @end
2978 /// @interface I + (void)foo; @end
2980 AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
2981 return Node.isInstanceMethod();
2984 /// Returns true when the Objective-C message is sent to a class.
2987 /// matcher = objcMessageExpr(isClassMessage())
2990 /// [NSString stringWithFormat:@"format"];
2994 /// NSString *x = @"hello";
2995 /// [x containsString:@"h"];
2997 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
2998 return Node.isClassMessage();
3001 /// Returns true when the Objective-C message is sent to an instance.
3004 /// matcher = objcMessageExpr(isInstanceMessage())
3007 /// NSString *x = @"hello";
3008 /// [x containsString:@"h"];
3012 /// [NSString stringWithFormat:@"format"];
3014 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3015 return Node.isInstanceMessage();
3018 /// Matches if the Objective-C message is sent to an instance,
3019 /// and the inner matcher matches on that instance.
3021 /// For example the method call in
3023 /// NSString *x = @"hello";
3024 /// [x containsString:@"h"];
3027 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3028 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3030 const Expr *ReceiverNode = Node.getInstanceReceiver();
3031 return (ReceiverNode != nullptr &&
3032 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3036 /// Matches when BaseName == Selector.getAsString()
3038 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3039 /// matches the outer message expr in the code below, but NOT the message
3040 /// invocation for self.bodyView.
3042 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3044 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3045 Selector Sel = Node.getSelector();
3046 return BaseName.compare(Sel.getAsString()) == 0;
3050 /// Matches when at least one of the supplied string equals to the
3051 /// Selector.getAsString()
3053 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3054 /// matches both of the expressions below:
3056 /// [myObj methodA:argA];
3057 /// [myObj methodB:argB];
3059 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3061 internal::hasAnySelectorFunc>
3064 /// Matches ObjC selectors whose name contains
3065 /// a substring matched by the given RegExp.
3066 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3067 /// matches the outer message expr in the code below, but NOT the message
3068 /// invocation for self.bodyView.
3070 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3072 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
3073 assert(!RegExp.empty());
3074 std::string SelectorString = Node.getSelector().getAsString();
3075 llvm::Regex RE(RegExp);
3076 return RE.match(SelectorString);
3079 /// Matches when the selector is the empty selector
3081 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3082 /// represent an error condition in the tree!
3083 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3084 return Node.getSelector().isNull();
3087 /// Matches when the selector is a Unary Selector
3089 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3090 /// matches self.bodyView in the code below, but NOT the outer message
3091 /// invocation of "loadHTMLString:baseURL:".
3093 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3095 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3096 return Node.getSelector().isUnarySelector();
3099 /// Matches when the selector is a keyword selector
3101 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3102 /// message expression in
3105 /// UIWebView *webView = ...;
3106 /// CGRect bodyFrame = webView.frame;
3107 /// bodyFrame.size.height = self.bodyContentHeight;
3108 /// webView.frame = bodyFrame;
3109 /// // ^---- matches here
3111 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3112 return Node.getSelector().isKeywordSelector();
3115 /// Matches when the selector has the specified number of arguments
3117 /// matcher = objCMessageExpr(numSelectorArgs(0));
3118 /// matches self.bodyView in the code below
3120 /// matcher = objCMessageExpr(numSelectorArgs(2));
3121 /// matches the invocation of "loadHTMLString:baseURL:" but not that
3122 /// of self.bodyView
3124 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3126 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3127 return Node.getSelector().getNumArgs() == N;
3130 /// Matches if the call expression's callee expression matches.
3134 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3135 /// void f() { f(); }
3137 /// callExpr(callee(expr()))
3138 /// matches this->x(), x(), y.x(), f()
3139 /// with callee(...)
3140 /// matching this->x, x, y.x, f respectively
3142 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3143 /// because this introduces ambiguous overloads with calls to Callee taking a
3144 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3145 /// implemented in terms of implicit casts.
3146 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3148 const Expr *ExprNode = Node.getCallee();
3149 return (ExprNode != nullptr &&
3150 InnerMatcher.matches(*ExprNode, Finder, Builder));
3153 /// Matches if the call expression's callee's declaration matches the
3156 /// Example matches y.x() (matcher = callExpr(callee(
3157 /// cxxMethodDecl(hasName("x")))))
3159 /// class Y { public: void x(); };
3160 /// void z() { Y y; y.x(); }
3162 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3164 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3167 /// Matches if the expression's or declaration's type matches a type
3170 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3171 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3172 /// and U (matcher = typedefDecl(hasType(asString("int")))
3173 /// and friend class X (matcher = friendDecl(hasType("X"))
3176 /// void y(X &x) { x; X z; }
3178 /// class Y { friend class X; };
3180 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3182 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3184 internal::Matcher<QualType>, InnerMatcher, 0) {
3185 QualType QT = internal::getUnderlyingType(Node);
3187 return InnerMatcher.matches(QT, Finder, Builder);
3191 /// Overloaded to match the declaration of the expression's or value
3192 /// declaration's type.
3194 /// In case of a value declaration (for example a variable declaration),
3195 /// this resolves one layer of indirection. For example, in the value
3196 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3197 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3198 /// declaration of x.
3200 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3201 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3202 /// and friend class X (matcher = friendDecl(hasType("X"))
3205 /// void y(X &x) { x; X z; }
3206 /// class Y { friend class X; };
3209 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
3210 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3211 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
3212 internal::Matcher<Decl>, InnerMatcher, 1) {
3213 QualType QT = internal::getUnderlyingType(Node);
3215 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3219 /// Matches if the type location of the declarator decl's type matches
3220 /// the inner matcher.
3226 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3228 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3229 if (!Node.getTypeSourceInfo())
3230 // This happens for example for implicit destructors.
3232 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3235 /// Matches if the matched type is represented by the given string.
3239 /// class Y { public: void x(); };
3240 /// void z() { Y* y; y->x(); }
3242 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3244 AST_MATCHER_P(QualType, asString, std::string, Name) {
3245 return Name == Node.getAsString();
3248 /// Matches if the matched type is a pointer type and the pointee type
3249 /// matches the specified matcher.
3251 /// Example matches y->x()
3252 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3253 /// cxxRecordDecl(hasName("Y")))))))
3255 /// class Y { public: void x(); };
3256 /// void z() { Y *y; y->x(); }
3259 QualType, pointsTo, internal::Matcher<QualType>,
3261 return (!Node.isNull() && Node->isAnyPointerType() &&
3262 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3265 /// Overloaded to match the pointee type's declaration.
3266 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3268 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3269 .matches(Node, Finder, Builder);
3272 /// Matches if the matched type matches the unqualified desugared
3273 /// type of the matched node.
3275 /// For example, in:
3280 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3282 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3284 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3288 /// Matches if the matched type is a reference type and the referenced
3289 /// type matches the specified matcher.
3291 /// Example matches X &x and const X &y
3292 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3301 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3303 return (!Node.isNull() && Node->isReferenceType() &&
3304 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3307 /// Matches QualTypes whose canonical type matches InnerMatcher.
3311 /// typedef int &int_ref;
3316 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3317 /// declaration of b but \c
3318 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3319 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3323 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3326 /// Overloaded to match the referenced type's declaration.
3327 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3329 return references(qualType(hasDeclaration(InnerMatcher)))
3330 .matches(Node, Finder, Builder);
3333 /// Matches on the implicit object argument of a member call expression. Unlike
3334 /// `on`, matches the argument directly without stripping away anything.
3338 /// class Y { public: void m(); };
3340 /// class X : public Y { void g(); };
3341 /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
3343 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
3344 /// cxxRecordDecl(hasName("Y")))))
3345 /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
3346 /// cxxMemberCallExpr(on(callExpr()))
3347 /// does not match `(g()).m()`, because the parens are not ignored.
3349 /// FIXME: Overload to allow directly matching types?
3350 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3351 internal::Matcher<Expr>, InnerMatcher) {
3352 const Expr *ExprNode = Node.getImplicitObjectArgument();
3353 return (ExprNode != nullptr &&
3354 InnerMatcher.matches(*ExprNode, Finder, Builder));
3357 /// Matches if the type of the expression's implicit object argument either
3358 /// matches the InnerMatcher, or is a pointer to a type that matches the
3363 /// class Y { public: void m(); };
3364 /// class X : public Y { void g(); };
3365 /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
3367 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3368 /// cxxRecordDecl(hasName("Y")))))
3369 /// matches `y.m()`, `p->m()` and `x.m()`.
3370 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3371 /// cxxRecordDecl(hasName("X")))))
3372 /// matches `x.g()`.
3373 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3374 internal::Matcher<QualType>, InnerMatcher, 0) {
3375 return onImplicitObjectArgument(
3376 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3377 .matches(Node, Finder, Builder);
3380 /// Overloaded to match the type's declaration.
3381 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3382 internal::Matcher<Decl>, InnerMatcher, 1) {
3383 return onImplicitObjectArgument(
3384 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3385 .matches(Node, Finder, Builder);
3388 /// Matches a DeclRefExpr that refers to a declaration that matches the
3389 /// specified matcher.
3391 /// Example matches x in if(x)
3392 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3397 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3399 const Decl *DeclNode = Node.getDecl();
3400 return (DeclNode != nullptr &&
3401 InnerMatcher.matches(*DeclNode, Finder, Builder));
3404 /// Matches a \c DeclRefExpr that refers to a declaration through a
3405 /// specific using shadow declaration.
3409 /// namespace a { void f() {} }
3412 /// f(); // Matches this ..
3413 /// a::f(); // .. but not this.
3416 /// declRefExpr(throughUsingDecl(anything()))
3418 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3419 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3420 const NamedDecl *FoundDecl = Node.getFoundDecl();
3421 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3422 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3426 /// Matches an \c OverloadExpr if any of the declarations in the set of
3427 /// overloads matches the given matcher.
3431 /// template <typename T> void foo(T);
3432 /// template <typename T> void bar(T);
3433 /// template <typename T> void baz(T t) {
3438 /// unresolvedLookupExpr(hasAnyDeclaration(
3439 /// functionTemplateDecl(hasName("foo"))))
3440 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3441 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3443 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3444 Node.decls_end(), Finder, Builder);
3447 /// Matches the Decl of a DeclStmt which has a single declaration.
3454 /// declStmt(hasSingleDecl(anything()))
3455 /// matches 'int c;' but not 'int a, b;'.
3456 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3457 if (Node.isSingleDecl()) {
3458 const Decl *FoundDecl = Node.getSingleDecl();
3459 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3464 /// Matches a variable declaration that has an initializer expression
3465 /// that matches the given matcher.
3467 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3469 /// bool y() { return true; }
3473 VarDecl, hasInitializer, internal::Matcher<Expr>,
3475 const Expr *Initializer = Node.getAnyInitializer();
3476 return (Initializer != nullptr &&
3477 InnerMatcher.matches(*Initializer, Finder, Builder));
3480 /// \brief Matches a static variable with local scope.
3482 /// Example matches y (matcher = varDecl(isStaticLocal()))
3490 AST_MATCHER(VarDecl, isStaticLocal) {
3491 return Node.isStaticLocal();
3494 /// Matches a variable declaration that has function scope and is a
3495 /// non-static local variable.
3497 /// Example matches x (matcher = varDecl(hasLocalStorage())
3505 AST_MATCHER(VarDecl, hasLocalStorage) {
3506 return Node.hasLocalStorage();
3509 /// Matches a variable declaration that does not have local storage.
3511 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3519 AST_MATCHER(VarDecl, hasGlobalStorage) {
3520 return Node.hasGlobalStorage();
3523 /// Matches a variable declaration that has automatic storage duration.
3525 /// Example matches x, but not y, z, or a.
3526 /// (matcher = varDecl(hasAutomaticStorageDuration())
3531 /// thread_local int z;
3535 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3536 return Node.getStorageDuration() == SD_Automatic;
3539 /// Matches a variable declaration that has static storage duration.
3540 /// It includes the variable declared at namespace scope and those declared
3541 /// with "static" and "extern" storage class specifiers.
3547 /// thread_local int z;
3552 /// varDecl(hasStaticStorageDuration())
3553 /// matches the function declaration y, a, b and c.
3555 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3556 return Node.getStorageDuration() == SD_Static;
3559 /// Matches a variable declaration that has thread storage duration.
3561 /// Example matches z, but not x, z, or a.
3562 /// (matcher = varDecl(hasThreadStorageDuration())
3567 /// thread_local int z;
3571 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3572 return Node.getStorageDuration() == SD_Thread;
3575 /// Matches a variable declaration that is an exception variable from
3576 /// a C++ catch block, or an Objective-C \@catch statement.
3578 /// Example matches x (matcher = varDecl(isExceptionVariable())
3582 /// } catch (int x) {
3586 AST_MATCHER(VarDecl, isExceptionVariable) {
3587 return Node.isExceptionVariable();
3590 /// Checks that a call expression or a constructor call expression has
3591 /// a specific number of arguments (including absent default arguments).
3593 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3595 /// void f(int x, int y);
3598 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3599 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3603 return Node.getNumArgs() == N;
3606 /// Matches the n'th argument of a call expression or a constructor
3607 /// call expression.
3609 /// Example matches y in x(y)
3610 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3612 /// void x(int) { int y; x(y); }
3614 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3615 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3618 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3619 return (N < Node.getNumArgs() &&
3620 InnerMatcher.matches(
3621 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3624 /// Matches the n'th item of an initializer list expression.
3626 /// Example matches y.
3627 /// (matcher = initListExpr(hasInit(0, expr())))
3631 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
3632 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
3633 return N < Node.getNumInits() &&
3634 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
3637 /// Matches declaration statements that contain a specific number of
3647 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3648 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3649 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3652 /// Matches the n'th declaration of a declaration statement.
3654 /// Note that this does not work for global declarations because the AST
3655 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3657 /// Example: Given non-global declarations
3663 /// declStmt(containsDeclaration(
3664 /// 0, varDecl(hasInitializer(anything()))))
3665 /// matches only 'int d = 2, e;', and
3666 /// declStmt(containsDeclaration(1, varDecl()))
3668 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3669 /// but 'int c;' is not matched.
3671 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3672 internal::Matcher<Decl>, InnerMatcher) {
3673 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3676 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3677 std::advance(Iterator, N);
3678 return InnerMatcher.matches(**Iterator, Finder, Builder);
3681 /// Matches a C++ catch statement that has a catch-all handler.
3693 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3694 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3695 return Node.getExceptionDecl() == nullptr;
3698 /// Matches a constructor initializer.
3703 /// Foo() : foo_(1) { }
3707 /// cxxRecordDecl(has(cxxConstructorDecl(
3708 /// hasAnyConstructorInitializer(anything())
3710 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3711 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3712 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3713 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3714 Node.init_end(), Finder, Builder);
3717 /// Matches the field declaration of a constructor initializer.
3722 /// Foo() : foo_(1) { }
3726 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3727 /// forField(hasName("foo_"))))))
3729 /// with forField matching foo_
3730 AST_MATCHER_P(CXXCtorInitializer, forField,
3731 internal::Matcher<FieldDecl>, InnerMatcher) {
3732 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3733 return (NodeAsDecl != nullptr &&
3734 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3737 /// Matches the initializer expression of a constructor initializer.
3742 /// Foo() : foo_(1) { }
3746 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3747 /// withInitializer(integerLiteral(equals(1)))))))
3749 /// with withInitializer matching (1)
3750 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3751 internal::Matcher<Expr>, InnerMatcher) {
3752 const Expr* NodeAsExpr = Node.getInit();
3753 return (NodeAsExpr != nullptr &&
3754 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3757 /// Matches a constructor initializer if it is explicitly written in
3758 /// code (as opposed to implicitly added by the compiler).
3764 /// Foo(int) : foo_("A") { }
3768 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3769 /// will match Foo(int), but not Foo()
3770 AST_MATCHER(CXXCtorInitializer, isWritten) {
3771 return Node.isWritten();
3774 /// Matches a constructor initializer if it is initializing a base, as
3775 /// opposed to a member.
3782 /// D(int i) : I(i) {}
3788 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3789 /// will match E(), but not match D(int).
3790 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3791 return Node.isBaseInitializer();
3794 /// Matches a constructor initializer if it is initializing a member, as
3795 /// opposed to a base.
3802 /// D(int i) : I(i) {}
3808 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3809 /// will match D(int), but not match E().
3810 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3811 return Node.isMemberInitializer();
3814 /// Matches any argument of a call expression or a constructor call
3815 /// expression, or an ObjC-message-send expression.
3819 /// void x(int, int, int) { int y; x(1, y, 42); }
3821 /// callExpr(hasAnyArgument(declRefExpr()))
3822 /// matches x(1, y, 42)
3823 /// with hasAnyArgument(...)
3826 /// For ObjectiveC, given
3828 /// @interface I - (void) f:(int) y; @end
3829 /// void foo(I *i) { [i f:12]; }
3831 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3832 /// matches [i f:12]
3833 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3834 AST_POLYMORPHIC_SUPPORTED_TYPES(
3835 CallExpr, CXXConstructExpr,
3836 CXXUnresolvedConstructExpr, ObjCMessageExpr),
3837 internal::Matcher<Expr>, InnerMatcher) {
3838 for (const Expr *Arg : Node.arguments()) {
3839 BoundNodesTreeBuilder Result(*Builder);
3840 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3841 *Builder = std::move(Result);
3848 /// Matches a constructor call expression which uses list initialization.
3849 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3850 return Node.isListInitialization();
3853 /// Matches a constructor call expression which requires
3854 /// zero initialization.
3859 /// struct point { double x; double y; };
3860 /// point pt[2] = { { 1.0, 2.0 } };
3863 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3864 /// will match the implicit array filler for pt[1].
3865 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3866 return Node.requiresZeroInitialization();
3869 /// Matches the n'th parameter of a function or an ObjC method
3870 /// declaration or a block.
3874 /// class X { void f(int x) {} };
3876 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3877 /// matches f(int x) {}
3878 /// with hasParameter(...)
3881 /// For ObjectiveC, given
3883 /// @interface I - (void) f:(int) y; @end
3886 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3887 /// matches the declaration of method f with hasParameter
3889 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3890 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3893 unsigned, N, internal::Matcher<ParmVarDecl>,
3895 return (N < Node.parameters().size()
3896 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3899 /// Matches all arguments and their respective ParmVarDecl.
3908 /// forEachArgumentWithParam(
3909 /// declRefExpr(to(varDecl(hasName("y")))),
3910 /// parmVarDecl(hasType(isInteger()))
3913 /// with declRefExpr(...)
3915 /// and parmVarDecl(...)
3917 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3918 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3920 internal::Matcher<Expr>, ArgMatcher,
3921 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3922 BoundNodesTreeBuilder Result;
3923 // The first argument of an overloaded member operator is the implicit object
3924 // argument of the method which should not be matched against a parameter, so
3925 // we skip over it here.
3926 BoundNodesTreeBuilder Matches;
3927 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3928 .matches(Node, Finder, &Matches)
3932 bool Matched = false;
3933 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3934 BoundNodesTreeBuilder ArgMatches(*Builder);
3935 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3936 Finder, &ArgMatches)) {
3937 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3938 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3939 hasParameter(ParamIndex, ParamMatcher)))),
3940 callExpr(callee(functionDecl(
3941 hasParameter(ParamIndex, ParamMatcher))))))
3942 .matches(Node, Finder, &ParamMatches)) {
3943 Result.addMatch(ParamMatches);
3949 *Builder = std::move(Result);
3953 /// Matches any parameter of a function or an ObjC method declaration or a
3956 /// Does not match the 'this' parameter of a method.
3960 /// class X { void f(int x, int y, int z) {} };
3962 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3963 /// matches f(int x, int y, int z) {}
3964 /// with hasAnyParameter(...)
3967 /// For ObjectiveC, given
3969 /// @interface I - (void) f:(int) y; @end
3972 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
3973 /// matches the declaration of method f with hasParameter
3976 /// For blocks, given
3978 /// b = ^(int y) { printf("%d", y) };
3981 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
3982 /// matches the declaration of the block b with hasParameter
3984 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
3985 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3988 internal::Matcher<ParmVarDecl>,
3990 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3991 Node.param_end(), Finder, Builder);
3994 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3995 /// specific parameter count.
3999 /// void f(int i) {}
4000 /// void g(int i, int j) {}
4001 /// void h(int i, int j);
4003 /// void k(int x, int y, int z, ...);
4005 /// functionDecl(parameterCountIs(2))
4006 /// matches \c g and \c h
4007 /// functionProtoType(parameterCountIs(2))
4008 /// matches \c g and \c h
4009 /// functionProtoType(parameterCountIs(3))
4011 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
4012 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4015 return Node.getNumParams() == N;
4018 /// Matches \c FunctionDecls that have a noreturn attribute.
4023 /// [[noreturn]] void a();
4024 /// __attribute__((noreturn)) void b();
4025 /// struct c { [[noreturn]] c(); };
4027 /// functionDecl(isNoReturn())
4028 /// matches all of those except
4032 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
4034 /// Matches the return type of a function declaration.
4038 /// class X { int f() { return 1; } };
4040 /// cxxMethodDecl(returns(asString("int")))
4041 /// matches int f() { return 1; }
4042 AST_MATCHER_P(FunctionDecl, returns,
4043 internal::Matcher<QualType>, InnerMatcher) {
4044 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
4047 /// Matches extern "C" function or variable declarations.
4051 /// extern "C" void f() {}
4052 /// extern "C" { void g() {} }
4054 /// extern "C" int x = 1;
4055 /// extern "C" int y = 2;
4058 /// functionDecl(isExternC())
4059 /// matches the declaration of f and g, but not the declaration of h.
4060 /// varDecl(isExternC())
4061 /// matches the declaration of x and y, but not the declaration of z.
4062 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4064 return Node.isExternC();
4067 /// Matches variable/function declarations that have "static" storage
4068 /// class specifier ("static" keyword) written in the source.
4072 /// static void f() {}
4073 /// static int i = 0;
4077 /// functionDecl(isStaticStorageClass())
4078 /// matches the function declaration f.
4079 /// varDecl(isStaticStorageClass())
4080 /// matches the variable declaration i.
4081 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
4082 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4084 return Node.getStorageClass() == SC_Static;
4087 /// Matches deleted function declarations.
4092 /// void DeletedFunc() = delete;
4094 /// functionDecl(isDeleted())
4095 /// matches the declaration of DeletedFunc, but not Func.
4096 AST_MATCHER(FunctionDecl, isDeleted) {
4097 return Node.isDeleted();
4100 /// Matches defaulted function declarations.
4104 /// class A { ~A(); };
4105 /// class B { ~B() = default; };
4107 /// functionDecl(isDefaulted())
4108 /// matches the declaration of ~B, but not ~A.
4109 AST_MATCHER(FunctionDecl, isDefaulted) {
4110 return Node.isDefaulted();
4113 /// Matches functions that have a dynamic exception specification.
4118 /// void g() noexcept;
4119 /// void h() noexcept(true);
4120 /// void i() noexcept(false);
4121 /// void j() throw();
4122 /// void k() throw(int);
4123 /// void l() throw(...);
4125 /// functionDecl(hasDynamicExceptionSpec()) and
4126 /// functionProtoType(hasDynamicExceptionSpec())
4127 /// match the declarations of j, k, and l, but not f, g, h, or i.
4128 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
4129 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4130 FunctionProtoType)) {
4131 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
4132 return FnTy->hasDynamicExceptionSpec();
4136 /// Matches functions that have a non-throwing exception specification.
4141 /// void g() noexcept;
4142 /// void h() throw();
4143 /// void i() throw(int);
4144 /// void j() noexcept(false);
4146 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
4147 /// match the declarations of g, and h, but not f, i or j.
4148 AST_POLYMORPHIC_MATCHER(isNoThrow,
4149 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4150 FunctionProtoType)) {
4151 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
4153 // If the function does not have a prototype, then it is assumed to be a
4154 // throwing function (as it would if the function did not have any exception
4159 // Assume the best for any unresolved exception specification.
4160 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
4163 return FnTy->isNothrow();
4166 /// Matches constexpr variable and function declarations,
4167 /// and if constexpr.
4171 /// constexpr int foo = 42;
4172 /// constexpr int bar();
4173 /// void baz() { if constexpr(1 > 0) {} }
4175 /// varDecl(isConstexpr())
4176 /// matches the declaration of foo.
4177 /// functionDecl(isConstexpr())
4178 /// matches the declaration of bar.
4179 /// ifStmt(isConstexpr())
4180 /// matches the if statement in baz.
4181 AST_POLYMORPHIC_MATCHER(isConstexpr,
4182 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
4185 return Node.isConstexpr();
4188 /// Matches the condition expression of an if statement, for loop,
4189 /// switch statement or conditional operator.
4191 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
4195 AST_POLYMORPHIC_MATCHER_P(
4197 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
4198 SwitchStmt, AbstractConditionalOperator),
4199 internal::Matcher<Expr>, InnerMatcher) {
4200 const Expr *const Condition = Node.getCond();
4201 return (Condition != nullptr &&
4202 InnerMatcher.matches(*Condition, Finder, Builder));
4205 /// Matches the then-statement of an if statement.
4207 /// Examples matches the if statement
4208 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
4210 /// if (false) true; else false;
4212 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
4213 const Stmt *const Then = Node.getThen();
4214 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
4217 /// Matches the else-statement of an if statement.
4219 /// Examples matches the if statement
4220 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
4222 /// if (false) false; else true;
4224 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
4225 const Stmt *const Else = Node.getElse();
4226 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
4229 /// Matches if a node equals a previously bound node.
4231 /// Matches a node if it equals the node previously bound to \p ID.
4235 /// class X { int a; int b; };
4238 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4239 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
4240 /// matches the class \c X, as \c a and \c b have the same type.
4242 /// Note that when multiple matches are involved via \c forEach* matchers,
4243 /// \c equalsBoundNodes acts as a filter.
4246 /// forEachDescendant(varDecl().bind("d")),
4247 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
4248 /// will trigger a match for each combination of variable declaration
4249 /// and reference to that variable declaration within a compound statement.
4250 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
4251 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
4254 // FIXME: Figure out whether it makes sense to allow this
4255 // on any other node types.
4256 // For *Loc it probably does not make sense, as those seem
4257 // unique. For NestedNameSepcifier it might make sense, as
4258 // those also have pointer identity, but I'm not sure whether
4259 // they're ever reused.
4260 internal::NotEqualsBoundNodePredicate Predicate;
4262 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
4263 return Builder->removeBindings(Predicate);
4266 /// Matches the condition variable statement in an if statement.
4270 /// if (A* a = GetAPointer()) {}
4272 /// hasConditionVariableStatement(...)
4273 /// matches 'A* a = GetAPointer()'.
4274 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
4275 internal::Matcher<DeclStmt>, InnerMatcher) {
4276 const DeclStmt* const DeclarationStatement =
4277 Node.getConditionVariableDeclStmt();
4278 return DeclarationStatement != nullptr &&
4279 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
4282 /// Matches the index expression of an array subscript expression.
4287 /// void f() { i[1] = 42; }
4289 /// arraySubscriptExpression(hasIndex(integerLiteral()))
4290 /// matches \c i[1] with the \c integerLiteral() matching \c 1
4291 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
4292 internal::Matcher<Expr>, InnerMatcher) {
4293 if (const Expr* Expression = Node.getIdx())
4294 return InnerMatcher.matches(*Expression, Finder, Builder);
4298 /// Matches the base expression of an array subscript expression.
4303 /// void f() { i[1] = 42; }
4305 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4306 /// hasSourceExpression(declRefExpr()))))
4307 /// matches \c i[1] with the \c declRefExpr() matching \c i
4308 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4309 internal::Matcher<Expr>, InnerMatcher) {
4310 if (const Expr* Expression = Node.getBase())
4311 return InnerMatcher.matches(*Expression, Finder, Builder);
4315 /// Matches a 'for', 'while', 'do while' statement or a function
4316 /// definition that has a given body.
4322 /// hasBody(compoundStmt())
4323 /// matches 'for (;;) {}'
4324 /// with compoundStmt()
4326 AST_POLYMORPHIC_MATCHER_P(hasBody,
4327 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4331 internal::Matcher<Stmt>, InnerMatcher) {
4332 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4333 return (Statement != nullptr &&
4334 InnerMatcher.matches(*Statement, Finder, Builder));
4337 /// Matches compound statements where at least one substatement matches
4338 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4344 /// hasAnySubstatement(compoundStmt())
4345 /// matches '{ {}; 1+2; }'
4346 /// with compoundStmt()
4348 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4349 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4351 internal::Matcher<Stmt>, InnerMatcher) {
4352 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4353 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4354 CS->body_end(), Finder, Builder);
4357 /// Checks that a compound statement contains a specific number of
4358 /// child statements.
4364 /// compoundStmt(statementCountIs(0)))
4366 /// but does not match the outer compound statement.
4367 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4368 return Node.size() == N;
4371 /// Matches literals that are equal to the given value of type ValueT.
4375 /// f('\0', false, 3.14, 42);
4377 /// characterLiteral(equals(0))
4379 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4381 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4383 /// integerLiteral(equals(42))
4386 /// Note that you cannot directly match a negative numeric literal because the
4387 /// minus sign is not part of the literal: It is a unary operator whose operand
4388 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4389 /// matcher to match the minus sign:
4391 /// unaryOperator(hasOperatorName("-"),
4392 /// hasUnaryOperand(integerLiteral(equals(13))))
4394 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4395 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4396 template <typename ValueT>
4397 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
4398 equals(const ValueT &Value) {
4399 return internal::PolymorphicMatcherWithParam1<
4400 internal::ValueEqualsMatcher,
4404 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4405 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4409 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4413 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4414 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4417 unsigned, Value, 1) {
4418 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4422 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4423 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4428 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4432 /// Matches the operator Name of operator expressions (binary or
4435 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4439 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4440 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4442 std::string, Name) {
4443 return Name == Node.getOpcodeStr(Node.getOpcode());
4446 /// Matches all kinds of assignment operators.
4448 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4454 /// Example 2: matches s1 = s2
4455 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4457 /// struct S { S& operator=(const S&); };
4458 /// void x() { S s1, s2; s1 = s2; })
4460 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4461 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4462 CXXOperatorCallExpr)) {
4463 return Node.isAssignmentOp();
4466 /// Matches the left hand side of binary operator expressions.
4468 /// Example matches a (matcher = binaryOperator(hasLHS()))
4472 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4473 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4474 ArraySubscriptExpr),
4475 internal::Matcher<Expr>, InnerMatcher) {
4476 const Expr *LeftHandSide = Node.getLHS();
4477 return (LeftHandSide != nullptr &&
4478 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4481 /// Matches the right hand side of binary operator expressions.
4483 /// Example matches b (matcher = binaryOperator(hasRHS()))
4487 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4488 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4489 ArraySubscriptExpr),
4490 internal::Matcher<Expr>, InnerMatcher) {
4491 const Expr *RightHandSide = Node.getRHS();
4492 return (RightHandSide != nullptr &&
4493 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4496 /// Matches if either the left hand side or the right hand side of a
4497 /// binary operator matches.
4498 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4499 const internal::Matcher<Expr> &InnerMatcher) {
4500 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4503 /// Matches if the operand of a unary operator matches.
4505 /// Example matches true (matcher = hasUnaryOperand(
4506 /// cxxBoolLiteral(equals(true))))
4510 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4511 internal::Matcher<Expr>, InnerMatcher) {
4512 const Expr * const Operand = Node.getSubExpr();
4513 return (Operand != nullptr &&
4514 InnerMatcher.matches(*Operand, Finder, Builder));
4517 /// Matches if the cast's source expression
4518 /// or opaque value's source expression matches the given matcher.
4520 /// Example 1: matches "a string"
4521 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4523 /// class URL { URL(string); };
4524 /// URL url = "a string";
4527 /// Example 2: matches 'b' (matcher =
4528 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4532 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4533 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4535 internal::Matcher<Expr>, InnerMatcher) {
4536 const Expr *const SubExpression =
4537 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4538 return (SubExpression != nullptr &&
4539 InnerMatcher.matches(*SubExpression, Finder, Builder));
4542 /// Matches casts that has a given cast kind.
4544 /// Example: matches the implicit cast around \c 0
4545 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4550 /// If the matcher is use from clang-query, CastKind parameter
4551 /// should be passed as a quoted string. e.g., ofKind("CK_NullToPointer").
4552 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4553 return Node.getCastKind() == Kind;
4556 /// Matches casts whose destination type matches a given matcher.
4558 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4559 /// actual casts "explicit" casts.)
4560 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4561 internal::Matcher<QualType>, InnerMatcher) {
4562 const QualType NodeType = Node.getTypeAsWritten();
4563 return InnerMatcher.matches(NodeType, Finder, Builder);
4566 /// Matches implicit casts whose destination type matches a given
4569 /// FIXME: Unit test this matcher
4570 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4571 internal::Matcher<QualType>, InnerMatcher) {
4572 return InnerMatcher.matches(Node.getType(), Finder, Builder);
4575 /// Matches RecordDecl object that are spelled with "struct."
4577 /// Example matches S, but not C or U.
4583 AST_MATCHER(RecordDecl, isStruct) {
4584 return Node.isStruct();
4587 /// Matches RecordDecl object that are spelled with "union."
4589 /// Example matches U, but not C or S.
4595 AST_MATCHER(RecordDecl, isUnion) {
4596 return Node.isUnion();
4599 /// Matches RecordDecl object that are spelled with "class."
4601 /// Example matches C, but not S or U.
4607 AST_MATCHER(RecordDecl, isClass) {
4608 return Node.isClass();
4611 /// Matches the true branch expression of a conditional operator.
4613 /// Example 1 (conditional ternary operator): matches a
4615 /// condition ? a : b
4618 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4622 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4623 internal::Matcher<Expr>, InnerMatcher) {
4624 const Expr *Expression = Node.getTrueExpr();
4625 return (Expression != nullptr &&
4626 InnerMatcher.matches(*Expression, Finder, Builder));
4629 /// Matches the false branch expression of a conditional operator
4630 /// (binary or ternary).
4632 /// Example matches b
4634 /// condition ? a : b
4637 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4638 internal::Matcher<Expr>, InnerMatcher) {
4639 const Expr *Expression = Node.getFalseExpr();
4640 return (Expression != nullptr &&
4641 InnerMatcher.matches(*Expression, Finder, Builder));
4644 /// Matches if a declaration has a body attached.
4646 /// Example matches A, va, fa
4649 /// class B; // Doesn't match, as it has no body.
4651 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4653 /// void fb(); // Doesn't match, as it has no body.
4655 /// - (void)ma; // Doesn't match, interface is declaration.
4657 /// @implementation X
4662 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4663 /// Matcher<ObjCMethodDecl>
4664 AST_POLYMORPHIC_MATCHER(isDefinition,
4665 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4668 return Node.isThisDeclarationADefinition();
4671 /// Matches if a function declaration is variadic.
4673 /// Example matches f, but not g or h. The function i will not match, even when
4674 /// compiled in C mode.
4678 /// template <typename... Ts> void h(Ts...);
4681 AST_MATCHER(FunctionDecl, isVariadic) {
4682 return Node.isVariadic();
4685 /// Matches the class declaration that the given method declaration
4688 /// FIXME: Generalize this for other kinds of declarations.
4689 /// FIXME: What other kind of declarations would we need to generalize
4692 /// Example matches A() in the last line
4693 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4694 /// ofClass(hasName("A"))))))
4702 AST_MATCHER_P(CXXMethodDecl, ofClass,
4703 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4704 const CXXRecordDecl *Parent = Node.getParent();
4705 return (Parent != nullptr &&
4706 InnerMatcher.matches(*Parent, Finder, Builder));
4709 /// Matches each method overridden by the given method. This matcher may
4710 /// produce multiple matches.
4714 /// class A { virtual void f(); };
4715 /// class B : public A { void f(); };
4716 /// class C : public B { void f(); };
4718 /// cxxMethodDecl(ofClass(hasName("C")),
4719 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4720 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4721 /// that B::f is not overridden by C::f).
4723 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4725 /// class A1 { virtual void f(); };
4726 /// class A2 { virtual void f(); };
4727 /// class C : public A1, public A2 { void f(); };
4729 /// cxxMethodDecl(ofClass(hasName("C")),
4730 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4731 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4732 /// once with "b" binding "A2::f" and "d" binding "C::f".
4733 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4734 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4735 BoundNodesTreeBuilder Result;
4736 bool Matched = false;
4737 for (const auto *Overridden : Node.overridden_methods()) {
4738 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4739 const bool OverriddenMatched =
4740 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4741 if (OverriddenMatched) {
4743 Result.addMatch(OverriddenBuilder);
4746 *Builder = std::move(Result);
4750 /// Matches if the given method declaration is virtual.
4756 /// virtual void x();
4760 AST_MATCHER(CXXMethodDecl, isVirtual) {
4761 return Node.isVirtual();
4764 /// Matches if the given method declaration has an explicit "virtual".
4770 /// virtual void x();
4772 /// class B : public A {
4777 /// matches A::x but not B::x
4778 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4779 return Node.isVirtualAsWritten();
4782 /// Matches if the given method or class declaration is final.
4786 /// class A final {};
4789 /// virtual void f();
4796 /// matches A and C::f, but not B, C, or B::f
4797 AST_POLYMORPHIC_MATCHER(isFinal,
4798 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4800 return Node.template hasAttr<FinalAttr>();
4803 /// Matches if the given method declaration is pure.
4809 /// virtual void x() = 0;
4813 AST_MATCHER(CXXMethodDecl, isPure) {
4814 return Node.isPure();
4817 /// Matches if the given method declaration is const.
4822 /// void foo() const;
4827 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4828 AST_MATCHER(CXXMethodDecl, isConst) {
4829 return Node.isConst();
4832 /// Matches if the given method declaration declares a copy assignment
4838 /// A &operator=(const A &);
4839 /// A &operator=(A &&);
4843 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4845 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4846 return Node.isCopyAssignmentOperator();
4849 /// Matches if the given method declaration declares a move assignment
4855 /// A &operator=(const A &);
4856 /// A &operator=(A &&);
4860 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4862 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4863 return Node.isMoveAssignmentOperator();
4866 /// Matches if the given method declaration overrides another method.
4872 /// virtual void x();
4874 /// class B : public A {
4876 /// virtual void x();
4880 AST_MATCHER(CXXMethodDecl, isOverride) {
4881 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4884 /// Matches method declarations that are user-provided.
4890 /// S(const S &) = default; // #2
4891 /// S(S &&) = delete; // #3
4894 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4895 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4896 return Node.isUserProvided();
4899 /// Matches member expressions that are called with '->' as opposed
4902 /// Member calls on the implicit this pointer match as called with '->'.
4907 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4908 /// template <class T> void f() { this->f<T>(); f<T>(); }
4912 /// template <class T>
4914 /// void x() { this->m; }
4917 /// memberExpr(isArrow())
4918 /// matches this->x, x, y.x, a, this->b
4919 /// cxxDependentScopeMemberExpr(isArrow())
4921 /// unresolvedMemberExpr(isArrow())
4922 /// matches this->f<T>, f<T>
4923 AST_POLYMORPHIC_MATCHER(
4924 isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
4925 CXXDependentScopeMemberExpr)) {
4926 return Node.isArrow();
4929 /// Matches QualType nodes that are of integer type.
4937 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4938 /// matches "a(int)", "b(long)", but not "c(double)".
4939 AST_MATCHER(QualType, isInteger) {
4940 return Node->isIntegerType();
4943 /// Matches QualType nodes that are of unsigned integer type.
4948 /// void b(unsigned long);
4951 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4952 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4953 AST_MATCHER(QualType, isUnsignedInteger) {
4954 return Node->isUnsignedIntegerType();
4957 /// Matches QualType nodes that are of signed integer type.
4962 /// void b(unsigned long);
4965 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4966 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4967 AST_MATCHER(QualType, isSignedInteger) {
4968 return Node->isSignedIntegerType();
4971 /// Matches QualType nodes that are of character type.
4976 /// void b(wchar_t);
4979 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4980 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4981 AST_MATCHER(QualType, isAnyCharacter) {
4982 return Node->isAnyCharacterType();
4985 /// Matches QualType nodes that are of any pointer type; this includes
4986 /// the Objective-C object pointer type, which is different despite being
4987 /// syntactically similar.
4991 /// int *i = nullptr;
4999 /// varDecl(hasType(isAnyPointer()))
5000 /// matches "int *i" and "Foo *f", but not "int j".
5001 AST_MATCHER(QualType, isAnyPointer) {
5002 return Node->isAnyPointerType();
5005 /// Matches QualType nodes that are const-qualified, i.e., that
5006 /// include "top-level" const.
5011 /// void b(int const);
5012 /// void c(const int);
5013 /// void d(const int*);
5014 /// void e(int const) {};
5016 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
5017 /// matches "void b(int const)", "void c(const int)" and
5018 /// "void e(int const) {}". It does not match d as there
5019 /// is no top-level const on the parameter type "const int *".
5020 AST_MATCHER(QualType, isConstQualified) {
5021 return Node.isConstQualified();
5024 /// Matches QualType nodes that are volatile-qualified, i.e., that
5025 /// include "top-level" volatile.
5030 /// void b(int volatile);
5031 /// void c(volatile int);
5032 /// void d(volatile int*);
5033 /// void e(int volatile) {};
5035 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
5036 /// matches "void b(int volatile)", "void c(volatile int)" and
5037 /// "void e(int volatile) {}". It does not match d as there
5038 /// is no top-level volatile on the parameter type "volatile int *".
5039 AST_MATCHER(QualType, isVolatileQualified) {
5040 return Node.isVolatileQualified();
5043 /// Matches QualType nodes that have local CV-qualifiers attached to
5044 /// the node, not hidden within a typedef.
5048 /// typedef const int const_int;
5051 /// int *volatile k;
5054 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
5055 /// \c i is const-qualified but the qualifier is not local.
5056 AST_MATCHER(QualType, hasLocalQualifiers) {
5057 return Node.hasLocalQualifiers();
5060 /// Matches a member expression where the member is matched by a
5065 /// struct { int first, second; } first, second;
5066 /// int i(second.first);
5067 /// int j(first.second);
5069 /// memberExpr(member(hasName("first")))
5070 /// matches second.first
5071 /// but not first.second (because the member name there is "second").
5072 AST_MATCHER_P(MemberExpr, member,
5073 internal::Matcher<ValueDecl>, InnerMatcher) {
5074 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
5077 /// Matches a member expression where the object expression is matched by a
5078 /// given matcher. Implicit object expressions are included; that is, it matches
5079 /// use of implicit `this`.
5085 /// int f(X x) { x.m; return m; }
5088 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
5089 /// matches `x.m`, but not `m`; however,
5090 /// memberExpr(hasObjectExpression(hasType(pointsTo(
5091 // cxxRecordDecl(hasName("X"))))))
5092 /// matches `m` (aka. `this->m`), but not `x.m`.
5093 AST_POLYMORPHIC_MATCHER_P(
5094 hasObjectExpression,
5095 AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
5096 CXXDependentScopeMemberExpr),
5097 internal::Matcher<Expr>, InnerMatcher) {
5098 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
5099 if (E->isImplicitAccess())
5101 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
5102 if (E->isImplicitAccess())
5104 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
5107 /// Matches any using shadow declaration.
5111 /// namespace X { void b(); }
5114 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
5115 /// matches \code using X::b \endcode
5116 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
5117 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
5118 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
5119 Node.shadow_end(), Finder, Builder);
5122 /// Matches a using shadow declaration where the target declaration is
5123 /// matched by the given matcher.
5127 /// namespace X { int a; void b(); }
5131 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
5132 /// matches \code using X::b \endcode
5133 /// but not \code using X::a \endcode
5134 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
5135 internal::Matcher<NamedDecl>, InnerMatcher) {
5136 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
5139 /// Matches template instantiations of function, class, or static
5140 /// member variable template instantiations.
5144 /// template <typename T> class X {}; class A {}; X<A> x;
5148 /// template <typename T> class X {}; class A {}; template class X<A>;
5152 /// template <typename T> class X {}; class A {}; extern template class X<A>;
5154 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5155 /// matches the template instantiation of X<A>.
5159 /// template <typename T> class X {}; class A {};
5160 /// template <> class X<A> {}; X<A> x;
5162 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5163 /// does not match, as X<A> is an explicit template specialization.
5165 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5166 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
5167 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5169 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
5170 Node.getTemplateSpecializationKind() ==
5171 TSK_ExplicitInstantiationDefinition ||
5172 Node.getTemplateSpecializationKind() ==
5173 TSK_ExplicitInstantiationDeclaration);
5176 /// Matches declarations that are template instantiations or are inside
5177 /// template instantiations.
5181 /// template<typename T> void A(T t) { T i; }
5185 /// functionDecl(isInstantiated())
5186 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
5187 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
5188 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5189 functionDecl(isTemplateInstantiation())));
5190 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
5193 /// Matches statements inside of a template instantiation.
5198 /// template<typename T> void A(T t) { T i; j += 42;}
5202 /// declStmt(isInTemplateInstantiation())
5203 /// matches 'int i;' and 'unsigned i'.
5204 /// unless(stmt(isInTemplateInstantiation()))
5205 /// will NOT match j += 42; as it's shared between the template definition and
5207 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
5209 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5210 functionDecl(isTemplateInstantiation())))));
5213 /// Matches explicit template specializations of function, class, or
5214 /// static member variable template instantiations.
5218 /// template<typename T> void A(T t) { }
5219 /// template<> void A(int N) { }
5221 /// functionDecl(isExplicitTemplateSpecialization())
5222 /// matches the specialization A<int>().
5224 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5225 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
5226 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5228 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
5231 /// Matches \c TypeLocs for which the given inner
5232 /// QualType-matcher matches.
5233 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
5234 internal::Matcher<QualType>, InnerMatcher, 0) {
5235 return internal::BindableMatcher<TypeLoc>(
5236 new internal::TypeLocTypeMatcher(InnerMatcher));
5239 /// Matches type \c bool.
5243 /// struct S { bool func(); };
5245 /// functionDecl(returns(booleanType()))
5246 /// matches "bool func();"
5247 AST_MATCHER(Type, booleanType) {
5248 return Node.isBooleanType();
5251 /// Matches type \c void.
5255 /// struct S { void func(); };
5257 /// functionDecl(returns(voidType()))
5258 /// matches "void func();"
5259 AST_MATCHER(Type, voidType) {
5260 return Node.isVoidType();
5263 template <typename NodeType>
5264 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
5266 /// Matches builtin Types.
5277 /// matches "int b", "float c" and "bool d"
5278 extern const AstTypeMatcher<BuiltinType> builtinType;
5280 /// Matches all kinds of arrays.
5284 /// int a[] = { 2, 3 };
5286 /// void f() { int c[a[0]]; }
5289 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
5290 extern const AstTypeMatcher<ArrayType> arrayType;
5292 /// Matches C99 complex types.
5296 /// _Complex float f;
5299 /// matches "_Complex float f"
5300 extern const AstTypeMatcher<ComplexType> complexType;
5302 /// Matches any real floating-point type (float, double, long double).
5309 /// realFloatingPointType()
5310 /// matches "float f" but not "int i"
5311 AST_MATCHER(Type, realFloatingPointType) {
5312 return Node.isRealFloatingType();
5315 /// Matches arrays and C99 complex types that have a specific element
5324 /// arrayType(hasElementType(builtinType()))
5325 /// matches "int b[7]"
5327 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5328 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5329 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5332 /// Matches C arrays with a specified constant size.
5338 /// int b[] = { 2, 3 };
5342 /// constantArrayType()
5343 /// matches "int a[2]"
5344 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5346 /// Matches nodes that have the specified size.
5352 /// int c[41], d[43];
5353 /// char *s = "abcd";
5354 /// wchar_t *ws = L"abcd";
5357 /// constantArrayType(hasSize(42))
5358 /// matches "int a[42]" and "int b[2 * 21]"
5359 /// stringLiteral(hasSize(4))
5360 /// matches "abcd", L"abcd"
5361 AST_POLYMORPHIC_MATCHER_P(hasSize,
5362 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5365 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5368 /// Matches C++ arrays whose size is a value-dependent expression.
5372 /// template<typename T, int Size>
5377 /// dependentSizedArrayType
5378 /// matches "T data[Size]"
5379 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5381 /// Matches C arrays with unspecified size.
5385 /// int a[] = { 2, 3 };
5387 /// void f(int c[]) { int d[a[0]]; };
5389 /// incompleteArrayType()
5390 /// matches "int a[]" and "int c[]"
5391 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5393 /// Matches C arrays with a specified size that is not an
5394 /// integer-constant-expression.
5399 /// int a[] = { 2, 3 }
5404 /// variableArrayType()
5405 /// matches "int c[a[0]]"
5406 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5408 /// Matches \c VariableArrayType nodes that have a specific size
5417 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5418 /// varDecl(hasName("b")))))))
5419 /// matches "int a[b]"
5420 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5421 internal::Matcher<Expr>, InnerMatcher) {
5422 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5425 /// Matches atomic types.
5432 /// matches "_Atomic(int) i"
5433 extern const AstTypeMatcher<AtomicType> atomicType;
5435 /// Matches atomic types with a specific value type.
5440 /// _Atomic(float) f;
5442 /// atomicType(hasValueType(isInteger()))
5443 /// matches "_Atomic(int) i"
5445 /// Usable as: Matcher<AtomicType>
5446 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5447 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5449 /// Matches types nodes representing C++11 auto types.
5454 /// int v[] = { 2, 3 }
5455 /// for (auto i : v) { }
5458 /// matches "auto n" and "auto i"
5459 extern const AstTypeMatcher<AutoType> autoType;
5461 /// Matches types nodes representing C++11 decltype(<expr>) types.
5467 /// decltype(i + j) result = i + j;
5470 /// matches "decltype(i + j)"
5471 extern const AstTypeMatcher<DecltypeType> decltypeType;
5473 /// Matches \c AutoType nodes where the deduced type is a specific type.
5475 /// Note: There is no \c TypeLoc for the deduced type and thus no
5476 /// \c getDeducedLoc() matcher.
5483 /// autoType(hasDeducedType(isInteger()))
5484 /// matches "auto a"
5486 /// Usable as: Matcher<AutoType>
5487 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5488 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5490 /// Matches \c DecltypeType nodes to find out the underlying type.
5494 /// decltype(1) a = 1;
5495 /// decltype(2.0) b = 2.0;
5497 /// decltypeType(hasUnderlyingType(isInteger()))
5498 /// matches the type of "a"
5500 /// Usable as: Matcher<DecltypeType>
5501 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
5502 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
5504 /// Matches \c FunctionType nodes.
5512 /// matches "int (*f)(int)" and the type of "g".
5513 extern const AstTypeMatcher<FunctionType> functionType;
5515 /// Matches \c FunctionProtoType nodes.
5522 /// functionProtoType()
5523 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
5524 /// In C mode, "g" is not matched because it does not contain a prototype.
5525 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
5527 /// Matches \c ParenType nodes.
5531 /// int (*ptr_to_array)[4];
5532 /// int *array_of_ptrs[4];
5535 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
5536 /// \c array_of_ptrs.
5537 extern const AstTypeMatcher<ParenType> parenType;
5539 /// Matches \c ParenType nodes where the inner type is a specific type.
5543 /// int (*ptr_to_array)[4];
5544 /// int (*ptr_to_func)(int);
5547 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5548 /// \c ptr_to_func but not \c ptr_to_array.
5550 /// Usable as: Matcher<ParenType>
5551 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5552 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5554 /// Matches block pointer types, i.e. types syntactically represented as
5555 /// "void (^)(int)".
5557 /// The \c pointee is always required to be a \c FunctionType.
5558 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5560 /// Matches member pointer types.
5563 /// struct A { int i; }
5564 /// A::* ptr = A::i;
5566 /// memberPointerType()
5567 /// matches "A::* ptr"
5568 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5570 /// Matches pointer types, but does not match Objective-C object pointer
5584 /// matches "int *a", but does not match "Foo *f".
5585 extern const AstTypeMatcher<PointerType> pointerType;
5587 /// Matches an Objective-C object pointer type, which is different from
5588 /// a pointer type, despite being syntactically similar.
5599 /// matches "Foo *f", but does not match "int *a".
5600 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5602 /// Matches both lvalue and rvalue reference types.
5615 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5616 extern const AstTypeMatcher<ReferenceType> referenceType;
5618 /// Matches lvalue reference types.
5631 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5632 /// matched since the type is deduced as int& by reference collapsing rules.
5633 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5635 /// Matches rvalue reference types.
5648 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5649 /// matched as it is deduced to int& by reference collapsing rules.
5650 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5652 /// Narrows PointerType (and similar) matchers to those where the
5653 /// \c pointee matches a given matcher.
5661 /// pointerType(pointee(isConstQualified(), isInteger()))
5662 /// matches "int const *b"
5664 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5665 /// Matcher<PointerType>, Matcher<ReferenceType>
5666 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5667 pointee, getPointee,
5668 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5669 PointerType, ReferenceType));
5671 /// Matches typedef types.
5678 /// matches "typedef int X"
5679 extern const AstTypeMatcher<TypedefType> typedefType;
5681 /// Matches enum types.
5685 /// enum C { Green };
5686 /// enum class S { Red };
5692 /// \c enumType() matches the type of the variable declarations of both \c c and
5694 extern const AstTypeMatcher<EnumType> enumType;
5696 /// Matches template specialization types.
5700 /// template <typename T>
5703 /// template class C<int>; // A
5704 /// C<char> var; // B
5707 /// \c templateSpecializationType() matches the type of the explicit
5708 /// instantiation in \c A and the type of the variable declaration in \c B.
5709 extern const AstTypeMatcher<TemplateSpecializationType>
5710 templateSpecializationType;
5712 /// Matches types nodes representing unary type transformations.
5716 /// typedef __underlying_type(T) type;
5718 /// unaryTransformType()
5719 /// matches "__underlying_type(T)"
5720 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5722 /// Matches record types (e.g. structs, classes).
5733 /// \c recordType() matches the type of the variable declarations of both \c c
5735 extern const AstTypeMatcher<RecordType> recordType;
5737 /// Matches tag types (record and enum types).
5748 /// \c tagType() matches the type of the variable declarations of both \c e
5750 extern const AstTypeMatcher<TagType> tagType;
5752 /// Matches types specified with an elaborated type keyword or with a
5768 /// \c elaboratedType() matches the type of the variable declarations of both
5770 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5772 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5773 /// matches \c InnerMatcher if the qualifier exists.
5785 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5786 /// matches the type of the variable declaration of \c d.
5787 AST_MATCHER_P(ElaboratedType, hasQualifier,
5788 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5789 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5790 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5795 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5807 /// \c elaboratedType(namesType(recordType(
5808 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5809 /// declaration of \c d.
5810 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5812 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5815 /// Matches types that represent the result of substituting a type for a
5816 /// template type parameter.
5820 /// template <typename T>
5826 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5827 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5828 substTemplateTypeParmType;
5830 /// Matches template type parameter substitutions that have a replacement
5831 /// type that matches the provided matcher.
5835 /// template <typename T>
5838 /// double j = F(i);
5841 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5842 AST_TYPE_TRAVERSE_MATCHER(
5843 hasReplacementType, getReplacementType,
5844 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5846 /// Matches template type parameter types.
5848 /// Example matches T, but not int.
5849 /// (matcher = templateTypeParmType())
5851 /// template <typename T> void f(int i);
5853 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5855 /// Matches injected class name types.
5857 /// Example matches S s, but not S<T> s.
5858 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5860 /// template <typename T> struct S {
5865 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5867 /// Matches decayed type
5868 /// Example matches i[] in declaration of f.
5869 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5870 /// Example matches i[1].
5871 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5873 /// void f(int i[]) {
5877 extern const AstTypeMatcher<DecayedType> decayedType;
5879 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
5880 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5882 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5885 /// Matches declarations whose declaration context, interpreted as a
5886 /// Decl, matches \c InnerMatcher.
5897 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5898 /// declaration of \c class \c D.
5899 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5900 const DeclContext *DC = Node.getDeclContext();
5901 if (!DC) return false;
5902 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5905 /// Matches nested name specifiers.
5910 /// struct A { static void f(); };
5912 /// void g() { A::f(); }
5916 /// nestedNameSpecifier()
5917 /// matches "ns::" and both "A::"
5918 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
5919 nestedNameSpecifier;
5921 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5922 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
5923 nestedNameSpecifierLoc;
5925 /// Matches \c NestedNameSpecifierLocs for which the given inner
5926 /// NestedNameSpecifier-matcher matches.
5927 AST_MATCHER_FUNCTION_P_OVERLOAD(
5928 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5929 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5930 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5931 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5935 /// Matches nested name specifiers that specify a type matching the
5936 /// given \c QualType matcher without qualifiers.
5940 /// struct A { struct B { struct C {}; }; };
5943 /// nestedNameSpecifier(specifiesType(
5944 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5947 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5948 internal::Matcher<QualType>, InnerMatcher) {
5949 if (!Node.getAsType())
5951 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5954 /// Matches nested name specifier locs that specify a type matching the
5955 /// given \c TypeLoc.
5959 /// struct A { struct B { struct C {}; }; };
5962 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5963 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5965 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5966 internal::Matcher<TypeLoc>, InnerMatcher) {
5967 return Node && Node.getNestedNameSpecifier()->getAsType() &&
5968 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5971 /// Matches on the prefix of a \c NestedNameSpecifier.
5975 /// struct A { struct B { struct C {}; }; };
5978 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5980 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5981 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5983 const NestedNameSpecifier *NextNode = Node.getPrefix();
5986 return InnerMatcher.matches(*NextNode, Finder, Builder);
5989 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
5993 /// struct A { struct B { struct C {}; }; };
5996 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5998 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5999 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
6001 NestedNameSpecifierLoc NextNode = Node.getPrefix();
6004 return InnerMatcher.matches(NextNode, Finder, Builder);
6007 /// Matches nested name specifiers that specify a namespace matching the
6008 /// given namespace matcher.
6012 /// namespace ns { struct A {}; }
6015 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
6017 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
6018 internal::Matcher<NamespaceDecl>, InnerMatcher) {
6019 if (!Node.getAsNamespace())
6021 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
6024 /// Overloads for the \c equalsNode matcher.
6025 /// FIXME: Implement for other node types.
6028 /// Matches if a node equals another node.
6030 /// \c Decl has pointer identity in the AST.
6031 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
6032 return &Node == Other;
6034 /// Matches if a node equals another node.
6036 /// \c Stmt has pointer identity in the AST.
6037 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
6038 return &Node == Other;
6040 /// Matches if a node equals another node.
6042 /// \c Type has pointer identity in the AST.
6043 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
6044 return &Node == Other;
6049 /// Matches each case or default statement belonging to the given switch
6050 /// statement. This matcher may produce multiple matches.
6054 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
6056 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
6057 /// matches four times, with "c" binding each of "case 1:", "case 2:",
6058 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
6059 /// "switch (1)", "switch (2)" and "switch (2)".
6060 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
6062 BoundNodesTreeBuilder Result;
6063 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
6064 // iteration order. We should use the more general iterating matchers once
6065 // they are capable of expressing this matcher (for example, it should ignore
6066 // case statements belonging to nested switch statements).
6067 bool Matched = false;
6068 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
6069 SC = SC->getNextSwitchCase()) {
6070 BoundNodesTreeBuilder CaseBuilder(*Builder);
6071 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
6074 Result.addMatch(CaseBuilder);
6077 *Builder = std::move(Result);
6081 /// Matches each constructor initializer in a constructor definition.
6085 /// class A { A() : i(42), j(42) {} int i; int j; };
6087 /// cxxConstructorDecl(forEachConstructorInitializer(
6088 /// forField(decl().bind("x"))
6090 /// will trigger two matches, binding for 'i' and 'j' respectively.
6091 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
6092 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
6093 BoundNodesTreeBuilder Result;
6094 bool Matched = false;
6095 for (const auto *I : Node.inits()) {
6096 BoundNodesTreeBuilder InitBuilder(*Builder);
6097 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
6099 Result.addMatch(InitBuilder);
6102 *Builder = std::move(Result);
6106 /// Matches constructor declarations that are copy constructors.
6112 /// S(const S &); // #2
6116 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
6117 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
6118 return Node.isCopyConstructor();
6121 /// Matches constructor declarations that are move constructors.
6127 /// S(const S &); // #2
6131 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
6132 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
6133 return Node.isMoveConstructor();
6136 /// Matches constructor declarations that are default constructors.
6142 /// S(const S &); // #2
6146 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
6147 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
6148 return Node.isDefaultConstructor();
6151 /// Matches constructors that delegate to another constructor.
6158 /// S(S &&) : S() {} // #3
6160 /// S::S() : S(0) {} // #4
6162 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
6164 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
6165 return Node.isDelegatingConstructor();
6168 /// Matches constructor, conversion function, and deduction guide declarations
6169 /// that have an explicit specifier if this explicit specifier is resolved to
6174 /// template<bool b>
6177 /// explicit S(double); // #2
6178 /// operator int(); // #3
6179 /// explicit operator bool(); // #4
6180 /// explicit(false) S(bool) // # 7
6181 /// explicit(true) S(char) // # 8
6182 /// explicit(b) S(S) // # 9
6184 /// S(int) -> S<true> // #5
6185 /// explicit S(double) -> S<false> // #6
6187 /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
6188 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
6189 /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
6190 AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
6191 CXXConstructorDecl, CXXConversionDecl,
6192 CXXDeductionGuideDecl)) {
6193 return Node.isExplicit();
6196 /// Matches the expression in an explicit specifier if present in the given
6201 /// template<bool b>
6204 /// explicit S(double); // #2
6205 /// operator int(); // #3
6206 /// explicit operator bool(); // #4
6207 /// explicit(false) S(bool) // # 7
6208 /// explicit(true) S(char) // # 8
6209 /// explicit(b) S(S) // # 9
6211 /// S(int) -> S<true> // #5
6212 /// explicit S(double) -> S<false> // #6
6214 /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
6215 /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
6216 /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
6217 AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
6219 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
6222 return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
6225 /// Matches function and namespace declarations that are marked with
6226 /// the inline keyword.
6230 /// inline void f();
6233 /// inline namespace m {}
6236 /// functionDecl(isInline()) will match ::f().
6237 /// namespaceDecl(isInline()) will match n::m.
6238 AST_POLYMORPHIC_MATCHER(isInline,
6239 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
6241 // This is required because the spelling of the function used to determine
6242 // whether inline is specified or not differs between the polymorphic types.
6243 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
6244 return FD->isInlineSpecified();
6245 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
6246 return NSD->isInline();
6247 llvm_unreachable("Not a valid polymorphic type");
6250 /// Matches anonymous namespace declarations.
6255 /// namespace {} // #1
6258 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
6259 AST_MATCHER(NamespaceDecl, isAnonymous) {
6260 return Node.isAnonymousNamespace();
6263 /// Matches declarations in the namespace `std`, but not in nested namespaces.
6267 /// class vector {};
6269 /// class vector {};
6271 /// class vector {};
6275 /// inline namespace __1 {
6276 /// class vector {}; // #1
6277 /// namespace experimental {
6278 /// class vector {};
6283 /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
6284 AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
6286 /// If the given case statement does not use the GNU case range
6287 /// extension, matches the constant given in the statement.
6291 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
6293 /// caseStmt(hasCaseConstant(integerLiteral()))
6294 /// matches "case 1:"
6295 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
6300 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
6303 /// Matches declaration that has a given attribute.
6307 /// __attribute__((device)) void f() { ... }
6309 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
6310 /// f. If the matcher is used from clang-query, attr::Kind parameter should be
6311 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
6312 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
6313 for (const auto *Attr : Node.attrs()) {
6314 if (Attr->getKind() == AttrKind)
6320 /// Matches the return value expression of a return statement
6326 /// hasReturnValue(binaryOperator())
6327 /// matches 'return a + b'
6328 /// with binaryOperator()
6329 /// matching 'a + b'
6330 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
6332 if (const auto *RetValue = Node.getRetValue())
6333 return InnerMatcher.matches(*RetValue, Finder, Builder);
6337 /// Matches CUDA kernel call expression.
6339 /// Example matches,
6341 /// kernel<<<i,j>>>();
6343 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
6346 /// Matches expressions that resolve to a null pointer constant, such as
6347 /// GNU's __null, C++11's nullptr, or C's NULL macro.
6351 /// void *v1 = NULL;
6352 /// void *v2 = nullptr;
6353 /// void *v3 = __null; // GNU extension
6354 /// char *cp = (char *)0;
6358 /// expr(nullPointerConstant())
6359 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
6360 /// initializer for i.
6361 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
6363 gnuNullExpr(), cxxNullPtrLiteralExpr(),
6364 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
6367 /// Matches declaration of the function the statement belongs to
6371 /// F& operator=(const F& o) {
6372 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
6376 /// returnStmt(forFunction(hasName("operator=")))
6377 /// matches 'return *this'
6378 /// but does match 'return > 0'
6379 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
6381 const auto &Parents = Finder->getASTContext().getParents(Node);
6383 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
6385 while(!Stack.empty()) {
6386 const auto &CurNode = Stack.back();
6388 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6389 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6392 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6393 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6398 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6399 Stack.push_back(Parent);
6405 /// Matches a declaration that has external formal linkage.
6407 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6416 /// Example matches f() because it has external formal linkage despite being
6417 /// unique to the translation unit as though it has internal likage
6418 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6425 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6426 return Node.hasExternalFormalLinkage();
6429 /// Matches a declaration that has default arguments.
6431 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6433 /// void x(int val) {}
6434 /// void y(int val = 0) {}
6436 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6437 return Node.hasDefaultArg();
6440 /// Matches array new expressions.
6444 /// MyClass *p1 = new MyClass[10];
6446 /// cxxNewExpr(isArray())
6447 /// matches the expression 'new MyClass[10]'.
6448 AST_MATCHER(CXXNewExpr, isArray) {
6449 return Node.isArray();
6452 /// Matches array new expressions with a given array size.
6456 /// MyClass *p1 = new MyClass[10];
6458 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
6459 /// matches the expression 'new MyClass[10]'.
6460 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
6461 return Node.isArray() && *Node.getArraySize() &&
6462 InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
6465 /// Matches a class declaration that is defined.
6467 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
6472 AST_MATCHER(CXXRecordDecl, hasDefinition) {
6473 return Node.hasDefinition();
6476 /// Matches C++11 scoped enum declaration.
6478 /// Example matches Y (matcher = enumDecl(isScoped()))
6481 /// enum class Y {};
6483 AST_MATCHER(EnumDecl, isScoped) {
6484 return Node.isScoped();
6487 /// Matches a function declared with a trailing return type.
6489 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
6492 /// auto Y() -> int {}
6494 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
6495 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
6496 return F->hasTrailingReturn();
6500 /// Matches expressions that match InnerMatcher that are possibly wrapped in an
6501 /// elidable constructor.
6503 /// In C++17 copy elidable constructors are no longer being
6504 /// generated in the AST as it is not permitted by the standard. They are
6505 /// however part of the AST in C++14 and earlier. Therefore, to write a matcher
6506 /// that works in all language modes, the matcher has to skip elidable
6507 /// constructor AST nodes if they appear in the AST. This matcher can be used to
6508 /// skip those elidable constructors.
6520 /// ``varDecl(hasInitializer(any(
6521 /// ignoringElidableConstructorCall(callExpr()),
6522 /// exprWithCleanups(ignoringElidableConstructorCall(callExpr()))))``
6523 /// matches ``H D = G()``
6524 AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
6525 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
6526 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(&Node)) {
6527 if (CtorExpr->isElidable()) {
6528 if (const auto *MaterializeTemp =
6529 dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
6530 return InnerMatcher.matches(*MaterializeTemp->GetTemporaryExpr(),
6535 return InnerMatcher.matches(Node, Finder, Builder);
6538 //----------------------------------------------------------------------------//
6540 //----------------------------------------------------------------------------//
6542 /// Matches any ``#pragma omp`` executable directive.
6547 /// #pragma omp parallel
6548 /// #pragma omp parallel default(none)
6549 /// #pragma omp taskyield
6552 /// ``ompExecutableDirective()`` matches ``omp parallel``,
6553 /// ``omp parallel default(none)`` and ``omp taskyield``.
6554 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
6555 ompExecutableDirective;
6557 /// Matches standalone OpenMP directives,
6558 /// i.e., directives that can't have a structured block.
6563 /// #pragma omp parallel
6565 /// #pragma omp taskyield
6568 /// ``ompExecutableDirective(isStandaloneDirective()))`` matches
6569 /// ``omp taskyield``.
6570 AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
6571 return Node.isStandaloneDirective();
6574 /// Matches the Stmt AST node that is marked as being the structured-block
6575 /// of an OpenMP executable directive.
6580 /// #pragma omp parallel
6584 /// ``stmt(isOMPStructuredBlock()))`` matches ``{}``.
6585 AST_MATCHER(Stmt, isOMPStructuredBlock) { return Node.isOMPStructuredBlock(); }
6587 /// Matches the structured-block of the OpenMP executable directive
6589 /// Prerequisite: the executable directive must not be standalone directive.
6590 /// If it is, it will never match.
6595 /// #pragma omp parallel
6597 /// #pragma omp parallel
6601 /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
6602 AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
6603 internal::Matcher<Stmt>, InnerMatcher) {
6604 if (Node.isStandaloneDirective())
6605 return false; // Standalone directives have no structured blocks.
6606 return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
6609 /// Matches any clause in an OpenMP directive.
6614 /// #pragma omp parallel
6615 /// #pragma omp parallel default(none)
6618 /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
6619 /// ``omp parallel default(none)``.
6620 AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
6621 internal::Matcher<OMPClause>, InnerMatcher) {
6622 ArrayRef<OMPClause *> Clauses = Node.clauses();
6623 return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
6624 Clauses.end(), Finder, Builder);
6627 /// Matches OpenMP ``default`` clause.
6632 /// #pragma omp parallel default(none)
6633 /// #pragma omp parallel default(shared)
6634 /// #pragma omp parallel
6637 /// ``ompDefaultClause()`` matches ``default(none)`` and ``default(shared)``.
6638 extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
6641 /// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
6646 /// #pragma omp parallel
6647 /// #pragma omp parallel default(none)
6648 /// #pragma omp parallel default(shared)
6651 /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
6652 AST_MATCHER(OMPDefaultClause, isNoneKind) {
6653 return Node.getDefaultKind() == OMPC_DEFAULT_none;
6656 /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
6661 /// #pragma omp parallel
6662 /// #pragma omp parallel default(none)
6663 /// #pragma omp parallel default(shared)
6666 /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
6667 AST_MATCHER(OMPDefaultClause, isSharedKind) {
6668 return Node.getDefaultKind() == OMPC_DEFAULT_shared;
6671 /// Matches if the OpenMP directive is allowed to contain the specified OpenMP
6677 /// #pragma omp parallel
6678 /// #pragma omp parallel for
6682 /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
6683 /// ``omp parallel`` and ``omp parallel for``.
6685 /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
6686 /// should be passed as a quoted string. e.g.,
6687 /// ``isAllowedToContainClauseKind("OMPC_default").``
6688 AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
6689 OpenMPClauseKind, CKind) {
6690 return isAllowedClauseForDirective(Node.getDirectiveKind(), CKind);
6693 //----------------------------------------------------------------------------//
6694 // End OpenMP handling.
6695 //----------------------------------------------------------------------------//
6697 } // namespace ast_matchers
6698 } // namespace clang
6700 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H