1 //===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements matchers to be used together with the MatchFinder to
13 // Matchers are created by generator functions, which can be combined in
14 // a functional in-language DSL to express queries over the C++ AST.
16 // For example, to match a class with a certain name, one would call:
17 // cxxRecordDecl(hasName("MyClass"))
18 // which returns a matcher that can be used to find all AST nodes that declare
19 // a class named 'MyClass'.
21 // For more complicated match expressions we're often interested in accessing
22 // multiple parts of the matched AST nodes once a match is found. In that case,
23 // use the id(...) matcher around the match expressions that match the nodes
24 // you want to access.
26 // For example, when we're interested in child classes of a certain class, we
28 // cxxRecordDecl(hasName("MyClass"), has(id("child", recordDecl())))
29 // When the match is found via the MatchFinder, a user provided callback will
30 // be called with a BoundNodes instance that contains a mapping from the
31 // strings that we provided for the id(...) calls to the nodes that were
33 // In the given example, each time our matcher finds a match we get a callback
34 // where "child" is bound to the RecordDecl node of the matching child
37 // See ASTMatchersInternal.h for a more in-depth explanation of the
38 // implementation details of the matcher framework.
40 // See ASTMatchFinder.h for how to use the generated matchers to run over
43 //===----------------------------------------------------------------------===//
45 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
46 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/ASTTypeTraits.h"
50 #include "clang/AST/Attr.h"
51 #include "clang/AST/Decl.h"
52 #include "clang/AST/DeclCXX.h"
53 #include "clang/AST/DeclFriend.h"
54 #include "clang/AST/DeclObjC.h"
55 #include "clang/AST/DeclTemplate.h"
56 #include "clang/AST/Expr.h"
57 #include "clang/AST/ExprCXX.h"
58 #include "clang/AST/ExprObjC.h"
59 #include "clang/AST/NestedNameSpecifier.h"
60 #include "clang/AST/OperationKinds.h"
61 #include "clang/AST/Stmt.h"
62 #include "clang/AST/StmtCXX.h"
63 #include "clang/AST/StmtObjC.h"
64 #include "clang/AST/TemplateBase.h"
65 #include "clang/AST/TemplateName.h"
66 #include "clang/AST/Type.h"
67 #include "clang/AST/TypeLoc.h"
68 #include "clang/ASTMatchers/ASTMatchersInternal.h"
69 #include "clang/ASTMatchers/ASTMatchersMacros.h"
70 #include "clang/Basic/AttrKinds.h"
71 #include "clang/Basic/ExceptionSpecificationType.h"
72 #include "clang/Basic/IdentifierTable.h"
73 #include "clang/Basic/LLVM.h"
74 #include "clang/Basic/SourceManager.h"
75 #include "clang/Basic/Specifiers.h"
76 #include "clang/Basic/TypeTraits.h"
77 #include "llvm/ADT/ArrayRef.h"
78 #include "llvm/ADT/SmallVector.h"
79 #include "llvm/ADT/StringRef.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/Regex.h"
93 namespace ast_matchers {
95 /// Maps string IDs to AST nodes matched by parts of a matcher.
97 /// The bound nodes are generated by calling \c bind("id") on the node matchers
98 /// of the nodes we want to access later.
100 /// The instances of BoundNodes are created by \c MatchFinder when the user's
101 /// callbacks are executed every time a match is found.
104 /// Returns the AST node bound to \c ID.
106 /// Returns NULL if there was no node bound to \c ID or if there is a node but
107 /// it cannot be converted to the specified type.
108 template <typename T>
109 const T *getNodeAs(StringRef ID) const {
110 return MyBoundNodes.getNodeAs<T>(ID);
113 /// Type of mapping from binding identifiers to bound nodes. This type
114 /// is an associative container with a key type of \c std::string and a value
115 /// type of \c clang::ast_type_traits::DynTypedNode
116 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
118 /// Retrieve mapping from binding identifiers to bound nodes.
119 const IDToNodeMap &getMap() const {
120 return MyBoundNodes.getMap();
124 friend class internal::BoundNodesTreeBuilder;
126 /// Create BoundNodes from a pre-filled map of bindings.
127 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
128 : MyBoundNodes(MyBoundNodes) {}
130 internal::BoundNodesMap MyBoundNodes;
133 /// If the provided matcher matches a node, binds the node to \c ID.
135 /// FIXME: Do we want to support this now that we have bind()?
136 template <typename T>
137 internal::Matcher<T> id(StringRef ID,
138 const internal::BindableMatcher<T> &InnerMatcher) {
139 return InnerMatcher.bind(ID);
142 /// Types of matchers for the top-level classes in the AST class
145 using DeclarationMatcher = internal::Matcher<Decl>;
146 using StatementMatcher = internal::Matcher<Stmt>;
147 using TypeMatcher = internal::Matcher<QualType>;
148 using TypeLocMatcher = internal::Matcher<TypeLoc>;
149 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
150 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
151 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
154 /// Matches any node.
156 /// Useful when another matcher requires a child matcher, but there's no
157 /// additional constraint. This will often be used with an explicit conversion
158 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
160 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
162 /// "int* p" and "void f()" in
167 /// Usable as: Any Matcher
168 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
170 /// Matches the top declaration context.
177 /// } // namespace NS
179 /// decl(hasDeclContext(translationUnitDecl()))
180 /// matches "int X", but not "int Y".
181 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
184 /// Matches typedef declarations.
192 /// matches "typedef int X", but not "using Y = int"
193 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
196 /// Matches typedef name declarations.
203 /// typedefNameDecl()
204 /// matches "typedef int X" and "using Y = int"
205 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
208 /// Matches type alias declarations.
216 /// matches "using Y = int", but not "typedef int X"
217 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
220 /// Matches type alias template declarations.
222 /// typeAliasTemplateDecl() matches
224 /// template <typename T>
227 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
228 typeAliasTemplateDecl;
230 /// Matches AST nodes that were expanded within the main-file.
232 /// Example matches X but not Y
233 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
243 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
244 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
245 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
246 auto &SourceManager = Finder->getASTContext().getSourceManager();
247 return SourceManager.isInMainFile(
248 SourceManager.getExpansionLoc(Node.getBeginLoc()));
251 /// Matches AST nodes that were expanded within system-header-files.
253 /// Example matches Y but not X
254 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
256 /// #include <SystemHeader.h>
264 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
265 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
266 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
267 auto &SourceManager = Finder->getASTContext().getSourceManager();
268 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
269 if (ExpansionLoc.isInvalid()) {
272 return SourceManager.isInSystemHeader(ExpansionLoc);
275 /// Matches AST nodes that were expanded within files whose name is
276 /// partially matching a given regex.
278 /// Example matches Y but not X
279 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
281 /// #include "ASTMatcher.h"
289 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
290 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
291 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
292 std::string, RegExp) {
293 auto &SourceManager = Finder->getASTContext().getSourceManager();
294 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
295 if (ExpansionLoc.isInvalid()) {
299 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
304 auto Filename = FileEntry->getName();
305 llvm::Regex RE(RegExp);
306 return RE.match(Filename);
309 /// Matches declarations.
311 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
318 extern const internal::VariadicAllOfMatcher<Decl> decl;
320 /// Matches a declaration of a linkage specification.
326 /// linkageSpecDecl()
327 /// matches "extern "C" {}"
328 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
331 /// Matches a declaration of anything that could have a name.
333 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
342 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
344 /// Matches a declaration of label.
353 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
355 /// Matches a declaration of a namespace.
360 /// namespace test {}
363 /// matches "namespace {}" and "namespace test {}"
364 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
367 /// Matches a declaration of a namespace alias.
371 /// namespace test {}
372 /// namespace alias = ::test;
374 /// namespaceAliasDecl()
375 /// matches "namespace alias" but not "namespace test"
376 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
379 /// Matches class, struct, and union declarations.
381 /// Example matches \c X, \c Z, \c U, and \c S
384 /// template<class T> class Z {};
388 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
390 /// Matches C++ class declarations.
392 /// Example matches \c X, \c Z
395 /// template<class T> class Z {};
397 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
400 /// Matches C++ class template declarations.
402 /// Example matches \c Z
404 /// template<class T> class Z {};
406 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
409 /// Matches C++ class template specializations.
413 /// template<typename T> class A {};
414 /// template<> class A<double> {};
417 /// classTemplateSpecializationDecl()
418 /// matches the specializations \c A<int> and \c A<double>
419 extern const internal::VariadicDynCastAllOfMatcher<
420 Decl, ClassTemplateSpecializationDecl>
421 classTemplateSpecializationDecl;
423 /// Matches C++ class template partial specializations.
427 /// template<class T1, class T2, int I>
430 /// template<class T, int I>
431 /// class A<T, T*, I> {};
434 /// class A<int, int, 1> {};
436 /// classTemplatePartialSpecializationDecl()
437 /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
438 extern const internal::VariadicDynCastAllOfMatcher<
439 Decl, ClassTemplatePartialSpecializationDecl>
440 classTemplatePartialSpecializationDecl;
442 /// Matches declarator declarations (field, variable, function
443 /// and non-type template parameter declarations).
447 /// class X { int y; };
450 /// matches \c int y.
451 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
454 /// Matches parameter variable declarations.
461 /// matches \c int x.
462 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
465 /// Matches C++ access specifier declarations.
475 /// matches 'public:'
476 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
479 /// Matches constructor initializers.
481 /// Examples matches \c i(42).
488 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
491 /// Matches template arguments.
495 /// template <typename T> struct C {};
498 /// templateArgument()
499 /// matches 'int' in C<int>.
500 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
502 /// Matches template name.
506 /// template <typename T> class X { };
510 /// matches 'X' in X<int>.
511 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
513 /// Matches non-type template parameter declarations.
517 /// template <typename T, int N> struct C {};
519 /// nonTypeTemplateParmDecl()
520 /// matches 'N', but not 'T'.
521 extern const internal::VariadicDynCastAllOfMatcher<Decl,
522 NonTypeTemplateParmDecl>
523 nonTypeTemplateParmDecl;
525 /// Matches template type parameter declarations.
529 /// template <typename T, int N> struct C {};
531 /// templateTypeParmDecl()
532 /// matches 'T', but not 'N'.
533 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
534 templateTypeParmDecl;
536 /// Matches public C++ declarations.
542 /// protected: int b;
546 /// fieldDecl(isPublic())
548 AST_MATCHER(Decl, isPublic) {
549 return Node.getAccess() == AS_public;
552 /// Matches protected C++ declarations.
558 /// protected: int b;
562 /// fieldDecl(isProtected())
564 AST_MATCHER(Decl, isProtected) {
565 return Node.getAccess() == AS_protected;
568 /// Matches private C++ declarations.
574 /// protected: int b;
578 /// fieldDecl(isPrivate())
580 AST_MATCHER(Decl, isPrivate) {
581 return Node.getAccess() == AS_private;
584 /// Matches non-static data members that are bit-fields.
593 /// fieldDecl(isBitField())
594 /// matches 'int a;' but not 'int b;'.
595 AST_MATCHER(FieldDecl, isBitField) {
596 return Node.isBitField();
599 /// Matches non-static data members that are bit-fields of the specified
610 /// fieldDecl(hasBitWidth(2))
611 /// matches 'int a;' and 'int c;' but not 'int b;'.
612 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
613 return Node.isBitField() &&
614 Node.getBitWidthValue(Finder->getASTContext()) == Width;
617 /// Matches non-static data members that have an in-class initializer.
627 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
628 /// matches 'int a;' but not 'int b;'.
629 /// fieldDecl(hasInClassInitializer(anything()))
630 /// matches 'int a;' and 'int b;' but not 'int c;'.
631 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
633 const Expr *Initializer = Node.getInClassInitializer();
634 return (Initializer != nullptr &&
635 InnerMatcher.matches(*Initializer, Finder, Builder));
638 /// Determines whether the function is "main", which is the entry point
639 /// into an executable program.
640 AST_MATCHER(FunctionDecl, isMain) {
641 return Node.isMain();
644 /// Matches the specialized template of a specialization declaration.
648 /// template<typename T> class A {}; #1
649 /// template<> class A<int> {}; #2
651 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
652 /// matches '#2' with classTemplateDecl() matching the class template
653 /// declaration of 'A' at #1.
654 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
655 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
656 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
657 return (Decl != nullptr &&
658 InnerMatcher.matches(*Decl, Finder, Builder));
661 /// Matches a declaration that has been implicitly added
662 /// by the compiler (eg. implicit default/copy constructors).
663 AST_MATCHER(Decl, isImplicit) {
664 return Node.isImplicit();
667 /// Matches classTemplateSpecializations, templateSpecializationType and
668 /// functionDecl that have at least one TemplateArgument matching the given
673 /// template<typename T> class A {};
674 /// template<> class A<double> {};
677 /// template<typename T> f() {};
678 /// void func() { f<int>(); };
682 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
683 /// refersToType(asString("int"))))
684 /// matches the specialization \c A<int>
686 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
687 /// matches the specialization \c f<int>
688 AST_POLYMORPHIC_MATCHER_P(
689 hasAnyTemplateArgument,
690 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
691 TemplateSpecializationType,
693 internal::Matcher<TemplateArgument>, InnerMatcher) {
694 ArrayRef<TemplateArgument> List =
695 internal::getTemplateSpecializationArgs(Node);
696 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
700 /// Matches expressions that match InnerMatcher after any implicit AST
701 /// nodes are stripped off.
703 /// Parentheses and explicit casts are not discarded.
713 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
715 /// would match the declarations for a, b, and c.
718 /// varDecl(hasInitializer(cxxConstructExpr()))
720 /// only match the declarations for b and c.
721 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
723 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
726 /// Matches expressions that match InnerMatcher after any implicit casts
727 /// are stripped off.
729 /// Parentheses and explicit casts are not discarded.
737 /// long e = (long) 0l;
741 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
742 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
744 /// would match the declarations for a, b, c, and d, but not e.
747 /// varDecl(hasInitializer(integerLiteral()))
748 /// varDecl(hasInitializer(declRefExpr()))
750 /// only match the declarations for b, c, and d.
751 AST_MATCHER_P(Expr, ignoringImpCasts,
752 internal::Matcher<Expr>, InnerMatcher) {
753 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
756 /// Matches expressions that match InnerMatcher after parentheses and
757 /// casts are stripped off.
759 /// Implicit and non-C Style casts are also discarded.
764 /// void* c = reinterpret_cast<char*>(0);
765 /// char d = char(0);
768 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
769 /// would match the declarations for a, b, c, and d.
771 /// varDecl(hasInitializer(integerLiteral()))
772 /// only match the declaration for a.
773 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
774 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
777 /// Matches expressions that match InnerMatcher after implicit casts and
778 /// parentheses are stripped off.
780 /// Explicit casts are not discarded.
788 /// long e = ((long) 0l);
791 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
792 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
793 /// would match the declarations for a, b, c, and d, but not e.
795 /// varDecl(hasInitializer(integerLiteral()))
796 /// varDecl(hasInitializer(declRefExpr()))
797 /// would only match the declaration for a.
798 AST_MATCHER_P(Expr, ignoringParenImpCasts,
799 internal::Matcher<Expr>, InnerMatcher) {
800 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
803 /// Matches types that match InnerMatcher after any parens are stripped.
807 /// void (*fp)(void);
811 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
813 /// would match the declaration for fp.
814 AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
816 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
819 /// Overload \c ignoringParens for \c Expr.
823 /// const char* str = ("my-string");
827 /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
829 /// would match the implicit cast resulting from the assignment.
830 AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
832 const Expr *E = Node.IgnoreParens();
833 return InnerMatcher.matches(*E, Finder, Builder);
836 /// Matches expressions that are instantiation-dependent even if it is
837 /// neither type- nor value-dependent.
839 /// In the following example, the expression sizeof(sizeof(T() + T()))
840 /// is instantiation-dependent (since it involves a template parameter T),
841 /// but is neither type- nor value-dependent, since the type of the inner
842 /// sizeof is known (std::size_t) and therefore the size of the outer
845 /// template<typename T>
846 /// void f(T x, T y) { sizeof(sizeof(T() + T()); }
848 /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
849 AST_MATCHER(Expr, isInstantiationDependent) {
850 return Node.isInstantiationDependent();
853 /// Matches expressions that are type-dependent because the template type
854 /// is not yet instantiated.
856 /// For example, the expressions "x" and "x + y" are type-dependent in
857 /// the following code, but "y" is not type-dependent:
859 /// template<typename T>
860 /// void add(T x, int y) {
864 /// expr(isTypeDependent()) matches x + y
865 AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
867 /// Matches expression that are value-dependent because they contain a
868 /// non-type template parameter.
870 /// For example, the array bound of "Chars" in the following example is
873 /// template<int Size> int f() { return Size; }
875 /// expr(isValueDependent()) matches return Size
876 AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
878 /// Matches classTemplateSpecializations, templateSpecializationType and
879 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
883 /// template<typename T, typename U> class A {};
887 /// template<typename T> void f() {}
888 /// void func() { f<int>(); };
890 /// classTemplateSpecializationDecl(hasTemplateArgument(
891 /// 1, refersToType(asString("int"))))
892 /// matches the specialization \c A<bool, int>
894 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
895 /// matches the specialization \c f<int>
896 AST_POLYMORPHIC_MATCHER_P2(
898 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
899 TemplateSpecializationType,
901 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
902 ArrayRef<TemplateArgument> List =
903 internal::getTemplateSpecializationArgs(Node);
904 if (List.size() <= N)
906 return InnerMatcher.matches(List[N], Finder, Builder);
909 /// Matches if the number of template arguments equals \p N.
913 /// template<typename T> struct C {};
916 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
918 AST_POLYMORPHIC_MATCHER_P(
919 templateArgumentCountIs,
920 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
921 TemplateSpecializationType),
923 return internal::getTemplateSpecializationArgs(Node).size() == N;
926 /// Matches a TemplateArgument that refers to a certain type.
931 /// template<typename T> struct A {};
934 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
935 /// refersToType(class(hasName("X")))))
936 /// matches the specialization \c A<X>
937 AST_MATCHER_P(TemplateArgument, refersToType,
938 internal::Matcher<QualType>, InnerMatcher) {
939 if (Node.getKind() != TemplateArgument::Type)
941 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
944 /// Matches a TemplateArgument that refers to a certain template.
948 /// template<template <typename> class S> class X {};
949 /// template<typename T> class Y {};
952 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
953 /// refersToTemplate(templateName())))
954 /// matches the specialization \c X<Y>
955 AST_MATCHER_P(TemplateArgument, refersToTemplate,
956 internal::Matcher<TemplateName>, InnerMatcher) {
957 if (Node.getKind() != TemplateArgument::Template)
959 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
962 /// Matches a canonical TemplateArgument that refers to a certain
967 /// struct B { int next; };
968 /// template<int(B::*next_ptr)> struct A {};
971 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
972 /// refersToDeclaration(fieldDecl(hasName("next")))))
973 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
975 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
976 internal::Matcher<Decl>, InnerMatcher) {
977 if (Node.getKind() == TemplateArgument::Declaration)
978 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
982 /// Matches a sugar TemplateArgument that refers to a certain expression.
986 /// struct B { int next; };
987 /// template<int(B::*next_ptr)> struct A {};
990 /// templateSpecializationType(hasAnyTemplateArgument(
991 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
992 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
994 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
995 if (Node.getKind() == TemplateArgument::Expression)
996 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1000 /// Matches a TemplateArgument that is an integral value.
1004 /// template<int T> struct C {};
1007 /// classTemplateSpecializationDecl(
1008 /// hasAnyTemplateArgument(isIntegral()))
1009 /// matches the implicit instantiation of C in C<42>
1010 /// with isIntegral() matching 42.
1011 AST_MATCHER(TemplateArgument, isIntegral) {
1012 return Node.getKind() == TemplateArgument::Integral;
1015 /// Matches a TemplateArgument that referes to an integral type.
1019 /// template<int T> struct C {};
1022 /// classTemplateSpecializationDecl(
1023 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1024 /// matches the implicit instantiation of C in C<42>.
1025 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1026 internal::Matcher<QualType>, InnerMatcher) {
1027 if (Node.getKind() != TemplateArgument::Integral)
1029 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1032 /// Matches a TemplateArgument of integral type with a given value.
1034 /// Note that 'Value' is a string as the template argument's value is
1035 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
1036 /// representation of that integral value in base 10.
1040 /// template<int T> struct C {};
1043 /// classTemplateSpecializationDecl(
1044 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
1045 /// matches the implicit instantiation of C in C<42>.
1046 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1047 std::string, Value) {
1048 if (Node.getKind() != TemplateArgument::Integral)
1050 return Node.getAsIntegral().toString(10) == Value;
1053 /// Matches an Objective-C autorelease pool statement.
1057 /// @autoreleasepool {
1061 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1062 /// inside the autorelease pool.
1063 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1064 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1066 /// Matches any value declaration.
1068 /// Example matches A, B, C and F
1070 /// enum X { A, B, C };
1073 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1075 /// Matches C++ constructor declarations.
1077 /// Example matches Foo::Foo() and Foo::Foo(int)
1083 /// int DoSomething();
1086 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1089 /// Matches explicit C++ destructor declarations.
1091 /// Example matches Foo::~Foo()
1098 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1101 /// Matches enum declarations.
1103 /// Example matches X
1109 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1111 /// Matches enum constants.
1113 /// Example matches A, B, C
1119 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1122 /// Matches method declarations.
1124 /// Example matches y
1126 /// class X { void y(); };
1128 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1131 /// Matches conversion operator declarations.
1133 /// Example matches the operator.
1135 /// class X { operator int() const; };
1137 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1140 /// Matches variable declarations.
1142 /// Note: this does not match declarations of member variables, which are
1143 /// "field" declarations in Clang parlance.
1145 /// Example matches a
1149 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1151 /// Matches field declarations.
1155 /// class X { int m; };
1159 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1161 /// Matches indirect field declarations.
1165 /// struct X { struct { int a; }; };
1167 /// indirectFieldDecl()
1169 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1172 /// Matches function declarations.
1174 /// Example matches f
1178 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1181 /// Matches C++ function template declarations.
1183 /// Example matches f
1185 /// template<class T> void f(T t) {}
1187 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1188 functionTemplateDecl;
1190 /// Matches friend declarations.
1194 /// class X { friend void foo(); };
1197 /// matches 'friend void foo()'.
1198 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1200 /// Matches statements.
1207 /// matches both the compound statement '{ ++a; }' and '++a'.
1208 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1210 /// Matches declaration statements.
1217 /// matches 'int a'.
1218 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1220 /// Matches member expressions.
1225 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1226 /// int a; static int b;
1230 /// matches this->x, x, y.x, a, this->b
1231 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1233 /// Matches unresolved member expressions.
1238 /// template <class T> void f();
1241 /// template <class T> void h() { X x; x.f<T>(); x.g(); }
1243 /// unresolvedMemberExpr()
1245 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1246 unresolvedMemberExpr;
1248 /// Matches member expressions where the actual member referenced could not be
1249 /// resolved because the base expression or the member name was dependent.
1253 /// template <class T> void f() { T t; t.g(); }
1255 /// cxxDependentScopeMemberExpr()
1257 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1258 CXXDependentScopeMemberExpr>
1259 cxxDependentScopeMemberExpr;
1261 /// Matches call expressions.
1263 /// Example matches x.y() and y()
1269 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1271 /// Matches call expressions which were resolved using ADL.
1273 /// Example matches y(x) but not y(42) or NS::y(x).
1284 /// y(x); // Matches
1285 /// NS::y(x); // Doesn't match
1286 /// y(42); // Doesn't match
1288 /// y(x); // Found by both unqualified lookup and ADL, doesn't match
1291 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1293 /// Matches lambda expressions.
1295 /// Example matches [&](){return 5;}
1297 /// [&](){return 5;}
1299 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1301 /// Matches member call expressions.
1303 /// Example matches x.y()
1308 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1311 /// Matches ObjectiveC Message invocation expressions.
1313 /// The innermost message send invokes the "alloc" class method on the
1314 /// NSString class, while the outermost message send invokes the
1315 /// "initWithString" instance method on the object returned from
1316 /// NSString's "alloc". This matcher should match both message sends.
1318 /// [[NSString alloc] initWithString:@"Hello"]
1320 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1323 /// Matches Objective-C interface declarations.
1325 /// Example matches Foo
1330 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1333 /// Matches Objective-C implementation declarations.
1335 /// Example matches Foo
1337 /// @implementation Foo
1340 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1341 objcImplementationDecl;
1343 /// Matches Objective-C protocol declarations.
1345 /// Example matches FooDelegate
1347 /// @protocol FooDelegate
1350 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1353 /// Matches Objective-C category declarations.
1355 /// Example matches Foo (Additions)
1357 /// @interface Foo (Additions)
1360 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1363 /// Matches Objective-C category definitions.
1365 /// Example matches Foo (Additions)
1367 /// @implementation Foo (Additions)
1370 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1371 objcCategoryImplDecl;
1373 /// Matches Objective-C method declarations.
1375 /// Example matches both declaration and definition of -[Foo method]
1381 /// @implementation Foo
1382 /// - (void)method {}
1385 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1388 /// Matches block declarations.
1390 /// Example matches the declaration of the nameless block printing an input
1394 /// myFunc(^(int p) {
1395 /// printf("%d", p);
1398 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1401 /// Matches Objective-C instance variable declarations.
1403 /// Example matches _enabled
1405 /// @implementation Foo {
1410 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1413 /// Matches Objective-C property declarations.
1415 /// Example matches enabled
1418 /// @property BOOL enabled;
1421 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1424 /// Matches Objective-C \@throw statements.
1426 /// Example matches \@throw
1430 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1433 /// Matches Objective-C @try statements.
1435 /// Example matches @try
1440 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1443 /// Matches Objective-C @catch statements.
1445 /// Example matches @catch
1450 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1453 /// Matches Objective-C @finally statements.
1455 /// Example matches @finally
1460 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1463 /// Matches expressions that introduce cleanups to be run at the end
1464 /// of the sub-expression's evaluation.
1466 /// Example matches std::string()
1468 /// const std::string str = std::string();
1470 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1473 /// Matches init list expressions.
1477 /// int a[] = { 1, 2 };
1478 /// struct B { int x, y; };
1482 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1483 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1486 /// Matches the syntactic form of init list expressions
1487 /// (if expression have it).
1488 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1489 internal::Matcher<Expr>, InnerMatcher) {
1490 const Expr *SyntForm = Node.getSyntacticForm();
1491 return (SyntForm != nullptr &&
1492 InnerMatcher.matches(*SyntForm, Finder, Builder));
1495 /// Matches C++ initializer list expressions.
1499 /// std::vector<int> a({ 1, 2, 3 });
1500 /// std::vector<int> b = { 4, 5 };
1501 /// int c[] = { 6, 7 };
1502 /// std::pair<int, int> d = { 8, 9 };
1504 /// cxxStdInitializerListExpr()
1505 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1506 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1507 CXXStdInitializerListExpr>
1508 cxxStdInitializerListExpr;
1510 /// Matches implicit initializers of init list expressions.
1514 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1516 /// implicitValueInitExpr()
1517 /// matches "[0].y" (implicitly)
1518 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1519 implicitValueInitExpr;
1521 /// Matches paren list expressions.
1522 /// ParenListExprs don't have a predefined type and are used for late parsing.
1523 /// In the final AST, they can be met in template declarations.
1527 /// template<typename T> class X {
1530 /// int a = 0, b = 1; int i = (a, b);
1534 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1535 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1536 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1539 /// Matches substitutions of non-type template parameters.
1543 /// template <int N>
1544 /// struct A { static const int n = N; };
1545 /// struct B : public A<42> {};
1547 /// substNonTypeTemplateParmExpr()
1548 /// matches "N" in the right-hand side of "static const int n = N;"
1549 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1550 SubstNonTypeTemplateParmExpr>
1551 substNonTypeTemplateParmExpr;
1553 /// Matches using declarations.
1557 /// namespace X { int x; }
1561 /// matches \code using X::x \endcode
1562 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1564 /// Matches using namespace declarations.
1568 /// namespace X { int x; }
1569 /// using namespace X;
1571 /// usingDirectiveDecl()
1572 /// matches \code using namespace X \endcode
1573 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1576 /// Matches reference to a name that can be looked up during parsing
1577 /// but could not be resolved to a specific declaration.
1581 /// template<typename T>
1582 /// T foo() { T a; return a; }
1583 /// template<typename T>
1588 /// unresolvedLookupExpr()
1589 /// matches \code foo<T>() \endcode
1590 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1591 unresolvedLookupExpr;
1593 /// Matches unresolved using value declarations.
1597 /// template<typename X>
1598 /// class C : private X {
1602 /// unresolvedUsingValueDecl()
1603 /// matches \code using X::x \endcode
1604 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1605 UnresolvedUsingValueDecl>
1606 unresolvedUsingValueDecl;
1608 /// Matches unresolved using value declarations that involve the
1613 /// template <typename T>
1614 /// struct Base { typedef T Foo; };
1616 /// template<typename T>
1617 /// struct S : private Base<T> {
1618 /// using typename Base<T>::Foo;
1621 /// unresolvedUsingTypenameDecl()
1622 /// matches \code using Base<T>::Foo \endcode
1623 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1624 UnresolvedUsingTypenameDecl>
1625 unresolvedUsingTypenameDecl;
1627 /// Matches a constant expression wrapper.
1629 /// Example matches the constant in the case statement:
1630 /// (matcher = constantExpr())
1636 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1639 /// Matches parentheses used in expressions.
1641 /// Example matches (foo() + 1)
1643 /// int foo() { return 1; }
1644 /// int a = (foo() + 1);
1646 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1648 /// Matches constructor call expressions (including implicit ones).
1650 /// Example matches string(ptr, n) and ptr within arguments of f
1651 /// (matcher = cxxConstructExpr())
1653 /// void f(const string &a, const string &b);
1656 /// f(string(ptr, n), ptr);
1658 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1661 /// Matches unresolved constructor call expressions.
1663 /// Example matches T(t) in return statement of f
1664 /// (matcher = cxxUnresolvedConstructExpr())
1666 /// template <typename T>
1667 /// void f(const T& t) { return T(t); }
1669 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1670 CXXUnresolvedConstructExpr>
1671 cxxUnresolvedConstructExpr;
1673 /// Matches implicit and explicit this expressions.
1675 /// Example matches the implicit this expression in "return i".
1676 /// (matcher = cxxThisExpr())
1680 /// int f() { return i; }
1683 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1686 /// Matches nodes where temporaries are created.
1688 /// Example matches FunctionTakesString(GetStringByValue())
1689 /// (matcher = cxxBindTemporaryExpr())
1691 /// FunctionTakesString(GetStringByValue());
1692 /// FunctionTakesStringByPointer(GetStringPointer());
1694 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1695 cxxBindTemporaryExpr;
1697 /// Matches nodes where temporaries are materialized.
1701 /// struct T {void func();};
1705 /// materializeTemporaryExpr() matches 'f()' in these statements
1711 /// but does not match
1715 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1716 MaterializeTemporaryExpr>
1717 materializeTemporaryExpr;
1719 /// Matches new expressions.
1726 /// matches 'new X'.
1727 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1729 /// Matches delete expressions.
1736 /// matches 'delete X'.
1737 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1740 /// Matches array subscript expressions.
1746 /// arraySubscriptExpr()
1748 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1751 /// Matches the value of a default argument at the call site.
1753 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1754 /// default value of the second parameter in the call expression f(42)
1755 /// (matcher = cxxDefaultArgExpr())
1757 /// void f(int x, int y = 0);
1760 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1763 /// Matches overloaded operator calls.
1765 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1766 /// binaryOperator matcher.
1767 /// Currently it does not match operators such as new delete.
1768 /// FIXME: figure out why these do not match?
1770 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1771 /// (matcher = cxxOperatorCallExpr())
1773 /// ostream &operator<< (ostream &out, int i) { };
1774 /// ostream &o; int b = 1, c = 1;
1777 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1778 cxxOperatorCallExpr;
1780 /// Matches expressions.
1782 /// Example matches x()
1784 /// void f() { x(); }
1786 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1788 /// Matches expressions that refer to declarations.
1790 /// Example matches x in if (x)
1795 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1798 /// Matches a reference to an ObjCIvar.
1800 /// Example: matches "a" in "init" method:
1802 /// @implementation A {
1809 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1812 /// Matches a reference to a block.
1814 /// Example: matches "^{}":
1816 /// void f() { ^{}(); }
1818 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
1820 /// Matches if statements.
1822 /// Example matches 'if (x) {}'
1826 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1828 /// Matches for statements.
1830 /// Example matches 'for (;;) {}'
1833 /// int i[] = {1, 2, 3}; for (auto a : i);
1835 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1837 /// Matches the increment statement of a for loop.
1840 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1841 /// matches '++x' in
1843 /// for (x; x < N; ++x) { }
1845 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1847 const Stmt *const Increment = Node.getInc();
1848 return (Increment != nullptr &&
1849 InnerMatcher.matches(*Increment, Finder, Builder));
1852 /// Matches the initialization statement of a for loop.
1855 /// forStmt(hasLoopInit(declStmt()))
1856 /// matches 'int x = 0' in
1858 /// for (int x = 0; x < N; ++x) { }
1860 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1862 const Stmt *const Init = Node.getInit();
1863 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1866 /// Matches range-based for statements.
1868 /// cxxForRangeStmt() matches 'for (auto a : i)'
1870 /// int i[] = {1, 2, 3}; for (auto a : i);
1871 /// for(int j = 0; j < 5; ++j);
1873 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1876 /// Matches the initialization statement of a for loop.
1879 /// forStmt(hasLoopVariable(anything()))
1880 /// matches 'int x' in
1882 /// for (int x : a) { }
1884 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1886 const VarDecl *const Var = Node.getLoopVariable();
1887 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1890 /// Matches the range initialization statement of a for loop.
1893 /// forStmt(hasRangeInit(anything()))
1896 /// for (int x : a) { }
1898 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1900 const Expr *const Init = Node.getRangeInit();
1901 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1904 /// Matches while statements.
1911 /// matches 'while (true) {}'.
1912 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1914 /// Matches do statements.
1918 /// do {} while (true);
1921 /// matches 'do {} while(true)'
1922 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1924 /// Matches break statements.
1928 /// while (true) { break; }
1932 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1934 /// Matches continue statements.
1938 /// while (true) { continue; }
1941 /// matches 'continue'
1942 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1945 /// Matches return statements.
1952 /// matches 'return 1'
1953 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1955 /// Matches goto statements.
1963 /// matches 'goto FOO'
1964 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1966 /// Matches label statements.
1975 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1977 /// Matches address of label statements (GNU extension).
1982 /// void *ptr = &&FOO;
1987 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
1990 /// Matches switch statements.
1994 /// switch(a) { case 42: break; default: break; }
1997 /// matches 'switch(a)'.
1998 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2000 /// Matches case and default statements inside switch statements.
2004 /// switch(a) { case 42: break; default: break; }
2007 /// matches 'case 42:' and 'default:'.
2008 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2010 /// Matches case statements inside switch statements.
2014 /// switch(a) { case 42: break; default: break; }
2017 /// matches 'case 42:'.
2018 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2020 /// Matches default statements inside switch statements.
2024 /// switch(a) { case 42: break; default: break; }
2027 /// matches 'default:'.
2028 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2031 /// Matches compound statements.
2033 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2037 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2040 /// Matches catch statements.
2043 /// try {} catch(int i) {}
2046 /// matches 'catch(int i)'
2047 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2050 /// Matches try statements.
2053 /// try {} catch(int i) {}
2056 /// matches 'try {}'
2057 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2059 /// Matches throw expressions.
2062 /// try { throw 5; } catch(int i) {}
2065 /// matches 'throw 5'
2066 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2069 /// Matches null statements.
2075 /// matches the second ';'
2076 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2078 /// Matches asm statements.
2082 /// __asm("mov al, 2");
2085 /// matches '__asm("mov al, 2")'
2086 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2088 /// Matches bool literals.
2090 /// Example matches true
2094 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2097 /// Matches string literals (also matches wide string literals).
2099 /// Example matches "abcd", L"abcd"
2101 /// char *s = "abcd";
2102 /// wchar_t *ws = L"abcd";
2104 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2107 /// Matches character literals (also matches wchar_t).
2109 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2112 /// Example matches 'a', L'a'
2115 /// wchar_t chw = L'a';
2117 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2120 /// Matches integer literals of all sizes / encodings, e.g.
2121 /// 1, 1L, 0x1 and 1U.
2123 /// Does not match character-encoded integers such as L'a'.
2124 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2127 /// Matches float literals of all sizes / encodings, e.g.
2128 /// 1.0, 1.0f, 1.0L and 1e10.
2130 /// Does not match implicit conversions such as
2134 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2137 /// Matches imaginary literals, which are based on integer and floating
2138 /// point literals e.g.: 1i, 1.0i
2139 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2142 /// Matches user defined literal operator call.
2144 /// Example match: "foo"_suffix
2145 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2148 /// Matches compound (i.e. non-scalar) literals
2150 /// Example match: {1}, (1, 2)
2152 /// int array[4] = {1};
2153 /// vector int myvec = (vector int)(1, 2);
2155 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2156 compoundLiteralExpr;
2158 /// Matches nullptr literal.
2159 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2160 cxxNullPtrLiteralExpr;
2162 /// Matches GNU __null expression.
2163 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2166 /// Matches atomic builtins.
2167 /// Example matches __atomic_load_n(ptr, 1)
2169 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2171 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2173 /// Matches statement expression (GNU extension).
2175 /// Example match: ({ int X = 4; X; })
2177 /// int C = ({ int X = 4; X; });
2179 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2181 /// Matches binary operator expressions.
2183 /// Example matches a || b
2187 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2190 /// Matches unary operator expressions.
2192 /// Example matches !a
2196 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2199 /// Matches conditional operator expressions.
2201 /// Example matches a ? b : c
2203 /// (a ? b : c) + 42
2205 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2206 conditionalOperator;
2208 /// Matches binary conditional operator expressions (GNU extension).
2210 /// Example matches a ?: b
2214 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2215 BinaryConditionalOperator>
2216 binaryConditionalOperator;
2218 /// Matches opaque value expressions. They are used as helpers
2219 /// to reference another expressions and can be met
2220 /// in BinaryConditionalOperators, for example.
2222 /// Example matches 'a'
2226 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2229 /// Matches a C++ static_assert declaration.
2232 /// staticAssertExpr()
2234 /// static_assert(sizeof(S) == sizeof(int))
2240 /// static_assert(sizeof(S) == sizeof(int));
2242 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2245 /// Matches a reinterpret_cast expression.
2247 /// Either the source expression or the destination type can be matched
2248 /// using has(), but hasDestinationType() is more specific and can be
2251 /// Example matches reinterpret_cast<char*>(&p) in
2253 /// void* p = reinterpret_cast<char*>(&p);
2255 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2256 cxxReinterpretCastExpr;
2258 /// Matches a C++ static_cast expression.
2260 /// \see hasDestinationType
2261 /// \see reinterpretCast
2264 /// cxxStaticCastExpr()
2266 /// static_cast<long>(8)
2269 /// long eight(static_cast<long>(8));
2271 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2274 /// Matches a dynamic_cast expression.
2277 /// cxxDynamicCastExpr()
2279 /// dynamic_cast<D*>(&b);
2282 /// struct B { virtual ~B() {} }; struct D : B {};
2284 /// D* p = dynamic_cast<D*>(&b);
2286 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2289 /// Matches a const_cast expression.
2291 /// Example: Matches const_cast<int*>(&r) in
2294 /// const int &r(n);
2295 /// int* p = const_cast<int*>(&r);
2297 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2300 /// Matches a C-style cast expression.
2302 /// Example: Matches (int) 2.2f in
2304 /// int i = (int) 2.2f;
2306 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2309 /// Matches explicit cast expressions.
2311 /// Matches any cast expression written in user code, whether it be a
2312 /// C-style cast, a functional-style cast, or a keyword cast.
2314 /// Does not match implicit conversions.
2316 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2317 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2318 /// actual cast expressions.
2320 /// \see hasDestinationType.
2322 /// Example: matches all five of the casts in
2324 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2326 /// but does not match the implicit conversion in
2330 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2333 /// Matches the implicit cast nodes of Clang's AST.
2335 /// This matches many different places, including function call return value
2336 /// eliding, as well as any type conversions.
2337 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2340 /// Matches any cast nodes of Clang's AST.
2342 /// Example: castExpr() matches each of the following:
2345 /// const_cast<Expr *>(SubExpr);
2348 /// but does not match
2353 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2355 /// Matches functional cast expressions
2357 /// Example: Matches Foo(bar);
2360 /// Foo g = (Foo) bar;
2361 /// Foo h = Foo(bar);
2363 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2364 cxxFunctionalCastExpr;
2366 /// Matches functional cast expressions having N != 1 arguments
2368 /// Example: Matches Foo(bar, bar)
2370 /// Foo h = Foo(bar, bar);
2372 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2373 cxxTemporaryObjectExpr;
2375 /// Matches predefined identifier expressions [C99 6.4.2.2].
2377 /// Example: Matches __func__
2379 /// printf("%s", __func__);
2381 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2384 /// Matches C99 designated initializer expressions [C99 6.7.8].
2386 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2388 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2390 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2393 /// Matches designated initializer expressions that contain
2394 /// a specific number of designators.
2398 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2399 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2401 /// designatorCountIs(2)
2402 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2403 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2404 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2405 return Node.size() == N;
2408 /// Matches \c QualTypes in the clang AST.
2409 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2411 /// Matches \c Types in the clang AST.
2412 extern const internal::VariadicAllOfMatcher<Type> type;
2414 /// Matches \c TypeLocs in the clang AST.
2415 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2417 /// Matches if any of the given matchers matches.
2419 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2420 /// matching submatcher.
2422 /// For example, in:
2424 /// class A { int a; int b; };
2428 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2429 /// has(fieldDecl(hasName("b")).bind("v"))))
2431 /// will generate two results binding "v", the first of which binds
2432 /// the field declaration of \c a, the second the field declaration of
2435 /// Usable as: Any Matcher
2436 extern const internal::VariadicOperatorMatcherFunc<
2437 2, std::numeric_limits<unsigned>::max()>
2440 /// Matches if any of the given matchers matches.
2442 /// Usable as: Any Matcher
2443 extern const internal::VariadicOperatorMatcherFunc<
2444 2, std::numeric_limits<unsigned>::max()>
2447 /// Matches if all given matchers match.
2449 /// Usable as: Any Matcher
2450 extern const internal::VariadicOperatorMatcherFunc<
2451 2, std::numeric_limits<unsigned>::max()>
2454 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2459 /// int y = sizeof(x) + alignof(x);
2461 /// unaryExprOrTypeTraitExpr()
2462 /// matches \c sizeof(x) and \c alignof(x)
2463 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2464 UnaryExprOrTypeTraitExpr>
2465 unaryExprOrTypeTraitExpr;
2467 /// Matches unary expressions that have a specific type of argument.
2471 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2473 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2474 /// matches \c sizeof(a) and \c alignof(c)
2475 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2476 internal::Matcher<QualType>, InnerMatcher) {
2477 const QualType ArgumentType = Node.getTypeOfArgument();
2478 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2481 /// Matches unary expressions of a certain kind.
2486 /// int s = sizeof(x) + alignof(x)
2488 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2489 /// matches \c sizeof(x)
2490 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2491 return Node.getKind() == Kind;
2494 /// Same as unaryExprOrTypeTraitExpr, but only matching
2496 inline internal::Matcher<Stmt> alignOfExpr(
2497 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2498 return stmt(unaryExprOrTypeTraitExpr(
2499 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2503 /// Same as unaryExprOrTypeTraitExpr, but only matching
2505 inline internal::Matcher<Stmt> sizeOfExpr(
2506 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2507 return stmt(unaryExprOrTypeTraitExpr(
2508 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2511 /// Matches NamedDecl nodes that have the specified name.
2513 /// Supports specifying enclosing namespaces or classes by prefixing the name
2514 /// with '<enclosing>::'.
2515 /// Does not match typedefs of an underlying type with the given name.
2517 /// Example matches X (Name == "X")
2522 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2524 /// namespace a { namespace b { class X; } }
2526 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2527 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2530 /// Matches NamedDecl nodes that have any of the specified names.
2532 /// This matcher is only provided as a performance optimization of hasName.
2534 /// hasAnyName(a, b, c)
2536 /// is equivalent to, but faster than
2538 /// anyOf(hasName(a), hasName(b), hasName(c))
2540 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2541 internal::hasAnyNameFunc>
2544 /// Matches NamedDecl nodes whose fully qualified names contain
2545 /// a substring matched by the given RegExp.
2547 /// Supports specifying enclosing namespaces or classes by
2548 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2549 /// of an underlying type with the given name.
2551 /// Example matches X (regexp == "::X")
2556 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2558 /// namespace foo { namespace bar { class X; } }
2560 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2561 assert(!RegExp.empty());
2562 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2563 llvm::Regex RE(RegExp);
2564 return RE.match(FullNameString);
2567 /// Matches overloaded operator names.
2569 /// Matches overloaded operator names specified in strings without the
2570 /// "operator" prefix: e.g. "<<".
2574 /// class A { int operator*(); };
2575 /// const A &operator<<(const A &a, const A &b);
2577 /// a << a; // <-- This matches
2580 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2581 /// specified line and
2582 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2583 /// matches the declaration of \c A.
2585 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2586 inline internal::PolymorphicMatcherWithParam1<
2587 internal::HasOverloadedOperatorNameMatcher, StringRef,
2588 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2589 hasOverloadedOperatorName(StringRef Name) {
2590 return internal::PolymorphicMatcherWithParam1<
2591 internal::HasOverloadedOperatorNameMatcher, StringRef,
2592 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2595 /// Matches C++ classes that are directly or indirectly derived from
2596 /// a class matching \c Base.
2598 /// Note that a class is not considered to be derived from itself.
2600 /// Example matches Y, Z, C (Base == hasName("X"))
2603 /// class Y : public X {}; // directly derived
2604 /// class Z : public Y {}; // indirectly derived
2607 /// class C : public B {}; // derived from a typedef of X
2610 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2614 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2616 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2617 internal::Matcher<NamedDecl>, Base) {
2618 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2621 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2622 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2623 assert(!BaseName.empty());
2624 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2627 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2629 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2630 internal::Matcher<NamedDecl>, Base, 0) {
2631 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2632 .matches(Node, Finder, Builder);
2635 /// Overloaded method as shortcut for
2636 /// \c isSameOrDerivedFrom(hasName(...)).
2637 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2639 assert(!BaseName.empty());
2640 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2643 /// Matches the first method of a class or struct that satisfies \c
2648 /// class A { void func(); };
2649 /// class B { void member(); };
2652 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2653 /// \c A but not \c B.
2654 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2656 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2657 Node.method_end(), Finder, Builder);
2660 /// Matches the generated class of lambda expressions.
2667 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2669 AST_MATCHER(CXXRecordDecl, isLambda) {
2670 return Node.isLambda();
2673 /// Matches AST nodes that have child AST nodes that match the
2674 /// provided matcher.
2676 /// Example matches X, Y
2677 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2679 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2680 /// class Y { class X {}; };
2681 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2684 /// ChildT must be an AST base type.
2686 /// Usable as: Any Matcher
2687 /// Note that has is direct matcher, so it also matches things like implicit
2688 /// casts and paren casts. If you are matching with expr then you should
2689 /// probably consider using ignoringParenImpCasts like:
2690 /// has(ignoringParenImpCasts(expr())).
2691 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2693 /// Matches AST nodes that have descendant AST nodes that match the
2694 /// provided matcher.
2696 /// Example matches X, Y, Z
2697 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2699 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2700 /// class Y { class X {}; };
2701 /// class Z { class Y { class X {}; }; };
2704 /// DescendantT must be an AST base type.
2706 /// Usable as: Any Matcher
2707 extern const internal::ArgumentAdaptingMatcherFunc<
2708 internal::HasDescendantMatcher>
2711 /// Matches AST nodes that have child AST nodes that match the
2712 /// provided matcher.
2714 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2715 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2718 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
2720 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2723 /// ChildT must be an AST base type.
2725 /// As opposed to 'has', 'forEach' will cause a match for each result that
2726 /// matches instead of only on the first one.
2728 /// Usable as: Any Matcher
2729 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2732 /// Matches AST nodes that have descendant AST nodes that match the
2733 /// provided matcher.
2735 /// Example matches X, A, A::X, B, B::C, B::C::X
2736 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2739 /// class A { class X {}; }; // Matches A, because A::X is a class of name
2741 /// class B { class C { class X {}; }; };
2744 /// DescendantT must be an AST base type.
2746 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2747 /// each result that matches instead of only on the first one.
2749 /// Note: Recursively combined ForEachDescendant can cause many matches:
2750 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2751 /// forEachDescendant(cxxRecordDecl())
2753 /// will match 10 times (plus injected class name matches) on:
2755 /// class A { class B { class C { class D { class E {}; }; }; }; };
2758 /// Usable as: Any Matcher
2759 extern const internal::ArgumentAdaptingMatcherFunc<
2760 internal::ForEachDescendantMatcher>
2763 /// Matches if the node or any descendant matches.
2765 /// Generates results for each match.
2767 /// For example, in:
2769 /// class A { class B {}; class C {}; };
2773 /// cxxRecordDecl(hasName("::A"),
2774 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2776 /// will generate results for \c A, \c B and \c C.
2778 /// Usable as: Any Matcher
2779 template <typename T>
2780 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2781 return eachOf(Matcher, forEachDescendant(Matcher));
2784 /// Matches AST nodes that have a parent that matches the provided
2789 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2791 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2793 /// Usable as: Any Matcher
2794 extern const internal::ArgumentAdaptingMatcherFunc<
2795 internal::HasParentMatcher,
2796 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2797 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2800 /// Matches AST nodes that have an ancestor that matches the provided
2805 /// void f() { if (true) { int x = 42; } }
2806 /// void g() { for (;;) { int x = 43; } }
2808 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2810 /// Usable as: Any Matcher
2811 extern const internal::ArgumentAdaptingMatcherFunc<
2812 internal::HasAncestorMatcher,
2813 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2814 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2817 /// Matches if the provided matcher does not match.
2819 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2825 /// Usable as: Any Matcher
2826 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2828 /// Matches a node if the declaration associated with that node
2829 /// matches the given matcher.
2831 /// The associated declaration is:
2832 /// - for type nodes, the declaration of the underlying type
2833 /// - for CallExpr, the declaration of the callee
2834 /// - for MemberExpr, the declaration of the referenced member
2835 /// - for CXXConstructExpr, the declaration of the constructor
2836 /// - for CXXNewExpr, the declaration of the operator new
2837 /// - for ObjCIvarExpr, the declaration of the ivar
2839 /// For type nodes, hasDeclaration will generally match the declaration of the
2840 /// sugared type. Given
2846 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2847 /// typedefDecl. A common use case is to match the underlying, desugared type.
2848 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2850 /// varDecl(hasType(hasUnqualifiedDesugaredType(
2851 /// recordType(hasDeclaration(decl())))))
2853 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2855 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2856 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2857 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2858 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2859 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2860 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2861 /// Matcher<UnresolvedUsingType>
2862 inline internal::PolymorphicMatcherWithParam1<
2863 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2864 void(internal::HasDeclarationSupportedTypes)>
2865 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2866 return internal::PolymorphicMatcherWithParam1<
2867 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2868 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2871 /// Matches a \c NamedDecl whose underlying declaration matches the given
2876 /// namespace N { template<class T> void f(T t); }
2877 /// template <class T> void g() { using N::f; f(T()); }
2879 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2880 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2881 /// matches the use of \c f in \c g() .
2882 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2884 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2886 return UnderlyingDecl != nullptr &&
2887 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2890 /// Matches on the implicit object argument of a member call expression.
2892 /// Example matches y.x()
2893 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2895 /// class Y { public: void x(); };
2896 /// void z() { Y y; y.x(); }
2899 /// FIXME: Overload to allow directly matching types?
2900 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2902 const Expr *ExprNode = Node.getImplicitObjectArgument()
2903 ->IgnoreParenImpCasts();
2904 return (ExprNode != nullptr &&
2905 InnerMatcher.matches(*ExprNode, Finder, Builder));
2909 /// Matches on the receiver of an ObjectiveC Message expression.
2912 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2913 /// matches the [webView ...] message invocation.
2915 /// NSString *webViewJavaScript = ...
2916 /// UIWebView *webView = ...
2917 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2919 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2921 const QualType TypeDecl = Node.getReceiverType();
2922 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2925 /// Returns true when the Objective-C message is sent to an instance.
2928 /// matcher = objcMessagaeExpr(isInstanceMessage())
2931 /// NSString *x = @"hello";
2932 /// [x containsString:@"h"];
2936 /// [NSString stringWithFormat:@"format"];
2938 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
2939 return Node.isInstanceMessage();
2942 /// Matches if the Objective-C message is sent to an instance,
2943 /// and the inner matcher matches on that instance.
2945 /// For example the method call in
2947 /// NSString *x = @"hello";
2948 /// [x containsString:@"h"];
2951 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
2952 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
2954 const Expr *ReceiverNode = Node.getInstanceReceiver();
2955 return (ReceiverNode != nullptr &&
2956 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
2960 /// Matches when BaseName == Selector.getAsString()
2962 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2963 /// matches the outer message expr in the code below, but NOT the message
2964 /// invocation for self.bodyView.
2966 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2968 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2969 Selector Sel = Node.getSelector();
2970 return BaseName.compare(Sel.getAsString()) == 0;
2974 /// Matches when at least one of the supplied string equals to the
2975 /// Selector.getAsString()
2977 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
2978 /// matches both of the expressions below:
2980 /// [myObj methodA:argA];
2981 /// [myObj methodB:argB];
2983 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
2985 internal::hasAnySelectorFunc>
2988 /// Matches ObjC selectors whose name contains
2989 /// a substring matched by the given RegExp.
2990 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2991 /// matches the outer message expr in the code below, but NOT the message
2992 /// invocation for self.bodyView.
2994 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2996 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2997 assert(!RegExp.empty());
2998 std::string SelectorString = Node.getSelector().getAsString();
2999 llvm::Regex RE(RegExp);
3000 return RE.match(SelectorString);
3003 /// Matches when the selector is the empty selector
3005 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3006 /// represent an error condition in the tree!
3007 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3008 return Node.getSelector().isNull();
3011 /// Matches when the selector is a Unary Selector
3013 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3014 /// matches self.bodyView in the code below, but NOT the outer message
3015 /// invocation of "loadHTMLString:baseURL:".
3017 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3019 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3020 return Node.getSelector().isUnarySelector();
3023 /// Matches when the selector is a keyword selector
3025 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3026 /// message expression in
3029 /// UIWebView *webView = ...;
3030 /// CGRect bodyFrame = webView.frame;
3031 /// bodyFrame.size.height = self.bodyContentHeight;
3032 /// webView.frame = bodyFrame;
3033 /// // ^---- matches here
3035 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3036 return Node.getSelector().isKeywordSelector();
3039 /// Matches when the selector has the specified number of arguments
3041 /// matcher = objCMessageExpr(numSelectorArgs(0));
3042 /// matches self.bodyView in the code below
3044 /// matcher = objCMessageExpr(numSelectorArgs(2));
3045 /// matches the invocation of "loadHTMLString:baseURL:" but not that
3046 /// of self.bodyView
3048 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3050 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3051 return Node.getSelector().getNumArgs() == N;
3054 /// Matches if the call expression's callee expression matches.
3058 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3059 /// void f() { f(); }
3061 /// callExpr(callee(expr()))
3062 /// matches this->x(), x(), y.x(), f()
3063 /// with callee(...)
3064 /// matching this->x, x, y.x, f respectively
3066 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3067 /// because this introduces ambiguous overloads with calls to Callee taking a
3068 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3069 /// implemented in terms of implicit casts.
3070 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3072 const Expr *ExprNode = Node.getCallee();
3073 return (ExprNode != nullptr &&
3074 InnerMatcher.matches(*ExprNode, Finder, Builder));
3077 /// Matches if the call expression's callee's declaration matches the
3080 /// Example matches y.x() (matcher = callExpr(callee(
3081 /// cxxMethodDecl(hasName("x")))))
3083 /// class Y { public: void x(); };
3084 /// void z() { Y y; y.x(); }
3086 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3088 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3091 /// Matches if the expression's or declaration's type matches a type
3094 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3095 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3096 /// and U (matcher = typedefDecl(hasType(asString("int")))
3097 /// and friend class X (matcher = friendDecl(hasType("X"))
3100 /// void y(X &x) { x; X z; }
3102 /// class Y { friend class X; };
3104 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3106 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3108 internal::Matcher<QualType>, InnerMatcher, 0) {
3109 QualType QT = internal::getUnderlyingType(Node);
3111 return InnerMatcher.matches(QT, Finder, Builder);
3115 /// Overloaded to match the declaration of the expression's or value
3116 /// declaration's type.
3118 /// In case of a value declaration (for example a variable declaration),
3119 /// this resolves one layer of indirection. For example, in the value
3120 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3121 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3122 /// declaration of x.
3124 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3125 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3126 /// and friend class X (matcher = friendDecl(hasType("X"))
3129 /// void y(X &x) { x; X z; }
3130 /// class Y { friend class X; };
3133 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
3134 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3135 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
3136 internal::Matcher<Decl>, InnerMatcher, 1) {
3137 QualType QT = internal::getUnderlyingType(Node);
3139 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3143 /// Matches if the type location of the declarator decl's type matches
3144 /// the inner matcher.
3150 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3152 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3153 if (!Node.getTypeSourceInfo())
3154 // This happens for example for implicit destructors.
3156 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3159 /// Matches if the matched type is represented by the given string.
3163 /// class Y { public: void x(); };
3164 /// void z() { Y* y; y->x(); }
3166 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3168 AST_MATCHER_P(QualType, asString, std::string, Name) {
3169 return Name == Node.getAsString();
3172 /// Matches if the matched type is a pointer type and the pointee type
3173 /// matches the specified matcher.
3175 /// Example matches y->x()
3176 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3177 /// cxxRecordDecl(hasName("Y")))))))
3179 /// class Y { public: void x(); };
3180 /// void z() { Y *y; y->x(); }
3183 QualType, pointsTo, internal::Matcher<QualType>,
3185 return (!Node.isNull() && Node->isAnyPointerType() &&
3186 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3189 /// Overloaded to match the pointee type's declaration.
3190 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3192 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3193 .matches(Node, Finder, Builder);
3196 /// Matches if the matched type matches the unqualified desugared
3197 /// type of the matched node.
3199 /// For example, in:
3204 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3206 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3208 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3212 /// Matches if the matched type is a reference type and the referenced
3213 /// type matches the specified matcher.
3215 /// Example matches X &x and const X &y
3216 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3225 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3227 return (!Node.isNull() && Node->isReferenceType() &&
3228 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3231 /// Matches QualTypes whose canonical type matches InnerMatcher.
3235 /// typedef int &int_ref;
3240 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3241 /// declaration of b but \c
3242 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3243 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3247 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3250 /// Overloaded to match the referenced type's declaration.
3251 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3253 return references(qualType(hasDeclaration(InnerMatcher)))
3254 .matches(Node, Finder, Builder);
3257 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3258 internal::Matcher<Expr>, InnerMatcher) {
3259 const Expr *ExprNode = Node.getImplicitObjectArgument();
3260 return (ExprNode != nullptr &&
3261 InnerMatcher.matches(*ExprNode, Finder, Builder));
3264 /// Matches if the expression's type either matches the specified
3265 /// matcher, or is a pointer to a type that matches the InnerMatcher.
3266 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3267 internal::Matcher<QualType>, InnerMatcher, 0) {
3268 return onImplicitObjectArgument(
3269 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3270 .matches(Node, Finder, Builder);
3273 /// Overloaded to match the type's declaration.
3274 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3275 internal::Matcher<Decl>, InnerMatcher, 1) {
3276 return onImplicitObjectArgument(
3277 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3278 .matches(Node, Finder, Builder);
3281 /// Matches a DeclRefExpr that refers to a declaration that matches the
3282 /// specified matcher.
3284 /// Example matches x in if(x)
3285 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3290 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3292 const Decl *DeclNode = Node.getDecl();
3293 return (DeclNode != nullptr &&
3294 InnerMatcher.matches(*DeclNode, Finder, Builder));
3297 /// Matches a \c DeclRefExpr that refers to a declaration through a
3298 /// specific using shadow declaration.
3302 /// namespace a { void f() {} }
3305 /// f(); // Matches this ..
3306 /// a::f(); // .. but not this.
3309 /// declRefExpr(throughUsingDecl(anything()))
3311 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3312 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3313 const NamedDecl *FoundDecl = Node.getFoundDecl();
3314 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3315 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3319 /// Matches an \c OverloadExpr if any of the declarations in the set of
3320 /// overloads matches the given matcher.
3324 /// template <typename T> void foo(T);
3325 /// template <typename T> void bar(T);
3326 /// template <typename T> void baz(T t) {
3331 /// unresolvedLookupExpr(hasAnyDeclaration(
3332 /// functionTemplateDecl(hasName("foo"))))
3333 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3334 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3336 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3337 Node.decls_end(), Finder, Builder);
3340 /// Matches the Decl of a DeclStmt which has a single declaration.
3347 /// declStmt(hasSingleDecl(anything()))
3348 /// matches 'int c;' but not 'int a, b;'.
3349 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3350 if (Node.isSingleDecl()) {
3351 const Decl *FoundDecl = Node.getSingleDecl();
3352 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3357 /// Matches a variable declaration that has an initializer expression
3358 /// that matches the given matcher.
3360 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3362 /// bool y() { return true; }
3366 VarDecl, hasInitializer, internal::Matcher<Expr>,
3368 const Expr *Initializer = Node.getAnyInitializer();
3369 return (Initializer != nullptr &&
3370 InnerMatcher.matches(*Initializer, Finder, Builder));
3373 /// \brief Matches a static variable with local scope.
3375 /// Example matches y (matcher = varDecl(isStaticLocal()))
3383 AST_MATCHER(VarDecl, isStaticLocal) {
3384 return Node.isStaticLocal();
3387 /// Matches a variable declaration that has function scope and is a
3388 /// non-static local variable.
3390 /// Example matches x (matcher = varDecl(hasLocalStorage())
3398 AST_MATCHER(VarDecl, hasLocalStorage) {
3399 return Node.hasLocalStorage();
3402 /// Matches a variable declaration that does not have local storage.
3404 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3412 AST_MATCHER(VarDecl, hasGlobalStorage) {
3413 return Node.hasGlobalStorage();
3416 /// Matches a variable declaration that has automatic storage duration.
3418 /// Example matches x, but not y, z, or a.
3419 /// (matcher = varDecl(hasAutomaticStorageDuration())
3424 /// thread_local int z;
3428 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3429 return Node.getStorageDuration() == SD_Automatic;
3432 /// Matches a variable declaration that has static storage duration.
3433 /// It includes the variable declared at namespace scope and those declared
3434 /// with "static" and "extern" storage class specifiers.
3440 /// thread_local int z;
3445 /// varDecl(hasStaticStorageDuration())
3446 /// matches the function declaration y, a, b and c.
3448 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3449 return Node.getStorageDuration() == SD_Static;
3452 /// Matches a variable declaration that has thread storage duration.
3454 /// Example matches z, but not x, z, or a.
3455 /// (matcher = varDecl(hasThreadStorageDuration())
3460 /// thread_local int z;
3464 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3465 return Node.getStorageDuration() == SD_Thread;
3468 /// Matches a variable declaration that is an exception variable from
3469 /// a C++ catch block, or an Objective-C \@catch statement.
3471 /// Example matches x (matcher = varDecl(isExceptionVariable())
3475 /// } catch (int x) {
3479 AST_MATCHER(VarDecl, isExceptionVariable) {
3480 return Node.isExceptionVariable();
3483 /// Checks that a call expression or a constructor call expression has
3484 /// a specific number of arguments (including absent default arguments).
3486 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3488 /// void f(int x, int y);
3491 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3492 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3496 return Node.getNumArgs() == N;
3499 /// Matches the n'th argument of a call expression or a constructor
3500 /// call expression.
3502 /// Example matches y in x(y)
3503 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3505 /// void x(int) { int y; x(y); }
3507 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3508 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3511 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3512 return (N < Node.getNumArgs() &&
3513 InnerMatcher.matches(
3514 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3517 /// Matches the n'th item of an initializer list expression.
3519 /// Example matches y.
3520 /// (matcher = initListExpr(hasInit(0, expr())))
3524 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
3525 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
3526 return N < Node.getNumInits() &&
3527 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
3530 /// Matches declaration statements that contain a specific number of
3540 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3541 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3542 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3545 /// Matches the n'th declaration of a declaration statement.
3547 /// Note that this does not work for global declarations because the AST
3548 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3550 /// Example: Given non-global declarations
3556 /// declStmt(containsDeclaration(
3557 /// 0, varDecl(hasInitializer(anything()))))
3558 /// matches only 'int d = 2, e;', and
3559 /// declStmt(containsDeclaration(1, varDecl()))
3561 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3562 /// but 'int c;' is not matched.
3564 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3565 internal::Matcher<Decl>, InnerMatcher) {
3566 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3569 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3570 std::advance(Iterator, N);
3571 return InnerMatcher.matches(**Iterator, Finder, Builder);
3574 /// Matches a C++ catch statement that has a catch-all handler.
3586 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3587 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3588 return Node.getExceptionDecl() == nullptr;
3591 /// Matches a constructor initializer.
3596 /// Foo() : foo_(1) { }
3600 /// cxxRecordDecl(has(cxxConstructorDecl(
3601 /// hasAnyConstructorInitializer(anything())
3603 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3604 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3605 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3606 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3607 Node.init_end(), Finder, Builder);
3610 /// Matches the field declaration of a constructor initializer.
3615 /// Foo() : foo_(1) { }
3619 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3620 /// forField(hasName("foo_"))))))
3622 /// with forField matching foo_
3623 AST_MATCHER_P(CXXCtorInitializer, forField,
3624 internal::Matcher<FieldDecl>, InnerMatcher) {
3625 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3626 return (NodeAsDecl != nullptr &&
3627 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3630 /// Matches the initializer expression of a constructor initializer.
3635 /// Foo() : foo_(1) { }
3639 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3640 /// withInitializer(integerLiteral(equals(1)))))))
3642 /// with withInitializer matching (1)
3643 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3644 internal::Matcher<Expr>, InnerMatcher) {
3645 const Expr* NodeAsExpr = Node.getInit();
3646 return (NodeAsExpr != nullptr &&
3647 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3650 /// Matches a constructor initializer if it is explicitly written in
3651 /// code (as opposed to implicitly added by the compiler).
3657 /// Foo(int) : foo_("A") { }
3661 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3662 /// will match Foo(int), but not Foo()
3663 AST_MATCHER(CXXCtorInitializer, isWritten) {
3664 return Node.isWritten();
3667 /// Matches a constructor initializer if it is initializing a base, as
3668 /// opposed to a member.
3675 /// D(int i) : I(i) {}
3681 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3682 /// will match E(), but not match D(int).
3683 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3684 return Node.isBaseInitializer();
3687 /// Matches a constructor initializer if it is initializing a member, as
3688 /// opposed to a base.
3695 /// D(int i) : I(i) {}
3701 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3702 /// will match D(int), but not match E().
3703 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3704 return Node.isMemberInitializer();
3707 /// Matches any argument of a call expression or a constructor call
3708 /// expression, or an ObjC-message-send expression.
3712 /// void x(int, int, int) { int y; x(1, y, 42); }
3714 /// callExpr(hasAnyArgument(declRefExpr()))
3715 /// matches x(1, y, 42)
3716 /// with hasAnyArgument(...)
3719 /// For ObjectiveC, given
3721 /// @interface I - (void) f:(int) y; @end
3722 /// void foo(I *i) { [i f:12]; }
3724 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3725 /// matches [i f:12]
3726 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3727 AST_POLYMORPHIC_SUPPORTED_TYPES(
3728 CallExpr, CXXConstructExpr,
3729 CXXUnresolvedConstructExpr, ObjCMessageExpr),
3730 internal::Matcher<Expr>, InnerMatcher) {
3731 for (const Expr *Arg : Node.arguments()) {
3732 BoundNodesTreeBuilder Result(*Builder);
3733 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3734 *Builder = std::move(Result);
3741 /// Matches a constructor call expression which uses list initialization.
3742 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3743 return Node.isListInitialization();
3746 /// Matches a constructor call expression which requires
3747 /// zero initialization.
3752 /// struct point { double x; double y; };
3753 /// point pt[2] = { { 1.0, 2.0 } };
3756 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3757 /// will match the implicit array filler for pt[1].
3758 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3759 return Node.requiresZeroInitialization();
3762 /// Matches the n'th parameter of a function or an ObjC method
3763 /// declaration or a block.
3767 /// class X { void f(int x) {} };
3769 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3770 /// matches f(int x) {}
3771 /// with hasParameter(...)
3774 /// For ObjectiveC, given
3776 /// @interface I - (void) f:(int) y; @end
3779 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3780 /// matches the declaration of method f with hasParameter
3782 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3783 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3786 unsigned, N, internal::Matcher<ParmVarDecl>,
3788 return (N < Node.parameters().size()
3789 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3792 /// Matches all arguments and their respective ParmVarDecl.
3801 /// forEachArgumentWithParam(
3802 /// declRefExpr(to(varDecl(hasName("y")))),
3803 /// parmVarDecl(hasType(isInteger()))
3806 /// with declRefExpr(...)
3808 /// and parmVarDecl(...)
3810 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3811 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3813 internal::Matcher<Expr>, ArgMatcher,
3814 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3815 BoundNodesTreeBuilder Result;
3816 // The first argument of an overloaded member operator is the implicit object
3817 // argument of the method which should not be matched against a parameter, so
3818 // we skip over it here.
3819 BoundNodesTreeBuilder Matches;
3820 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3821 .matches(Node, Finder, &Matches)
3825 bool Matched = false;
3826 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3827 BoundNodesTreeBuilder ArgMatches(*Builder);
3828 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3829 Finder, &ArgMatches)) {
3830 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3831 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3832 hasParameter(ParamIndex, ParamMatcher)))),
3833 callExpr(callee(functionDecl(
3834 hasParameter(ParamIndex, ParamMatcher))))))
3835 .matches(Node, Finder, &ParamMatches)) {
3836 Result.addMatch(ParamMatches);
3842 *Builder = std::move(Result);
3846 /// Matches any parameter of a function or an ObjC method declaration or a
3849 /// Does not match the 'this' parameter of a method.
3853 /// class X { void f(int x, int y, int z) {} };
3855 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3856 /// matches f(int x, int y, int z) {}
3857 /// with hasAnyParameter(...)
3860 /// For ObjectiveC, given
3862 /// @interface I - (void) f:(int) y; @end
3865 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
3866 /// matches the declaration of method f with hasParameter
3869 /// For blocks, given
3871 /// b = ^(int y) { printf("%d", y) };
3874 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
3875 /// matches the declaration of the block b with hasParameter
3877 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
3878 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3881 internal::Matcher<ParmVarDecl>,
3883 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3884 Node.param_end(), Finder, Builder);
3887 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3888 /// specific parameter count.
3892 /// void f(int i) {}
3893 /// void g(int i, int j) {}
3894 /// void h(int i, int j);
3896 /// void k(int x, int y, int z, ...);
3898 /// functionDecl(parameterCountIs(2))
3899 /// matches \c g and \c h
3900 /// functionProtoType(parameterCountIs(2))
3901 /// matches \c g and \c h
3902 /// functionProtoType(parameterCountIs(3))
3904 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3905 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3908 return Node.getNumParams() == N;
3911 /// Matches \c FunctionDecls that have a noreturn attribute.
3916 /// [[noreturn]] void a();
3917 /// __attribute__((noreturn)) void b();
3918 /// struct c { [[noreturn]] c(); };
3920 /// functionDecl(isNoReturn())
3921 /// matches all of those except
3925 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
3927 /// Matches the return type of a function declaration.
3931 /// class X { int f() { return 1; } };
3933 /// cxxMethodDecl(returns(asString("int")))
3934 /// matches int f() { return 1; }
3935 AST_MATCHER_P(FunctionDecl, returns,
3936 internal::Matcher<QualType>, InnerMatcher) {
3937 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3940 /// Matches extern "C" function or variable declarations.
3944 /// extern "C" void f() {}
3945 /// extern "C" { void g() {} }
3947 /// extern "C" int x = 1;
3948 /// extern "C" int y = 2;
3951 /// functionDecl(isExternC())
3952 /// matches the declaration of f and g, but not the declaration of h.
3953 /// varDecl(isExternC())
3954 /// matches the declaration of x and y, but not the declaration of z.
3955 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3957 return Node.isExternC();
3960 /// Matches variable/function declarations that have "static" storage
3961 /// class specifier ("static" keyword) written in the source.
3965 /// static void f() {}
3966 /// static int i = 0;
3970 /// functionDecl(isStaticStorageClass())
3971 /// matches the function declaration f.
3972 /// varDecl(isStaticStorageClass())
3973 /// matches the variable declaration i.
3974 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
3975 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3977 return Node.getStorageClass() == SC_Static;
3980 /// Matches deleted function declarations.
3985 /// void DeletedFunc() = delete;
3987 /// functionDecl(isDeleted())
3988 /// matches the declaration of DeletedFunc, but not Func.
3989 AST_MATCHER(FunctionDecl, isDeleted) {
3990 return Node.isDeleted();
3993 /// Matches defaulted function declarations.
3997 /// class A { ~A(); };
3998 /// class B { ~B() = default; };
4000 /// functionDecl(isDefaulted())
4001 /// matches the declaration of ~B, but not ~A.
4002 AST_MATCHER(FunctionDecl, isDefaulted) {
4003 return Node.isDefaulted();
4006 /// Matches functions that have a dynamic exception specification.
4011 /// void g() noexcept;
4012 /// void h() noexcept(true);
4013 /// void i() noexcept(false);
4014 /// void j() throw();
4015 /// void k() throw(int);
4016 /// void l() throw(...);
4018 /// functionDecl(hasDynamicExceptionSpec()) and
4019 /// functionProtoType(hasDynamicExceptionSpec())
4020 /// match the declarations of j, k, and l, but not f, g, h, or i.
4021 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
4022 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4023 FunctionProtoType)) {
4024 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
4025 return FnTy->hasDynamicExceptionSpec();
4029 /// Matches functions that have a non-throwing exception specification.
4034 /// void g() noexcept;
4035 /// void h() throw();
4036 /// void i() throw(int);
4037 /// void j() noexcept(false);
4039 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
4040 /// match the declarations of g, and h, but not f, i or j.
4041 AST_POLYMORPHIC_MATCHER(isNoThrow,
4042 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4043 FunctionProtoType)) {
4044 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
4046 // If the function does not have a prototype, then it is assumed to be a
4047 // throwing function (as it would if the function did not have any exception
4052 // Assume the best for any unresolved exception specification.
4053 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
4056 return FnTy->isNothrow();
4059 /// Matches constexpr variable and function declarations,
4060 /// and if constexpr.
4064 /// constexpr int foo = 42;
4065 /// constexpr int bar();
4066 /// void baz() { if constexpr(1 > 0) {} }
4068 /// varDecl(isConstexpr())
4069 /// matches the declaration of foo.
4070 /// functionDecl(isConstexpr())
4071 /// matches the declaration of bar.
4072 /// ifStmt(isConstexpr())
4073 /// matches the if statement in baz.
4074 AST_POLYMORPHIC_MATCHER(isConstexpr,
4075 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
4078 return Node.isConstexpr();
4081 /// Matches the condition expression of an if statement, for loop,
4082 /// switch statement or conditional operator.
4084 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
4088 AST_POLYMORPHIC_MATCHER_P(
4090 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
4091 SwitchStmt, AbstractConditionalOperator),
4092 internal::Matcher<Expr>, InnerMatcher) {
4093 const Expr *const Condition = Node.getCond();
4094 return (Condition != nullptr &&
4095 InnerMatcher.matches(*Condition, Finder, Builder));
4098 /// Matches the then-statement of an if statement.
4100 /// Examples matches the if statement
4101 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
4103 /// if (false) true; else false;
4105 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
4106 const Stmt *const Then = Node.getThen();
4107 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
4110 /// Matches the else-statement of an if statement.
4112 /// Examples matches the if statement
4113 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
4115 /// if (false) false; else true;
4117 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
4118 const Stmt *const Else = Node.getElse();
4119 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
4122 /// Matches if a node equals a previously bound node.
4124 /// Matches a node if it equals the node previously bound to \p ID.
4128 /// class X { int a; int b; };
4131 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4132 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
4133 /// matches the class \c X, as \c a and \c b have the same type.
4135 /// Note that when multiple matches are involved via \c forEach* matchers,
4136 /// \c equalsBoundNodes acts as a filter.
4139 /// forEachDescendant(varDecl().bind("d")),
4140 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
4141 /// will trigger a match for each combination of variable declaration
4142 /// and reference to that variable declaration within a compound statement.
4143 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
4144 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
4147 // FIXME: Figure out whether it makes sense to allow this
4148 // on any other node types.
4149 // For *Loc it probably does not make sense, as those seem
4150 // unique. For NestedNameSepcifier it might make sense, as
4151 // those also have pointer identity, but I'm not sure whether
4152 // they're ever reused.
4153 internal::NotEqualsBoundNodePredicate Predicate;
4155 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
4156 return Builder->removeBindings(Predicate);
4159 /// Matches the condition variable statement in an if statement.
4163 /// if (A* a = GetAPointer()) {}
4165 /// hasConditionVariableStatement(...)
4166 /// matches 'A* a = GetAPointer()'.
4167 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
4168 internal::Matcher<DeclStmt>, InnerMatcher) {
4169 const DeclStmt* const DeclarationStatement =
4170 Node.getConditionVariableDeclStmt();
4171 return DeclarationStatement != nullptr &&
4172 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
4175 /// Matches the index expression of an array subscript expression.
4180 /// void f() { i[1] = 42; }
4182 /// arraySubscriptExpression(hasIndex(integerLiteral()))
4183 /// matches \c i[1] with the \c integerLiteral() matching \c 1
4184 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
4185 internal::Matcher<Expr>, InnerMatcher) {
4186 if (const Expr* Expression = Node.getIdx())
4187 return InnerMatcher.matches(*Expression, Finder, Builder);
4191 /// Matches the base expression of an array subscript expression.
4196 /// void f() { i[1] = 42; }
4198 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4199 /// hasSourceExpression(declRefExpr()))))
4200 /// matches \c i[1] with the \c declRefExpr() matching \c i
4201 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4202 internal::Matcher<Expr>, InnerMatcher) {
4203 if (const Expr* Expression = Node.getBase())
4204 return InnerMatcher.matches(*Expression, Finder, Builder);
4208 /// Matches a 'for', 'while', 'do while' statement or a function
4209 /// definition that has a given body.
4215 /// hasBody(compoundStmt())
4216 /// matches 'for (;;) {}'
4217 /// with compoundStmt()
4219 AST_POLYMORPHIC_MATCHER_P(hasBody,
4220 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4224 internal::Matcher<Stmt>, InnerMatcher) {
4225 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4226 return (Statement != nullptr &&
4227 InnerMatcher.matches(*Statement, Finder, Builder));
4230 /// Matches compound statements where at least one substatement matches
4231 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4237 /// hasAnySubstatement(compoundStmt())
4238 /// matches '{ {}; 1+2; }'
4239 /// with compoundStmt()
4241 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4242 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4244 internal::Matcher<Stmt>, InnerMatcher) {
4245 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4246 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4247 CS->body_end(), Finder, Builder);
4250 /// Checks that a compound statement contains a specific number of
4251 /// child statements.
4257 /// compoundStmt(statementCountIs(0)))
4259 /// but does not match the outer compound statement.
4260 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4261 return Node.size() == N;
4264 /// Matches literals that are equal to the given value of type ValueT.
4268 /// f('\0', false, 3.14, 42);
4270 /// characterLiteral(equals(0))
4272 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4274 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4276 /// integerLiteral(equals(42))
4279 /// Note that you cannot directly match a negative numeric literal because the
4280 /// minus sign is not part of the literal: It is a unary operator whose operand
4281 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4282 /// matcher to match the minus sign:
4284 /// unaryOperator(hasOperatorName("-"),
4285 /// hasUnaryOperand(integerLiteral(equals(13))))
4287 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4288 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4289 template <typename ValueT>
4290 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
4291 equals(const ValueT &Value) {
4292 return internal::PolymorphicMatcherWithParam1<
4293 internal::ValueEqualsMatcher,
4297 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4298 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4302 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4306 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4307 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4310 unsigned, Value, 1) {
4311 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4315 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4316 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4321 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4325 /// Matches the operator Name of operator expressions (binary or
4328 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4332 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4333 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4335 std::string, Name) {
4336 return Name == Node.getOpcodeStr(Node.getOpcode());
4339 /// Matches all kinds of assignment operators.
4341 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4347 /// Example 2: matches s1 = s2
4348 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4350 /// struct S { S& operator=(const S&); };
4351 /// void x() { S s1, s2; s1 = s2; })
4353 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4354 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4355 CXXOperatorCallExpr)) {
4356 return Node.isAssignmentOp();
4359 /// Matches the left hand side of binary operator expressions.
4361 /// Example matches a (matcher = binaryOperator(hasLHS()))
4365 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4366 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4367 ArraySubscriptExpr),
4368 internal::Matcher<Expr>, InnerMatcher) {
4369 const Expr *LeftHandSide = Node.getLHS();
4370 return (LeftHandSide != nullptr &&
4371 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4374 /// Matches the right hand side of binary operator expressions.
4376 /// Example matches b (matcher = binaryOperator(hasRHS()))
4380 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4381 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4382 ArraySubscriptExpr),
4383 internal::Matcher<Expr>, InnerMatcher) {
4384 const Expr *RightHandSide = Node.getRHS();
4385 return (RightHandSide != nullptr &&
4386 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4389 /// Matches if either the left hand side or the right hand side of a
4390 /// binary operator matches.
4391 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4392 const internal::Matcher<Expr> &InnerMatcher) {
4393 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4396 /// Matches if the operand of a unary operator matches.
4398 /// Example matches true (matcher = hasUnaryOperand(
4399 /// cxxBoolLiteral(equals(true))))
4403 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4404 internal::Matcher<Expr>, InnerMatcher) {
4405 const Expr * const Operand = Node.getSubExpr();
4406 return (Operand != nullptr &&
4407 InnerMatcher.matches(*Operand, Finder, Builder));
4410 /// Matches if the cast's source expression
4411 /// or opaque value's source expression matches the given matcher.
4413 /// Example 1: matches "a string"
4414 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4416 /// class URL { URL(string); };
4417 /// URL url = "a string";
4420 /// Example 2: matches 'b' (matcher =
4421 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4425 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4426 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4428 internal::Matcher<Expr>, InnerMatcher) {
4429 const Expr *const SubExpression =
4430 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4431 return (SubExpression != nullptr &&
4432 InnerMatcher.matches(*SubExpression, Finder, Builder));
4435 /// Matches casts that has a given cast kind.
4437 /// Example: matches the implicit cast around \c 0
4438 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4442 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4443 return Node.getCastKind() == Kind;
4446 /// Matches casts whose destination type matches a given matcher.
4448 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4449 /// actual casts "explicit" casts.)
4450 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4451 internal::Matcher<QualType>, InnerMatcher) {
4452 const QualType NodeType = Node.getTypeAsWritten();
4453 return InnerMatcher.matches(NodeType, Finder, Builder);
4456 /// Matches implicit casts whose destination type matches a given
4459 /// FIXME: Unit test this matcher
4460 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4461 internal::Matcher<QualType>, InnerMatcher) {
4462 return InnerMatcher.matches(Node.getType(), Finder, Builder);
4465 /// Matches RecordDecl object that are spelled with "struct."
4467 /// Example matches S, but not C or U.
4473 AST_MATCHER(RecordDecl, isStruct) {
4474 return Node.isStruct();
4477 /// Matches RecordDecl object that are spelled with "union."
4479 /// Example matches U, but not C or S.
4485 AST_MATCHER(RecordDecl, isUnion) {
4486 return Node.isUnion();
4489 /// Matches RecordDecl object that are spelled with "class."
4491 /// Example matches C, but not S or U.
4497 AST_MATCHER(RecordDecl, isClass) {
4498 return Node.isClass();
4501 /// Matches the true branch expression of a conditional operator.
4503 /// Example 1 (conditional ternary operator): matches a
4505 /// condition ? a : b
4508 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4512 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4513 internal::Matcher<Expr>, InnerMatcher) {
4514 const Expr *Expression = Node.getTrueExpr();
4515 return (Expression != nullptr &&
4516 InnerMatcher.matches(*Expression, Finder, Builder));
4519 /// Matches the false branch expression of a conditional operator
4520 /// (binary or ternary).
4522 /// Example matches b
4524 /// condition ? a : b
4527 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4528 internal::Matcher<Expr>, InnerMatcher) {
4529 const Expr *Expression = Node.getFalseExpr();
4530 return (Expression != nullptr &&
4531 InnerMatcher.matches(*Expression, Finder, Builder));
4534 /// Matches if a declaration has a body attached.
4536 /// Example matches A, va, fa
4539 /// class B; // Doesn't match, as it has no body.
4541 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4543 /// void fb(); // Doesn't match, as it has no body.
4545 /// - (void)ma; // Doesn't match, interface is declaration.
4547 /// @implementation X
4552 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4553 /// Matcher<ObjCMethodDecl>
4554 AST_POLYMORPHIC_MATCHER(isDefinition,
4555 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4558 return Node.isThisDeclarationADefinition();
4561 /// Matches if a function declaration is variadic.
4563 /// Example matches f, but not g or h. The function i will not match, even when
4564 /// compiled in C mode.
4568 /// template <typename... Ts> void h(Ts...);
4571 AST_MATCHER(FunctionDecl, isVariadic) {
4572 return Node.isVariadic();
4575 /// Matches the class declaration that the given method declaration
4578 /// FIXME: Generalize this for other kinds of declarations.
4579 /// FIXME: What other kind of declarations would we need to generalize
4582 /// Example matches A() in the last line
4583 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4584 /// ofClass(hasName("A"))))))
4592 AST_MATCHER_P(CXXMethodDecl, ofClass,
4593 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4594 const CXXRecordDecl *Parent = Node.getParent();
4595 return (Parent != nullptr &&
4596 InnerMatcher.matches(*Parent, Finder, Builder));
4599 /// Matches each method overridden by the given method. This matcher may
4600 /// produce multiple matches.
4604 /// class A { virtual void f(); };
4605 /// class B : public A { void f(); };
4606 /// class C : public B { void f(); };
4608 /// cxxMethodDecl(ofClass(hasName("C")),
4609 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4610 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4611 /// that B::f is not overridden by C::f).
4613 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4615 /// class A1 { virtual void f(); };
4616 /// class A2 { virtual void f(); };
4617 /// class C : public A1, public A2 { void f(); };
4619 /// cxxMethodDecl(ofClass(hasName("C")),
4620 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4621 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4622 /// once with "b" binding "A2::f" and "d" binding "C::f".
4623 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4624 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4625 BoundNodesTreeBuilder Result;
4626 bool Matched = false;
4627 for (const auto *Overridden : Node.overridden_methods()) {
4628 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4629 const bool OverriddenMatched =
4630 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4631 if (OverriddenMatched) {
4633 Result.addMatch(OverriddenBuilder);
4636 *Builder = std::move(Result);
4640 /// Matches if the given method declaration is virtual.
4646 /// virtual void x();
4650 AST_MATCHER(CXXMethodDecl, isVirtual) {
4651 return Node.isVirtual();
4654 /// Matches if the given method declaration has an explicit "virtual".
4660 /// virtual void x();
4662 /// class B : public A {
4667 /// matches A::x but not B::x
4668 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4669 return Node.isVirtualAsWritten();
4672 /// Matches if the given method or class declaration is final.
4676 /// class A final {};
4679 /// virtual void f();
4686 /// matches A and C::f, but not B, C, or B::f
4687 AST_POLYMORPHIC_MATCHER(isFinal,
4688 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4690 return Node.template hasAttr<FinalAttr>();
4693 /// Matches if the given method declaration is pure.
4699 /// virtual void x() = 0;
4703 AST_MATCHER(CXXMethodDecl, isPure) {
4704 return Node.isPure();
4707 /// Matches if the given method declaration is const.
4712 /// void foo() const;
4717 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4718 AST_MATCHER(CXXMethodDecl, isConst) {
4719 return Node.isConst();
4722 /// Matches if the given method declaration declares a copy assignment
4728 /// A &operator=(const A &);
4729 /// A &operator=(A &&);
4733 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4735 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4736 return Node.isCopyAssignmentOperator();
4739 /// Matches if the given method declaration declares a move assignment
4745 /// A &operator=(const A &);
4746 /// A &operator=(A &&);
4750 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4752 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4753 return Node.isMoveAssignmentOperator();
4756 /// Matches if the given method declaration overrides another method.
4762 /// virtual void x();
4764 /// class B : public A {
4766 /// virtual void x();
4770 AST_MATCHER(CXXMethodDecl, isOverride) {
4771 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4774 /// Matches method declarations that are user-provided.
4780 /// S(const S &) = default; // #2
4781 /// S(S &&) = delete; // #3
4784 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4785 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4786 return Node.isUserProvided();
4789 /// Matches member expressions that are called with '->' as opposed
4792 /// Member calls on the implicit this pointer match as called with '->'.
4797 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4798 /// template <class T> void f() { this->f<T>(); f<T>(); }
4802 /// template <class T>
4804 /// void x() { this->m; }
4807 /// memberExpr(isArrow())
4808 /// matches this->x, x, y.x, a, this->b
4809 /// cxxDependentScopeMemberExpr(isArrow())
4811 /// unresolvedMemberExpr(isArrow())
4812 /// matches this->f<T>, f<T>
4813 AST_POLYMORPHIC_MATCHER(
4814 isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
4815 CXXDependentScopeMemberExpr)) {
4816 return Node.isArrow();
4819 /// Matches QualType nodes that are of integer type.
4827 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4828 /// matches "a(int)", "b(long)", but not "c(double)".
4829 AST_MATCHER(QualType, isInteger) {
4830 return Node->isIntegerType();
4833 /// Matches QualType nodes that are of unsigned integer type.
4838 /// void b(unsigned long);
4841 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4842 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4843 AST_MATCHER(QualType, isUnsignedInteger) {
4844 return Node->isUnsignedIntegerType();
4847 /// Matches QualType nodes that are of signed integer type.
4852 /// void b(unsigned long);
4855 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4856 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4857 AST_MATCHER(QualType, isSignedInteger) {
4858 return Node->isSignedIntegerType();
4861 /// Matches QualType nodes that are of character type.
4866 /// void b(wchar_t);
4869 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4870 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4871 AST_MATCHER(QualType, isAnyCharacter) {
4872 return Node->isAnyCharacterType();
4875 /// Matches QualType nodes that are of any pointer type; this includes
4876 /// the Objective-C object pointer type, which is different despite being
4877 /// syntactically similar.
4881 /// int *i = nullptr;
4889 /// varDecl(hasType(isAnyPointer()))
4890 /// matches "int *i" and "Foo *f", but not "int j".
4891 AST_MATCHER(QualType, isAnyPointer) {
4892 return Node->isAnyPointerType();
4895 /// Matches QualType nodes that are const-qualified, i.e., that
4896 /// include "top-level" const.
4901 /// void b(int const);
4902 /// void c(const int);
4903 /// void d(const int*);
4904 /// void e(int const) {};
4906 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4907 /// matches "void b(int const)", "void c(const int)" and
4908 /// "void e(int const) {}". It does not match d as there
4909 /// is no top-level const on the parameter type "const int *".
4910 AST_MATCHER(QualType, isConstQualified) {
4911 return Node.isConstQualified();
4914 /// Matches QualType nodes that are volatile-qualified, i.e., that
4915 /// include "top-level" volatile.
4920 /// void b(int volatile);
4921 /// void c(volatile int);
4922 /// void d(volatile int*);
4923 /// void e(int volatile) {};
4925 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4926 /// matches "void b(int volatile)", "void c(volatile int)" and
4927 /// "void e(int volatile) {}". It does not match d as there
4928 /// is no top-level volatile on the parameter type "volatile int *".
4929 AST_MATCHER(QualType, isVolatileQualified) {
4930 return Node.isVolatileQualified();
4933 /// Matches QualType nodes that have local CV-qualifiers attached to
4934 /// the node, not hidden within a typedef.
4938 /// typedef const int const_int;
4941 /// int *volatile k;
4944 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4945 /// \c i is const-qualified but the qualifier is not local.
4946 AST_MATCHER(QualType, hasLocalQualifiers) {
4947 return Node.hasLocalQualifiers();
4950 /// Matches a member expression where the member is matched by a
4955 /// struct { int first, second; } first, second;
4956 /// int i(second.first);
4957 /// int j(first.second);
4959 /// memberExpr(member(hasName("first")))
4960 /// matches second.first
4961 /// but not first.second (because the member name there is "second").
4962 AST_MATCHER_P(MemberExpr, member,
4963 internal::Matcher<ValueDecl>, InnerMatcher) {
4964 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4967 /// Matches a member expression where the object expression is
4968 /// matched by a given matcher.
4972 /// struct X { int m; };
4973 /// void f(X x) { x.m; m; }
4975 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4976 /// matches "x.m" and "m"
4977 /// with hasObjectExpression(...)
4978 /// matching "x" and the implicit object expression of "m" which has type X*.
4979 AST_POLYMORPHIC_MATCHER_P(
4980 hasObjectExpression,
4981 AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
4982 CXXDependentScopeMemberExpr),
4983 internal::Matcher<Expr>, InnerMatcher) {
4984 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
4985 if (E->isImplicitAccess())
4987 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
4988 if (E->isImplicitAccess())
4990 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4993 /// Matches any using shadow declaration.
4997 /// namespace X { void b(); }
5000 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
5001 /// matches \code using X::b \endcode
5002 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
5003 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
5004 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
5005 Node.shadow_end(), Finder, Builder);
5008 /// Matches a using shadow declaration where the target declaration is
5009 /// matched by the given matcher.
5013 /// namespace X { int a; void b(); }
5017 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
5018 /// matches \code using X::b \endcode
5019 /// but not \code using X::a \endcode
5020 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
5021 internal::Matcher<NamedDecl>, InnerMatcher) {
5022 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
5025 /// Matches template instantiations of function, class, or static
5026 /// member variable template instantiations.
5030 /// template <typename T> class X {}; class A {}; X<A> x;
5034 /// template <typename T> class X {}; class A {}; template class X<A>;
5038 /// template <typename T> class X {}; class A {}; extern template class X<A>;
5040 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5041 /// matches the template instantiation of X<A>.
5045 /// template <typename T> class X {}; class A {};
5046 /// template <> class X<A> {}; X<A> x;
5048 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5049 /// does not match, as X<A> is an explicit template specialization.
5051 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5052 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
5053 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5055 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
5056 Node.getTemplateSpecializationKind() ==
5057 TSK_ExplicitInstantiationDefinition ||
5058 Node.getTemplateSpecializationKind() ==
5059 TSK_ExplicitInstantiationDeclaration);
5062 /// Matches declarations that are template instantiations or are inside
5063 /// template instantiations.
5067 /// template<typename T> void A(T t) { T i; }
5071 /// functionDecl(isInstantiated())
5072 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
5073 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
5074 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5075 functionDecl(isTemplateInstantiation())));
5076 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
5079 /// Matches statements inside of a template instantiation.
5084 /// template<typename T> void A(T t) { T i; j += 42;}
5088 /// declStmt(isInTemplateInstantiation())
5089 /// matches 'int i;' and 'unsigned i'.
5090 /// unless(stmt(isInTemplateInstantiation()))
5091 /// will NOT match j += 42; as it's shared between the template definition and
5093 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
5095 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5096 functionDecl(isTemplateInstantiation())))));
5099 /// Matches explicit template specializations of function, class, or
5100 /// static member variable template instantiations.
5104 /// template<typename T> void A(T t) { }
5105 /// template<> void A(int N) { }
5107 /// functionDecl(isExplicitTemplateSpecialization())
5108 /// matches the specialization A<int>().
5110 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5111 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
5112 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5114 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
5117 /// Matches \c TypeLocs for which the given inner
5118 /// QualType-matcher matches.
5119 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
5120 internal::Matcher<QualType>, InnerMatcher, 0) {
5121 return internal::BindableMatcher<TypeLoc>(
5122 new internal::TypeLocTypeMatcher(InnerMatcher));
5125 /// Matches type \c bool.
5129 /// struct S { bool func(); };
5131 /// functionDecl(returns(booleanType()))
5132 /// matches "bool func();"
5133 AST_MATCHER(Type, booleanType) {
5134 return Node.isBooleanType();
5137 /// Matches type \c void.
5141 /// struct S { void func(); };
5143 /// functionDecl(returns(voidType()))
5144 /// matches "void func();"
5145 AST_MATCHER(Type, voidType) {
5146 return Node.isVoidType();
5149 template <typename NodeType>
5150 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
5152 /// Matches builtin Types.
5163 /// matches "int b", "float c" and "bool d"
5164 extern const AstTypeMatcher<BuiltinType> builtinType;
5166 /// Matches all kinds of arrays.
5170 /// int a[] = { 2, 3 };
5172 /// void f() { int c[a[0]]; }
5175 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
5176 extern const AstTypeMatcher<ArrayType> arrayType;
5178 /// Matches C99 complex types.
5182 /// _Complex float f;
5185 /// matches "_Complex float f"
5186 extern const AstTypeMatcher<ComplexType> complexType;
5188 /// Matches any real floating-point type (float, double, long double).
5195 /// realFloatingPointType()
5196 /// matches "float f" but not "int i"
5197 AST_MATCHER(Type, realFloatingPointType) {
5198 return Node.isRealFloatingType();
5201 /// Matches arrays and C99 complex types that have a specific element
5210 /// arrayType(hasElementType(builtinType()))
5211 /// matches "int b[7]"
5213 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5214 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5215 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5218 /// Matches C arrays with a specified constant size.
5224 /// int b[] = { 2, 3 };
5228 /// constantArrayType()
5229 /// matches "int a[2]"
5230 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5232 /// Matches nodes that have the specified size.
5238 /// int c[41], d[43];
5239 /// char *s = "abcd";
5240 /// wchar_t *ws = L"abcd";
5243 /// constantArrayType(hasSize(42))
5244 /// matches "int a[42]" and "int b[2 * 21]"
5245 /// stringLiteral(hasSize(4))
5246 /// matches "abcd", L"abcd"
5247 AST_POLYMORPHIC_MATCHER_P(hasSize,
5248 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5251 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5254 /// Matches C++ arrays whose size is a value-dependent expression.
5258 /// template<typename T, int Size>
5263 /// dependentSizedArrayType
5264 /// matches "T data[Size]"
5265 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5267 /// Matches C arrays with unspecified size.
5271 /// int a[] = { 2, 3 };
5273 /// void f(int c[]) { int d[a[0]]; };
5275 /// incompleteArrayType()
5276 /// matches "int a[]" and "int c[]"
5277 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5279 /// Matches C arrays with a specified size that is not an
5280 /// integer-constant-expression.
5285 /// int a[] = { 2, 3 }
5290 /// variableArrayType()
5291 /// matches "int c[a[0]]"
5292 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5294 /// Matches \c VariableArrayType nodes that have a specific size
5303 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5304 /// varDecl(hasName("b")))))))
5305 /// matches "int a[b]"
5306 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5307 internal::Matcher<Expr>, InnerMatcher) {
5308 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5311 /// Matches atomic types.
5318 /// matches "_Atomic(int) i"
5319 extern const AstTypeMatcher<AtomicType> atomicType;
5321 /// Matches atomic types with a specific value type.
5326 /// _Atomic(float) f;
5328 /// atomicType(hasValueType(isInteger()))
5329 /// matches "_Atomic(int) i"
5331 /// Usable as: Matcher<AtomicType>
5332 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5333 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5335 /// Matches types nodes representing C++11 auto types.
5340 /// int v[] = { 2, 3 }
5341 /// for (auto i : v) { }
5344 /// matches "auto n" and "auto i"
5345 extern const AstTypeMatcher<AutoType> autoType;
5347 /// Matches types nodes representing C++11 decltype(<expr>) types.
5353 /// decltype(i + j) result = i + j;
5356 /// matches "decltype(i + j)"
5357 extern const AstTypeMatcher<DecltypeType> decltypeType;
5359 /// Matches \c AutoType nodes where the deduced type is a specific type.
5361 /// Note: There is no \c TypeLoc for the deduced type and thus no
5362 /// \c getDeducedLoc() matcher.
5369 /// autoType(hasDeducedType(isInteger()))
5370 /// matches "auto a"
5372 /// Usable as: Matcher<AutoType>
5373 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5374 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5376 /// Matches \c DecltypeType nodes to find out the underlying type.
5380 /// decltype(1) a = 1;
5381 /// decltype(2.0) b = 2.0;
5383 /// decltypeType(hasUnderlyingType(isInteger()))
5384 /// matches the type of "a"
5386 /// Usable as: Matcher<DecltypeType>
5387 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
5388 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
5390 /// Matches \c FunctionType nodes.
5398 /// matches "int (*f)(int)" and the type of "g".
5399 extern const AstTypeMatcher<FunctionType> functionType;
5401 /// Matches \c FunctionProtoType nodes.
5408 /// functionProtoType()
5409 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
5410 /// In C mode, "g" is not matched because it does not contain a prototype.
5411 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
5413 /// Matches \c ParenType nodes.
5417 /// int (*ptr_to_array)[4];
5418 /// int *array_of_ptrs[4];
5421 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
5422 /// \c array_of_ptrs.
5423 extern const AstTypeMatcher<ParenType> parenType;
5425 /// Matches \c ParenType nodes where the inner type is a specific type.
5429 /// int (*ptr_to_array)[4];
5430 /// int (*ptr_to_func)(int);
5433 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5434 /// \c ptr_to_func but not \c ptr_to_array.
5436 /// Usable as: Matcher<ParenType>
5437 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5438 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5440 /// Matches block pointer types, i.e. types syntactically represented as
5441 /// "void (^)(int)".
5443 /// The \c pointee is always required to be a \c FunctionType.
5444 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5446 /// Matches member pointer types.
5449 /// struct A { int i; }
5450 /// A::* ptr = A::i;
5452 /// memberPointerType()
5453 /// matches "A::* ptr"
5454 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5456 /// Matches pointer types, but does not match Objective-C object pointer
5470 /// matches "int *a", but does not match "Foo *f".
5471 extern const AstTypeMatcher<PointerType> pointerType;
5473 /// Matches an Objective-C object pointer type, which is different from
5474 /// a pointer type, despite being syntactically similar.
5485 /// matches "Foo *f", but does not match "int *a".
5486 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5488 /// Matches both lvalue and rvalue reference types.
5501 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5502 extern const AstTypeMatcher<ReferenceType> referenceType;
5504 /// Matches lvalue reference types.
5517 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5518 /// matched since the type is deduced as int& by reference collapsing rules.
5519 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5521 /// Matches rvalue reference types.
5534 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5535 /// matched as it is deduced to int& by reference collapsing rules.
5536 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5538 /// Narrows PointerType (and similar) matchers to those where the
5539 /// \c pointee matches a given matcher.
5547 /// pointerType(pointee(isConstQualified(), isInteger()))
5548 /// matches "int const *b"
5550 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5551 /// Matcher<PointerType>, Matcher<ReferenceType>
5552 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5553 pointee, getPointee,
5554 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5555 PointerType, ReferenceType));
5557 /// Matches typedef types.
5564 /// matches "typedef int X"
5565 extern const AstTypeMatcher<TypedefType> typedefType;
5567 /// Matches enum types.
5571 /// enum C { Green };
5572 /// enum class S { Red };
5578 /// \c enumType() matches the type of the variable declarations of both \c c and
5580 extern const AstTypeMatcher<EnumType> enumType;
5582 /// Matches template specialization types.
5586 /// template <typename T>
5589 /// template class C<int>; // A
5590 /// C<char> var; // B
5593 /// \c templateSpecializationType() matches the type of the explicit
5594 /// instantiation in \c A and the type of the variable declaration in \c B.
5595 extern const AstTypeMatcher<TemplateSpecializationType>
5596 templateSpecializationType;
5598 /// Matches types nodes representing unary type transformations.
5602 /// typedef __underlying_type(T) type;
5604 /// unaryTransformType()
5605 /// matches "__underlying_type(T)"
5606 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5608 /// Matches record types (e.g. structs, classes).
5619 /// \c recordType() matches the type of the variable declarations of both \c c
5621 extern const AstTypeMatcher<RecordType> recordType;
5623 /// Matches tag types (record and enum types).
5634 /// \c tagType() matches the type of the variable declarations of both \c e
5636 extern const AstTypeMatcher<TagType> tagType;
5638 /// Matches types specified with an elaborated type keyword or with a
5654 /// \c elaboratedType() matches the type of the variable declarations of both
5656 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5658 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5659 /// matches \c InnerMatcher if the qualifier exists.
5671 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5672 /// matches the type of the variable declaration of \c d.
5673 AST_MATCHER_P(ElaboratedType, hasQualifier,
5674 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5675 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5676 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5681 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5693 /// \c elaboratedType(namesType(recordType(
5694 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5695 /// declaration of \c d.
5696 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5698 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5701 /// Matches types that represent the result of substituting a type for a
5702 /// template type parameter.
5706 /// template <typename T>
5712 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5713 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5714 substTemplateTypeParmType;
5716 /// Matches template type parameter substitutions that have a replacement
5717 /// type that matches the provided matcher.
5721 /// template <typename T>
5724 /// double j = F(i);
5727 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5728 AST_TYPE_TRAVERSE_MATCHER(
5729 hasReplacementType, getReplacementType,
5730 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5732 /// Matches template type parameter types.
5734 /// Example matches T, but not int.
5735 /// (matcher = templateTypeParmType())
5737 /// template <typename T> void f(int i);
5739 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5741 /// Matches injected class name types.
5743 /// Example matches S s, but not S<T> s.
5744 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5746 /// template <typename T> struct S {
5751 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5753 /// Matches decayed type
5754 /// Example matches i[] in declaration of f.
5755 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5756 /// Example matches i[1].
5757 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5759 /// void f(int i[]) {
5763 extern const AstTypeMatcher<DecayedType> decayedType;
5765 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
5766 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5768 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5771 /// Matches declarations whose declaration context, interpreted as a
5772 /// Decl, matches \c InnerMatcher.
5783 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5784 /// declaration of \c class \c D.
5785 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5786 const DeclContext *DC = Node.getDeclContext();
5787 if (!DC) return false;
5788 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5791 /// Matches nested name specifiers.
5796 /// struct A { static void f(); };
5798 /// void g() { A::f(); }
5802 /// nestedNameSpecifier()
5803 /// matches "ns::" and both "A::"
5804 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
5805 nestedNameSpecifier;
5807 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5808 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
5809 nestedNameSpecifierLoc;
5811 /// Matches \c NestedNameSpecifierLocs for which the given inner
5812 /// NestedNameSpecifier-matcher matches.
5813 AST_MATCHER_FUNCTION_P_OVERLOAD(
5814 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5815 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5816 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5817 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5821 /// Matches nested name specifiers that specify a type matching the
5822 /// given \c QualType matcher without qualifiers.
5826 /// struct A { struct B { struct C {}; }; };
5829 /// nestedNameSpecifier(specifiesType(
5830 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5833 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5834 internal::Matcher<QualType>, InnerMatcher) {
5835 if (!Node.getAsType())
5837 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5840 /// Matches nested name specifier locs that specify a type matching the
5841 /// given \c TypeLoc.
5845 /// struct A { struct B { struct C {}; }; };
5848 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5849 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5851 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5852 internal::Matcher<TypeLoc>, InnerMatcher) {
5853 return Node && Node.getNestedNameSpecifier()->getAsType() &&
5854 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5857 /// Matches on the prefix of a \c NestedNameSpecifier.
5861 /// struct A { struct B { struct C {}; }; };
5864 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5866 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5867 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5869 const NestedNameSpecifier *NextNode = Node.getPrefix();
5872 return InnerMatcher.matches(*NextNode, Finder, Builder);
5875 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
5879 /// struct A { struct B { struct C {}; }; };
5882 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5884 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5885 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5887 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5890 return InnerMatcher.matches(NextNode, Finder, Builder);
5893 /// Matches nested name specifiers that specify a namespace matching the
5894 /// given namespace matcher.
5898 /// namespace ns { struct A {}; }
5901 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5903 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5904 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5905 if (!Node.getAsNamespace())
5907 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5910 /// Overloads for the \c equalsNode matcher.
5911 /// FIXME: Implement for other node types.
5914 /// Matches if a node equals another node.
5916 /// \c Decl has pointer identity in the AST.
5917 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5918 return &Node == Other;
5920 /// Matches if a node equals another node.
5922 /// \c Stmt has pointer identity in the AST.
5923 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5924 return &Node == Other;
5926 /// Matches if a node equals another node.
5928 /// \c Type has pointer identity in the AST.
5929 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5930 return &Node == Other;
5935 /// Matches each case or default statement belonging to the given switch
5936 /// statement. This matcher may produce multiple matches.
5940 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5942 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5943 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5944 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5945 /// "switch (1)", "switch (2)" and "switch (2)".
5946 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5948 BoundNodesTreeBuilder Result;
5949 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5950 // iteration order. We should use the more general iterating matchers once
5951 // they are capable of expressing this matcher (for example, it should ignore
5952 // case statements belonging to nested switch statements).
5953 bool Matched = false;
5954 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5955 SC = SC->getNextSwitchCase()) {
5956 BoundNodesTreeBuilder CaseBuilder(*Builder);
5957 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5960 Result.addMatch(CaseBuilder);
5963 *Builder = std::move(Result);
5967 /// Matches each constructor initializer in a constructor definition.
5971 /// class A { A() : i(42), j(42) {} int i; int j; };
5973 /// cxxConstructorDecl(forEachConstructorInitializer(
5974 /// forField(decl().bind("x"))
5976 /// will trigger two matches, binding for 'i' and 'j' respectively.
5977 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5978 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5979 BoundNodesTreeBuilder Result;
5980 bool Matched = false;
5981 for (const auto *I : Node.inits()) {
5982 BoundNodesTreeBuilder InitBuilder(*Builder);
5983 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5985 Result.addMatch(InitBuilder);
5988 *Builder = std::move(Result);
5992 /// Matches constructor declarations that are copy constructors.
5998 /// S(const S &); // #2
6002 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
6003 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
6004 return Node.isCopyConstructor();
6007 /// Matches constructor declarations that are move constructors.
6013 /// S(const S &); // #2
6017 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
6018 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
6019 return Node.isMoveConstructor();
6022 /// Matches constructor declarations that are default constructors.
6028 /// S(const S &); // #2
6032 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
6033 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
6034 return Node.isDefaultConstructor();
6037 /// Matches constructors that delegate to another constructor.
6044 /// S(S &&) : S() {} // #3
6046 /// S::S() : S(0) {} // #4
6048 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
6050 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
6051 return Node.isDelegatingConstructor();
6054 /// Matches constructor and conversion declarations that are marked with
6055 /// the explicit keyword.
6061 /// explicit S(double); // #2
6062 /// operator int(); // #3
6063 /// explicit operator bool(); // #4
6066 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
6067 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
6068 AST_POLYMORPHIC_MATCHER(isExplicit,
6069 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
6070 CXXConversionDecl)) {
6071 return Node.isExplicit();
6074 /// Matches function and namespace declarations that are marked with
6075 /// the inline keyword.
6079 /// inline void f();
6082 /// inline namespace m {}
6085 /// functionDecl(isInline()) will match ::f().
6086 /// namespaceDecl(isInline()) will match n::m.
6087 AST_POLYMORPHIC_MATCHER(isInline,
6088 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
6090 // This is required because the spelling of the function used to determine
6091 // whether inline is specified or not differs between the polymorphic types.
6092 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
6093 return FD->isInlineSpecified();
6094 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
6095 return NSD->isInline();
6096 llvm_unreachable("Not a valid polymorphic type");
6099 /// Matches anonymous namespace declarations.
6104 /// namespace {} // #1
6107 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
6108 AST_MATCHER(NamespaceDecl, isAnonymous) {
6109 return Node.isAnonymousNamespace();
6112 /// If the given case statement does not use the GNU case range
6113 /// extension, matches the constant given in the statement.
6117 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
6119 /// caseStmt(hasCaseConstant(integerLiteral()))
6120 /// matches "case 1:"
6121 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
6126 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
6129 /// Matches declaration that has a given attribute.
6133 /// __attribute__((device)) void f() { ... }
6135 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
6136 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
6137 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
6138 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
6139 for (const auto *Attr : Node.attrs()) {
6140 if (Attr->getKind() == AttrKind)
6146 /// Matches the return value expression of a return statement
6152 /// hasReturnValue(binaryOperator())
6153 /// matches 'return a + b'
6154 /// with binaryOperator()
6155 /// matching 'a + b'
6156 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
6158 if (const auto *RetValue = Node.getRetValue())
6159 return InnerMatcher.matches(*RetValue, Finder, Builder);
6163 /// Matches CUDA kernel call expression.
6165 /// Example matches,
6167 /// kernel<<<i,j>>>();
6169 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
6172 /// Matches expressions that resolve to a null pointer constant, such as
6173 /// GNU's __null, C++11's nullptr, or C's NULL macro.
6177 /// void *v1 = NULL;
6178 /// void *v2 = nullptr;
6179 /// void *v3 = __null; // GNU extension
6180 /// char *cp = (char *)0;
6184 /// expr(nullPointerConstant())
6185 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
6186 /// initializer for i.
6187 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
6189 gnuNullExpr(), cxxNullPtrLiteralExpr(),
6190 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
6193 /// Matches declaration of the function the statement belongs to
6197 /// F& operator=(const F& o) {
6198 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
6202 /// returnStmt(forFunction(hasName("operator=")))
6203 /// matches 'return *this'
6204 /// but does match 'return > 0'
6205 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
6207 const auto &Parents = Finder->getASTContext().getParents(Node);
6209 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
6211 while(!Stack.empty()) {
6212 const auto &CurNode = Stack.back();
6214 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6215 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6218 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6219 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6224 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6225 Stack.push_back(Parent);
6231 /// Matches a declaration that has external formal linkage.
6233 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6242 /// Example matches f() because it has external formal linkage despite being
6243 /// unique to the translation unit as though it has internal likage
6244 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6251 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6252 return Node.hasExternalFormalLinkage();
6255 /// Matches a declaration that has default arguments.
6257 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6259 /// void x(int val) {}
6260 /// void y(int val = 0) {}
6262 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6263 return Node.hasDefaultArg();
6266 /// Matches array new expressions.
6270 /// MyClass *p1 = new MyClass[10];
6272 /// cxxNewExpr(isArray())
6273 /// matches the expression 'new MyClass[10]'.
6274 AST_MATCHER(CXXNewExpr, isArray) {
6275 return Node.isArray();
6278 /// Matches array new expressions with a given array size.
6282 /// MyClass *p1 = new MyClass[10];
6284 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
6285 /// matches the expression 'new MyClass[10]'.
6286 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
6287 return Node.isArray() &&
6288 InnerMatcher.matches(*Node.getArraySize(), Finder, Builder);
6291 /// Matches a class declaration that is defined.
6293 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
6298 AST_MATCHER(CXXRecordDecl, hasDefinition) {
6299 return Node.hasDefinition();
6302 /// Matches C++11 scoped enum declaration.
6304 /// Example matches Y (matcher = enumDecl(isScoped()))
6307 /// enum class Y {};
6309 AST_MATCHER(EnumDecl, isScoped) {
6310 return Node.isScoped();
6313 /// Matches a function declared with a trailing return type.
6315 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
6318 /// auto Y() -> int {}
6320 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
6321 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
6322 return F->hasTrailingReturn();
6326 } // namespace ast_matchers
6327 } // namespace clang
6329 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H