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.getLocStart()));
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.getLocStart());
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.getLocStart());
295 if (ExpansionLoc.isInvalid()) {
299 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
304 auto Filename = FileEntry->getName();
305 llvm::Regex RE(RegExp);
306 return RE.match(Filename);
309 /// 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 declarator declarations (field, variable, function
424 /// and non-type template parameter declarations).
428 /// class X { int y; };
431 /// matches \c int y.
432 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
435 /// Matches parameter variable declarations.
442 /// matches \c int x.
443 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
446 /// Matches C++ access specifier declarations.
456 /// matches 'public:'
457 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
460 /// Matches constructor initializers.
462 /// Examples matches \c i(42).
469 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
472 /// Matches template arguments.
476 /// template <typename T> struct C {};
479 /// templateArgument()
480 /// matches 'int' in C<int>.
481 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
483 /// Matches template name.
487 /// template <typename T> class X { };
491 /// matches 'X' in X<int>.
492 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
494 /// Matches non-type template parameter declarations.
498 /// template <typename T, int N> struct C {};
500 /// nonTypeTemplateParmDecl()
501 /// matches 'N', but not 'T'.
502 extern const internal::VariadicDynCastAllOfMatcher<Decl,
503 NonTypeTemplateParmDecl>
504 nonTypeTemplateParmDecl;
506 /// Matches template type parameter declarations.
510 /// template <typename T, int N> struct C {};
512 /// templateTypeParmDecl()
513 /// matches 'T', but not 'N'.
514 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
515 templateTypeParmDecl;
517 /// Matches public C++ declarations.
523 /// protected: int b;
527 /// fieldDecl(isPublic())
529 AST_MATCHER(Decl, isPublic) {
530 return Node.getAccess() == AS_public;
533 /// Matches protected C++ declarations.
539 /// protected: int b;
543 /// fieldDecl(isProtected())
545 AST_MATCHER(Decl, isProtected) {
546 return Node.getAccess() == AS_protected;
549 /// Matches private C++ declarations.
555 /// protected: int b;
559 /// fieldDecl(isPrivate())
561 AST_MATCHER(Decl, isPrivate) {
562 return Node.getAccess() == AS_private;
565 /// Matches non-static data members that are bit-fields.
574 /// fieldDecl(isBitField())
575 /// matches 'int a;' but not 'int b;'.
576 AST_MATCHER(FieldDecl, isBitField) {
577 return Node.isBitField();
580 /// Matches non-static data members that are bit-fields of the specified
591 /// fieldDecl(hasBitWidth(2))
592 /// matches 'int a;' and 'int c;' but not 'int b;'.
593 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
594 return Node.isBitField() &&
595 Node.getBitWidthValue(Finder->getASTContext()) == Width;
598 /// Matches non-static data members that have an in-class initializer.
608 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
609 /// matches 'int a;' but not 'int b;'.
610 /// fieldDecl(hasInClassInitializer(anything()))
611 /// matches 'int a;' and 'int b;' but not 'int c;'.
612 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
614 const Expr *Initializer = Node.getInClassInitializer();
615 return (Initializer != nullptr &&
616 InnerMatcher.matches(*Initializer, Finder, Builder));
619 /// Determines whether the function is "main", which is the entry point
620 /// into an executable program.
621 AST_MATCHER(FunctionDecl, isMain) {
622 return Node.isMain();
625 /// Matches the specialized template of a specialization declaration.
629 /// tempalate<typename T> class A {};
630 /// typedef A<int> B;
632 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
633 /// matches 'B' with classTemplateDecl() matching the class template
634 /// declaration of 'A'.
635 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
636 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
637 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
638 return (Decl != nullptr &&
639 InnerMatcher.matches(*Decl, Finder, Builder));
642 /// Matches a declaration that has been implicitly added
643 /// by the compiler (eg. implicit default/copy constructors).
644 AST_MATCHER(Decl, isImplicit) {
645 return Node.isImplicit();
648 /// Matches classTemplateSpecializations, templateSpecializationType and
649 /// functionDecl that have at least one TemplateArgument matching the given
654 /// template<typename T> class A {};
655 /// template<> class A<double> {};
658 /// template<typename T> f() {};
659 /// void func() { f<int>(); };
663 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
664 /// refersToType(asString("int"))))
665 /// matches the specialization \c A<int>
667 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
668 /// matches the specialization \c f<int>
669 AST_POLYMORPHIC_MATCHER_P(
670 hasAnyTemplateArgument,
671 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
672 TemplateSpecializationType,
674 internal::Matcher<TemplateArgument>, InnerMatcher) {
675 ArrayRef<TemplateArgument> List =
676 internal::getTemplateSpecializationArgs(Node);
677 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
681 /// Matches expressions that match InnerMatcher after any implicit AST
682 /// nodes are stripped off.
684 /// Parentheses and explicit casts are not discarded.
694 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
696 /// would match the declarations for a, b, and c.
699 /// varDecl(hasInitializer(cxxConstructExpr()))
701 /// only match the declarations for b and c.
702 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
704 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
707 /// Matches expressions that match InnerMatcher after any implicit casts
708 /// are stripped off.
710 /// Parentheses and explicit casts are not discarded.
718 /// long e = (long) 0l;
722 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
723 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
725 /// would match the declarations for a, b, c, and d, but not e.
728 /// varDecl(hasInitializer(integerLiteral()))
729 /// varDecl(hasInitializer(declRefExpr()))
731 /// only match the declarations for b, c, and d.
732 AST_MATCHER_P(Expr, ignoringImpCasts,
733 internal::Matcher<Expr>, InnerMatcher) {
734 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
737 /// Matches expressions that match InnerMatcher after parentheses and
738 /// casts are stripped off.
740 /// Implicit and non-C Style casts are also discarded.
745 /// void* c = reinterpret_cast<char*>(0);
746 /// char d = char(0);
749 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
750 /// would match the declarations for a, b, c, and d.
752 /// varDecl(hasInitializer(integerLiteral()))
753 /// only match the declaration for a.
754 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
755 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
758 /// Matches expressions that match InnerMatcher after implicit casts and
759 /// parentheses are stripped off.
761 /// Explicit casts are not discarded.
769 /// long e = ((long) 0l);
772 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
773 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
774 /// would match the declarations for a, b, c, and d, but not e.
776 /// varDecl(hasInitializer(integerLiteral()))
777 /// varDecl(hasInitializer(declRefExpr()))
778 /// would only match the declaration for a.
779 AST_MATCHER_P(Expr, ignoringParenImpCasts,
780 internal::Matcher<Expr>, InnerMatcher) {
781 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
784 /// Matches types that match InnerMatcher after any parens are stripped.
788 /// void (*fp)(void);
792 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
794 /// would match the declaration for fp.
795 AST_MATCHER_P(QualType, ignoringParens,
796 internal::Matcher<QualType>, InnerMatcher) {
797 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
800 /// Matches classTemplateSpecializations, templateSpecializationType and
801 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
805 /// template<typename T, typename U> class A {};
809 /// template<typename T> void f() {}
810 /// void func() { f<int>(); };
812 /// classTemplateSpecializationDecl(hasTemplateArgument(
813 /// 1, refersToType(asString("int"))))
814 /// matches the specialization \c A<bool, int>
816 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
817 /// matches the specialization \c f<int>
818 AST_POLYMORPHIC_MATCHER_P2(
820 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
821 TemplateSpecializationType,
823 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
824 ArrayRef<TemplateArgument> List =
825 internal::getTemplateSpecializationArgs(Node);
826 if (List.size() <= N)
828 return InnerMatcher.matches(List[N], Finder, Builder);
831 /// Matches if the number of template arguments equals \p N.
835 /// template<typename T> struct C {};
838 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
840 AST_POLYMORPHIC_MATCHER_P(
841 templateArgumentCountIs,
842 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
843 TemplateSpecializationType),
845 return internal::getTemplateSpecializationArgs(Node).size() == N;
848 /// Matches a TemplateArgument that refers to a certain type.
853 /// template<typename T> struct A {};
856 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
857 /// refersToType(class(hasName("X")))))
858 /// matches the specialization \c A<X>
859 AST_MATCHER_P(TemplateArgument, refersToType,
860 internal::Matcher<QualType>, InnerMatcher) {
861 if (Node.getKind() != TemplateArgument::Type)
863 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
866 /// Matches a TemplateArgument that refers to a certain template.
870 /// template<template <typename> class S> class X {};
871 /// template<typename T> class Y {};"
874 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
875 /// refersToTemplate(templateName())))
876 /// matches the specialization \c X<Y>
877 AST_MATCHER_P(TemplateArgument, refersToTemplate,
878 internal::Matcher<TemplateName>, InnerMatcher) {
879 if (Node.getKind() != TemplateArgument::Template)
881 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
884 /// Matches a canonical TemplateArgument that refers to a certain
889 /// struct B { int next; };
890 /// template<int(B::*next_ptr)> struct A {};
893 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
894 /// refersToDeclaration(fieldDecl(hasName("next")))))
895 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
897 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
898 internal::Matcher<Decl>, InnerMatcher) {
899 if (Node.getKind() == TemplateArgument::Declaration)
900 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
904 /// Matches a sugar TemplateArgument that refers to a certain expression.
908 /// struct B { int next; };
909 /// template<int(B::*next_ptr)> struct A {};
912 /// templateSpecializationType(hasAnyTemplateArgument(
913 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
914 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
916 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
917 if (Node.getKind() == TemplateArgument::Expression)
918 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
922 /// Matches a TemplateArgument that is an integral value.
926 /// template<int T> struct C {};
929 /// classTemplateSpecializationDecl(
930 /// hasAnyTemplateArgument(isIntegral()))
931 /// matches the implicit instantiation of C in C<42>
932 /// with isIntegral() matching 42.
933 AST_MATCHER(TemplateArgument, isIntegral) {
934 return Node.getKind() == TemplateArgument::Integral;
937 /// Matches a TemplateArgument that referes to an integral type.
941 /// template<int T> struct C {};
944 /// classTemplateSpecializationDecl(
945 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
946 /// matches the implicit instantiation of C in C<42>.
947 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
948 internal::Matcher<QualType>, InnerMatcher) {
949 if (Node.getKind() != TemplateArgument::Integral)
951 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
954 /// Matches a TemplateArgument of integral type with a given value.
956 /// Note that 'Value' is a string as the template argument's value is
957 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
958 /// representation of that integral value in base 10.
962 /// template<int T> struct C {};
965 /// classTemplateSpecializationDecl(
966 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
967 /// matches the implicit instantiation of C in C<42>.
968 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
969 std::string, Value) {
970 if (Node.getKind() != TemplateArgument::Integral)
972 return Node.getAsIntegral().toString(10) == Value;
975 /// Matches an Objective-C autorelease pool statement.
979 /// @autoreleasepool {
983 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
984 /// inside the autorelease pool.
985 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
986 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
988 /// Matches any value declaration.
990 /// Example matches A, B, C and F
992 /// enum X { A, B, C };
995 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
997 /// Matches C++ constructor declarations.
999 /// Example matches Foo::Foo() and Foo::Foo(int)
1005 /// int DoSomething();
1008 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1011 /// Matches explicit C++ destructor declarations.
1013 /// Example matches Foo::~Foo()
1020 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1023 /// Matches enum declarations.
1025 /// Example matches X
1031 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1033 /// Matches enum constants.
1035 /// Example matches A, B, C
1041 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1044 /// Matches method declarations.
1046 /// Example matches y
1048 /// class X { void y(); };
1050 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1053 /// Matches conversion operator declarations.
1055 /// Example matches the operator.
1057 /// class X { operator int() const; };
1059 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1062 /// Matches variable declarations.
1064 /// Note: this does not match declarations of member variables, which are
1065 /// "field" declarations in Clang parlance.
1067 /// Example matches a
1071 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1073 /// Matches field declarations.
1077 /// class X { int m; };
1081 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1083 /// Matches function declarations.
1085 /// Example matches f
1089 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1092 /// Matches C++ function template declarations.
1094 /// Example matches f
1096 /// template<class T> void f(T t) {}
1098 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1099 functionTemplateDecl;
1101 /// Matches friend declarations.
1105 /// class X { friend void foo(); };
1108 /// matches 'friend void foo()'.
1109 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1111 /// Matches statements.
1118 /// matches both the compound statement '{ ++a; }' and '++a'.
1119 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1121 /// Matches declaration statements.
1128 /// matches 'int a'.
1129 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1131 /// Matches member expressions.
1136 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1137 /// int a; static int b;
1141 /// matches this->x, x, y.x, a, this->b
1142 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1144 /// Matches call expressions.
1146 /// Example matches x.y() and y()
1152 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1154 /// Matches lambda expressions.
1156 /// Example matches [&](){return 5;}
1158 /// [&](){return 5;}
1160 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1162 /// Matches member call expressions.
1164 /// Example matches x.y()
1169 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1172 /// Matches ObjectiveC Message invocation expressions.
1174 /// The innermost message send invokes the "alloc" class method on the
1175 /// NSString class, while the outermost message send invokes the
1176 /// "initWithString" instance method on the object returned from
1177 /// NSString's "alloc". This matcher should match both message sends.
1179 /// [[NSString alloc] initWithString:@"Hello"]
1181 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1184 /// Matches Objective-C interface declarations.
1186 /// Example matches Foo
1191 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1194 /// Matches Objective-C implementation declarations.
1196 /// Example matches Foo
1198 /// @implementation Foo
1201 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1202 objcImplementationDecl;
1204 /// Matches Objective-C protocol declarations.
1206 /// Example matches FooDelegate
1208 /// @protocol FooDelegate
1211 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1214 /// Matches Objective-C category declarations.
1216 /// Example matches Foo (Additions)
1218 /// @interface Foo (Additions)
1221 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1224 /// Matches Objective-C category definitions.
1226 /// Example matches Foo (Additions)
1228 /// @implementation Foo (Additions)
1231 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1232 objcCategoryImplDecl;
1234 /// Matches Objective-C method declarations.
1236 /// Example matches both declaration and definition of -[Foo method]
1242 /// @implementation Foo
1243 /// - (void)method {}
1246 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1249 /// Matches block declarations.
1251 /// Example matches the declaration of the nameless block printing an input
1255 /// myFunc(^(int p) {
1256 /// printf("%d", p);
1259 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1262 /// Matches Objective-C instance variable declarations.
1264 /// Example matches _enabled
1266 /// @implementation Foo {
1271 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1274 /// Matches Objective-C property declarations.
1276 /// Example matches enabled
1279 /// @property BOOL enabled;
1282 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1285 /// Matches Objective-C \@throw statements.
1287 /// Example matches \@throw
1291 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1294 /// Matches Objective-C @try statements.
1296 /// Example matches @try
1301 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1304 /// Matches Objective-C @catch statements.
1306 /// Example matches @catch
1311 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1314 /// Matches Objective-C @finally statements.
1316 /// Example matches @finally
1321 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1324 /// Matches expressions that introduce cleanups to be run at the end
1325 /// of the sub-expression's evaluation.
1327 /// Example matches std::string()
1329 /// const std::string str = std::string();
1331 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1334 /// Matches init list expressions.
1338 /// int a[] = { 1, 2 };
1339 /// struct B { int x, y; };
1343 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1344 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1347 /// Matches the syntactic form of init list expressions
1348 /// (if expression have it).
1349 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1350 internal::Matcher<Expr>, InnerMatcher) {
1351 const Expr *SyntForm = Node.getSyntacticForm();
1352 return (SyntForm != nullptr &&
1353 InnerMatcher.matches(*SyntForm, Finder, Builder));
1356 /// Matches C++ initializer list expressions.
1360 /// std::vector<int> a({ 1, 2, 3 });
1361 /// std::vector<int> b = { 4, 5 };
1362 /// int c[] = { 6, 7 };
1363 /// std::pair<int, int> d = { 8, 9 };
1365 /// cxxStdInitializerListExpr()
1366 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1367 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1368 CXXStdInitializerListExpr>
1369 cxxStdInitializerListExpr;
1371 /// Matches implicit initializers of init list expressions.
1375 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1377 /// implicitValueInitExpr()
1378 /// matches "[0].y" (implicitly)
1379 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1380 implicitValueInitExpr;
1382 /// Matches paren list expressions.
1383 /// ParenListExprs don't have a predefined type and are used for late parsing.
1384 /// In the final AST, they can be met in template declarations.
1388 /// template<typename T> class X {
1391 /// int a = 0, b = 1; int i = (a, b);
1395 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1396 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1397 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1400 /// Matches substitutions of non-type template parameters.
1404 /// template <int N>
1405 /// struct A { static const int n = N; };
1406 /// struct B : public A<42> {};
1408 /// substNonTypeTemplateParmExpr()
1409 /// matches "N" in the right-hand side of "static const int n = N;"
1410 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1411 SubstNonTypeTemplateParmExpr>
1412 substNonTypeTemplateParmExpr;
1414 /// Matches using declarations.
1418 /// namespace X { int x; }
1422 /// matches \code using X::x \endcode
1423 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1425 /// Matches using namespace declarations.
1429 /// namespace X { int x; }
1430 /// using namespace X;
1432 /// usingDirectiveDecl()
1433 /// matches \code using namespace X \endcode
1434 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1437 /// Matches reference to a name that can be looked up during parsing
1438 /// but could not be resolved to a specific declaration.
1442 /// template<typename T>
1443 /// T foo() { T a; return a; }
1444 /// template<typename T>
1449 /// unresolvedLookupExpr()
1450 /// matches \code foo<T>() \endcode
1451 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1452 unresolvedLookupExpr;
1454 /// Matches unresolved using value declarations.
1458 /// template<typename X>
1459 /// class C : private X {
1463 /// unresolvedUsingValueDecl()
1464 /// matches \code using X::x \endcode
1465 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1466 UnresolvedUsingValueDecl>
1467 unresolvedUsingValueDecl;
1469 /// Matches unresolved using value declarations that involve the
1474 /// template <typename T>
1475 /// struct Base { typedef T Foo; };
1477 /// template<typename T>
1478 /// struct S : private Base<T> {
1479 /// using typename Base<T>::Foo;
1482 /// unresolvedUsingTypenameDecl()
1483 /// matches \code using Base<T>::Foo \endcode
1484 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1485 UnresolvedUsingTypenameDecl>
1486 unresolvedUsingTypenameDecl;
1488 /// Matches parentheses used in expressions.
1490 /// Example matches (foo() + 1)
1492 /// int foo() { return 1; }
1493 /// int a = (foo() + 1);
1495 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1497 /// Matches constructor call expressions (including implicit ones).
1499 /// Example matches string(ptr, n) and ptr within arguments of f
1500 /// (matcher = cxxConstructExpr())
1502 /// void f(const string &a, const string &b);
1505 /// f(string(ptr, n), ptr);
1507 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1510 /// Matches unresolved constructor call expressions.
1512 /// Example matches T(t) in return statement of f
1513 /// (matcher = cxxUnresolvedConstructExpr())
1515 /// template <typename T>
1516 /// void f(const T& t) { return T(t); }
1518 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1519 CXXUnresolvedConstructExpr>
1520 cxxUnresolvedConstructExpr;
1522 /// Matches implicit and explicit this expressions.
1524 /// Example matches the implicit this expression in "return i".
1525 /// (matcher = cxxThisExpr())
1529 /// int f() { return i; }
1532 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1535 /// Matches nodes where temporaries are created.
1537 /// Example matches FunctionTakesString(GetStringByValue())
1538 /// (matcher = cxxBindTemporaryExpr())
1540 /// FunctionTakesString(GetStringByValue());
1541 /// FunctionTakesStringByPointer(GetStringPointer());
1543 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1544 cxxBindTemporaryExpr;
1546 /// Matches nodes where temporaries are materialized.
1550 /// struct T {void func();};
1554 /// materializeTemporaryExpr() matches 'f()' in these statements
1560 /// but does not match
1564 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1565 MaterializeTemporaryExpr>
1566 materializeTemporaryExpr;
1568 /// Matches new expressions.
1575 /// matches 'new X'.
1576 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1578 /// Matches delete expressions.
1585 /// matches 'delete X'.
1586 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1589 /// Matches array subscript expressions.
1595 /// arraySubscriptExpr()
1597 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1600 /// Matches the value of a default argument at the call site.
1602 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1603 /// default value of the second parameter in the call expression f(42)
1604 /// (matcher = cxxDefaultArgExpr())
1606 /// void f(int x, int y = 0);
1609 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1612 /// Matches overloaded operator calls.
1614 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1615 /// binaryOperator matcher.
1616 /// Currently it does not match operators such as new delete.
1617 /// FIXME: figure out why these do not match?
1619 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1620 /// (matcher = cxxOperatorCallExpr())
1622 /// ostream &operator<< (ostream &out, int i) { };
1623 /// ostream &o; int b = 1, c = 1;
1626 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1627 cxxOperatorCallExpr;
1629 /// Matches expressions.
1631 /// Example matches x()
1633 /// void f() { x(); }
1635 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1637 /// Matches expressions that refer to declarations.
1639 /// Example matches x in if (x)
1644 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1647 /// Matches a reference to an ObjCIvar.
1649 /// Example: matches "a" in "init" method:
1651 /// @implementation A {
1658 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1661 /// Matches if statements.
1663 /// Example matches 'if (x) {}'
1667 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1669 /// Matches for statements.
1671 /// Example matches 'for (;;) {}'
1674 /// int i[] = {1, 2, 3}; for (auto a : i);
1676 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1678 /// Matches the increment statement of a for loop.
1681 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1682 /// matches '++x' in
1684 /// for (x; x < N; ++x) { }
1686 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1688 const Stmt *const Increment = Node.getInc();
1689 return (Increment != nullptr &&
1690 InnerMatcher.matches(*Increment, Finder, Builder));
1693 /// Matches the initialization statement of a for loop.
1696 /// forStmt(hasLoopInit(declStmt()))
1697 /// matches 'int x = 0' in
1699 /// for (int x = 0; x < N; ++x) { }
1701 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1703 const Stmt *const Init = Node.getInit();
1704 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1707 /// Matches range-based for statements.
1709 /// cxxForRangeStmt() matches 'for (auto a : i)'
1711 /// int i[] = {1, 2, 3}; for (auto a : i);
1712 /// for(int j = 0; j < 5; ++j);
1714 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1717 /// Matches the initialization statement of a for loop.
1720 /// forStmt(hasLoopVariable(anything()))
1721 /// matches 'int x' in
1723 /// for (int x : a) { }
1725 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1727 const VarDecl *const Var = Node.getLoopVariable();
1728 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1731 /// Matches the range initialization statement of a for loop.
1734 /// forStmt(hasRangeInit(anything()))
1737 /// for (int x : a) { }
1739 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1741 const Expr *const Init = Node.getRangeInit();
1742 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1745 /// Matches while statements.
1752 /// matches 'while (true) {}'.
1753 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1755 /// Matches do statements.
1759 /// do {} while (true);
1762 /// matches 'do {} while(true)'
1763 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1765 /// Matches break statements.
1769 /// while (true) { break; }
1773 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1775 /// Matches continue statements.
1779 /// while (true) { continue; }
1782 /// matches 'continue'
1783 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1786 /// Matches return statements.
1793 /// matches 'return 1'
1794 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1796 /// Matches goto statements.
1804 /// matches 'goto FOO'
1805 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1807 /// Matches label statements.
1816 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1818 /// Matches address of label statements (GNU extension).
1823 /// void *ptr = &&FOO;
1828 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
1831 /// Matches switch statements.
1835 /// switch(a) { case 42: break; default: break; }
1838 /// matches 'switch(a)'.
1839 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1841 /// Matches case and default statements inside switch statements.
1845 /// switch(a) { case 42: break; default: break; }
1848 /// matches 'case 42:' and 'default:'.
1849 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1851 /// Matches case statements inside switch statements.
1855 /// switch(a) { case 42: break; default: break; }
1858 /// matches 'case 42:'.
1859 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1861 /// Matches default statements inside switch statements.
1865 /// switch(a) { case 42: break; default: break; }
1868 /// matches 'default:'.
1869 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
1872 /// Matches compound statements.
1874 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
1878 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
1881 /// Matches catch statements.
1884 /// try {} catch(int i) {}
1887 /// matches 'catch(int i)'
1888 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
1891 /// Matches try statements.
1894 /// try {} catch(int i) {}
1897 /// matches 'try {}'
1898 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1900 /// Matches throw expressions.
1903 /// try { throw 5; } catch(int i) {}
1906 /// matches 'throw 5'
1907 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
1910 /// Matches null statements.
1916 /// matches the second ';'
1917 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1919 /// Matches asm statements.
1923 /// __asm("mov al, 2");
1926 /// matches '__asm("mov al, 2")'
1927 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1929 /// Matches bool literals.
1931 /// Example matches true
1935 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
1938 /// Matches string literals (also matches wide string literals).
1940 /// Example matches "abcd", L"abcd"
1942 /// char *s = "abcd";
1943 /// wchar_t *ws = L"abcd";
1945 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
1948 /// Matches character literals (also matches wchar_t).
1950 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1953 /// Example matches 'a', L'a'
1956 /// wchar_t chw = L'a';
1958 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
1961 /// Matches integer literals of all sizes / encodings, e.g.
1962 /// 1, 1L, 0x1 and 1U.
1964 /// Does not match character-encoded integers such as L'a'.
1965 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
1968 /// Matches float literals of all sizes / encodings, e.g.
1969 /// 1.0, 1.0f, 1.0L and 1e10.
1971 /// Does not match implicit conversions such as
1975 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
1978 /// Matches user defined literal operator call.
1980 /// Example match: "foo"_suffix
1981 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
1984 /// Matches compound (i.e. non-scalar) literals
1986 /// Example match: {1}, (1, 2)
1988 /// int array[4] = {1};
1989 /// vector int myvec = (vector int)(1, 2);
1991 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
1992 compoundLiteralExpr;
1994 /// Matches nullptr literal.
1995 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
1996 cxxNullPtrLiteralExpr;
1998 /// Matches GNU __null expression.
1999 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2002 /// Matches atomic builtins.
2003 /// Example matches __atomic_load_n(ptr, 1)
2005 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2007 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2009 /// Matches statement expression (GNU extension).
2011 /// Example match: ({ int X = 4; X; })
2013 /// int C = ({ int X = 4; X; });
2015 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2017 /// Matches binary operator expressions.
2019 /// Example matches a || b
2023 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2026 /// Matches unary operator expressions.
2028 /// Example matches !a
2032 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2035 /// Matches conditional operator expressions.
2037 /// Example matches a ? b : c
2039 /// (a ? b : c) + 42
2041 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2042 conditionalOperator;
2044 /// Matches binary conditional operator expressions (GNU extension).
2046 /// Example matches a ?: b
2050 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2051 BinaryConditionalOperator>
2052 binaryConditionalOperator;
2054 /// Matches opaque value expressions. They are used as helpers
2055 /// to reference another expressions and can be met
2056 /// in BinaryConditionalOperators, for example.
2058 /// Example matches 'a'
2062 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2065 /// Matches a C++ static_assert declaration.
2068 /// staticAssertExpr()
2070 /// static_assert(sizeof(S) == sizeof(int))
2076 /// static_assert(sizeof(S) == sizeof(int));
2078 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2081 /// Matches a reinterpret_cast expression.
2083 /// Either the source expression or the destination type can be matched
2084 /// using has(), but hasDestinationType() is more specific and can be
2087 /// Example matches reinterpret_cast<char*>(&p) in
2089 /// void* p = reinterpret_cast<char*>(&p);
2091 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2092 cxxReinterpretCastExpr;
2094 /// Matches a C++ static_cast expression.
2096 /// \see hasDestinationType
2097 /// \see reinterpretCast
2100 /// cxxStaticCastExpr()
2102 /// static_cast<long>(8)
2105 /// long eight(static_cast<long>(8));
2107 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2110 /// Matches a dynamic_cast expression.
2113 /// cxxDynamicCastExpr()
2115 /// dynamic_cast<D*>(&b);
2118 /// struct B { virtual ~B() {} }; struct D : B {};
2120 /// D* p = dynamic_cast<D*>(&b);
2122 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2125 /// Matches a const_cast expression.
2127 /// Example: Matches const_cast<int*>(&r) in
2130 /// const int &r(n);
2131 /// int* p = const_cast<int*>(&r);
2133 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2136 /// Matches a C-style cast expression.
2138 /// Example: Matches (int) 2.2f in
2140 /// int i = (int) 2.2f;
2142 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2145 /// Matches explicit cast expressions.
2147 /// Matches any cast expression written in user code, whether it be a
2148 /// C-style cast, a functional-style cast, or a keyword cast.
2150 /// Does not match implicit conversions.
2152 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2153 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2154 /// actual cast expressions.
2156 /// \see hasDestinationType.
2158 /// Example: matches all five of the casts in
2160 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2162 /// but does not match the implicit conversion in
2166 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2169 /// Matches the implicit cast nodes of Clang's AST.
2171 /// This matches many different places, including function call return value
2172 /// eliding, as well as any type conversions.
2173 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2176 /// Matches any cast nodes of Clang's AST.
2178 /// Example: castExpr() matches each of the following:
2181 /// const_cast<Expr *>(SubExpr);
2184 /// but does not match
2189 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2191 /// Matches functional cast expressions
2193 /// Example: Matches Foo(bar);
2196 /// Foo g = (Foo) bar;
2197 /// Foo h = Foo(bar);
2199 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2200 cxxFunctionalCastExpr;
2202 /// Matches functional cast expressions having N != 1 arguments
2204 /// Example: Matches Foo(bar, bar)
2206 /// Foo h = Foo(bar, bar);
2208 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2209 cxxTemporaryObjectExpr;
2211 /// Matches predefined identifier expressions [C99 6.4.2.2].
2213 /// Example: Matches __func__
2215 /// printf("%s", __func__);
2217 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2220 /// Matches C99 designated initializer expressions [C99 6.7.8].
2222 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2224 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2226 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2229 /// Matches designated initializer expressions that contain
2230 /// a specific number of designators.
2234 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2235 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2237 /// designatorCountIs(2)
2238 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2239 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2240 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2241 return Node.size() == N;
2244 /// Matches \c QualTypes in the clang AST.
2245 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2247 /// Matches \c Types in the clang AST.
2248 extern const internal::VariadicAllOfMatcher<Type> type;
2250 /// Matches \c TypeLocs in the clang AST.
2251 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2253 /// Matches if any of the given matchers matches.
2255 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2256 /// matching submatcher.
2258 /// For example, in:
2260 /// class A { int a; int b; };
2264 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2265 /// has(fieldDecl(hasName("b")).bind("v"))))
2267 /// will generate two results binding "v", the first of which binds
2268 /// the field declaration of \c a, the second the field declaration of
2271 /// Usable as: Any Matcher
2272 extern const internal::VariadicOperatorMatcherFunc<
2273 2, std::numeric_limits<unsigned>::max()>
2276 /// Matches if any of the given matchers matches.
2278 /// Usable as: Any Matcher
2279 extern const internal::VariadicOperatorMatcherFunc<
2280 2, std::numeric_limits<unsigned>::max()>
2283 /// Matches if all given matchers match.
2285 /// Usable as: Any Matcher
2286 extern const internal::VariadicOperatorMatcherFunc<
2287 2, std::numeric_limits<unsigned>::max()>
2290 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2295 /// int y = sizeof(x) + alignof(x);
2297 /// unaryExprOrTypeTraitExpr()
2298 /// matches \c sizeof(x) and \c alignof(x)
2299 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2300 UnaryExprOrTypeTraitExpr>
2301 unaryExprOrTypeTraitExpr;
2303 /// Matches unary expressions that have a specific type of argument.
2307 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2309 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2310 /// matches \c sizeof(a) and \c alignof(c)
2311 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2312 internal::Matcher<QualType>, InnerMatcher) {
2313 const QualType ArgumentType = Node.getTypeOfArgument();
2314 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2317 /// Matches unary expressions of a certain kind.
2322 /// int s = sizeof(x) + alignof(x)
2324 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2325 /// matches \c sizeof(x)
2326 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2327 return Node.getKind() == Kind;
2330 /// Same as unaryExprOrTypeTraitExpr, but only matching
2332 inline internal::Matcher<Stmt> alignOfExpr(
2333 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2334 return stmt(unaryExprOrTypeTraitExpr(allOf(
2335 ofKind(UETT_AlignOf), InnerMatcher)));
2338 /// Same as unaryExprOrTypeTraitExpr, but only matching
2340 inline internal::Matcher<Stmt> sizeOfExpr(
2341 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2342 return stmt(unaryExprOrTypeTraitExpr(
2343 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2346 /// Matches NamedDecl nodes that have the specified name.
2348 /// Supports specifying enclosing namespaces or classes by prefixing the name
2349 /// with '<enclosing>::'.
2350 /// Does not match typedefs of an underlying type with the given name.
2352 /// Example matches X (Name == "X")
2357 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2359 /// namespace a { namespace b { class X; } }
2361 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2362 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2365 /// Matches NamedDecl nodes that have any of the specified names.
2367 /// This matcher is only provided as a performance optimization of hasName.
2369 /// hasAnyName(a, b, c)
2371 /// is equivalent to, but faster than
2373 /// anyOf(hasName(a), hasName(b), hasName(c))
2375 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2376 internal::hasAnyNameFunc>
2379 /// Matches NamedDecl nodes whose fully qualified names contain
2380 /// a substring matched by the given RegExp.
2382 /// Supports specifying enclosing namespaces or classes by
2383 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2384 /// of an underlying type with the given name.
2386 /// Example matches X (regexp == "::X")
2391 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2393 /// namespace foo { namespace bar { class X; } }
2395 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2396 assert(!RegExp.empty());
2397 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2398 llvm::Regex RE(RegExp);
2399 return RE.match(FullNameString);
2402 /// Matches overloaded operator names.
2404 /// Matches overloaded operator names specified in strings without the
2405 /// "operator" prefix: e.g. "<<".
2409 /// class A { int operator*(); };
2410 /// const A &operator<<(const A &a, const A &b);
2412 /// a << a; // <-- This matches
2415 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2416 /// specified line and
2417 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2418 /// matches the declaration of \c A.
2420 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2421 inline internal::PolymorphicMatcherWithParam1<
2422 internal::HasOverloadedOperatorNameMatcher, StringRef,
2423 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2424 hasOverloadedOperatorName(StringRef Name) {
2425 return internal::PolymorphicMatcherWithParam1<
2426 internal::HasOverloadedOperatorNameMatcher, StringRef,
2427 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2430 /// Matches C++ classes that are directly or indirectly derived from
2431 /// a class matching \c Base.
2433 /// Note that a class is not considered to be derived from itself.
2435 /// Example matches Y, Z, C (Base == hasName("X"))
2438 /// class Y : public X {}; // directly derived
2439 /// class Z : public Y {}; // indirectly derived
2442 /// class C : public B {}; // derived from a typedef of X
2445 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2449 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2451 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2452 internal::Matcher<NamedDecl>, Base) {
2453 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2456 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2457 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2458 assert(!BaseName.empty());
2459 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2462 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2464 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2465 internal::Matcher<NamedDecl>, Base, 0) {
2466 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2467 .matches(Node, Finder, Builder);
2470 /// Overloaded method as shortcut for
2471 /// \c isSameOrDerivedFrom(hasName(...)).
2472 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2474 assert(!BaseName.empty());
2475 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2478 /// Matches the first method of a class or struct that satisfies \c
2483 /// class A { void func(); };
2484 /// class B { void member(); };
2487 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2488 /// \c A but not \c B.
2489 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2491 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2492 Node.method_end(), Finder, Builder);
2495 /// Matches the generated class of lambda expressions.
2502 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2504 AST_MATCHER(CXXRecordDecl, isLambda) {
2505 return Node.isLambda();
2508 /// Matches AST nodes that have child AST nodes that match the
2509 /// provided matcher.
2511 /// Example matches X, Y
2512 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2514 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2515 /// class Y { class X {}; };
2516 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2519 /// ChildT must be an AST base type.
2521 /// Usable as: Any Matcher
2522 /// Note that has is direct matcher, so it also matches things like implicit
2523 /// casts and paren casts. If you are matching with expr then you should
2524 /// probably consider using ignoringParenImpCasts like:
2525 /// has(ignoringParenImpCasts(expr())).
2526 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2528 /// Matches AST nodes that have descendant AST nodes that match the
2529 /// provided matcher.
2531 /// Example matches X, Y, Z
2532 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2534 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2535 /// class Y { class X {}; };
2536 /// class Z { class Y { class X {}; }; };
2539 /// DescendantT must be an AST base type.
2541 /// Usable as: Any Matcher
2542 extern const internal::ArgumentAdaptingMatcherFunc<
2543 internal::HasDescendantMatcher>
2546 /// Matches AST nodes that have child AST nodes that match the
2547 /// provided matcher.
2549 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2550 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2553 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
2555 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2558 /// ChildT must be an AST base type.
2560 /// As opposed to 'has', 'forEach' will cause a match for each result that
2561 /// matches instead of only on the first one.
2563 /// Usable as: Any Matcher
2564 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2567 /// Matches AST nodes that have descendant AST nodes that match the
2568 /// provided matcher.
2570 /// Example matches X, A, A::X, B, B::C, B::C::X
2571 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2574 /// class A { class X {}; }; // Matches A, because A::X is a class of name
2576 /// class B { class C { class X {}; }; };
2579 /// DescendantT must be an AST base type.
2581 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2582 /// each result that matches instead of only on the first one.
2584 /// Note: Recursively combined ForEachDescendant can cause many matches:
2585 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2586 /// forEachDescendant(cxxRecordDecl())
2588 /// will match 10 times (plus injected class name matches) on:
2590 /// class A { class B { class C { class D { class E {}; }; }; }; };
2593 /// Usable as: Any Matcher
2594 extern const internal::ArgumentAdaptingMatcherFunc<
2595 internal::ForEachDescendantMatcher>
2598 /// Matches if the node or any descendant matches.
2600 /// Generates results for each match.
2602 /// For example, in:
2604 /// class A { class B {}; class C {}; };
2608 /// cxxRecordDecl(hasName("::A"),
2609 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2611 /// will generate results for \c A, \c B and \c C.
2613 /// Usable as: Any Matcher
2614 template <typename T>
2615 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2616 return eachOf(Matcher, forEachDescendant(Matcher));
2619 /// Matches AST nodes that have a parent that matches the provided
2624 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2626 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2628 /// Usable as: Any Matcher
2629 extern const internal::ArgumentAdaptingMatcherFunc<
2630 internal::HasParentMatcher,
2631 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2632 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2635 /// Matches AST nodes that have an ancestor that matches the provided
2640 /// void f() { if (true) { int x = 42; } }
2641 /// void g() { for (;;) { int x = 43; } }
2643 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2645 /// Usable as: Any Matcher
2646 extern const internal::ArgumentAdaptingMatcherFunc<
2647 internal::HasAncestorMatcher,
2648 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2649 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2652 /// Matches if the provided matcher does not match.
2654 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2660 /// Usable as: Any Matcher
2661 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2663 /// Matches a node if the declaration associated with that node
2664 /// matches the given matcher.
2666 /// The associated declaration is:
2667 /// - for type nodes, the declaration of the underlying type
2668 /// - for CallExpr, the declaration of the callee
2669 /// - for MemberExpr, the declaration of the referenced member
2670 /// - for CXXConstructExpr, the declaration of the constructor
2671 /// - for CXXNewExpr, the declaration of the operator new
2672 /// - for ObjCIvarExpr, the declaration of the ivar
2674 /// For type nodes, hasDeclaration will generally match the declaration of the
2675 /// sugared type. Given
2681 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2682 /// typedefDecl. A common use case is to match the underlying, desugared type.
2683 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2685 /// varDecl(hasType(hasUnqualifiedDesugaredType(
2686 /// recordType(hasDeclaration(decl())))))
2688 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2690 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2691 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2692 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2693 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2694 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2695 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2696 /// Matcher<UnresolvedUsingType>
2697 inline internal::PolymorphicMatcherWithParam1<
2698 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2699 void(internal::HasDeclarationSupportedTypes)>
2700 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2701 return internal::PolymorphicMatcherWithParam1<
2702 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2703 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2706 /// Matches a \c NamedDecl whose underlying declaration matches the given
2711 /// namespace N { template<class T> void f(T t); }
2712 /// template <class T> void g() { using N::f; f(T()); }
2714 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2715 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2716 /// matches the use of \c f in \c g() .
2717 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2719 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2721 return UnderlyingDecl != nullptr &&
2722 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2725 /// Matches on the implicit object argument of a member call expression.
2727 /// Example matches y.x()
2728 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2730 /// class Y { public: void x(); };
2731 /// void z() { Y y; y.x(); }
2734 /// FIXME: Overload to allow directly matching types?
2735 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2737 const Expr *ExprNode = Node.getImplicitObjectArgument()
2738 ->IgnoreParenImpCasts();
2739 return (ExprNode != nullptr &&
2740 InnerMatcher.matches(*ExprNode, Finder, Builder));
2744 /// Matches on the receiver of an ObjectiveC Message expression.
2747 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2748 /// matches the [webView ...] message invocation.
2750 /// NSString *webViewJavaScript = ...
2751 /// UIWebView *webView = ...
2752 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2754 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2756 const QualType TypeDecl = Node.getReceiverType();
2757 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2760 /// Returns true when the Objective-C message is sent to an instance.
2763 /// matcher = objcMessagaeExpr(isInstanceMessage())
2766 /// NSString *x = @"hello";
2767 /// [x containsString:@"h"];
2771 /// [NSString stringWithFormat:@"format"];
2773 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
2774 return Node.isInstanceMessage();
2777 /// Matches if the Objective-C message is sent to an instance,
2778 /// and the inner matcher matches on that instance.
2780 /// For example the method call in
2782 /// NSString *x = @"hello";
2783 /// [x containsString:@"h"];
2786 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
2787 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
2789 const Expr *ReceiverNode = Node.getInstanceReceiver();
2790 return (ReceiverNode != nullptr &&
2791 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
2795 /// Matches when BaseName == Selector.getAsString()
2797 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2798 /// matches the outer message expr in the code below, but NOT the message
2799 /// invocation for self.bodyView.
2801 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2803 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2804 Selector Sel = Node.getSelector();
2805 return BaseName.compare(Sel.getAsString()) == 0;
2809 /// Matches when at least one of the supplied string equals to the
2810 /// Selector.getAsString()
2812 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
2813 /// matches both of the expressions below:
2815 /// [myObj methodA:argA];
2816 /// [myObj methodB:argB];
2818 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
2820 internal::hasAnySelectorFunc>
2823 /// Matches ObjC selectors whose name contains
2824 /// a substring matched by the given RegExp.
2825 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2826 /// matches the outer message expr in the code below, but NOT the message
2827 /// invocation for self.bodyView.
2829 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2831 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2832 assert(!RegExp.empty());
2833 std::string SelectorString = Node.getSelector().getAsString();
2834 llvm::Regex RE(RegExp);
2835 return RE.match(SelectorString);
2838 /// Matches when the selector is the empty selector
2840 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2841 /// represent an error condition in the tree!
2842 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2843 return Node.getSelector().isNull();
2846 /// Matches when the selector is a Unary Selector
2848 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2849 /// matches self.bodyView in the code below, but NOT the outer message
2850 /// invocation of "loadHTMLString:baseURL:".
2852 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2854 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2855 return Node.getSelector().isUnarySelector();
2858 /// Matches when the selector is a keyword selector
2860 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2861 /// message expression in
2864 /// UIWebView *webView = ...;
2865 /// CGRect bodyFrame = webView.frame;
2866 /// bodyFrame.size.height = self.bodyContentHeight;
2867 /// webView.frame = bodyFrame;
2868 /// // ^---- matches here
2870 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2871 return Node.getSelector().isKeywordSelector();
2874 /// Matches when the selector has the specified number of arguments
2876 /// matcher = objCMessageExpr(numSelectorArgs(0));
2877 /// matches self.bodyView in the code below
2879 /// matcher = objCMessageExpr(numSelectorArgs(2));
2880 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2881 /// of self.bodyView
2883 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2885 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2886 return Node.getSelector().getNumArgs() == N;
2889 /// Matches if the call expression's callee expression matches.
2893 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2894 /// void f() { f(); }
2896 /// callExpr(callee(expr()))
2897 /// matches this->x(), x(), y.x(), f()
2898 /// with callee(...)
2899 /// matching this->x, x, y.x, f respectively
2901 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2902 /// because this introduces ambiguous overloads with calls to Callee taking a
2903 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2904 /// implemented in terms of implicit casts.
2905 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2907 const Expr *ExprNode = Node.getCallee();
2908 return (ExprNode != nullptr &&
2909 InnerMatcher.matches(*ExprNode, Finder, Builder));
2912 /// Matches if the call expression's callee's declaration matches the
2915 /// Example matches y.x() (matcher = callExpr(callee(
2916 /// cxxMethodDecl(hasName("x")))))
2918 /// class Y { public: void x(); };
2919 /// void z() { Y y; y.x(); }
2921 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2923 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2926 /// Matches if the expression's or declaration's type matches a type
2929 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2930 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2931 /// and U (matcher = typedefDecl(hasType(asString("int")))
2932 /// and friend class X (matcher = friendDecl(hasType("X"))
2935 /// void y(X &x) { x; X z; }
2937 /// class Y { friend class X; };
2939 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2941 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
2943 internal::Matcher<QualType>, InnerMatcher, 0) {
2944 QualType QT = internal::getUnderlyingType(Node);
2946 return InnerMatcher.matches(QT, Finder, Builder);
2950 /// Overloaded to match the declaration of the expression's or value
2951 /// declaration's type.
2953 /// In case of a value declaration (for example a variable declaration),
2954 /// this resolves one layer of indirection. For example, in the value
2955 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2956 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2957 /// declaration of x.
2959 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2960 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2961 /// and friend class X (matcher = friendDecl(hasType("X"))
2964 /// void y(X &x) { x; X z; }
2965 /// class Y { friend class X; };
2968 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2969 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2970 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
2971 internal::Matcher<Decl>, InnerMatcher, 1) {
2972 QualType QT = internal::getUnderlyingType(Node);
2974 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
2978 /// Matches if the type location of the declarator decl's type matches
2979 /// the inner matcher.
2985 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2987 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2988 if (!Node.getTypeSourceInfo())
2989 // This happens for example for implicit destructors.
2991 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2994 /// Matches if the matched type is represented by the given string.
2998 /// class Y { public: void x(); };
2999 /// void z() { Y* y; y->x(); }
3001 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3003 AST_MATCHER_P(QualType, asString, std::string, Name) {
3004 return Name == Node.getAsString();
3007 /// Matches if the matched type is a pointer type and the pointee type
3008 /// matches the specified matcher.
3010 /// Example matches y->x()
3011 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3012 /// cxxRecordDecl(hasName("Y")))))))
3014 /// class Y { public: void x(); };
3015 /// void z() { Y *y; y->x(); }
3018 QualType, pointsTo, internal::Matcher<QualType>,
3020 return (!Node.isNull() && Node->isAnyPointerType() &&
3021 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3024 /// Overloaded to match the pointee type's declaration.
3025 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3027 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3028 .matches(Node, Finder, Builder);
3031 /// Matches if the matched type matches the unqualified desugared
3032 /// type of the matched node.
3034 /// For example, in:
3039 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3041 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3043 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3047 /// Matches if the matched type is a reference type and the referenced
3048 /// type matches the specified matcher.
3050 /// Example matches X &x and const X &y
3051 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3060 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3062 return (!Node.isNull() && Node->isReferenceType() &&
3063 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3066 /// Matches QualTypes whose canonical type matches InnerMatcher.
3070 /// typedef int &int_ref;
3075 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3076 /// declaration of b but \c
3077 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3078 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3082 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3085 /// Overloaded to match the referenced type's declaration.
3086 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3088 return references(qualType(hasDeclaration(InnerMatcher)))
3089 .matches(Node, Finder, Builder);
3092 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3093 internal::Matcher<Expr>, InnerMatcher) {
3094 const Expr *ExprNode = Node.getImplicitObjectArgument();
3095 return (ExprNode != nullptr &&
3096 InnerMatcher.matches(*ExprNode, Finder, Builder));
3099 /// Matches if the expression's type either matches the specified
3100 /// matcher, or is a pointer to a type that matches the InnerMatcher.
3101 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3102 internal::Matcher<QualType>, InnerMatcher, 0) {
3103 return onImplicitObjectArgument(
3104 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3105 .matches(Node, Finder, Builder);
3108 /// Overloaded to match the type's declaration.
3109 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3110 internal::Matcher<Decl>, InnerMatcher, 1) {
3111 return onImplicitObjectArgument(
3112 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3113 .matches(Node, Finder, Builder);
3116 /// Matches a DeclRefExpr that refers to a declaration that matches the
3117 /// specified matcher.
3119 /// Example matches x in if(x)
3120 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3125 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3127 const Decl *DeclNode = Node.getDecl();
3128 return (DeclNode != nullptr &&
3129 InnerMatcher.matches(*DeclNode, Finder, Builder));
3132 /// Matches a \c DeclRefExpr that refers to a declaration through a
3133 /// specific using shadow declaration.
3137 /// namespace a { void f() {} }
3140 /// f(); // Matches this ..
3141 /// a::f(); // .. but not this.
3144 /// declRefExpr(throughUsingDecl(anything()))
3146 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3147 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3148 const NamedDecl *FoundDecl = Node.getFoundDecl();
3149 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3150 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3154 /// Matches an \c OverloadExpr if any of the declarations in the set of
3155 /// overloads matches the given matcher.
3159 /// template <typename T> void foo(T);
3160 /// template <typename T> void bar(T);
3161 /// template <typename T> void baz(T t) {
3166 /// unresolvedLookupExpr(hasAnyDeclaration(
3167 /// functionTemplateDecl(hasName("foo"))))
3168 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3169 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3171 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3172 Node.decls_end(), Finder, Builder);
3175 /// Matches the Decl of a DeclStmt which has a single declaration.
3182 /// declStmt(hasSingleDecl(anything()))
3183 /// matches 'int c;' but not 'int a, b;'.
3184 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3185 if (Node.isSingleDecl()) {
3186 const Decl *FoundDecl = Node.getSingleDecl();
3187 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3192 /// Matches a variable declaration that has an initializer expression
3193 /// that matches the given matcher.
3195 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3197 /// bool y() { return true; }
3201 VarDecl, hasInitializer, internal::Matcher<Expr>,
3203 const Expr *Initializer = Node.getAnyInitializer();
3204 return (Initializer != nullptr &&
3205 InnerMatcher.matches(*Initializer, Finder, Builder));
3208 /// Matches a variable declaration that has function scope and is a
3209 /// non-static local variable.
3211 /// Example matches x (matcher = varDecl(hasLocalStorage())
3219 AST_MATCHER(VarDecl, hasLocalStorage) {
3220 return Node.hasLocalStorage();
3223 /// Matches a variable declaration that does not have local storage.
3225 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3233 AST_MATCHER(VarDecl, hasGlobalStorage) {
3234 return Node.hasGlobalStorage();
3237 /// Matches a variable declaration that has automatic storage duration.
3239 /// Example matches x, but not y, z, or a.
3240 /// (matcher = varDecl(hasAutomaticStorageDuration())
3245 /// thread_local int z;
3249 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3250 return Node.getStorageDuration() == SD_Automatic;
3253 /// Matches a variable declaration that has static storage duration.
3254 /// It includes the variable declared at namespace scope and those declared
3255 /// with "static" and "extern" storage class specifiers.
3261 /// thread_local int z;
3266 /// varDecl(hasStaticStorageDuration())
3267 /// matches the function declaration y, a, b and c.
3269 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3270 return Node.getStorageDuration() == SD_Static;
3273 /// Matches a variable declaration that has thread storage duration.
3275 /// Example matches z, but not x, z, or a.
3276 /// (matcher = varDecl(hasThreadStorageDuration())
3281 /// thread_local int z;
3285 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3286 return Node.getStorageDuration() == SD_Thread;
3289 /// Matches a variable declaration that is an exception variable from
3290 /// a C++ catch block, or an Objective-C \@catch statement.
3292 /// Example matches x (matcher = varDecl(isExceptionVariable())
3296 /// } catch (int x) {
3300 AST_MATCHER(VarDecl, isExceptionVariable) {
3301 return Node.isExceptionVariable();
3304 /// Checks that a call expression or a constructor call expression has
3305 /// a specific number of arguments (including absent default arguments).
3307 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3309 /// void f(int x, int y);
3312 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3313 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3317 return Node.getNumArgs() == N;
3320 /// Matches the n'th argument of a call expression or a constructor
3321 /// call expression.
3323 /// Example matches y in x(y)
3324 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3326 /// void x(int) { int y; x(y); }
3328 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3329 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3332 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3333 return (N < Node.getNumArgs() &&
3334 InnerMatcher.matches(
3335 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3338 /// Matches declaration statements that contain a specific number of
3348 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3349 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3350 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3353 /// Matches the n'th declaration of a declaration statement.
3355 /// Note that this does not work for global declarations because the AST
3356 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3358 /// Example: Given non-global declarations
3364 /// declStmt(containsDeclaration(
3365 /// 0, varDecl(hasInitializer(anything()))))
3366 /// matches only 'int d = 2, e;', and
3367 /// declStmt(containsDeclaration(1, varDecl()))
3369 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3370 /// but 'int c;' is not matched.
3372 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3373 internal::Matcher<Decl>, InnerMatcher) {
3374 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3377 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3378 std::advance(Iterator, N);
3379 return InnerMatcher.matches(**Iterator, Finder, Builder);
3382 /// Matches a C++ catch statement that has a catch-all handler.
3394 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3395 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3396 return Node.getExceptionDecl() == nullptr;
3399 /// Matches a constructor initializer.
3404 /// Foo() : foo_(1) { }
3408 /// cxxRecordDecl(has(cxxConstructorDecl(
3409 /// hasAnyConstructorInitializer(anything())
3411 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3412 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3413 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3414 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3415 Node.init_end(), Finder, Builder);
3418 /// Matches the field declaration of a constructor initializer.
3423 /// Foo() : foo_(1) { }
3427 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3428 /// forField(hasName("foo_"))))))
3430 /// with forField matching foo_
3431 AST_MATCHER_P(CXXCtorInitializer, forField,
3432 internal::Matcher<FieldDecl>, InnerMatcher) {
3433 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3434 return (NodeAsDecl != nullptr &&
3435 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3438 /// Matches the initializer expression of a constructor initializer.
3443 /// Foo() : foo_(1) { }
3447 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3448 /// withInitializer(integerLiteral(equals(1)))))))
3450 /// with withInitializer matching (1)
3451 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3452 internal::Matcher<Expr>, InnerMatcher) {
3453 const Expr* NodeAsExpr = Node.getInit();
3454 return (NodeAsExpr != nullptr &&
3455 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3458 /// Matches a constructor initializer if it is explicitly written in
3459 /// code (as opposed to implicitly added by the compiler).
3465 /// Foo(int) : foo_("A") { }
3469 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3470 /// will match Foo(int), but not Foo()
3471 AST_MATCHER(CXXCtorInitializer, isWritten) {
3472 return Node.isWritten();
3475 /// Matches a constructor initializer if it is initializing a base, as
3476 /// opposed to a member.
3483 /// D(int i) : I(i) {}
3489 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3490 /// will match E(), but not match D(int).
3491 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3492 return Node.isBaseInitializer();
3495 /// Matches a constructor initializer if it is initializing a member, as
3496 /// opposed to a base.
3503 /// D(int i) : I(i) {}
3509 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3510 /// will match D(int), but not match E().
3511 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3512 return Node.isMemberInitializer();
3515 /// Matches any argument of a call expression or a constructor call
3516 /// expression, or an ObjC-message-send expression.
3520 /// void x(int, int, int) { int y; x(1, y, 42); }
3522 /// callExpr(hasAnyArgument(declRefExpr()))
3523 /// matches x(1, y, 42)
3524 /// with hasAnyArgument(...)
3527 /// For ObjectiveC, given
3529 /// @interface I - (void) f:(int) y; @end
3530 /// void foo(I *i) { [i f:12]; }
3532 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3533 /// matches [i f:12]
3534 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3535 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3538 internal::Matcher<Expr>, InnerMatcher) {
3539 for (const Expr *Arg : Node.arguments()) {
3540 BoundNodesTreeBuilder Result(*Builder);
3541 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3542 *Builder = std::move(Result);
3549 /// Matches a constructor call expression which uses list initialization.
3550 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3551 return Node.isListInitialization();
3554 /// Matches a constructor call expression which requires
3555 /// zero initialization.
3560 /// struct point { double x; double y; };
3561 /// point pt[2] = { { 1.0, 2.0 } };
3564 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3565 /// will match the implicit array filler for pt[1].
3566 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3567 return Node.requiresZeroInitialization();
3570 /// Matches the n'th parameter of a function or an ObjC method
3571 /// declaration or a block.
3575 /// class X { void f(int x) {} };
3577 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3578 /// matches f(int x) {}
3579 /// with hasParameter(...)
3582 /// For ObjectiveC, given
3584 /// @interface I - (void) f:(int) y; @end
3587 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3588 /// matches the declaration of method f with hasParameter
3590 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3591 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3594 unsigned, N, internal::Matcher<ParmVarDecl>,
3596 return (N < Node.parameters().size()
3597 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3600 /// Matches all arguments and their respective ParmVarDecl.
3609 /// forEachArgumentWithParam(
3610 /// declRefExpr(to(varDecl(hasName("y")))),
3611 /// parmVarDecl(hasType(isInteger()))
3614 /// with declRefExpr(...)
3616 /// and parmVarDecl(...)
3618 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3619 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3621 internal::Matcher<Expr>, ArgMatcher,
3622 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3623 BoundNodesTreeBuilder Result;
3624 // The first argument of an overloaded member operator is the implicit object
3625 // argument of the method which should not be matched against a parameter, so
3626 // we skip over it here.
3627 BoundNodesTreeBuilder Matches;
3628 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3629 .matches(Node, Finder, &Matches)
3633 bool Matched = false;
3634 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3635 BoundNodesTreeBuilder ArgMatches(*Builder);
3636 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3637 Finder, &ArgMatches)) {
3638 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3639 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3640 hasParameter(ParamIndex, ParamMatcher)))),
3641 callExpr(callee(functionDecl(
3642 hasParameter(ParamIndex, ParamMatcher))))))
3643 .matches(Node, Finder, &ParamMatches)) {
3644 Result.addMatch(ParamMatches);
3650 *Builder = std::move(Result);
3654 /// Matches any parameter of a function or an ObjC method declaration or a
3657 /// Does not match the 'this' parameter of a method.
3661 /// class X { void f(int x, int y, int z) {} };
3663 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3664 /// matches f(int x, int y, int z) {}
3665 /// with hasAnyParameter(...)
3668 /// For ObjectiveC, given
3670 /// @interface I - (void) f:(int) y; @end
3673 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
3674 /// matches the declaration of method f with hasParameter
3677 /// For blocks, given
3679 /// b = ^(int y) { printf("%d", y) };
3682 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
3683 /// matches the declaration of the block b with hasParameter
3685 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
3686 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3689 internal::Matcher<ParmVarDecl>,
3691 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3692 Node.param_end(), Finder, Builder);
3695 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3696 /// specific parameter count.
3700 /// void f(int i) {}
3701 /// void g(int i, int j) {}
3702 /// void h(int i, int j);
3704 /// void k(int x, int y, int z, ...);
3706 /// functionDecl(parameterCountIs(2))
3707 /// matches \c g and \c h
3708 /// functionProtoType(parameterCountIs(2))
3709 /// matches \c g and \c h
3710 /// functionProtoType(parameterCountIs(3))
3712 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3713 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3716 return Node.getNumParams() == N;
3719 /// Matches \c FunctionDecls that have a noreturn attribute.
3724 /// [[noreturn]] void a();
3725 /// __attribute__((noreturn)) void b();
3726 /// struct c { [[noreturn]] c(); };
3728 /// functionDecl(isNoReturn())
3729 /// matches all of those except
3733 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
3735 /// Matches the return type of a function declaration.
3739 /// class X { int f() { return 1; } };
3741 /// cxxMethodDecl(returns(asString("int")))
3742 /// matches int f() { return 1; }
3743 AST_MATCHER_P(FunctionDecl, returns,
3744 internal::Matcher<QualType>, InnerMatcher) {
3745 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3748 /// Matches extern "C" function or variable declarations.
3752 /// extern "C" void f() {}
3753 /// extern "C" { void g() {} }
3755 /// extern "C" int x = 1;
3756 /// extern "C" int y = 2;
3759 /// functionDecl(isExternC())
3760 /// matches the declaration of f and g, but not the declaration of h.
3761 /// varDecl(isExternC())
3762 /// matches the declaration of x and y, but not the declaration of z.
3763 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3765 return Node.isExternC();
3768 /// Matches variable/function declarations that have "static" storage
3769 /// class specifier ("static" keyword) written in the source.
3773 /// static void f() {}
3774 /// static int i = 0;
3778 /// functionDecl(isStaticStorageClass())
3779 /// matches the function declaration f.
3780 /// varDecl(isStaticStorageClass())
3781 /// matches the variable declaration i.
3782 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
3783 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3785 return Node.getStorageClass() == SC_Static;
3788 /// Matches deleted function declarations.
3793 /// void DeletedFunc() = delete;
3795 /// functionDecl(isDeleted())
3796 /// matches the declaration of DeletedFunc, but not Func.
3797 AST_MATCHER(FunctionDecl, isDeleted) {
3798 return Node.isDeleted();
3801 /// Matches defaulted function declarations.
3805 /// class A { ~A(); };
3806 /// class B { ~B() = default; };
3808 /// functionDecl(isDefaulted())
3809 /// matches the declaration of ~B, but not ~A.
3810 AST_MATCHER(FunctionDecl, isDefaulted) {
3811 return Node.isDefaulted();
3814 /// Matches functions that have a dynamic exception specification.
3819 /// void g() noexcept;
3820 /// void h() noexcept(true);
3821 /// void i() noexcept(false);
3822 /// void j() throw();
3823 /// void k() throw(int);
3824 /// void l() throw(...);
3826 /// functionDecl(hasDynamicExceptionSpec()) and
3827 /// functionProtoType(hasDynamicExceptionSpec())
3828 /// match the declarations of j, k, and l, but not f, g, h, or i.
3829 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
3830 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3831 FunctionProtoType)) {
3832 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
3833 return FnTy->hasDynamicExceptionSpec();
3837 /// Matches functions that have a non-throwing exception specification.
3842 /// void g() noexcept;
3843 /// void h() throw();
3844 /// void i() throw(int);
3845 /// void j() noexcept(false);
3847 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
3848 /// match the declarations of g, and h, but not f, i or j.
3849 AST_POLYMORPHIC_MATCHER(isNoThrow,
3850 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3851 FunctionProtoType)) {
3852 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
3854 // If the function does not have a prototype, then it is assumed to be a
3855 // throwing function (as it would if the function did not have any exception
3860 // Assume the best for any unresolved exception specification.
3861 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3864 return FnTy->isNothrow();
3867 /// Matches constexpr variable and function declarations,
3868 /// and if constexpr.
3872 /// constexpr int foo = 42;
3873 /// constexpr int bar();
3874 /// void baz() { if constexpr(1 > 0) {} }
3876 /// varDecl(isConstexpr())
3877 /// matches the declaration of foo.
3878 /// functionDecl(isConstexpr())
3879 /// matches the declaration of bar.
3880 /// ifStmt(isConstexpr())
3881 /// matches the if statement in baz.
3882 AST_POLYMORPHIC_MATCHER(isConstexpr,
3883 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3886 return Node.isConstexpr();
3889 /// Matches the condition expression of an if statement, for loop,
3890 /// switch statement or conditional operator.
3892 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3896 AST_POLYMORPHIC_MATCHER_P(
3898 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3899 SwitchStmt, AbstractConditionalOperator),
3900 internal::Matcher<Expr>, InnerMatcher) {
3901 const Expr *const Condition = Node.getCond();
3902 return (Condition != nullptr &&
3903 InnerMatcher.matches(*Condition, Finder, Builder));
3906 /// Matches the then-statement of an if statement.
3908 /// Examples matches the if statement
3909 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3911 /// if (false) true; else false;
3913 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3914 const Stmt *const Then = Node.getThen();
3915 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3918 /// Matches the else-statement of an if statement.
3920 /// Examples matches the if statement
3921 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3923 /// if (false) false; else true;
3925 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3926 const Stmt *const Else = Node.getElse();
3927 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3930 /// Matches if a node equals a previously bound node.
3932 /// Matches a node if it equals the node previously bound to \p ID.
3936 /// class X { int a; int b; };
3939 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3940 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3941 /// matches the class \c X, as \c a and \c b have the same type.
3943 /// Note that when multiple matches are involved via \c forEach* matchers,
3944 /// \c equalsBoundNodes acts as a filter.
3947 /// forEachDescendant(varDecl().bind("d")),
3948 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3949 /// will trigger a match for each combination of variable declaration
3950 /// and reference to that variable declaration within a compound statement.
3951 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3952 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3955 // FIXME: Figure out whether it makes sense to allow this
3956 // on any other node types.
3957 // For *Loc it probably does not make sense, as those seem
3958 // unique. For NestedNameSepcifier it might make sense, as
3959 // those also have pointer identity, but I'm not sure whether
3960 // they're ever reused.
3961 internal::NotEqualsBoundNodePredicate Predicate;
3963 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3964 return Builder->removeBindings(Predicate);
3967 /// Matches the condition variable statement in an if statement.
3971 /// if (A* a = GetAPointer()) {}
3973 /// hasConditionVariableStatement(...)
3974 /// matches 'A* a = GetAPointer()'.
3975 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3976 internal::Matcher<DeclStmt>, InnerMatcher) {
3977 const DeclStmt* const DeclarationStatement =
3978 Node.getConditionVariableDeclStmt();
3979 return DeclarationStatement != nullptr &&
3980 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3983 /// Matches the index expression of an array subscript expression.
3988 /// void f() { i[1] = 42; }
3990 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3991 /// matches \c i[1] with the \c integerLiteral() matching \c 1
3992 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3993 internal::Matcher<Expr>, InnerMatcher) {
3994 if (const Expr* Expression = Node.getIdx())
3995 return InnerMatcher.matches(*Expression, Finder, Builder);
3999 /// Matches the base expression of an array subscript expression.
4004 /// void f() { i[1] = 42; }
4006 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4007 /// hasSourceExpression(declRefExpr()))))
4008 /// matches \c i[1] with the \c declRefExpr() matching \c i
4009 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4010 internal::Matcher<Expr>, InnerMatcher) {
4011 if (const Expr* Expression = Node.getBase())
4012 return InnerMatcher.matches(*Expression, Finder, Builder);
4016 /// Matches a 'for', 'while', 'do while' statement or a function
4017 /// definition that has a given body.
4023 /// hasBody(compoundStmt())
4024 /// matches 'for (;;) {}'
4025 /// with compoundStmt()
4027 AST_POLYMORPHIC_MATCHER_P(hasBody,
4028 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4032 internal::Matcher<Stmt>, InnerMatcher) {
4033 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4034 return (Statement != nullptr &&
4035 InnerMatcher.matches(*Statement, Finder, Builder));
4038 /// Matches compound statements where at least one substatement matches
4039 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4045 /// hasAnySubstatement(compoundStmt())
4046 /// matches '{ {}; 1+2; }'
4047 /// with compoundStmt()
4049 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4050 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4052 internal::Matcher<Stmt>, InnerMatcher) {
4053 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4054 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4055 CS->body_end(), Finder, Builder);
4058 /// Checks that a compound statement contains a specific number of
4059 /// child statements.
4065 /// compoundStmt(statementCountIs(0)))
4067 /// but does not match the outer compound statement.
4068 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4069 return Node.size() == N;
4072 /// Matches literals that are equal to the given value of type ValueT.
4076 /// f('\0', false, 3.14, 42);
4078 /// characterLiteral(equals(0))
4080 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4082 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4084 /// integerLiteral(equals(42))
4087 /// Note that you cannot directly match a negative numeric literal because the
4088 /// minus sign is not part of the literal: It is a unary operator whose operand
4089 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4090 /// matcher to match the minus sign:
4092 /// unaryOperator(hasOperatorName("-"),
4093 /// hasUnaryOperand(integerLiteral(equals(13))))
4095 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4096 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4097 template <typename ValueT>
4098 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
4099 equals(const ValueT &Value) {
4100 return internal::PolymorphicMatcherWithParam1<
4101 internal::ValueEqualsMatcher,
4105 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4106 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4110 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4114 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4115 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4118 unsigned, Value, 1) {
4119 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4123 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4124 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4129 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4133 /// Matches the operator Name of operator expressions (binary or
4136 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4140 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4141 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4143 std::string, Name) {
4144 return Name == Node.getOpcodeStr(Node.getOpcode());
4147 /// Matches all kinds of assignment operators.
4149 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4155 /// Example 2: matches s1 = s2
4156 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4158 /// struct S { S& operator=(const S&); };
4159 /// void x() { S s1, s2; s1 = s2; })
4161 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4162 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4163 CXXOperatorCallExpr)) {
4164 return Node.isAssignmentOp();
4167 /// Matches the left hand side of binary operator expressions.
4169 /// Example matches a (matcher = binaryOperator(hasLHS()))
4173 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4174 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4175 ArraySubscriptExpr),
4176 internal::Matcher<Expr>, InnerMatcher) {
4177 const Expr *LeftHandSide = Node.getLHS();
4178 return (LeftHandSide != nullptr &&
4179 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4182 /// Matches the right hand side of binary operator expressions.
4184 /// Example matches b (matcher = binaryOperator(hasRHS()))
4188 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4189 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4190 ArraySubscriptExpr),
4191 internal::Matcher<Expr>, InnerMatcher) {
4192 const Expr *RightHandSide = Node.getRHS();
4193 return (RightHandSide != nullptr &&
4194 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4197 /// Matches if either the left hand side or the right hand side of a
4198 /// binary operator matches.
4199 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4200 const internal::Matcher<Expr> &InnerMatcher) {
4201 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4204 /// Matches if the operand of a unary operator matches.
4206 /// Example matches true (matcher = hasUnaryOperand(
4207 /// cxxBoolLiteral(equals(true))))
4211 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4212 internal::Matcher<Expr>, InnerMatcher) {
4213 const Expr * const Operand = Node.getSubExpr();
4214 return (Operand != nullptr &&
4215 InnerMatcher.matches(*Operand, Finder, Builder));
4218 /// Matches if the cast's source expression
4219 /// or opaque value's source expression matches the given matcher.
4221 /// Example 1: matches "a string"
4222 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4224 /// class URL { URL(string); };
4225 /// URL url = "a string";
4228 /// Example 2: matches 'b' (matcher =
4229 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4233 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4234 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4236 internal::Matcher<Expr>, InnerMatcher) {
4237 const Expr *const SubExpression =
4238 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4239 return (SubExpression != nullptr &&
4240 InnerMatcher.matches(*SubExpression, Finder, Builder));
4243 /// Matches casts that has a given cast kind.
4245 /// Example: matches the implicit cast around \c 0
4246 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4250 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4251 return Node.getCastKind() == Kind;
4254 /// Matches casts whose destination type matches a given matcher.
4256 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4257 /// actual casts "explicit" casts.)
4258 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4259 internal::Matcher<QualType>, InnerMatcher) {
4260 const QualType NodeType = Node.getTypeAsWritten();
4261 return InnerMatcher.matches(NodeType, Finder, Builder);
4264 /// Matches implicit casts whose destination type matches a given
4267 /// FIXME: Unit test this matcher
4268 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4269 internal::Matcher<QualType>, InnerMatcher) {
4270 return InnerMatcher.matches(Node.getType(), Finder, Builder);
4273 /// Matches RecordDecl object that are spelled with "struct."
4275 /// Example matches S, but not C or U.
4281 AST_MATCHER(RecordDecl, isStruct) {
4282 return Node.isStruct();
4285 /// Matches RecordDecl object that are spelled with "union."
4287 /// Example matches U, but not C or S.
4293 AST_MATCHER(RecordDecl, isUnion) {
4294 return Node.isUnion();
4297 /// Matches RecordDecl object that are spelled with "class."
4299 /// Example matches C, but not S or U.
4305 AST_MATCHER(RecordDecl, isClass) {
4306 return Node.isClass();
4309 /// Matches the true branch expression of a conditional operator.
4311 /// Example 1 (conditional ternary operator): matches a
4313 /// condition ? a : b
4316 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4320 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4321 internal::Matcher<Expr>, InnerMatcher) {
4322 const Expr *Expression = Node.getTrueExpr();
4323 return (Expression != nullptr &&
4324 InnerMatcher.matches(*Expression, Finder, Builder));
4327 /// Matches the false branch expression of a conditional operator
4328 /// (binary or ternary).
4330 /// Example matches b
4332 /// condition ? a : b
4335 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4336 internal::Matcher<Expr>, InnerMatcher) {
4337 const Expr *Expression = Node.getFalseExpr();
4338 return (Expression != nullptr &&
4339 InnerMatcher.matches(*Expression, Finder, Builder));
4342 /// Matches if a declaration has a body attached.
4344 /// Example matches A, va, fa
4347 /// class B; // Doesn't match, as it has no body.
4349 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4351 /// void fb(); // Doesn't match, as it has no body.
4353 /// - (void)ma; // Doesn't match, interface is declaration.
4355 /// @implementation X
4360 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4361 /// Matcher<ObjCMethodDecl>
4362 AST_POLYMORPHIC_MATCHER(isDefinition,
4363 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4366 return Node.isThisDeclarationADefinition();
4369 /// Matches if a function declaration is variadic.
4371 /// Example matches f, but not g or h. The function i will not match, even when
4372 /// compiled in C mode.
4376 /// template <typename... Ts> void h(Ts...);
4379 AST_MATCHER(FunctionDecl, isVariadic) {
4380 return Node.isVariadic();
4383 /// Matches the class declaration that the given method declaration
4386 /// FIXME: Generalize this for other kinds of declarations.
4387 /// FIXME: What other kind of declarations would we need to generalize
4390 /// Example matches A() in the last line
4391 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4392 /// ofClass(hasName("A"))))))
4400 AST_MATCHER_P(CXXMethodDecl, ofClass,
4401 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4402 const CXXRecordDecl *Parent = Node.getParent();
4403 return (Parent != nullptr &&
4404 InnerMatcher.matches(*Parent, Finder, Builder));
4407 /// Matches each method overridden by the given method. This matcher may
4408 /// produce multiple matches.
4412 /// class A { virtual void f(); };
4413 /// class B : public A { void f(); };
4414 /// class C : public B { void f(); };
4416 /// cxxMethodDecl(ofClass(hasName("C")),
4417 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4418 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4419 /// that B::f is not overridden by C::f).
4421 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4423 /// class A1 { virtual void f(); };
4424 /// class A2 { virtual void f(); };
4425 /// class C : public A1, public A2 { void f(); };
4427 /// cxxMethodDecl(ofClass(hasName("C")),
4428 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4429 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4430 /// once with "b" binding "A2::f" and "d" binding "C::f".
4431 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4432 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4433 BoundNodesTreeBuilder Result;
4434 bool Matched = false;
4435 for (const auto *Overridden : Node.overridden_methods()) {
4436 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4437 const bool OverriddenMatched =
4438 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4439 if (OverriddenMatched) {
4441 Result.addMatch(OverriddenBuilder);
4444 *Builder = std::move(Result);
4448 /// Matches if the given method declaration is virtual.
4454 /// virtual void x();
4458 AST_MATCHER(CXXMethodDecl, isVirtual) {
4459 return Node.isVirtual();
4462 /// Matches if the given method declaration has an explicit "virtual".
4468 /// virtual void x();
4470 /// class B : public A {
4475 /// matches A::x but not B::x
4476 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4477 return Node.isVirtualAsWritten();
4480 /// Matches if the given method or class declaration is final.
4484 /// class A final {};
4487 /// virtual void f();
4494 /// matches A and C::f, but not B, C, or B::f
4495 AST_POLYMORPHIC_MATCHER(isFinal,
4496 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4498 return Node.template hasAttr<FinalAttr>();
4501 /// Matches if the given method declaration is pure.
4507 /// virtual void x() = 0;
4511 AST_MATCHER(CXXMethodDecl, isPure) {
4512 return Node.isPure();
4515 /// Matches if the given method declaration is const.
4520 /// void foo() const;
4525 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4526 AST_MATCHER(CXXMethodDecl, isConst) {
4527 return Node.isConst();
4530 /// Matches if the given method declaration declares a copy assignment
4536 /// A &operator=(const A &);
4537 /// A &operator=(A &&);
4541 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4543 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4544 return Node.isCopyAssignmentOperator();
4547 /// Matches if the given method declaration declares a move assignment
4553 /// A &operator=(const A &);
4554 /// A &operator=(A &&);
4558 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4560 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4561 return Node.isMoveAssignmentOperator();
4564 /// Matches if the given method declaration overrides another method.
4570 /// virtual void x();
4572 /// class B : public A {
4574 /// virtual void x();
4578 AST_MATCHER(CXXMethodDecl, isOverride) {
4579 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4582 /// Matches method declarations that are user-provided.
4588 /// S(const S &) = default; // #2
4589 /// S(S &&) = delete; // #3
4592 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4593 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4594 return Node.isUserProvided();
4597 /// Matches member expressions that are called with '->' as opposed
4600 /// Member calls on the implicit this pointer match as called with '->'.
4605 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4610 /// memberExpr(isArrow())
4611 /// matches this->x, x, y.x, a, this->b
4612 AST_MATCHER(MemberExpr, isArrow) {
4613 return Node.isArrow();
4616 /// Matches QualType nodes that are of integer type.
4624 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4625 /// matches "a(int)", "b(long)", but not "c(double)".
4626 AST_MATCHER(QualType, isInteger) {
4627 return Node->isIntegerType();
4630 /// Matches QualType nodes that are of unsigned integer type.
4635 /// void b(unsigned long);
4638 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4639 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4640 AST_MATCHER(QualType, isUnsignedInteger) {
4641 return Node->isUnsignedIntegerType();
4644 /// Matches QualType nodes that are of signed integer type.
4649 /// void b(unsigned long);
4652 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4653 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4654 AST_MATCHER(QualType, isSignedInteger) {
4655 return Node->isSignedIntegerType();
4658 /// Matches QualType nodes that are of character type.
4663 /// void b(wchar_t);
4666 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4667 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4668 AST_MATCHER(QualType, isAnyCharacter) {
4669 return Node->isAnyCharacterType();
4672 /// Matches QualType nodes that are of any pointer type; this includes
4673 /// the Objective-C object pointer type, which is different despite being
4674 /// syntactically similar.
4678 /// int *i = nullptr;
4686 /// varDecl(hasType(isAnyPointer()))
4687 /// matches "int *i" and "Foo *f", but not "int j".
4688 AST_MATCHER(QualType, isAnyPointer) {
4689 return Node->isAnyPointerType();
4692 /// Matches QualType nodes that are const-qualified, i.e., that
4693 /// include "top-level" const.
4698 /// void b(int const);
4699 /// void c(const int);
4700 /// void d(const int*);
4701 /// void e(int const) {};
4703 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4704 /// matches "void b(int const)", "void c(const int)" and
4705 /// "void e(int const) {}". It does not match d as there
4706 /// is no top-level const on the parameter type "const int *".
4707 AST_MATCHER(QualType, isConstQualified) {
4708 return Node.isConstQualified();
4711 /// Matches QualType nodes that are volatile-qualified, i.e., that
4712 /// include "top-level" volatile.
4717 /// void b(int volatile);
4718 /// void c(volatile int);
4719 /// void d(volatile int*);
4720 /// void e(int volatile) {};
4722 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4723 /// matches "void b(int volatile)", "void c(volatile int)" and
4724 /// "void e(int volatile) {}". It does not match d as there
4725 /// is no top-level volatile on the parameter type "volatile int *".
4726 AST_MATCHER(QualType, isVolatileQualified) {
4727 return Node.isVolatileQualified();
4730 /// Matches QualType nodes that have local CV-qualifiers attached to
4731 /// the node, not hidden within a typedef.
4735 /// typedef const int const_int;
4738 /// int *volatile k;
4741 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4742 /// \c i is const-qualified but the qualifier is not local.
4743 AST_MATCHER(QualType, hasLocalQualifiers) {
4744 return Node.hasLocalQualifiers();
4747 /// Matches a member expression where the member is matched by a
4752 /// struct { int first, second; } first, second;
4753 /// int i(second.first);
4754 /// int j(first.second);
4756 /// memberExpr(member(hasName("first")))
4757 /// matches second.first
4758 /// but not first.second (because the member name there is "second").
4759 AST_MATCHER_P(MemberExpr, member,
4760 internal::Matcher<ValueDecl>, InnerMatcher) {
4761 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4764 /// Matches a member expression where the object expression is
4765 /// matched by a given matcher.
4769 /// struct X { int m; };
4770 /// void f(X x) { x.m; m; }
4772 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4773 /// matches "x.m" and "m"
4774 /// with hasObjectExpression(...)
4775 /// matching "x" and the implicit object expression of "m" which has type X*.
4776 AST_MATCHER_P(MemberExpr, hasObjectExpression,
4777 internal::Matcher<Expr>, InnerMatcher) {
4778 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4781 /// Matches any using shadow declaration.
4785 /// namespace X { void b(); }
4788 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
4789 /// matches \code using X::b \endcode
4790 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
4791 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4792 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
4793 Node.shadow_end(), Finder, Builder);
4796 /// Matches a using shadow declaration where the target declaration is
4797 /// matched by the given matcher.
4801 /// namespace X { int a; void b(); }
4805 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
4806 /// matches \code using X::b \endcode
4807 /// but not \code using X::a \endcode
4808 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
4809 internal::Matcher<NamedDecl>, InnerMatcher) {
4810 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
4813 /// Matches template instantiations of function, class, or static
4814 /// member variable template instantiations.
4818 /// template <typename T> class X {}; class A {}; X<A> x;
4822 /// template <typename T> class X {}; class A {}; template class X<A>;
4826 /// template <typename T> class X {}; class A {}; extern template class X<A>;
4828 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4829 /// matches the template instantiation of X<A>.
4833 /// template <typename T> class X {}; class A {};
4834 /// template <> class X<A> {}; X<A> x;
4836 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4837 /// does not match, as X<A> is an explicit template specialization.
4839 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4840 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4841 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4843 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4844 Node.getTemplateSpecializationKind() ==
4845 TSK_ExplicitInstantiationDefinition ||
4846 Node.getTemplateSpecializationKind() ==
4847 TSK_ExplicitInstantiationDeclaration);
4850 /// Matches declarations that are template instantiations or are inside
4851 /// template instantiations.
4855 /// template<typename T> void A(T t) { T i; }
4859 /// functionDecl(isInstantiated())
4860 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
4861 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4862 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4863 functionDecl(isTemplateInstantiation())));
4864 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4867 /// Matches statements inside of a template instantiation.
4872 /// template<typename T> void A(T t) { T i; j += 42;}
4876 /// declStmt(isInTemplateInstantiation())
4877 /// matches 'int i;' and 'unsigned i'.
4878 /// unless(stmt(isInTemplateInstantiation()))
4879 /// will NOT match j += 42; as it's shared between the template definition and
4881 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4883 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4884 functionDecl(isTemplateInstantiation())))));
4887 /// Matches explicit template specializations of function, class, or
4888 /// static member variable template instantiations.
4892 /// template<typename T> void A(T t) { }
4893 /// template<> void A(int N) { }
4895 /// functionDecl(isExplicitTemplateSpecialization())
4896 /// matches the specialization A<int>().
4898 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
4899 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4900 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4902 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4905 /// Matches \c TypeLocs for which the given inner
4906 /// QualType-matcher matches.
4907 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4908 internal::Matcher<QualType>, InnerMatcher, 0) {
4909 return internal::BindableMatcher<TypeLoc>(
4910 new internal::TypeLocTypeMatcher(InnerMatcher));
4913 /// Matches type \c bool.
4917 /// struct S { bool func(); };
4919 /// functionDecl(returns(booleanType()))
4920 /// matches "bool func();"
4921 AST_MATCHER(Type, booleanType) {
4922 return Node.isBooleanType();
4925 /// Matches type \c void.
4929 /// struct S { void func(); };
4931 /// functionDecl(returns(voidType()))
4932 /// matches "void func();"
4933 AST_MATCHER(Type, voidType) {
4934 return Node.isVoidType();
4937 template <typename NodeType>
4938 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
4940 /// Matches builtin Types.
4951 /// matches "int b", "float c" and "bool d"
4952 extern const AstTypeMatcher<BuiltinType> builtinType;
4954 /// Matches all kinds of arrays.
4958 /// int a[] = { 2, 3 };
4960 /// void f() { int c[a[0]]; }
4963 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4964 extern const AstTypeMatcher<ArrayType> arrayType;
4966 /// Matches C99 complex types.
4970 /// _Complex float f;
4973 /// matches "_Complex float f"
4974 extern const AstTypeMatcher<ComplexType> complexType;
4976 /// Matches any real floating-point type (float, double, long double).
4983 /// realFloatingPointType()
4984 /// matches "float f" but not "int i"
4985 AST_MATCHER(Type, realFloatingPointType) {
4986 return Node.isRealFloatingType();
4989 /// Matches arrays and C99 complex types that have a specific element
4998 /// arrayType(hasElementType(builtinType()))
4999 /// matches "int b[7]"
5001 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5002 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5003 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5006 /// Matches C arrays with a specified constant size.
5012 /// int b[] = { 2, 3 };
5016 /// constantArrayType()
5017 /// matches "int a[2]"
5018 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5020 /// Matches nodes that have the specified size.
5026 /// int c[41], d[43];
5027 /// char *s = "abcd";
5028 /// wchar_t *ws = L"abcd";
5031 /// constantArrayType(hasSize(42))
5032 /// matches "int a[42]" and "int b[2 * 21]"
5033 /// stringLiteral(hasSize(4))
5034 /// matches "abcd", L"abcd"
5035 AST_POLYMORPHIC_MATCHER_P(hasSize,
5036 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5039 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5042 /// Matches C++ arrays whose size is a value-dependent expression.
5046 /// template<typename T, int Size>
5051 /// dependentSizedArrayType
5052 /// matches "T data[Size]"
5053 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5055 /// Matches C arrays with unspecified size.
5059 /// int a[] = { 2, 3 };
5061 /// void f(int c[]) { int d[a[0]]; };
5063 /// incompleteArrayType()
5064 /// matches "int a[]" and "int c[]"
5065 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5067 /// Matches C arrays with a specified size that is not an
5068 /// integer-constant-expression.
5073 /// int a[] = { 2, 3 }
5078 /// variableArrayType()
5079 /// matches "int c[a[0]]"
5080 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5082 /// Matches \c VariableArrayType nodes that have a specific size
5091 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5092 /// varDecl(hasName("b")))))))
5093 /// matches "int a[b]"
5094 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5095 internal::Matcher<Expr>, InnerMatcher) {
5096 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5099 /// Matches atomic types.
5106 /// matches "_Atomic(int) i"
5107 extern const AstTypeMatcher<AtomicType> atomicType;
5109 /// Matches atomic types with a specific value type.
5114 /// _Atomic(float) f;
5116 /// atomicType(hasValueType(isInteger()))
5117 /// matches "_Atomic(int) i"
5119 /// Usable as: Matcher<AtomicType>
5120 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5121 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5123 /// Matches types nodes representing C++11 auto types.
5128 /// int v[] = { 2, 3 }
5129 /// for (auto i : v) { }
5132 /// matches "auto n" and "auto i"
5133 extern const AstTypeMatcher<AutoType> autoType;
5135 /// Matches types nodes representing C++11 decltype(<expr>) types.
5141 /// decltype(i + j) result = i + j;
5144 /// matches "decltype(i + j)"
5145 extern const AstTypeMatcher<DecltypeType> decltypeType;
5147 /// Matches \c AutoType nodes where the deduced type is a specific type.
5149 /// Note: There is no \c TypeLoc for the deduced type and thus no
5150 /// \c getDeducedLoc() matcher.
5157 /// autoType(hasDeducedType(isInteger()))
5158 /// matches "auto a"
5160 /// Usable as: Matcher<AutoType>
5161 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5162 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5164 /// Matches \c DecltypeType nodes to find out the underlying type.
5168 /// decltype(1) a = 1;
5169 /// decltype(2.0) b = 2.0;
5171 /// decltypeType(hasUnderlyingType(isInteger()))
5172 /// matches "auto a"
5174 /// Usable as: Matcher<DecltypeType>
5175 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
5176 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
5178 /// Matches \c FunctionType nodes.
5186 /// matches "int (*f)(int)" and the type of "g".
5187 extern const AstTypeMatcher<FunctionType> functionType;
5189 /// Matches \c FunctionProtoType nodes.
5196 /// functionProtoType()
5197 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
5198 /// In C mode, "g" is not matched because it does not contain a prototype.
5199 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
5201 /// Matches \c ParenType nodes.
5205 /// int (*ptr_to_array)[4];
5206 /// int *array_of_ptrs[4];
5209 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
5210 /// \c array_of_ptrs.
5211 extern const AstTypeMatcher<ParenType> parenType;
5213 /// Matches \c ParenType nodes where the inner type is a specific type.
5217 /// int (*ptr_to_array)[4];
5218 /// int (*ptr_to_func)(int);
5221 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5222 /// \c ptr_to_func but not \c ptr_to_array.
5224 /// Usable as: Matcher<ParenType>
5225 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5226 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5228 /// Matches block pointer types, i.e. types syntactically represented as
5229 /// "void (^)(int)".
5231 /// The \c pointee is always required to be a \c FunctionType.
5232 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5234 /// Matches member pointer types.
5237 /// struct A { int i; }
5238 /// A::* ptr = A::i;
5240 /// memberPointerType()
5241 /// matches "A::* ptr"
5242 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5244 /// Matches pointer types, but does not match Objective-C object pointer
5258 /// matches "int *a", but does not match "Foo *f".
5259 extern const AstTypeMatcher<PointerType> pointerType;
5261 /// Matches an Objective-C object pointer type, which is different from
5262 /// a pointer type, despite being syntactically similar.
5273 /// matches "Foo *f", but does not match "int *a".
5274 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5276 /// Matches both lvalue and rvalue reference types.
5289 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5290 extern const AstTypeMatcher<ReferenceType> referenceType;
5292 /// Matches lvalue reference types.
5305 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5306 /// matched since the type is deduced as int& by reference collapsing rules.
5307 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5309 /// Matches rvalue reference types.
5322 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5323 /// matched as it is deduced to int& by reference collapsing rules.
5324 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5326 /// Narrows PointerType (and similar) matchers to those where the
5327 /// \c pointee matches a given matcher.
5335 /// pointerType(pointee(isConstQualified(), isInteger()))
5336 /// matches "int const *b"
5338 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5339 /// Matcher<PointerType>, Matcher<ReferenceType>
5340 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5341 pointee, getPointee,
5342 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5343 PointerType, ReferenceType));
5345 /// Matches typedef types.
5352 /// matches "typedef int X"
5353 extern const AstTypeMatcher<TypedefType> typedefType;
5355 /// Matches enum types.
5359 /// enum C { Green };
5360 /// enum class S { Red };
5366 /// \c enumType() matches the type of the variable declarations of both \c c and
5368 extern const AstTypeMatcher<EnumType> enumType;
5370 /// Matches template specialization types.
5374 /// template <typename T>
5377 /// template class C<int>; // A
5378 /// C<char> var; // B
5381 /// \c templateSpecializationType() matches the type of the explicit
5382 /// instantiation in \c A and the type of the variable declaration in \c B.
5383 extern const AstTypeMatcher<TemplateSpecializationType>
5384 templateSpecializationType;
5386 /// Matches types nodes representing unary type transformations.
5390 /// typedef __underlying_type(T) type;
5392 /// unaryTransformType()
5393 /// matches "__underlying_type(T)"
5394 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5396 /// Matches record types (e.g. structs, classes).
5407 /// \c recordType() matches the type of the variable declarations of both \c c
5409 extern const AstTypeMatcher<RecordType> recordType;
5411 /// Matches tag types (record and enum types).
5422 /// \c tagType() matches the type of the variable declarations of both \c e
5424 extern const AstTypeMatcher<TagType> tagType;
5426 /// Matches types specified with an elaborated type keyword or with a
5442 /// \c elaboratedType() matches the type of the variable declarations of both
5444 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5446 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5447 /// matches \c InnerMatcher if the qualifier exists.
5459 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5460 /// matches the type of the variable declaration of \c d.
5461 AST_MATCHER_P(ElaboratedType, hasQualifier,
5462 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5463 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5464 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5469 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5481 /// \c elaboratedType(namesType(recordType(
5482 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5483 /// declaration of \c d.
5484 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5486 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5489 /// Matches types that represent the result of substituting a type for a
5490 /// template type parameter.
5494 /// template <typename T>
5500 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5501 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5502 substTemplateTypeParmType;
5504 /// Matches template type parameter substitutions that have a replacement
5505 /// type that matches the provided matcher.
5509 /// template <typename T>
5512 /// double j = F(i);
5515 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5516 AST_TYPE_TRAVERSE_MATCHER(
5517 hasReplacementType, getReplacementType,
5518 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5520 /// Matches template type parameter types.
5522 /// Example matches T, but not int.
5523 /// (matcher = templateTypeParmType())
5525 /// template <typename T> void f(int i);
5527 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5529 /// Matches injected class name types.
5531 /// Example matches S s, but not S<T> s.
5532 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5534 /// template <typename T> struct S {
5539 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5541 /// Matches decayed type
5542 /// Example matches i[] in declaration of f.
5543 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5544 /// Example matches i[1].
5545 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5547 /// void f(int i[]) {
5551 extern const AstTypeMatcher<DecayedType> decayedType;
5553 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
5554 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5556 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5559 /// Matches declarations whose declaration context, interpreted as a
5560 /// Decl, matches \c InnerMatcher.
5571 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5572 /// declaration of \c class \c D.
5573 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5574 const DeclContext *DC = Node.getDeclContext();
5575 if (!DC) return false;
5576 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5579 /// Matches nested name specifiers.
5584 /// struct A { static void f(); };
5586 /// void g() { A::f(); }
5590 /// nestedNameSpecifier()
5591 /// matches "ns::" and both "A::"
5592 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
5593 nestedNameSpecifier;
5595 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5596 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
5597 nestedNameSpecifierLoc;
5599 /// Matches \c NestedNameSpecifierLocs for which the given inner
5600 /// NestedNameSpecifier-matcher matches.
5601 AST_MATCHER_FUNCTION_P_OVERLOAD(
5602 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5603 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5604 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5605 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5609 /// Matches nested name specifiers that specify a type matching the
5610 /// given \c QualType matcher without qualifiers.
5614 /// struct A { struct B { struct C {}; }; };
5617 /// nestedNameSpecifier(specifiesType(
5618 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5621 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5622 internal::Matcher<QualType>, InnerMatcher) {
5623 if (!Node.getAsType())
5625 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5628 /// Matches nested name specifier locs that specify a type matching the
5629 /// given \c TypeLoc.
5633 /// struct A { struct B { struct C {}; }; };
5636 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5637 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5639 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5640 internal::Matcher<TypeLoc>, InnerMatcher) {
5641 return Node && Node.getNestedNameSpecifier()->getAsType() &&
5642 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5645 /// Matches on the prefix of a \c NestedNameSpecifier.
5649 /// struct A { struct B { struct C {}; }; };
5652 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5654 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5655 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5657 const NestedNameSpecifier *NextNode = Node.getPrefix();
5660 return InnerMatcher.matches(*NextNode, Finder, Builder);
5663 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
5667 /// struct A { struct B { struct C {}; }; };
5670 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5672 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5673 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5675 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5678 return InnerMatcher.matches(NextNode, Finder, Builder);
5681 /// Matches nested name specifiers that specify a namespace matching the
5682 /// given namespace matcher.
5686 /// namespace ns { struct A {}; }
5689 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5691 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5692 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5693 if (!Node.getAsNamespace())
5695 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5698 /// Overloads for the \c equalsNode matcher.
5699 /// FIXME: Implement for other node types.
5702 /// Matches if a node equals another node.
5704 /// \c Decl has pointer identity in the AST.
5705 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5706 return &Node == Other;
5708 /// Matches if a node equals another node.
5710 /// \c Stmt has pointer identity in the AST.
5711 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5712 return &Node == Other;
5714 /// Matches if a node equals another node.
5716 /// \c Type has pointer identity in the AST.
5717 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5718 return &Node == Other;
5723 /// Matches each case or default statement belonging to the given switch
5724 /// statement. This matcher may produce multiple matches.
5728 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5730 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5731 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5732 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5733 /// "switch (1)", "switch (2)" and "switch (2)".
5734 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5736 BoundNodesTreeBuilder Result;
5737 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5738 // iteration order. We should use the more general iterating matchers once
5739 // they are capable of expressing this matcher (for example, it should ignore
5740 // case statements belonging to nested switch statements).
5741 bool Matched = false;
5742 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5743 SC = SC->getNextSwitchCase()) {
5744 BoundNodesTreeBuilder CaseBuilder(*Builder);
5745 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5748 Result.addMatch(CaseBuilder);
5751 *Builder = std::move(Result);
5755 /// Matches each constructor initializer in a constructor definition.
5759 /// class A { A() : i(42), j(42) {} int i; int j; };
5761 /// cxxConstructorDecl(forEachConstructorInitializer(
5762 /// forField(decl().bind("x"))
5764 /// will trigger two matches, binding for 'i' and 'j' respectively.
5765 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5766 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5767 BoundNodesTreeBuilder Result;
5768 bool Matched = false;
5769 for (const auto *I : Node.inits()) {
5770 BoundNodesTreeBuilder InitBuilder(*Builder);
5771 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5773 Result.addMatch(InitBuilder);
5776 *Builder = std::move(Result);
5780 /// Matches constructor declarations that are copy constructors.
5786 /// S(const S &); // #2
5790 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
5791 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
5792 return Node.isCopyConstructor();
5795 /// Matches constructor declarations that are move constructors.
5801 /// S(const S &); // #2
5805 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
5806 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
5807 return Node.isMoveConstructor();
5810 /// Matches constructor declarations that are default constructors.
5816 /// S(const S &); // #2
5820 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
5821 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
5822 return Node.isDefaultConstructor();
5825 /// Matches constructors that delegate to another constructor.
5832 /// S(S &&) : S() {} // #3
5834 /// S::S() : S(0) {} // #4
5836 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
5838 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
5839 return Node.isDelegatingConstructor();
5842 /// Matches constructor and conversion declarations that are marked with
5843 /// the explicit keyword.
5849 /// explicit S(double); // #2
5850 /// operator int(); // #3
5851 /// explicit operator bool(); // #4
5854 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
5855 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
5856 AST_POLYMORPHIC_MATCHER(isExplicit,
5857 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
5858 CXXConversionDecl)) {
5859 return Node.isExplicit();
5862 /// Matches function and namespace declarations that are marked with
5863 /// the inline keyword.
5867 /// inline void f();
5870 /// inline namespace m {}
5873 /// functionDecl(isInline()) will match ::f().
5874 /// namespaceDecl(isInline()) will match n::m.
5875 AST_POLYMORPHIC_MATCHER(isInline,
5876 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
5878 // This is required because the spelling of the function used to determine
5879 // whether inline is specified or not differs between the polymorphic types.
5880 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
5881 return FD->isInlineSpecified();
5882 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
5883 return NSD->isInline();
5884 llvm_unreachable("Not a valid polymorphic type");
5887 /// Matches anonymous namespace declarations.
5892 /// namespace {} // #1
5895 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
5896 AST_MATCHER(NamespaceDecl, isAnonymous) {
5897 return Node.isAnonymousNamespace();
5900 /// If the given case statement does not use the GNU case range
5901 /// extension, matches the constant given in the statement.
5905 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
5907 /// caseStmt(hasCaseConstant(integerLiteral()))
5908 /// matches "case 1:"
5909 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
5914 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
5917 /// Matches declaration that has a given attribute.
5921 /// __attribute__((device)) void f() { ... }
5923 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
5924 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
5925 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
5926 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
5927 for (const auto *Attr : Node.attrs()) {
5928 if (Attr->getKind() == AttrKind)
5934 /// Matches the return value expression of a return statement
5940 /// hasReturnValue(binaryOperator())
5941 /// matches 'return a + b'
5942 /// with binaryOperator()
5943 /// matching 'a + b'
5944 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5946 if (const auto *RetValue = Node.getRetValue())
5947 return InnerMatcher.matches(*RetValue, Finder, Builder);
5951 /// Matches CUDA kernel call expression.
5953 /// Example matches,
5955 /// kernel<<<i,j>>>();
5957 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
5960 /// Matches expressions that resolve to a null pointer constant, such as
5961 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5965 /// void *v1 = NULL;
5966 /// void *v2 = nullptr;
5967 /// void *v3 = __null; // GNU extension
5968 /// char *cp = (char *)0;
5972 /// expr(nullPointerConstant())
5973 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5974 /// initializer for i.
5975 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5977 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5978 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5981 /// Matches declaration of the function the statement belongs to
5985 /// F& operator=(const F& o) {
5986 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
5990 /// returnStmt(forFunction(hasName("operator=")))
5991 /// matches 'return *this'
5992 /// but does match 'return > 0'
5993 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
5995 const auto &Parents = Finder->getASTContext().getParents(Node);
5997 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
5999 while(!Stack.empty()) {
6000 const auto &CurNode = Stack.back();
6002 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6003 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6006 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6007 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6012 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6013 Stack.push_back(Parent);
6019 /// Matches a declaration that has external formal linkage.
6021 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6030 /// Example matches f() because it has external formal linkage despite being
6031 /// unique to the translation unit as though it has internal likage
6032 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6039 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6040 return Node.hasExternalFormalLinkage();
6043 /// Matches a declaration that has default arguments.
6045 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6047 /// void x(int val) {}
6048 /// void y(int val = 0) {}
6050 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6051 return Node.hasDefaultArg();
6054 /// Matches array new expressions.
6058 /// MyClass *p1 = new MyClass[10];
6060 /// cxxNewExpr(isArray())
6061 /// matches the expression 'new MyClass[10]'.
6062 AST_MATCHER(CXXNewExpr, isArray) {
6063 return Node.isArray();
6066 /// Matches array new expressions with a given array size.
6070 /// MyClass *p1 = new MyClass[10];
6072 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
6073 /// matches the expression 'new MyClass[10]'.
6074 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
6075 return Node.isArray() &&
6076 InnerMatcher.matches(*Node.getArraySize(), Finder, Builder);
6079 /// Matches a class declaration that is defined.
6081 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
6086 AST_MATCHER(CXXRecordDecl, hasDefinition) {
6087 return Node.hasDefinition();
6090 /// Matches C++11 scoped enum declaration.
6092 /// Example matches Y (matcher = enumDecl(isScoped()))
6095 /// enum class Y {};
6097 AST_MATCHER(EnumDecl, isScoped) {
6098 return Node.isScoped();
6101 /// Matches a function declared with a trailing return type.
6103 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
6106 /// auto Y() -> int {}
6108 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
6109 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
6110 return F->hasTrailingReturn();
6114 } // namespace ast_matchers
6115 } // namespace clang
6117 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H