1 //===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements matchers to be used together with the MatchFinder to
12 // Matchers are created by generator functions, which can be combined in
13 // a functional in-language DSL to express queries over the C++ AST.
15 // For example, to match a class with a certain name, one would call:
16 // cxxRecordDecl(hasName("MyClass"))
17 // which returns a matcher that can be used to find all AST nodes that declare
18 // a class named 'MyClass'.
20 // For more complicated match expressions we're often interested in accessing
21 // multiple parts of the matched AST nodes once a match is found. In that case,
22 // call `.bind("name")` on match expressions that match the nodes you want to
25 // For example, when we're interested in child classes of a certain class, we
27 // cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child")))
28 // When the match is found via the MatchFinder, a user provided callback will
29 // be called with a BoundNodes instance that contains a mapping from the
30 // strings that we provided for the `.bind()` calls to the nodes that were
32 // In the given example, each time our matcher finds a match we get a callback
33 // where "child" is bound to the RecordDecl node of the matching child
36 // See ASTMatchersInternal.h for a more in-depth explanation of the
37 // implementation details of the matcher framework.
39 // See ASTMatchFinder.h for how to use the generated matchers to run over
42 //===----------------------------------------------------------------------===//
44 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
45 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
47 #include "clang/AST/ASTContext.h"
48 #include "clang/AST/ASTTypeTraits.h"
49 #include "clang/AST/Attr.h"
50 #include "clang/AST/CXXInheritance.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/LambdaCapture.h"
60 #include "clang/AST/NestedNameSpecifier.h"
61 #include "clang/AST/OpenMPClause.h"
62 #include "clang/AST/OperationKinds.h"
63 #include "clang/AST/ParentMapContext.h"
64 #include "clang/AST/Stmt.h"
65 #include "clang/AST/StmtCXX.h"
66 #include "clang/AST/StmtObjC.h"
67 #include "clang/AST/StmtOpenMP.h"
68 #include "clang/AST/TemplateBase.h"
69 #include "clang/AST/TemplateName.h"
70 #include "clang/AST/Type.h"
71 #include "clang/AST/TypeLoc.h"
72 #include "clang/ASTMatchers/ASTMatchersInternal.h"
73 #include "clang/ASTMatchers/ASTMatchersMacros.h"
74 #include "clang/Basic/AttrKinds.h"
75 #include "clang/Basic/ExceptionSpecificationType.h"
76 #include "clang/Basic/FileManager.h"
77 #include "clang/Basic/IdentifierTable.h"
78 #include "clang/Basic/LLVM.h"
79 #include "clang/Basic/SourceManager.h"
80 #include "clang/Basic/Specifiers.h"
81 #include "clang/Basic/TypeTraits.h"
82 #include "llvm/ADT/ArrayRef.h"
83 #include "llvm/ADT/SmallVector.h"
84 #include "llvm/ADT/StringRef.h"
85 #include "llvm/Support/Casting.h"
86 #include "llvm/Support/Compiler.h"
87 #include "llvm/Support/ErrorHandling.h"
88 #include "llvm/Support/Regex.h"
98 namespace ast_matchers {
100 /// Maps string IDs to AST nodes matched by parts of a matcher.
102 /// The bound nodes are generated by calling \c bind("id") on the node matchers
103 /// of the nodes we want to access later.
105 /// The instances of BoundNodes are created by \c MatchFinder when the user's
106 /// callbacks are executed every time a match is found.
109 /// Returns the AST node bound to \c ID.
111 /// Returns NULL if there was no node bound to \c ID or if there is a node but
112 /// it cannot be converted to the specified type.
113 template <typename T>
114 const T *getNodeAs(StringRef ID) const {
115 return MyBoundNodes.getNodeAs<T>(ID);
118 /// Type of mapping from binding identifiers to bound nodes. This type
119 /// is an associative container with a key type of \c std::string and a value
120 /// type of \c clang::DynTypedNode
121 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
123 /// Retrieve mapping from binding identifiers to bound nodes.
124 const IDToNodeMap &getMap() const {
125 return MyBoundNodes.getMap();
129 friend class internal::BoundNodesTreeBuilder;
131 /// Create BoundNodes from a pre-filled map of bindings.
132 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
133 : MyBoundNodes(MyBoundNodes) {}
135 internal::BoundNodesMap MyBoundNodes;
138 /// Types of matchers for the top-level classes in the AST class
141 using DeclarationMatcher = internal::Matcher<Decl>;
142 using StatementMatcher = internal::Matcher<Stmt>;
143 using TypeMatcher = internal::Matcher<QualType>;
144 using TypeLocMatcher = internal::Matcher<TypeLoc>;
145 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
146 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
147 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
150 /// Matches any node.
152 /// Useful when another matcher requires a child matcher, but there's no
153 /// additional constraint. This will often be used with an explicit conversion
154 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
156 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
158 /// "int* p" and "void f()" in
163 /// Usable as: Any Matcher
164 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
166 /// Matches the top declaration context.
173 /// } // namespace NS
175 /// decl(hasDeclContext(translationUnitDecl()))
176 /// matches "int X", but not "int Y".
177 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
180 /// Matches typedef declarations.
188 /// matches "typedef int X", but not "using Y = int"
189 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
192 /// Matches typedef name declarations.
199 /// typedefNameDecl()
200 /// matches "typedef int X" and "using Y = int"
201 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
204 /// Matches type alias declarations.
212 /// matches "using Y = int", but not "typedef int X"
213 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
216 /// Matches type alias template declarations.
218 /// typeAliasTemplateDecl() matches
220 /// template <typename T>
223 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
224 typeAliasTemplateDecl;
226 /// Matches AST nodes that were expanded within the main-file.
228 /// Example matches X but not Y
229 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
239 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
240 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
241 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
242 auto &SourceManager = Finder->getASTContext().getSourceManager();
243 return SourceManager.isInMainFile(
244 SourceManager.getExpansionLoc(Node.getBeginLoc()));
247 /// Matches AST nodes that were expanded within system-header-files.
249 /// Example matches Y but not X
250 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
252 /// #include <SystemHeader.h>
260 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
261 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
262 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
263 auto &SourceManager = Finder->getASTContext().getSourceManager();
264 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
265 if (ExpansionLoc.isInvalid()) {
268 return SourceManager.isInSystemHeader(ExpansionLoc);
271 /// Matches AST nodes that were expanded within files whose name is
272 /// partially matching a given regex.
274 /// Example matches Y but not X
275 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
277 /// #include "ASTMatcher.h"
285 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
286 AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
287 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt,
290 auto &SourceManager = Finder->getASTContext().getSourceManager();
291 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
292 if (ExpansionLoc.isInvalid()) {
296 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
301 auto Filename = FileEntry->getName();
302 return RegExp->match(Filename);
305 /// Matches statements that are (transitively) expanded from the named macro.
306 /// Does not match if only part of the statement is expanded from that macro or
307 /// if different parts of the the statement are expanded from different
308 /// appearances of the macro.
310 /// FIXME: Change to be a polymorphic matcher that works on any syntactic
311 /// node. There's nothing `Stmt`-specific about it.
312 AST_MATCHER_P(Stmt, isExpandedFromMacro, llvm::StringRef, MacroName) {
313 // Verifies that the statement' beginning and ending are both expanded from
314 // the same instance of the given macro.
315 auto& Context = Finder->getASTContext();
316 llvm::Optional<SourceLocation> B =
317 internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
318 if (!B) return false;
319 llvm::Optional<SourceLocation> E =
320 internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
321 if (!E) return false;
325 /// Matches declarations.
327 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
334 extern const internal::VariadicAllOfMatcher<Decl> decl;
336 /// Matches a declaration of a linkage specification.
342 /// linkageSpecDecl()
343 /// matches "extern "C" {}"
344 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
347 /// Matches a declaration of anything that could have a name.
349 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
358 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
360 /// Matches a declaration of label.
369 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
371 /// Matches a declaration of a namespace.
376 /// namespace test {}
379 /// matches "namespace {}" and "namespace test {}"
380 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
383 /// Matches a declaration of a namespace alias.
387 /// namespace test {}
388 /// namespace alias = ::test;
390 /// namespaceAliasDecl()
391 /// matches "namespace alias" but not "namespace test"
392 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
395 /// Matches class, struct, and union declarations.
397 /// Example matches \c X, \c Z, \c U, and \c S
400 /// template<class T> class Z {};
404 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
406 /// Matches C++ class declarations.
408 /// Example matches \c X, \c Z
411 /// template<class T> class Z {};
413 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
416 /// Matches C++ class template declarations.
418 /// Example matches \c Z
420 /// template<class T> class Z {};
422 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
425 /// Matches C++ class template specializations.
429 /// template<typename T> class A {};
430 /// template<> class A<double> {};
433 /// classTemplateSpecializationDecl()
434 /// matches the specializations \c A<int> and \c A<double>
435 extern const internal::VariadicDynCastAllOfMatcher<
436 Decl, ClassTemplateSpecializationDecl>
437 classTemplateSpecializationDecl;
439 /// Matches C++ class template partial specializations.
443 /// template<class T1, class T2, int I>
446 /// template<class T, int I>
447 /// class A<T, T*, I> {};
450 /// class A<int, int, 1> {};
452 /// classTemplatePartialSpecializationDecl()
453 /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
454 extern const internal::VariadicDynCastAllOfMatcher<
455 Decl, ClassTemplatePartialSpecializationDecl>
456 classTemplatePartialSpecializationDecl;
458 /// Matches declarator declarations (field, variable, function
459 /// and non-type template parameter declarations).
463 /// class X { int y; };
466 /// matches \c int y.
467 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
470 /// Matches parameter variable declarations.
477 /// matches \c int x.
478 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
481 /// Matches C++ access specifier declarations.
491 /// matches 'public:'
492 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
495 /// Matches constructor initializers.
497 /// Examples matches \c i(42).
504 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
507 /// Matches template arguments.
511 /// template <typename T> struct C {};
514 /// templateArgument()
515 /// matches 'int' in C<int>.
516 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
518 /// Matches template name.
522 /// template <typename T> class X { };
526 /// matches 'X' in X<int>.
527 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
529 /// Matches non-type template parameter declarations.
533 /// template <typename T, int N> struct C {};
535 /// nonTypeTemplateParmDecl()
536 /// matches 'N', but not 'T'.
537 extern const internal::VariadicDynCastAllOfMatcher<Decl,
538 NonTypeTemplateParmDecl>
539 nonTypeTemplateParmDecl;
541 /// Matches template type parameter declarations.
545 /// template <typename T, int N> struct C {};
547 /// templateTypeParmDecl()
548 /// matches 'T', but not 'N'.
549 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
550 templateTypeParmDecl;
552 /// Matches public C++ declarations and C++ base specifers that specify public
558 /// public: int a; // fieldDecl(isPublic()) matches 'a'
559 /// protected: int b;
566 /// class Derived1 : public Base {}; // matches 'Base'
567 /// struct Derived2 : Base {}; // matches 'Base'
569 AST_POLYMORPHIC_MATCHER(isPublic,
570 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
572 return getAccessSpecifier(Node) == AS_public;
575 /// Matches protected C++ declarations and C++ base specifers that specify
576 /// protected inheritance.
582 /// protected: int b; // fieldDecl(isProtected()) matches 'b'
589 /// class Derived : protected Base {}; // matches 'Base'
591 AST_POLYMORPHIC_MATCHER(isProtected,
592 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
594 return getAccessSpecifier(Node) == AS_protected;
597 /// Matches private C++ declarations and C++ base specifers that specify private
604 /// protected: int b;
605 /// private: int c; // fieldDecl(isPrivate()) matches 'c'
611 /// struct Derived1 : private Base {}; // matches 'Base'
612 /// class Derived2 : Base {}; // matches 'Base'
614 AST_POLYMORPHIC_MATCHER(isPrivate,
615 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
617 return getAccessSpecifier(Node) == AS_private;
620 /// Matches non-static data members that are bit-fields.
629 /// fieldDecl(isBitField())
630 /// matches 'int a;' but not 'int b;'.
631 AST_MATCHER(FieldDecl, isBitField) {
632 return Node.isBitField();
635 /// Matches non-static data members that are bit-fields of the specified
646 /// fieldDecl(hasBitWidth(2))
647 /// matches 'int a;' and 'int c;' but not 'int b;'.
648 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
649 return Node.isBitField() &&
650 Node.getBitWidthValue(Finder->getASTContext()) == Width;
653 /// Matches non-static data members that have an in-class initializer.
663 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
664 /// matches 'int a;' but not 'int b;'.
665 /// fieldDecl(hasInClassInitializer(anything()))
666 /// matches 'int a;' and 'int b;' but not 'int c;'.
667 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
669 const Expr *Initializer = Node.getInClassInitializer();
670 return (Initializer != nullptr &&
671 InnerMatcher.matches(*Initializer, Finder, Builder));
674 /// Determines whether the function is "main", which is the entry point
675 /// into an executable program.
676 AST_MATCHER(FunctionDecl, isMain) {
677 return Node.isMain();
680 /// Matches the specialized template of a specialization declaration.
684 /// template<typename T> class A {}; #1
685 /// template<> class A<int> {}; #2
687 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
688 /// matches '#2' with classTemplateDecl() matching the class template
689 /// declaration of 'A' at #1.
690 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
691 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
692 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
693 return (Decl != nullptr &&
694 InnerMatcher.matches(*Decl, Finder, Builder));
697 /// Matches a declaration that has been implicitly added
698 /// by the compiler (eg. implicit default/copy constructors).
699 AST_MATCHER(Decl, isImplicit) {
700 return Node.isImplicit();
703 /// Matches classTemplateSpecializations, templateSpecializationType and
704 /// functionDecl that have at least one TemplateArgument matching the given
709 /// template<typename T> class A {};
710 /// template<> class A<double> {};
713 /// template<typename T> f() {};
714 /// void func() { f<int>(); };
718 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
719 /// refersToType(asString("int"))))
720 /// matches the specialization \c A<int>
722 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
723 /// matches the specialization \c f<int>
724 AST_POLYMORPHIC_MATCHER_P(
725 hasAnyTemplateArgument,
726 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
727 TemplateSpecializationType,
729 internal::Matcher<TemplateArgument>, InnerMatcher) {
730 ArrayRef<TemplateArgument> List =
731 internal::getTemplateSpecializationArgs(Node);
732 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
736 /// Causes all nested matchers to be matched with the specified traversal kind.
747 /// traverse(TK_IgnoreImplicitCastsAndParentheses,
748 /// varDecl(hasInitializer(floatLiteral().bind("init")))
751 /// matches the variable declaration with "init" bound to the "3.0".
752 template <typename T>
753 internal::Matcher<T> traverse(TraversalKind TK,
754 const internal::Matcher<T> &InnerMatcher) {
755 return internal::DynTypedMatcher::constructRestrictedWrapper(
756 new internal::TraversalMatcher<T>(TK, InnerMatcher),
757 InnerMatcher.getID().first)
758 .template unconditionalConvertTo<T>();
761 template <typename T>
762 internal::BindableMatcher<T>
763 traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
764 return internal::BindableMatcher<T>(
765 internal::DynTypedMatcher::constructRestrictedWrapper(
766 new internal::TraversalMatcher<T>(TK, InnerMatcher),
767 InnerMatcher.getID().first)
768 .template unconditionalConvertTo<T>());
771 template <typename... T>
772 internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
773 traverse(TraversalKind TK,
774 const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
775 return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
779 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
780 typename T, typename ToTypes>
781 internal::TraversalWrapper<
782 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
783 traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
784 ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
785 return internal::TraversalWrapper<
786 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
787 ToTypes>>(TK, InnerMatcher);
790 template <template <typename T, typename P1> class MatcherT, typename P1,
791 typename ReturnTypesF>
792 internal::TraversalWrapper<
793 internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>
794 traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam1<
795 MatcherT, P1, ReturnTypesF> &InnerMatcher) {
796 return internal::TraversalWrapper<
797 internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>(
801 template <template <typename T, typename P1, typename P2> class MatcherT,
802 typename P1, typename P2, typename ReturnTypesF>
803 internal::TraversalWrapper<
804 internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>
805 traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
806 MatcherT, P1, P2, ReturnTypesF> &InnerMatcher) {
807 return internal::TraversalWrapper<
808 internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>(
812 /// Matches expressions that match InnerMatcher after any implicit AST
813 /// nodes are stripped off.
815 /// Parentheses and explicit casts are not discarded.
825 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
827 /// would match the declarations for a, b, and c.
830 /// varDecl(hasInitializer(cxxConstructExpr()))
832 /// only match the declarations for b and c.
833 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
835 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
838 /// Matches expressions that match InnerMatcher after any implicit casts
839 /// are stripped off.
841 /// Parentheses and explicit casts are not discarded.
849 /// long e = (long) 0l;
853 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
854 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
856 /// would match the declarations for a, b, c, and d, but not e.
859 /// varDecl(hasInitializer(integerLiteral()))
860 /// varDecl(hasInitializer(declRefExpr()))
862 /// only match the declarations for b, c, and d.
863 AST_MATCHER_P(Expr, ignoringImpCasts,
864 internal::Matcher<Expr>, InnerMatcher) {
865 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
868 /// Matches expressions that match InnerMatcher after parentheses and
869 /// casts are stripped off.
871 /// Implicit and non-C Style casts are also discarded.
876 /// void* c = reinterpret_cast<char*>(0);
877 /// char d = char(0);
880 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
881 /// would match the declarations for a, b, c, and d.
883 /// varDecl(hasInitializer(integerLiteral()))
884 /// only match the declaration for a.
885 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
886 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
889 /// Matches expressions that match InnerMatcher after implicit casts and
890 /// parentheses are stripped off.
892 /// Explicit casts are not discarded.
900 /// long e = ((long) 0l);
903 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
904 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
905 /// would match the declarations for a, b, c, and d, but not e.
907 /// varDecl(hasInitializer(integerLiteral()))
908 /// varDecl(hasInitializer(declRefExpr()))
909 /// would only match the declaration for a.
910 AST_MATCHER_P(Expr, ignoringParenImpCasts,
911 internal::Matcher<Expr>, InnerMatcher) {
912 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
915 /// Matches types that match InnerMatcher after any parens are stripped.
919 /// void (*fp)(void);
923 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
925 /// would match the declaration for fp.
926 AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
928 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
931 /// Overload \c ignoringParens for \c Expr.
935 /// const char* str = ("my-string");
939 /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
941 /// would match the implicit cast resulting from the assignment.
942 AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
944 const Expr *E = Node.IgnoreParens();
945 return InnerMatcher.matches(*E, Finder, Builder);
948 /// Matches expressions that are instantiation-dependent even if it is
949 /// neither type- nor value-dependent.
951 /// In the following example, the expression sizeof(sizeof(T() + T()))
952 /// is instantiation-dependent (since it involves a template parameter T),
953 /// but is neither type- nor value-dependent, since the type of the inner
954 /// sizeof is known (std::size_t) and therefore the size of the outer
957 /// template<typename T>
958 /// void f(T x, T y) { sizeof(sizeof(T() + T()); }
960 /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
961 AST_MATCHER(Expr, isInstantiationDependent) {
962 return Node.isInstantiationDependent();
965 /// Matches expressions that are type-dependent because the template type
966 /// is not yet instantiated.
968 /// For example, the expressions "x" and "x + y" are type-dependent in
969 /// the following code, but "y" is not type-dependent:
971 /// template<typename T>
972 /// void add(T x, int y) {
976 /// expr(isTypeDependent()) matches x + y
977 AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
979 /// Matches expression that are value-dependent because they contain a
980 /// non-type template parameter.
982 /// For example, the array bound of "Chars" in the following example is
985 /// template<int Size> int f() { return Size; }
987 /// expr(isValueDependent()) matches return Size
988 AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
990 /// Matches classTemplateSpecializations, templateSpecializationType and
991 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
995 /// template<typename T, typename U> class A {};
999 /// template<typename T> void f() {}
1000 /// void func() { f<int>(); };
1002 /// classTemplateSpecializationDecl(hasTemplateArgument(
1003 /// 1, refersToType(asString("int"))))
1004 /// matches the specialization \c A<bool, int>
1006 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1007 /// matches the specialization \c f<int>
1008 AST_POLYMORPHIC_MATCHER_P2(
1009 hasTemplateArgument,
1010 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
1011 TemplateSpecializationType,
1013 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1014 ArrayRef<TemplateArgument> List =
1015 internal::getTemplateSpecializationArgs(Node);
1016 if (List.size() <= N)
1018 return InnerMatcher.matches(List[N], Finder, Builder);
1021 /// Matches if the number of template arguments equals \p N.
1025 /// template<typename T> struct C {};
1028 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1030 AST_POLYMORPHIC_MATCHER_P(
1031 templateArgumentCountIs,
1032 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
1033 TemplateSpecializationType),
1035 return internal::getTemplateSpecializationArgs(Node).size() == N;
1038 /// Matches a TemplateArgument that refers to a certain type.
1043 /// template<typename T> struct A {};
1046 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1047 /// refersToType(class(hasName("X")))))
1048 /// matches the specialization \c A<X>
1049 AST_MATCHER_P(TemplateArgument, refersToType,
1050 internal::Matcher<QualType>, InnerMatcher) {
1051 if (Node.getKind() != TemplateArgument::Type)
1053 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1056 /// Matches a TemplateArgument that refers to a certain template.
1060 /// template<template <typename> class S> class X {};
1061 /// template<typename T> class Y {};
1064 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1065 /// refersToTemplate(templateName())))
1066 /// matches the specialization \c X<Y>
1067 AST_MATCHER_P(TemplateArgument, refersToTemplate,
1068 internal::Matcher<TemplateName>, InnerMatcher) {
1069 if (Node.getKind() != TemplateArgument::Template)
1071 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1074 /// Matches a canonical TemplateArgument that refers to a certain
1079 /// struct B { int next; };
1080 /// template<int(B::*next_ptr)> struct A {};
1083 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1084 /// refersToDeclaration(fieldDecl(hasName("next")))))
1085 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1087 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1088 internal::Matcher<Decl>, InnerMatcher) {
1089 if (Node.getKind() == TemplateArgument::Declaration)
1090 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1094 /// Matches a sugar TemplateArgument that refers to a certain expression.
1098 /// struct B { int next; };
1099 /// template<int(B::*next_ptr)> struct A {};
1102 /// templateSpecializationType(hasAnyTemplateArgument(
1103 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1104 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1106 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1107 if (Node.getKind() == TemplateArgument::Expression)
1108 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1112 /// Matches a TemplateArgument that is an integral value.
1116 /// template<int T> struct C {};
1119 /// classTemplateSpecializationDecl(
1120 /// hasAnyTemplateArgument(isIntegral()))
1121 /// matches the implicit instantiation of C in C<42>
1122 /// with isIntegral() matching 42.
1123 AST_MATCHER(TemplateArgument, isIntegral) {
1124 return Node.getKind() == TemplateArgument::Integral;
1127 /// Matches a TemplateArgument that referes to an integral type.
1131 /// template<int T> struct C {};
1134 /// classTemplateSpecializationDecl(
1135 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1136 /// matches the implicit instantiation of C in C<42>.
1137 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1138 internal::Matcher<QualType>, InnerMatcher) {
1139 if (Node.getKind() != TemplateArgument::Integral)
1141 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1144 /// Matches a TemplateArgument of integral type with a given value.
1146 /// Note that 'Value' is a string as the template argument's value is
1147 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
1148 /// representation of that integral value in base 10.
1152 /// template<int T> struct C {};
1155 /// classTemplateSpecializationDecl(
1156 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
1157 /// matches the implicit instantiation of C in C<42>.
1158 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1159 std::string, Value) {
1160 if (Node.getKind() != TemplateArgument::Integral)
1162 return Node.getAsIntegral().toString(10) == Value;
1165 /// Matches an Objective-C autorelease pool statement.
1169 /// @autoreleasepool {
1173 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1174 /// inside the autorelease pool.
1175 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1176 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1178 /// Matches any value declaration.
1180 /// Example matches A, B, C and F
1182 /// enum X { A, B, C };
1185 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1187 /// Matches C++ constructor declarations.
1189 /// Example matches Foo::Foo() and Foo::Foo(int)
1195 /// int DoSomething();
1198 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1201 /// Matches explicit C++ destructor declarations.
1203 /// Example matches Foo::~Foo()
1210 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1213 /// Matches enum declarations.
1215 /// Example matches X
1221 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1223 /// Matches enum constants.
1225 /// Example matches A, B, C
1231 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1234 /// Matches tag declarations.
1236 /// Example matches X, Z, U, S, E
1239 /// template<class T> class Z {};
1246 extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1248 /// Matches method declarations.
1250 /// Example matches y
1252 /// class X { void y(); };
1254 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1257 /// Matches conversion operator declarations.
1259 /// Example matches the operator.
1261 /// class X { operator int() const; };
1263 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1266 /// Matches user-defined and implicitly generated deduction guide.
1268 /// Example matches the deduction guide.
1270 /// template<typename T>
1271 /// class X { X(int) };
1272 /// X(int) -> X<int>;
1274 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1275 cxxDeductionGuideDecl;
1277 /// Matches variable declarations.
1279 /// Note: this does not match declarations of member variables, which are
1280 /// "field" declarations in Clang parlance.
1282 /// Example matches a
1286 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1288 /// Matches field declarations.
1292 /// class X { int m; };
1296 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1298 /// Matches indirect field declarations.
1302 /// struct X { struct { int a; }; };
1304 /// indirectFieldDecl()
1306 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1309 /// Matches function declarations.
1311 /// Example matches f
1315 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1318 /// Matches C++ function template declarations.
1320 /// Example matches f
1322 /// template<class T> void f(T t) {}
1324 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1325 functionTemplateDecl;
1327 /// Matches friend declarations.
1331 /// class X { friend void foo(); };
1334 /// matches 'friend void foo()'.
1335 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1337 /// Matches statements.
1344 /// matches both the compound statement '{ ++a; }' and '++a'.
1345 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1347 /// Matches declaration statements.
1354 /// matches 'int a'.
1355 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1357 /// Matches member expressions.
1362 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1363 /// int a; static int b;
1367 /// matches this->x, x, y.x, a, this->b
1368 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1370 /// Matches unresolved member expressions.
1375 /// template <class T> void f();
1378 /// template <class T> void h() { X x; x.f<T>(); x.g(); }
1380 /// unresolvedMemberExpr()
1382 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1383 unresolvedMemberExpr;
1385 /// Matches member expressions where the actual member referenced could not be
1386 /// resolved because the base expression or the member name was dependent.
1390 /// template <class T> void f() { T t; t.g(); }
1392 /// cxxDependentScopeMemberExpr()
1394 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1395 CXXDependentScopeMemberExpr>
1396 cxxDependentScopeMemberExpr;
1398 /// Matches call expressions.
1400 /// Example matches x.y() and y()
1406 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1408 /// Matches call expressions which were resolved using ADL.
1410 /// Example matches y(x) but not y(42) or NS::y(x).
1421 /// y(x); // Matches
1422 /// NS::y(x); // Doesn't match
1423 /// y(42); // Doesn't match
1425 /// y(x); // Found by both unqualified lookup and ADL, doesn't match
1428 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1430 /// Matches lambda expressions.
1432 /// Example matches [&](){return 5;}
1434 /// [&](){return 5;}
1436 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1438 /// Matches member call expressions.
1440 /// Example matches x.y()
1445 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1448 /// Matches ObjectiveC Message invocation expressions.
1450 /// The innermost message send invokes the "alloc" class method on the
1451 /// NSString class, while the outermost message send invokes the
1452 /// "initWithString" instance method on the object returned from
1453 /// NSString's "alloc". This matcher should match both message sends.
1455 /// [[NSString alloc] initWithString:@"Hello"]
1457 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1460 /// Matches Objective-C interface declarations.
1462 /// Example matches Foo
1467 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1470 /// Matches Objective-C implementation declarations.
1472 /// Example matches Foo
1474 /// @implementation Foo
1477 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1478 objcImplementationDecl;
1480 /// Matches Objective-C protocol declarations.
1482 /// Example matches FooDelegate
1484 /// @protocol FooDelegate
1487 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1490 /// Matches Objective-C category declarations.
1492 /// Example matches Foo (Additions)
1494 /// @interface Foo (Additions)
1497 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1500 /// Matches Objective-C category definitions.
1502 /// Example matches Foo (Additions)
1504 /// @implementation Foo (Additions)
1507 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1508 objcCategoryImplDecl;
1510 /// Matches Objective-C method declarations.
1512 /// Example matches both declaration and definition of -[Foo method]
1518 /// @implementation Foo
1519 /// - (void)method {}
1522 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1525 /// Matches block declarations.
1527 /// Example matches the declaration of the nameless block printing an input
1531 /// myFunc(^(int p) {
1532 /// printf("%d", p);
1535 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1538 /// Matches Objective-C instance variable declarations.
1540 /// Example matches _enabled
1542 /// @implementation Foo {
1547 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1550 /// Matches Objective-C property declarations.
1552 /// Example matches enabled
1555 /// @property BOOL enabled;
1558 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1561 /// Matches Objective-C \@throw statements.
1563 /// Example matches \@throw
1567 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1570 /// Matches Objective-C @try statements.
1572 /// Example matches @try
1577 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1580 /// Matches Objective-C @catch statements.
1582 /// Example matches @catch
1587 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1590 /// Matches Objective-C @finally statements.
1592 /// Example matches @finally
1597 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1600 /// Matches expressions that introduce cleanups to be run at the end
1601 /// of the sub-expression's evaluation.
1603 /// Example matches std::string()
1605 /// const std::string str = std::string();
1607 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1610 /// Matches init list expressions.
1614 /// int a[] = { 1, 2 };
1615 /// struct B { int x, y; };
1619 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1620 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1623 /// Matches the syntactic form of init list expressions
1624 /// (if expression have it).
1625 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1626 internal::Matcher<Expr>, InnerMatcher) {
1627 const Expr *SyntForm = Node.getSyntacticForm();
1628 return (SyntForm != nullptr &&
1629 InnerMatcher.matches(*SyntForm, Finder, Builder));
1632 /// Matches C++ initializer list expressions.
1636 /// std::vector<int> a({ 1, 2, 3 });
1637 /// std::vector<int> b = { 4, 5 };
1638 /// int c[] = { 6, 7 };
1639 /// std::pair<int, int> d = { 8, 9 };
1641 /// cxxStdInitializerListExpr()
1642 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1643 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1644 CXXStdInitializerListExpr>
1645 cxxStdInitializerListExpr;
1647 /// Matches implicit initializers of init list expressions.
1651 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1653 /// implicitValueInitExpr()
1654 /// matches "[0].y" (implicitly)
1655 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1656 implicitValueInitExpr;
1658 /// Matches paren list expressions.
1659 /// ParenListExprs don't have a predefined type and are used for late parsing.
1660 /// In the final AST, they can be met in template declarations.
1664 /// template<typename T> class X {
1667 /// int a = 0, b = 1; int i = (a, b);
1671 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1672 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1673 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1676 /// Matches substitutions of non-type template parameters.
1680 /// template <int N>
1681 /// struct A { static const int n = N; };
1682 /// struct B : public A<42> {};
1684 /// substNonTypeTemplateParmExpr()
1685 /// matches "N" in the right-hand side of "static const int n = N;"
1686 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1687 SubstNonTypeTemplateParmExpr>
1688 substNonTypeTemplateParmExpr;
1690 /// Matches using declarations.
1694 /// namespace X { int x; }
1698 /// matches \code using X::x \endcode
1699 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1701 /// Matches using namespace declarations.
1705 /// namespace X { int x; }
1706 /// using namespace X;
1708 /// usingDirectiveDecl()
1709 /// matches \code using namespace X \endcode
1710 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1713 /// Matches reference to a name that can be looked up during parsing
1714 /// but could not be resolved to a specific declaration.
1718 /// template<typename T>
1719 /// T foo() { T a; return a; }
1720 /// template<typename T>
1725 /// unresolvedLookupExpr()
1726 /// matches \code foo<T>() \endcode
1727 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1728 unresolvedLookupExpr;
1730 /// Matches unresolved using value declarations.
1734 /// template<typename X>
1735 /// class C : private X {
1739 /// unresolvedUsingValueDecl()
1740 /// matches \code using X::x \endcode
1741 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1742 UnresolvedUsingValueDecl>
1743 unresolvedUsingValueDecl;
1745 /// Matches unresolved using value declarations that involve the
1750 /// template <typename T>
1751 /// struct Base { typedef T Foo; };
1753 /// template<typename T>
1754 /// struct S : private Base<T> {
1755 /// using typename Base<T>::Foo;
1758 /// unresolvedUsingTypenameDecl()
1759 /// matches \code using Base<T>::Foo \endcode
1760 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1761 UnresolvedUsingTypenameDecl>
1762 unresolvedUsingTypenameDecl;
1764 /// Matches a constant expression wrapper.
1766 /// Example matches the constant in the case statement:
1767 /// (matcher = constantExpr())
1773 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1776 /// Matches parentheses used in expressions.
1778 /// Example matches (foo() + 1)
1780 /// int foo() { return 1; }
1781 /// int a = (foo() + 1);
1783 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1785 /// Matches constructor call expressions (including implicit ones).
1787 /// Example matches string(ptr, n) and ptr within arguments of f
1788 /// (matcher = cxxConstructExpr())
1790 /// void f(const string &a, const string &b);
1793 /// f(string(ptr, n), ptr);
1795 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1798 /// Matches unresolved constructor call expressions.
1800 /// Example matches T(t) in return statement of f
1801 /// (matcher = cxxUnresolvedConstructExpr())
1803 /// template <typename T>
1804 /// void f(const T& t) { return T(t); }
1806 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1807 CXXUnresolvedConstructExpr>
1808 cxxUnresolvedConstructExpr;
1810 /// Matches implicit and explicit this expressions.
1812 /// Example matches the implicit this expression in "return i".
1813 /// (matcher = cxxThisExpr())
1817 /// int f() { return i; }
1820 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1823 /// Matches nodes where temporaries are created.
1825 /// Example matches FunctionTakesString(GetStringByValue())
1826 /// (matcher = cxxBindTemporaryExpr())
1828 /// FunctionTakesString(GetStringByValue());
1829 /// FunctionTakesStringByPointer(GetStringPointer());
1831 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1832 cxxBindTemporaryExpr;
1834 /// Matches nodes where temporaries are materialized.
1838 /// struct T {void func();};
1842 /// materializeTemporaryExpr() matches 'f()' in these statements
1848 /// but does not match
1852 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1853 MaterializeTemporaryExpr>
1854 materializeTemporaryExpr;
1856 /// Matches new expressions.
1863 /// matches 'new X'.
1864 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1866 /// Matches delete expressions.
1873 /// matches 'delete X'.
1874 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1877 /// Matches noexcept expressions.
1881 /// bool a() noexcept;
1882 /// bool b() noexcept(true);
1883 /// bool c() noexcept(false);
1884 /// bool d() noexcept(noexcept(a()));
1885 /// bool e = noexcept(b()) || noexcept(c());
1887 /// cxxNoexceptExpr()
1888 /// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1889 /// doesn't match the noexcept specifier in the declarations a, b, c or d.
1890 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1893 /// Matches array subscript expressions.
1899 /// arraySubscriptExpr()
1901 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1904 /// Matches the value of a default argument at the call site.
1906 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1907 /// default value of the second parameter in the call expression f(42)
1908 /// (matcher = cxxDefaultArgExpr())
1910 /// void f(int x, int y = 0);
1913 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1916 /// Matches overloaded operator calls.
1918 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1919 /// binaryOperator matcher.
1920 /// Currently it does not match operators such as new delete.
1921 /// FIXME: figure out why these do not match?
1923 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1924 /// (matcher = cxxOperatorCallExpr())
1926 /// ostream &operator<< (ostream &out, int i) { };
1927 /// ostream &o; int b = 1, c = 1;
1930 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1931 cxxOperatorCallExpr;
1933 /// Matches expressions.
1935 /// Example matches x()
1937 /// void f() { x(); }
1939 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1941 /// Matches expressions that refer to declarations.
1943 /// Example matches x in if (x)
1948 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1951 /// Matches a reference to an ObjCIvar.
1953 /// Example: matches "a" in "init" method:
1955 /// @implementation A {
1962 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1965 /// Matches a reference to a block.
1967 /// Example: matches "^{}":
1969 /// void f() { ^{}(); }
1971 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
1973 /// Matches if statements.
1975 /// Example matches 'if (x) {}'
1979 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1981 /// Matches for statements.
1983 /// Example matches 'for (;;) {}'
1986 /// int i[] = {1, 2, 3}; for (auto a : i);
1988 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1990 /// Matches the increment statement of a for loop.
1993 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1994 /// matches '++x' in
1996 /// for (x; x < N; ++x) { }
1998 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2000 const Stmt *const Increment = Node.getInc();
2001 return (Increment != nullptr &&
2002 InnerMatcher.matches(*Increment, Finder, Builder));
2005 /// Matches the initialization statement of a for loop.
2008 /// forStmt(hasLoopInit(declStmt()))
2009 /// matches 'int x = 0' in
2011 /// for (int x = 0; x < N; ++x) { }
2013 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2015 const Stmt *const Init = Node.getInit();
2016 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2019 /// Matches range-based for statements.
2021 /// cxxForRangeStmt() matches 'for (auto a : i)'
2023 /// int i[] = {1, 2, 3}; for (auto a : i);
2024 /// for(int j = 0; j < 5; ++j);
2026 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2029 /// Matches the initialization statement of a for loop.
2032 /// forStmt(hasLoopVariable(anything()))
2033 /// matches 'int x' in
2035 /// for (int x : a) { }
2037 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2039 const VarDecl *const Var = Node.getLoopVariable();
2040 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2043 /// Matches the range initialization statement of a for loop.
2046 /// forStmt(hasRangeInit(anything()))
2049 /// for (int x : a) { }
2051 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2053 const Expr *const Init = Node.getRangeInit();
2054 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2057 /// Matches while statements.
2064 /// matches 'while (true) {}'.
2065 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2067 /// Matches do statements.
2071 /// do {} while (true);
2074 /// matches 'do {} while(true)'
2075 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2077 /// Matches break statements.
2081 /// while (true) { break; }
2085 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2087 /// Matches continue statements.
2091 /// while (true) { continue; }
2094 /// matches 'continue'
2095 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2098 /// Matches return statements.
2105 /// matches 'return 1'
2106 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2108 /// Matches goto statements.
2116 /// matches 'goto FOO'
2117 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2119 /// Matches label statements.
2128 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2130 /// Matches address of label statements (GNU extension).
2135 /// void *ptr = &&FOO;
2140 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2143 /// Matches switch statements.
2147 /// switch(a) { case 42: break; default: break; }
2150 /// matches 'switch(a)'.
2151 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2153 /// Matches case and default statements inside switch statements.
2157 /// switch(a) { case 42: break; default: break; }
2160 /// matches 'case 42:' and 'default:'.
2161 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2163 /// Matches case statements inside switch statements.
2167 /// switch(a) { case 42: break; default: break; }
2170 /// matches 'case 42:'.
2171 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2173 /// Matches default statements inside switch statements.
2177 /// switch(a) { case 42: break; default: break; }
2180 /// matches 'default:'.
2181 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2184 /// Matches compound statements.
2186 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2190 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2193 /// Matches catch statements.
2196 /// try {} catch(int i) {}
2199 /// matches 'catch(int i)'
2200 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2203 /// Matches try statements.
2206 /// try {} catch(int i) {}
2209 /// matches 'try {}'
2210 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2212 /// Matches throw expressions.
2215 /// try { throw 5; } catch(int i) {}
2218 /// matches 'throw 5'
2219 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2222 /// Matches null statements.
2228 /// matches the second ';'
2229 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2231 /// Matches asm statements.
2235 /// __asm("mov al, 2");
2238 /// matches '__asm("mov al, 2")'
2239 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2241 /// Matches bool literals.
2243 /// Example matches true
2247 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2250 /// Matches string literals (also matches wide string literals).
2252 /// Example matches "abcd", L"abcd"
2254 /// char *s = "abcd";
2255 /// wchar_t *ws = L"abcd";
2257 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2260 /// Matches character literals (also matches wchar_t).
2262 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2265 /// Example matches 'a', L'a'
2268 /// wchar_t chw = L'a';
2270 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2273 /// Matches integer literals of all sizes / encodings, e.g.
2274 /// 1, 1L, 0x1 and 1U.
2276 /// Does not match character-encoded integers such as L'a'.
2277 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2280 /// Matches float literals of all sizes / encodings, e.g.
2281 /// 1.0, 1.0f, 1.0L and 1e10.
2283 /// Does not match implicit conversions such as
2287 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2290 /// Matches imaginary literals, which are based on integer and floating
2291 /// point literals e.g.: 1i, 1.0i
2292 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2295 /// Matches fixed point literals
2296 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2299 /// Matches user defined literal operator call.
2301 /// Example match: "foo"_suffix
2302 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2305 /// Matches compound (i.e. non-scalar) literals
2307 /// Example match: {1}, (1, 2)
2309 /// int array[4] = {1};
2310 /// vector int myvec = (vector int)(1, 2);
2312 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2313 compoundLiteralExpr;
2315 /// Matches nullptr literal.
2316 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2317 cxxNullPtrLiteralExpr;
2319 /// Matches GNU __builtin_choose_expr.
2320 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2323 /// Matches GNU __null expression.
2324 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2327 /// Matches atomic builtins.
2328 /// Example matches __atomic_load_n(ptr, 1)
2330 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2332 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2334 /// Matches statement expression (GNU extension).
2336 /// Example match: ({ int X = 4; X; })
2338 /// int C = ({ int X = 4; X; });
2340 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2342 /// Matches binary operator expressions.
2344 /// Example matches a || b
2348 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2351 /// Matches unary operator expressions.
2353 /// Example matches !a
2357 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2360 /// Matches conditional operator expressions.
2362 /// Example matches a ? b : c
2364 /// (a ? b : c) + 42
2366 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2367 conditionalOperator;
2369 /// Matches binary conditional operator expressions (GNU extension).
2371 /// Example matches a ?: b
2375 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2376 BinaryConditionalOperator>
2377 binaryConditionalOperator;
2379 /// Matches opaque value expressions. They are used as helpers
2380 /// to reference another expressions and can be met
2381 /// in BinaryConditionalOperators, for example.
2383 /// Example matches 'a'
2387 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2390 /// Matches a C++ static_assert declaration.
2393 /// staticAssertExpr()
2395 /// static_assert(sizeof(S) == sizeof(int))
2401 /// static_assert(sizeof(S) == sizeof(int));
2403 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2406 /// Matches a reinterpret_cast expression.
2408 /// Either the source expression or the destination type can be matched
2409 /// using has(), but hasDestinationType() is more specific and can be
2412 /// Example matches reinterpret_cast<char*>(&p) in
2414 /// void* p = reinterpret_cast<char*>(&p);
2416 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2417 cxxReinterpretCastExpr;
2419 /// Matches a C++ static_cast expression.
2421 /// \see hasDestinationType
2422 /// \see reinterpretCast
2425 /// cxxStaticCastExpr()
2427 /// static_cast<long>(8)
2430 /// long eight(static_cast<long>(8));
2432 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2435 /// Matches a dynamic_cast expression.
2438 /// cxxDynamicCastExpr()
2440 /// dynamic_cast<D*>(&b);
2443 /// struct B { virtual ~B() {} }; struct D : B {};
2445 /// D* p = dynamic_cast<D*>(&b);
2447 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2450 /// Matches a const_cast expression.
2452 /// Example: Matches const_cast<int*>(&r) in
2455 /// const int &r(n);
2456 /// int* p = const_cast<int*>(&r);
2458 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2461 /// Matches a C-style cast expression.
2463 /// Example: Matches (int) 2.2f in
2465 /// int i = (int) 2.2f;
2467 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2470 /// Matches explicit cast expressions.
2472 /// Matches any cast expression written in user code, whether it be a
2473 /// C-style cast, a functional-style cast, or a keyword cast.
2475 /// Does not match implicit conversions.
2477 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2478 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2479 /// actual cast expressions.
2481 /// \see hasDestinationType.
2483 /// Example: matches all five of the casts in
2485 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2487 /// but does not match the implicit conversion in
2491 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2494 /// Matches the implicit cast nodes of Clang's AST.
2496 /// This matches many different places, including function call return value
2497 /// eliding, as well as any type conversions.
2498 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2501 /// Matches any cast nodes of Clang's AST.
2503 /// Example: castExpr() matches each of the following:
2506 /// const_cast<Expr *>(SubExpr);
2509 /// but does not match
2514 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2516 /// Matches functional cast expressions
2518 /// Example: Matches Foo(bar);
2521 /// Foo g = (Foo) bar;
2522 /// Foo h = Foo(bar);
2524 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2525 cxxFunctionalCastExpr;
2527 /// Matches functional cast expressions having N != 1 arguments
2529 /// Example: Matches Foo(bar, bar)
2531 /// Foo h = Foo(bar, bar);
2533 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2534 cxxTemporaryObjectExpr;
2536 /// Matches predefined identifier expressions [C99 6.4.2.2].
2538 /// Example: Matches __func__
2540 /// printf("%s", __func__);
2542 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2545 /// Matches C99 designated initializer expressions [C99 6.7.8].
2547 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2549 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2551 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2554 /// Matches designated initializer expressions that contain
2555 /// a specific number of designators.
2559 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2560 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2562 /// designatorCountIs(2)
2563 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2564 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2565 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2566 return Node.size() == N;
2569 /// Matches \c QualTypes in the clang AST.
2570 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2572 /// Matches \c Types in the clang AST.
2573 extern const internal::VariadicAllOfMatcher<Type> type;
2575 /// Matches \c TypeLocs in the clang AST.
2576 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2578 /// Matches if any of the given matchers matches.
2580 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2581 /// matching submatcher.
2583 /// For example, in:
2585 /// class A { int a; int b; };
2589 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2590 /// has(fieldDecl(hasName("b")).bind("v"))))
2592 /// will generate two results binding "v", the first of which binds
2593 /// the field declaration of \c a, the second the field declaration of
2596 /// Usable as: Any Matcher
2597 extern const internal::VariadicOperatorMatcherFunc<
2598 2, std::numeric_limits<unsigned>::max()>
2601 /// Matches if any of the given matchers matches.
2603 /// Usable as: Any Matcher
2604 extern const internal::VariadicOperatorMatcherFunc<
2605 2, std::numeric_limits<unsigned>::max()>
2608 /// Matches if all given matchers match.
2610 /// Usable as: Any Matcher
2611 extern const internal::VariadicOperatorMatcherFunc<
2612 2, std::numeric_limits<unsigned>::max()>
2615 /// Matches any node regardless of the submatcher.
2617 /// However, \c optionally will retain any bindings generated by the submatcher.
2618 /// Useful when additional information which may or may not present about a main
2619 /// matching node is desired.
2621 /// For example, in:
2631 /// fieldDecl(hasName("bar")).bind("var")
2632 /// ))).bind("record")
2634 /// will produce a result binding for both "record" and "var".
2635 /// The matcher will produce a "record" binding for even if there is no data
2636 /// member named "bar" in that class.
2638 /// Usable as: Any Matcher
2639 extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2641 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2646 /// int y = sizeof(x) + alignof(x);
2648 /// unaryExprOrTypeTraitExpr()
2649 /// matches \c sizeof(x) and \c alignof(x)
2650 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2651 UnaryExprOrTypeTraitExpr>
2652 unaryExprOrTypeTraitExpr;
2654 /// Matches unary expressions that have a specific type of argument.
2658 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2660 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2661 /// matches \c sizeof(a) and \c alignof(c)
2662 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2663 internal::Matcher<QualType>, InnerMatcher) {
2664 const QualType ArgumentType = Node.getTypeOfArgument();
2665 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2668 /// Matches unary expressions of a certain kind.
2673 /// int s = sizeof(x) + alignof(x)
2675 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2676 /// matches \c sizeof(x)
2678 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2679 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2680 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2681 return Node.getKind() == Kind;
2684 /// Same as unaryExprOrTypeTraitExpr, but only matching
2686 inline internal::BindableMatcher<Stmt> alignOfExpr(
2687 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2688 return stmt(unaryExprOrTypeTraitExpr(
2689 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2693 /// Same as unaryExprOrTypeTraitExpr, but only matching
2695 inline internal::BindableMatcher<Stmt> sizeOfExpr(
2696 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2697 return stmt(unaryExprOrTypeTraitExpr(
2698 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2701 /// Matches NamedDecl nodes that have the specified name.
2703 /// Supports specifying enclosing namespaces or classes by prefixing the name
2704 /// with '<enclosing>::'.
2705 /// Does not match typedefs of an underlying type with the given name.
2707 /// Example matches X (Name == "X")
2712 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2714 /// namespace a { namespace b { class X; } }
2716 inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
2717 return internal::Matcher<NamedDecl>(
2718 new internal::HasNameMatcher({std::string(Name)}));
2721 /// Matches NamedDecl nodes that have any of the specified names.
2723 /// This matcher is only provided as a performance optimization of hasName.
2725 /// hasAnyName(a, b, c)
2727 /// is equivalent to, but faster than
2729 /// anyOf(hasName(a), hasName(b), hasName(c))
2731 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2732 internal::hasAnyNameFunc>
2735 /// Matches NamedDecl nodes whose fully qualified names contain
2736 /// a substring matched by the given RegExp.
2738 /// Supports specifying enclosing namespaces or classes by
2739 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2740 /// of an underlying type with the given name.
2742 /// Example matches X (regexp == "::X")
2747 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2749 /// namespace foo { namespace bar { class X; } }
2751 AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
2752 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2753 return RegExp->match(FullNameString);
2756 /// Matches overloaded operator names.
2758 /// Matches overloaded operator names specified in strings without the
2759 /// "operator" prefix: e.g. "<<".
2763 /// class A { int operator*(); };
2764 /// const A &operator<<(const A &a, const A &b);
2766 /// a << a; // <-- This matches
2769 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2770 /// specified line and
2771 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2772 /// matches the declaration of \c A.
2774 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2775 inline internal::PolymorphicMatcherWithParam1<
2776 internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
2777 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2778 hasOverloadedOperatorName(StringRef Name) {
2779 return internal::PolymorphicMatcherWithParam1<
2780 internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
2781 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(
2782 {std::string(Name)});
2785 /// Matches overloaded operator names.
2787 /// Matches overloaded operator names specified in strings without the
2788 /// "operator" prefix: e.g. "<<".
2790 /// hasAnyOverloadesOperatorName("+", "-")
2791 /// Is equivalent to
2792 /// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
2793 extern const internal::VariadicFunction<
2794 internal::PolymorphicMatcherWithParam1<
2795 internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
2796 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>,
2797 StringRef, internal::hasAnyOverloadedOperatorNameFunc>
2798 hasAnyOverloadedOperatorName;
2800 /// Matches C++ classes that are directly or indirectly derived from a class
2801 /// matching \c Base, or Objective-C classes that directly or indirectly
2802 /// subclass a class matching \c Base.
2804 /// Note that a class is not considered to be derived from itself.
2806 /// Example matches Y, Z, C (Base == hasName("X"))
2809 /// class Y : public X {}; // directly derived
2810 /// class Z : public Y {}; // indirectly derived
2813 /// class C : public B {}; // derived from a typedef of X
2816 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2820 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2823 /// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
2825 /// @interface NSObject @end
2826 /// @interface Bar : NSObject @end
2829 /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
2830 AST_POLYMORPHIC_MATCHER_P(
2832 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2833 internal::Matcher<NamedDecl>, Base) {
2834 // Check if the node is a C++ struct/union/class.
2835 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2836 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
2838 // The node must be an Objective-C class.
2839 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2840 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
2841 /*Directly=*/false);
2844 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2845 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2847 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2848 std::string, BaseName, 1) {
2849 if (BaseName.empty())
2852 const auto M = isDerivedFrom(hasName(BaseName));
2854 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2855 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2857 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2858 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2861 /// Matches C++ classes that have a direct or indirect base matching \p
2862 /// BaseSpecMatcher.
2865 /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
2868 /// class Bar : Foo {};
2869 /// class Baz : Bar {};
2870 /// class SpecialBase;
2871 /// class Proxy : SpecialBase {}; // matches Proxy
2872 /// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
2875 // FIXME: Refactor this and isDerivedFrom to reuse implementation.
2876 AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
2878 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
2881 /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
2884 /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
2887 /// class Bar : Foo {};
2888 /// class Baz : Bar {};
2889 /// class SpecialBase;
2890 /// class Proxy : SpecialBase {}; // matches Proxy
2891 /// class IndirectlyDerived : Proxy {}; // doesn't match
2893 AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
2895 return Node.hasDefinition() &&
2896 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
2897 return BaseSpecMatcher.matches(Base, Finder, Builder);
2901 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2903 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2904 isSameOrDerivedFrom,
2905 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2906 internal::Matcher<NamedDecl>, Base, 0) {
2907 const auto M = anyOf(Base, isDerivedFrom(Base));
2909 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2910 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2912 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2913 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2916 /// Overloaded method as shortcut for
2917 /// \c isSameOrDerivedFrom(hasName(...)).
2918 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2919 isSameOrDerivedFrom,
2920 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2921 std::string, BaseName, 1) {
2922 if (BaseName.empty())
2925 const auto M = isSameOrDerivedFrom(hasName(BaseName));
2927 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2928 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2930 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2931 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2934 /// Matches C++ or Objective-C classes that are directly derived from a class
2935 /// matching \c Base.
2937 /// Note that a class is not considered to be derived from itself.
2939 /// Example matches Y, C (Base == hasName("X"))
2942 /// class Y : public X {}; // directly derived
2943 /// class Z : public Y {}; // indirectly derived
2946 /// class C : public B {}; // derived from a typedef of X
2949 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2953 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2955 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2956 isDirectlyDerivedFrom,
2957 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2958 internal::Matcher<NamedDecl>, Base, 0) {
2959 // Check if the node is a C++ struct/union/class.
2960 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2961 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
2963 // The node must be an Objective-C class.
2964 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2965 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
2969 /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
2970 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2971 isDirectlyDerivedFrom,
2972 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2973 std::string, BaseName, 1) {
2974 if (BaseName.empty())
2976 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
2978 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2979 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2981 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2982 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2984 /// Matches the first method of a class or struct that satisfies \c
2989 /// class A { void func(); };
2990 /// class B { void member(); };
2993 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2994 /// \c A but not \c B.
2995 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2997 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2998 Node.method_end(), Finder, Builder);
3001 /// Matches the generated class of lambda expressions.
3008 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3010 AST_MATCHER(CXXRecordDecl, isLambda) {
3011 return Node.isLambda();
3014 /// Matches AST nodes that have child AST nodes that match the
3015 /// provided matcher.
3017 /// Example matches X, Y
3018 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3020 /// class X {}; // Matches X, because X::X is a class of name X inside X.
3021 /// class Y { class X {}; };
3022 /// class Z { class Y { class X {}; }; }; // Does not match Z.
3025 /// ChildT must be an AST base type.
3027 /// Usable as: Any Matcher
3028 /// Note that has is direct matcher, so it also matches things like implicit
3029 /// casts and paren casts. If you are matching with expr then you should
3030 /// probably consider using ignoringParenImpCasts like:
3031 /// has(ignoringParenImpCasts(expr())).
3032 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3034 /// Matches AST nodes that have descendant AST nodes that match the
3035 /// provided matcher.
3037 /// Example matches X, Y, Z
3038 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3040 /// class X {}; // Matches X, because X::X is a class of name X inside X.
3041 /// class Y { class X {}; };
3042 /// class Z { class Y { class X {}; }; };
3045 /// DescendantT must be an AST base type.
3047 /// Usable as: Any Matcher
3048 extern const internal::ArgumentAdaptingMatcherFunc<
3049 internal::HasDescendantMatcher>
3052 /// Matches AST nodes that have child AST nodes that match the
3053 /// provided matcher.
3055 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3056 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3059 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3061 /// class Z { class Y { class X {}; }; }; // Does not match Z.
3064 /// ChildT must be an AST base type.
3066 /// As opposed to 'has', 'forEach' will cause a match for each result that
3067 /// matches instead of only on the first one.
3069 /// Usable as: Any Matcher
3070 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3073 /// Matches AST nodes that have descendant AST nodes that match the
3074 /// provided matcher.
3076 /// Example matches X, A, A::X, B, B::C, B::C::X
3077 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3080 /// class A { class X {}; }; // Matches A, because A::X is a class of name
3082 /// class B { class C { class X {}; }; };
3085 /// DescendantT must be an AST base type.
3087 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3088 /// each result that matches instead of only on the first one.
3090 /// Note: Recursively combined ForEachDescendant can cause many matches:
3091 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3092 /// forEachDescendant(cxxRecordDecl())
3094 /// will match 10 times (plus injected class name matches) on:
3096 /// class A { class B { class C { class D { class E {}; }; }; }; };
3099 /// Usable as: Any Matcher
3100 extern const internal::ArgumentAdaptingMatcherFunc<
3101 internal::ForEachDescendantMatcher>
3104 /// Matches if the node or any descendant matches.
3106 /// Generates results for each match.
3108 /// For example, in:
3110 /// class A { class B {}; class C {}; };
3114 /// cxxRecordDecl(hasName("::A"),
3115 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3117 /// will generate results for \c A, \c B and \c C.
3119 /// Usable as: Any Matcher
3120 template <typename T>
3121 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3122 return eachOf(Matcher, forEachDescendant(Matcher));
3125 /// Matches AST nodes that have a parent that matches the provided
3130 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3132 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3134 /// Usable as: Any Matcher
3135 extern const internal::ArgumentAdaptingMatcherFunc<
3136 internal::HasParentMatcher,
3137 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
3138 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
3141 /// Matches AST nodes that have an ancestor that matches the provided
3146 /// void f() { if (true) { int x = 42; } }
3147 /// void g() { for (;;) { int x = 43; } }
3149 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3151 /// Usable as: Any Matcher
3152 extern const internal::ArgumentAdaptingMatcherFunc<
3153 internal::HasAncestorMatcher,
3154 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
3155 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
3158 /// Matches if the provided matcher does not match.
3160 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3166 /// Usable as: Any Matcher
3167 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3169 /// Matches a node if the declaration associated with that node
3170 /// matches the given matcher.
3172 /// The associated declaration is:
3173 /// - for type nodes, the declaration of the underlying type
3174 /// - for CallExpr, the declaration of the callee
3175 /// - for MemberExpr, the declaration of the referenced member
3176 /// - for CXXConstructExpr, the declaration of the constructor
3177 /// - for CXXNewExpr, the declaration of the operator new
3178 /// - for ObjCIvarExpr, the declaration of the ivar
3180 /// For type nodes, hasDeclaration will generally match the declaration of the
3181 /// sugared type. Given
3187 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3188 /// typedefDecl. A common use case is to match the underlying, desugared type.
3189 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3191 /// varDecl(hasType(hasUnqualifiedDesugaredType(
3192 /// recordType(hasDeclaration(decl())))))
3194 /// In this matcher, the decl will match the CXXRecordDecl of class X.
3196 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3197 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3198 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3199 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3200 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3201 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3202 /// Matcher<UnresolvedUsingType>
3203 inline internal::PolymorphicMatcherWithParam1<
3204 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
3205 void(internal::HasDeclarationSupportedTypes)>
3206 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3207 return internal::PolymorphicMatcherWithParam1<
3208 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
3209 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
3212 /// Matches a \c NamedDecl whose underlying declaration matches the given
3217 /// namespace N { template<class T> void f(T t); }
3218 /// template <class T> void g() { using N::f; f(T()); }
3220 /// \c unresolvedLookupExpr(hasAnyDeclaration(
3221 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3222 /// matches the use of \c f in \c g() .
3223 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3225 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3227 return UnderlyingDecl != nullptr &&
3228 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3231 /// Matches on the implicit object argument of a member call expression, after
3232 /// stripping off any parentheses or implicit casts.
3236 /// class Y { public: void m(); };
3238 /// class X : public Y {};
3239 /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3241 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3242 /// matches `y.m()` and `(g()).m()`.
3243 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3244 /// matches `x.m()`.
3245 /// cxxMemberCallExpr(on(callExpr()))
3246 /// matches `(g()).m()`.
3248 /// FIXME: Overload to allow directly matching types?
3249 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3251 const Expr *ExprNode = Node.getImplicitObjectArgument()
3252 ->IgnoreParenImpCasts();
3253 return (ExprNode != nullptr &&
3254 InnerMatcher.matches(*ExprNode, Finder, Builder));
3258 /// Matches on the receiver of an ObjectiveC Message expression.
3261 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3262 /// matches the [webView ...] message invocation.
3264 /// NSString *webViewJavaScript = ...
3265 /// UIWebView *webView = ...
3266 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3268 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3270 const QualType TypeDecl = Node.getReceiverType();
3271 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3274 /// Returns true when the Objective-C method declaration is a class method.
3277 /// matcher = objcMethodDecl(isClassMethod())
3280 /// @interface I + (void)foo; @end
3284 /// @interface I - (void)bar; @end
3286 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
3287 return Node.isClassMethod();
3290 /// Returns true when the Objective-C method declaration is an instance method.
3293 /// matcher = objcMethodDecl(isInstanceMethod())
3296 /// @interface I - (void)bar; @end
3300 /// @interface I + (void)foo; @end
3302 AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
3303 return Node.isInstanceMethod();
3306 /// Returns true when the Objective-C message is sent to a class.
3309 /// matcher = objcMessageExpr(isClassMessage())
3312 /// [NSString stringWithFormat:@"format"];
3316 /// NSString *x = @"hello";
3317 /// [x containsString:@"h"];
3319 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
3320 return Node.isClassMessage();
3323 /// Returns true when the Objective-C message is sent to an instance.
3326 /// matcher = objcMessageExpr(isInstanceMessage())
3329 /// NSString *x = @"hello";
3330 /// [x containsString:@"h"];
3334 /// [NSString stringWithFormat:@"format"];
3336 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3337 return Node.isInstanceMessage();
3340 /// Matches if the Objective-C message is sent to an instance,
3341 /// and the inner matcher matches on that instance.
3343 /// For example the method call in
3345 /// NSString *x = @"hello";
3346 /// [x containsString:@"h"];
3349 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3350 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3352 const Expr *ReceiverNode = Node.getInstanceReceiver();
3353 return (ReceiverNode != nullptr &&
3354 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3358 /// Matches when BaseName == Selector.getAsString()
3360 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3361 /// matches the outer message expr in the code below, but NOT the message
3362 /// invocation for self.bodyView.
3364 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3366 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3367 Selector Sel = Node.getSelector();
3368 return BaseName.compare(Sel.getAsString()) == 0;
3372 /// Matches when at least one of the supplied string equals to the
3373 /// Selector.getAsString()
3375 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3376 /// matches both of the expressions below:
3378 /// [myObj methodA:argA];
3379 /// [myObj methodB:argB];
3381 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3383 internal::hasAnySelectorFunc>
3386 /// Matches ObjC selectors whose name contains
3387 /// a substring matched by the given RegExp.
3388 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3389 /// matches the outer message expr in the code below, but NOT the message
3390 /// invocation for self.bodyView.
3392 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3394 AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3395 std::string SelectorString = Node.getSelector().getAsString();
3396 return RegExp->match(SelectorString);
3399 /// Matches when the selector is the empty selector
3401 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3402 /// represent an error condition in the tree!
3403 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3404 return Node.getSelector().isNull();
3407 /// Matches when the selector is a Unary Selector
3409 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3410 /// matches self.bodyView in the code below, but NOT the outer message
3411 /// invocation of "loadHTMLString:baseURL:".
3413 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3415 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3416 return Node.getSelector().isUnarySelector();
3419 /// Matches when the selector is a keyword selector
3421 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3422 /// message expression in
3425 /// UIWebView *webView = ...;
3426 /// CGRect bodyFrame = webView.frame;
3427 /// bodyFrame.size.height = self.bodyContentHeight;
3428 /// webView.frame = bodyFrame;
3429 /// // ^---- matches here
3431 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3432 return Node.getSelector().isKeywordSelector();
3435 /// Matches when the selector has the specified number of arguments
3437 /// matcher = objCMessageExpr(numSelectorArgs(0));
3438 /// matches self.bodyView in the code below
3440 /// matcher = objCMessageExpr(numSelectorArgs(2));
3441 /// matches the invocation of "loadHTMLString:baseURL:" but not that
3442 /// of self.bodyView
3444 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3446 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3447 return Node.getSelector().getNumArgs() == N;
3450 /// Matches if the call expression's callee expression matches.
3454 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3455 /// void f() { f(); }
3457 /// callExpr(callee(expr()))
3458 /// matches this->x(), x(), y.x(), f()
3459 /// with callee(...)
3460 /// matching this->x, x, y.x, f respectively
3462 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3463 /// because this introduces ambiguous overloads with calls to Callee taking a
3464 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3465 /// implemented in terms of implicit casts.
3466 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3468 const Expr *ExprNode = Node.getCallee();
3469 return (ExprNode != nullptr &&
3470 InnerMatcher.matches(*ExprNode, Finder, Builder));
3473 /// Matches if the call expression's callee's declaration matches the
3476 /// Example matches y.x() (matcher = callExpr(callee(
3477 /// cxxMethodDecl(hasName("x")))))
3479 /// class Y { public: void x(); };
3480 /// void z() { Y y; y.x(); }
3482 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3484 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3487 /// Matches if the expression's or declaration's type matches a type
3490 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3491 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3492 /// and U (matcher = typedefDecl(hasType(asString("int")))
3493 /// and friend class X (matcher = friendDecl(hasType("X"))
3496 /// void y(X &x) { x; X z; }
3498 /// class Y { friend class X; };
3500 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3502 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3504 internal::Matcher<QualType>, InnerMatcher, 0) {
3505 QualType QT = internal::getUnderlyingType(Node);
3507 return InnerMatcher.matches(QT, Finder, Builder);
3511 /// Overloaded to match the declaration of the expression's or value
3512 /// declaration's type.
3514 /// In case of a value declaration (for example a variable declaration),
3515 /// this resolves one layer of indirection. For example, in the value
3516 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3517 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3518 /// declaration of x.
3520 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3521 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3522 /// and friend class X (matcher = friendDecl(hasType("X"))
3525 /// void y(X &x) { x; X z; }
3526 /// class Y { friend class X; };
3529 /// Example matches class Derived
3530 /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
3533 /// class Derived : Base {};
3536 /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
3537 /// Matcher<CXXBaseSpecifier>
3538 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3540 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
3542 internal::Matcher<Decl>, InnerMatcher, 1) {
3543 QualType QT = internal::getUnderlyingType(Node);
3545 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3549 /// Matches if the type location of the declarator decl's type matches
3550 /// the inner matcher.
3556 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3558 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3559 if (!Node.getTypeSourceInfo())
3560 // This happens for example for implicit destructors.
3562 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3565 /// Matches if the matched type is represented by the given string.
3569 /// class Y { public: void x(); };
3570 /// void z() { Y* y; y->x(); }
3572 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3574 AST_MATCHER_P(QualType, asString, std::string, Name) {
3575 return Name == Node.getAsString();
3578 /// Matches if the matched type is a pointer type and the pointee type
3579 /// matches the specified matcher.
3581 /// Example matches y->x()
3582 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3583 /// cxxRecordDecl(hasName("Y")))))))
3585 /// class Y { public: void x(); };
3586 /// void z() { Y *y; y->x(); }
3589 QualType, pointsTo, internal::Matcher<QualType>,
3591 return (!Node.isNull() && Node->isAnyPointerType() &&
3592 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3595 /// Overloaded to match the pointee type's declaration.
3596 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3598 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3599 .matches(Node, Finder, Builder);
3602 /// Matches if the matched type matches the unqualified desugared
3603 /// type of the matched node.
3605 /// For example, in:
3610 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3612 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3614 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3618 /// Matches if the matched type is a reference type and the referenced
3619 /// type matches the specified matcher.
3621 /// Example matches X &x and const X &y
3622 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3631 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3633 return (!Node.isNull() && Node->isReferenceType() &&
3634 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3637 /// Matches QualTypes whose canonical type matches InnerMatcher.
3641 /// typedef int &int_ref;
3646 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3647 /// declaration of b but \c
3648 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3649 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3653 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3656 /// Overloaded to match the referenced type's declaration.
3657 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3659 return references(qualType(hasDeclaration(InnerMatcher)))
3660 .matches(Node, Finder, Builder);
3663 /// Matches on the implicit object argument of a member call expression. Unlike
3664 /// `on`, matches the argument directly without stripping away anything.
3668 /// class Y { public: void m(); };
3670 /// class X : public Y { void g(); };
3671 /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
3673 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
3674 /// cxxRecordDecl(hasName("Y")))))
3675 /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
3676 /// cxxMemberCallExpr(on(callExpr()))
3677 /// does not match `(g()).m()`, because the parens are not ignored.
3679 /// FIXME: Overload to allow directly matching types?
3680 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3681 internal::Matcher<Expr>, InnerMatcher) {
3682 const Expr *ExprNode = Node.getImplicitObjectArgument();
3683 return (ExprNode != nullptr &&
3684 InnerMatcher.matches(*ExprNode, Finder, Builder));
3687 /// Matches if the type of the expression's implicit object argument either
3688 /// matches the InnerMatcher, or is a pointer to a type that matches the
3693 /// class Y { public: void m(); };
3694 /// class X : public Y { void g(); };
3695 /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
3697 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3698 /// cxxRecordDecl(hasName("Y")))))
3699 /// matches `y.m()`, `p->m()` and `x.m()`.
3700 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3701 /// cxxRecordDecl(hasName("X")))))
3702 /// matches `x.g()`.
3703 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3704 internal::Matcher<QualType>, InnerMatcher, 0) {
3705 return onImplicitObjectArgument(
3706 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3707 .matches(Node, Finder, Builder);
3710 /// Overloaded to match the type's declaration.
3711 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3712 internal::Matcher<Decl>, InnerMatcher, 1) {
3713 return onImplicitObjectArgument(
3714 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3715 .matches(Node, Finder, Builder);
3718 /// Matches a DeclRefExpr that refers to a declaration that matches the
3719 /// specified matcher.
3721 /// Example matches x in if(x)
3722 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3727 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3729 const Decl *DeclNode = Node.getDecl();
3730 return (DeclNode != nullptr &&
3731 InnerMatcher.matches(*DeclNode, Finder, Builder));
3734 /// Matches a \c DeclRefExpr that refers to a declaration through a
3735 /// specific using shadow declaration.
3739 /// namespace a { void f() {} }
3742 /// f(); // Matches this ..
3743 /// a::f(); // .. but not this.
3746 /// declRefExpr(throughUsingDecl(anything()))
3748 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3749 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3750 const NamedDecl *FoundDecl = Node.getFoundDecl();
3751 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3752 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3756 /// Matches an \c OverloadExpr if any of the declarations in the set of
3757 /// overloads matches the given matcher.
3761 /// template <typename T> void foo(T);
3762 /// template <typename T> void bar(T);
3763 /// template <typename T> void baz(T t) {
3768 /// unresolvedLookupExpr(hasAnyDeclaration(
3769 /// functionTemplateDecl(hasName("foo"))))
3770 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3771 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3773 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3774 Node.decls_end(), Finder, Builder);
3777 /// Matches the Decl of a DeclStmt which has a single declaration.
3784 /// declStmt(hasSingleDecl(anything()))
3785 /// matches 'int c;' but not 'int a, b;'.
3786 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3787 if (Node.isSingleDecl()) {
3788 const Decl *FoundDecl = Node.getSingleDecl();
3789 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3794 /// Matches a variable declaration that has an initializer expression
3795 /// that matches the given matcher.
3797 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3799 /// bool y() { return true; }
3803 VarDecl, hasInitializer, internal::Matcher<Expr>,
3805 const Expr *Initializer = Node.getAnyInitializer();
3806 return (Initializer != nullptr &&
3807 InnerMatcher.matches(*Initializer, Finder, Builder));
3810 /// \brief Matches a static variable with local scope.
3812 /// Example matches y (matcher = varDecl(isStaticLocal()))
3820 AST_MATCHER(VarDecl, isStaticLocal) {
3821 return Node.isStaticLocal();
3824 /// Matches a variable declaration that has function scope and is a
3825 /// non-static local variable.
3827 /// Example matches x (matcher = varDecl(hasLocalStorage())
3835 AST_MATCHER(VarDecl, hasLocalStorage) {
3836 return Node.hasLocalStorage();
3839 /// Matches a variable declaration that does not have local storage.
3841 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3849 AST_MATCHER(VarDecl, hasGlobalStorage) {
3850 return Node.hasGlobalStorage();
3853 /// Matches a variable declaration that has automatic storage duration.
3855 /// Example matches x, but not y, z, or a.
3856 /// (matcher = varDecl(hasAutomaticStorageDuration())
3861 /// thread_local int z;
3865 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3866 return Node.getStorageDuration() == SD_Automatic;
3869 /// Matches a variable declaration that has static storage duration.
3870 /// It includes the variable declared at namespace scope and those declared
3871 /// with "static" and "extern" storage class specifiers.
3877 /// thread_local int z;
3882 /// varDecl(hasStaticStorageDuration())
3883 /// matches the function declaration y, a, b and c.
3885 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3886 return Node.getStorageDuration() == SD_Static;
3889 /// Matches a variable declaration that has thread storage duration.
3891 /// Example matches z, but not x, z, or a.
3892 /// (matcher = varDecl(hasThreadStorageDuration())
3897 /// thread_local int z;
3901 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3902 return Node.getStorageDuration() == SD_Thread;
3905 /// Matches a variable declaration that is an exception variable from
3906 /// a C++ catch block, or an Objective-C \@catch statement.
3908 /// Example matches x (matcher = varDecl(isExceptionVariable())
3912 /// } catch (int x) {
3916 AST_MATCHER(VarDecl, isExceptionVariable) {
3917 return Node.isExceptionVariable();
3920 /// Checks that a call expression or a constructor call expression has
3921 /// a specific number of arguments (including absent default arguments).
3923 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3925 /// void f(int x, int y);
3928 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3929 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3933 return Node.getNumArgs() == N;
3936 /// Matches the n'th argument of a call expression or a constructor
3937 /// call expression.
3939 /// Example matches y in x(y)
3940 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3942 /// void x(int) { int y; x(y); }
3944 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3945 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3948 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3949 return (N < Node.getNumArgs() &&
3950 InnerMatcher.matches(
3951 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3954 /// Matches the n'th item of an initializer list expression.
3956 /// Example matches y.
3957 /// (matcher = initListExpr(hasInit(0, expr())))
3961 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
3962 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
3963 return N < Node.getNumInits() &&
3964 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
3967 /// Matches declaration statements that contain a specific number of
3977 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3978 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3979 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3982 /// Matches the n'th declaration of a declaration statement.
3984 /// Note that this does not work for global declarations because the AST
3985 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3987 /// Example: Given non-global declarations
3993 /// declStmt(containsDeclaration(
3994 /// 0, varDecl(hasInitializer(anything()))))
3995 /// matches only 'int d = 2, e;', and
3996 /// declStmt(containsDeclaration(1, varDecl()))
3998 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3999 /// but 'int c;' is not matched.
4001 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4002 internal::Matcher<Decl>, InnerMatcher) {
4003 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4006 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4007 std::advance(Iterator, N);
4008 return InnerMatcher.matches(**Iterator, Finder, Builder);
4011 /// Matches a C++ catch statement that has a catch-all handler.
4023 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4024 AST_MATCHER(CXXCatchStmt, isCatchAll) {
4025 return Node.getExceptionDecl() == nullptr;
4028 /// Matches a constructor initializer.
4033 /// Foo() : foo_(1) { }
4037 /// cxxRecordDecl(has(cxxConstructorDecl(
4038 /// hasAnyConstructorInitializer(anything())
4040 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4041 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4042 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4043 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4044 Node.init_end(), Finder, Builder);
4047 /// Matches the field declaration of a constructor initializer.
4052 /// Foo() : foo_(1) { }
4056 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4057 /// forField(hasName("foo_"))))))
4059 /// with forField matching foo_
4060 AST_MATCHER_P(CXXCtorInitializer, forField,
4061 internal::Matcher<FieldDecl>, InnerMatcher) {
4062 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4063 return (NodeAsDecl != nullptr &&
4064 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4067 /// Matches the initializer expression of a constructor initializer.
4072 /// Foo() : foo_(1) { }
4076 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4077 /// withInitializer(integerLiteral(equals(1)))))))
4079 /// with withInitializer matching (1)
4080 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
4081 internal::Matcher<Expr>, InnerMatcher) {
4082 const Expr* NodeAsExpr = Node.getInit();
4083 return (NodeAsExpr != nullptr &&
4084 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4087 /// Matches a constructor initializer if it is explicitly written in
4088 /// code (as opposed to implicitly added by the compiler).
4094 /// Foo(int) : foo_("A") { }
4098 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4099 /// will match Foo(int), but not Foo()
4100 AST_MATCHER(CXXCtorInitializer, isWritten) {
4101 return Node.isWritten();
4104 /// Matches a constructor initializer if it is initializing a base, as
4105 /// opposed to a member.
4112 /// D(int i) : I(i) {}
4118 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4119 /// will match E(), but not match D(int).
4120 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4121 return Node.isBaseInitializer();
4124 /// Matches a constructor initializer if it is initializing a member, as
4125 /// opposed to a base.
4132 /// D(int i) : I(i) {}
4138 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4139 /// will match D(int), but not match E().
4140 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4141 return Node.isMemberInitializer();
4144 /// Matches any argument of a call expression or a constructor call
4145 /// expression, or an ObjC-message-send expression.
4149 /// void x(int, int, int) { int y; x(1, y, 42); }
4151 /// callExpr(hasAnyArgument(declRefExpr()))
4152 /// matches x(1, y, 42)
4153 /// with hasAnyArgument(...)
4156 /// For ObjectiveC, given
4158 /// @interface I - (void) f:(int) y; @end
4159 /// void foo(I *i) { [i f:12]; }
4161 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4162 /// matches [i f:12]
4163 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
4164 AST_POLYMORPHIC_SUPPORTED_TYPES(
4165 CallExpr, CXXConstructExpr,
4166 CXXUnresolvedConstructExpr, ObjCMessageExpr),
4167 internal::Matcher<Expr>, InnerMatcher) {
4168 for (const Expr *Arg : Node.arguments()) {
4169 BoundNodesTreeBuilder Result(*Builder);
4170 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4171 *Builder = std::move(Result);
4178 /// Matches any capture of a lambda expression.
4184 /// auto f = [x](){};
4187 /// lambdaExpr(hasAnyCapture(anything()))
4188 /// matches [x](){};
4189 AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>,
4191 for (const LambdaCapture &Capture : Node.captures()) {
4192 if (Capture.capturesVariable()) {
4193 BoundNodesTreeBuilder Result(*Builder);
4194 if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) {
4195 *Builder = std::move(Result);
4203 /// Matches any capture of 'this' in a lambda expression.
4209 /// auto f = [this](){};
4213 /// lambdaExpr(hasAnyCapture(cxxThisExpr()))
4214 /// matches [this](){};
4215 AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture,
4216 internal::Matcher<CXXThisExpr>, InnerMatcher, 1) {
4217 return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) {
4218 return LC.capturesThis();
4222 /// Matches a constructor call expression which uses list initialization.
4223 AST_MATCHER(CXXConstructExpr, isListInitialization) {
4224 return Node.isListInitialization();
4227 /// Matches a constructor call expression which requires
4228 /// zero initialization.
4233 /// struct point { double x; double y; };
4234 /// point pt[2] = { { 1.0, 2.0 } };
4237 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
4238 /// will match the implicit array filler for pt[1].
4239 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
4240 return Node.requiresZeroInitialization();
4243 /// Matches the n'th parameter of a function or an ObjC method
4244 /// declaration or a block.
4248 /// class X { void f(int x) {} };
4250 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
4251 /// matches f(int x) {}
4252 /// with hasParameter(...)
4255 /// For ObjectiveC, given
4257 /// @interface I - (void) f:(int) y; @end
4260 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
4261 /// matches the declaration of method f with hasParameter
4263 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
4264 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4267 unsigned, N, internal::Matcher<ParmVarDecl>,
4269 return (N < Node.parameters().size()
4270 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4273 /// Matches all arguments and their respective ParmVarDecl.
4282 /// forEachArgumentWithParam(
4283 /// declRefExpr(to(varDecl(hasName("y")))),
4284 /// parmVarDecl(hasType(isInteger()))
4287 /// with declRefExpr(...)
4289 /// and parmVarDecl(...)
4291 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4292 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
4294 internal::Matcher<Expr>, ArgMatcher,
4295 internal::Matcher<ParmVarDecl>, ParamMatcher) {
4296 BoundNodesTreeBuilder Result;
4297 // The first argument of an overloaded member operator is the implicit object
4298 // argument of the method which should not be matched against a parameter, so
4299 // we skip over it here.
4300 BoundNodesTreeBuilder Matches;
4301 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4302 .matches(Node, Finder, &Matches)
4306 bool Matched = false;
4307 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
4308 BoundNodesTreeBuilder ArgMatches(*Builder);
4309 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4310 Finder, &ArgMatches)) {
4311 BoundNodesTreeBuilder ParamMatches(ArgMatches);
4312 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4313 hasParameter(ParamIndex, ParamMatcher)))),
4314 callExpr(callee(functionDecl(
4315 hasParameter(ParamIndex, ParamMatcher))))))
4316 .matches(Node, Finder, &ParamMatches)) {
4317 Result.addMatch(ParamMatches);
4323 *Builder = std::move(Result);
4327 /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
4328 /// list. The parameter list could be that of either a block, function, or
4335 /// void f(int a, int b, int c) {
4339 /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
4341 /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
4342 AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
4343 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
4345 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
4346 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4347 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
4348 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4349 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
4350 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
4355 /// Matches any parameter of a function or an ObjC method declaration or a
4358 /// Does not match the 'this' parameter of a method.
4362 /// class X { void f(int x, int y, int z) {} };
4364 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
4365 /// matches f(int x, int y, int z) {}
4366 /// with hasAnyParameter(...)
4369 /// For ObjectiveC, given
4371 /// @interface I - (void) f:(int) y; @end
4374 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
4375 /// matches the declaration of method f with hasParameter
4378 /// For blocks, given
4380 /// b = ^(int y) { printf("%d", y) };
4383 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
4384 /// matches the declaration of the block b with hasParameter
4386 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
4387 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4390 internal::Matcher<ParmVarDecl>,
4392 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
4393 Node.param_end(), Finder, Builder);
4396 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
4397 /// specific parameter count.
4401 /// void f(int i) {}
4402 /// void g(int i, int j) {}
4403 /// void h(int i, int j);
4405 /// void k(int x, int y, int z, ...);
4407 /// functionDecl(parameterCountIs(2))
4408 /// matches \c g and \c h
4409 /// functionProtoType(parameterCountIs(2))
4410 /// matches \c g and \c h
4411 /// functionProtoType(parameterCountIs(3))
4413 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
4414 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4417 return Node.getNumParams() == N;
4420 /// Matches \c FunctionDecls that have a noreturn attribute.
4425 /// [[noreturn]] void a();
4426 /// __attribute__((noreturn)) void b();
4427 /// struct c { [[noreturn]] c(); };
4429 /// functionDecl(isNoReturn())
4430 /// matches all of those except
4434 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
4436 /// Matches the return type of a function declaration.
4440 /// class X { int f() { return 1; } };
4442 /// cxxMethodDecl(returns(asString("int")))
4443 /// matches int f() { return 1; }
4444 AST_MATCHER_P(FunctionDecl, returns,
4445 internal::Matcher<QualType>, InnerMatcher) {
4446 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
4449 /// Matches extern "C" function or variable declarations.
4453 /// extern "C" void f() {}
4454 /// extern "C" { void g() {} }
4456 /// extern "C" int x = 1;
4457 /// extern "C" int y = 2;
4460 /// functionDecl(isExternC())
4461 /// matches the declaration of f and g, but not the declaration of h.
4462 /// varDecl(isExternC())
4463 /// matches the declaration of x and y, but not the declaration of z.
4464 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4466 return Node.isExternC();
4469 /// Matches variable/function declarations that have "static" storage
4470 /// class specifier ("static" keyword) written in the source.
4474 /// static void f() {}
4475 /// static int i = 0;
4479 /// functionDecl(isStaticStorageClass())
4480 /// matches the function declaration f.
4481 /// varDecl(isStaticStorageClass())
4482 /// matches the variable declaration i.
4483 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
4484 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4486 return Node.getStorageClass() == SC_Static;
4489 /// Matches deleted function declarations.
4494 /// void DeletedFunc() = delete;
4496 /// functionDecl(isDeleted())
4497 /// matches the declaration of DeletedFunc, but not Func.
4498 AST_MATCHER(FunctionDecl, isDeleted) {
4499 return Node.isDeleted();
4502 /// Matches defaulted function declarations.
4506 /// class A { ~A(); };
4507 /// class B { ~B() = default; };
4509 /// functionDecl(isDefaulted())
4510 /// matches the declaration of ~B, but not ~A.
4511 AST_MATCHER(FunctionDecl, isDefaulted) {
4512 return Node.isDefaulted();
4515 /// Matches functions that have a dynamic exception specification.
4520 /// void g() noexcept;
4521 /// void h() noexcept(true);
4522 /// void i() noexcept(false);
4523 /// void j() throw();
4524 /// void k() throw(int);
4525 /// void l() throw(...);
4527 /// functionDecl(hasDynamicExceptionSpec()) and
4528 /// functionProtoType(hasDynamicExceptionSpec())
4529 /// match the declarations of j, k, and l, but not f, g, h, or i.
4530 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
4531 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4532 FunctionProtoType)) {
4533 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
4534 return FnTy->hasDynamicExceptionSpec();
4538 /// Matches functions that have a non-throwing exception specification.
4543 /// void g() noexcept;
4544 /// void h() throw();
4545 /// void i() throw(int);
4546 /// void j() noexcept(false);
4548 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
4549 /// match the declarations of g, and h, but not f, i or j.
4550 AST_POLYMORPHIC_MATCHER(isNoThrow,
4551 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4552 FunctionProtoType)) {
4553 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
4555 // If the function does not have a prototype, then it is assumed to be a
4556 // throwing function (as it would if the function did not have any exception
4561 // Assume the best for any unresolved exception specification.
4562 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
4565 return FnTy->isNothrow();
4568 /// Matches constexpr variable and function declarations,
4569 /// and if constexpr.
4573 /// constexpr int foo = 42;
4574 /// constexpr int bar();
4575 /// void baz() { if constexpr(1 > 0) {} }
4577 /// varDecl(isConstexpr())
4578 /// matches the declaration of foo.
4579 /// functionDecl(isConstexpr())
4580 /// matches the declaration of bar.
4581 /// ifStmt(isConstexpr())
4582 /// matches the if statement in baz.
4583 AST_POLYMORPHIC_MATCHER(isConstexpr,
4584 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
4587 return Node.isConstexpr();
4590 /// Matches selection statements with initializer.
4595 /// if (int i = foobar(); i > 0) {}
4596 /// switch (int i = foobar(); i) {}
4597 /// for (auto& a = get_range(); auto& x : a) {}
4600 /// if (foobar() > 0) {}
4601 /// switch (foobar()) {}
4602 /// for (auto& x : get_range()) {}
4605 /// ifStmt(hasInitStatement(anything()))
4606 /// matches the if statement in foo but not in bar.
4607 /// switchStmt(hasInitStatement(anything()))
4608 /// matches the switch statement in foo but not in bar.
4609 /// cxxForRangeStmt(hasInitStatement(anything()))
4610 /// matches the range for statement in foo but not in bar.
4611 AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
4612 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt,
4614 internal::Matcher<Stmt>, InnerMatcher) {
4615 const Stmt *Init = Node.getInit();
4616 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
4619 /// Matches the condition expression of an if statement, for loop,
4620 /// switch statement or conditional operator.
4622 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
4626 AST_POLYMORPHIC_MATCHER_P(
4628 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
4629 SwitchStmt, AbstractConditionalOperator),
4630 internal::Matcher<Expr>, InnerMatcher) {
4631 const Expr *const Condition = Node.getCond();
4632 return (Condition != nullptr &&
4633 InnerMatcher.matches(*Condition, Finder, Builder));
4636 /// Matches the then-statement of an if statement.
4638 /// Examples matches the if statement
4639 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
4641 /// if (false) true; else false;
4643 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
4644 const Stmt *const Then = Node.getThen();
4645 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
4648 /// Matches the else-statement of an if statement.
4650 /// Examples matches the if statement
4651 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
4653 /// if (false) false; else true;
4655 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
4656 const Stmt *const Else = Node.getElse();
4657 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
4660 /// Matches if a node equals a previously bound node.
4662 /// Matches a node if it equals the node previously bound to \p ID.
4666 /// class X { int a; int b; };
4669 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4670 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
4671 /// matches the class \c X, as \c a and \c b have the same type.
4673 /// Note that when multiple matches are involved via \c forEach* matchers,
4674 /// \c equalsBoundNodes acts as a filter.
4677 /// forEachDescendant(varDecl().bind("d")),
4678 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
4679 /// will trigger a match for each combination of variable declaration
4680 /// and reference to that variable declaration within a compound statement.
4681 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
4682 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
4685 // FIXME: Figure out whether it makes sense to allow this
4686 // on any other node types.
4687 // For *Loc it probably does not make sense, as those seem
4688 // unique. For NestedNameSepcifier it might make sense, as
4689 // those also have pointer identity, but I'm not sure whether
4690 // they're ever reused.
4691 internal::NotEqualsBoundNodePredicate Predicate;
4693 Predicate.Node = DynTypedNode::create(Node);
4694 return Builder->removeBindings(Predicate);
4697 /// Matches the condition variable statement in an if statement.
4701 /// if (A* a = GetAPointer()) {}
4703 /// hasConditionVariableStatement(...)
4704 /// matches 'A* a = GetAPointer()'.
4705 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
4706 internal::Matcher<DeclStmt>, InnerMatcher) {
4707 const DeclStmt* const DeclarationStatement =
4708 Node.getConditionVariableDeclStmt();
4709 return DeclarationStatement != nullptr &&
4710 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
4713 /// Matches the index expression of an array subscript expression.
4718 /// void f() { i[1] = 42; }
4720 /// arraySubscriptExpression(hasIndex(integerLiteral()))
4721 /// matches \c i[1] with the \c integerLiteral() matching \c 1
4722 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
4723 internal::Matcher<Expr>, InnerMatcher) {
4724 if (const Expr* Expression = Node.getIdx())
4725 return InnerMatcher.matches(*Expression, Finder, Builder);
4729 /// Matches the base expression of an array subscript expression.
4734 /// void f() { i[1] = 42; }
4736 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4737 /// hasSourceExpression(declRefExpr()))))
4738 /// matches \c i[1] with the \c declRefExpr() matching \c i
4739 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4740 internal::Matcher<Expr>, InnerMatcher) {
4741 if (const Expr* Expression = Node.getBase())
4742 return InnerMatcher.matches(*Expression, Finder, Builder);
4746 /// Matches a 'for', 'while', 'do while' statement or a function
4747 /// definition that has a given body.
4753 /// hasBody(compoundStmt())
4754 /// matches 'for (;;) {}'
4755 /// with compoundStmt()
4757 AST_POLYMORPHIC_MATCHER_P(hasBody,
4758 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4762 internal::Matcher<Stmt>, InnerMatcher) {
4763 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4764 return (Statement != nullptr &&
4765 InnerMatcher.matches(*Statement, Finder, Builder));
4768 /// Matches compound statements where at least one substatement matches
4769 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4775 /// hasAnySubstatement(compoundStmt())
4776 /// matches '{ {}; 1+2; }'
4777 /// with compoundStmt()
4779 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4780 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4782 internal::Matcher<Stmt>, InnerMatcher) {
4783 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4784 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4785 CS->body_end(), Finder, Builder);
4788 /// Checks that a compound statement contains a specific number of
4789 /// child statements.
4795 /// compoundStmt(statementCountIs(0)))
4797 /// but does not match the outer compound statement.
4798 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4799 return Node.size() == N;
4802 /// Matches literals that are equal to the given value of type ValueT.
4806 /// f('\0', false, 3.14, 42);
4808 /// characterLiteral(equals(0))
4810 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4812 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4814 /// integerLiteral(equals(42))
4817 /// Note that you cannot directly match a negative numeric literal because the
4818 /// minus sign is not part of the literal: It is a unary operator whose operand
4819 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4820 /// matcher to match the minus sign:
4822 /// unaryOperator(hasOperatorName("-"),
4823 /// hasUnaryOperand(integerLiteral(equals(13))))
4825 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4826 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4827 template <typename ValueT>
4828 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
4829 equals(const ValueT &Value) {
4830 return internal::PolymorphicMatcherWithParam1<
4831 internal::ValueEqualsMatcher,
4835 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4836 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4840 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4844 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4845 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4848 unsigned, Value, 1) {
4849 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4853 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4854 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4859 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4863 /// Matches the operator Name of operator expressions (binary or
4866 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4870 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4871 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4873 std::string, Name) {
4874 return Name == Node.getOpcodeStr(Node.getOpcode());
4877 /// Matches operator expressions (binary or unary) that have any of the
4878 /// specified names.
4880 /// hasAnyOperatorName("+", "-")
4881 /// Is equivalent to
4882 /// anyOf(hasOperatorName("+"), hasOperatorName("-"))
4883 extern const internal::VariadicFunction<
4884 internal::PolymorphicMatcherWithParam1<
4885 internal::HasAnyOperatorNameMatcher, std::vector<std::string>,
4886 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, UnaryOperator)>,
4887 StringRef, internal::hasAnyOperatorNameFunc>
4890 /// Matches all kinds of assignment operators.
4892 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4898 /// Example 2: matches s1 = s2
4899 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4901 /// struct S { S& operator=(const S&); };
4902 /// void x() { S s1, s2; s1 = s2; }
4904 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4905 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4906 CXXOperatorCallExpr)) {
4907 return Node.isAssignmentOp();
4910 /// Matches comparison operators.
4912 /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
4918 /// Example 2: matches s1 < s2
4919 /// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
4921 /// struct S { bool operator<(const S& other); };
4922 /// void x(S s1, S s2) { bool b1 = s1 < s2; }
4924 AST_POLYMORPHIC_MATCHER(isComparisonOperator,
4925 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4926 CXXOperatorCallExpr)) {
4927 return Node.isComparisonOp();
4930 /// Matches the left hand side of binary operator expressions.
4932 /// Example matches a (matcher = binaryOperator(hasLHS()))
4936 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4937 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4938 ArraySubscriptExpr),
4939 internal::Matcher<Expr>, InnerMatcher) {
4940 const Expr *LeftHandSide = Node.getLHS();
4941 return (LeftHandSide != nullptr &&
4942 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4945 /// Matches the right hand side of binary operator expressions.
4947 /// Example matches b (matcher = binaryOperator(hasRHS()))
4951 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4952 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4953 ArraySubscriptExpr),
4954 internal::Matcher<Expr>, InnerMatcher) {
4955 const Expr *RightHandSide = Node.getRHS();
4956 return (RightHandSide != nullptr &&
4957 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4960 /// Matches if either the left hand side or the right hand side of a
4961 /// binary operator matches.
4962 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4963 const internal::Matcher<Expr> &InnerMatcher) {
4964 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4967 /// Matches if both matchers match with opposite sides of the binary operator.
4969 /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
4970 /// integerLiteral(equals(2)))
4974 /// 1 + 1 // No match
4975 /// 2 + 2 // No match
4977 inline internal::Matcher<BinaryOperator>
4978 hasOperands(const internal::Matcher<Expr> &Matcher1,
4979 const internal::Matcher<Expr> &Matcher2) {
4980 return anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
4981 allOf(hasLHS(Matcher2), hasRHS(Matcher1)));
4984 /// Matches if the operand of a unary operator matches.
4986 /// Example matches true (matcher = hasUnaryOperand(
4987 /// cxxBoolLiteral(equals(true))))
4991 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4992 internal::Matcher<Expr>, InnerMatcher) {
4993 const Expr * const Operand = Node.getSubExpr();
4994 return (Operand != nullptr &&
4995 InnerMatcher.matches(*Operand, Finder, Builder));
4998 /// Matches if the cast's source expression
4999 /// or opaque value's source expression matches the given matcher.
5001 /// Example 1: matches "a string"
5002 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
5004 /// class URL { URL(string); };
5005 /// URL url = "a string";
5008 /// Example 2: matches 'b' (matcher =
5009 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
5013 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
5014 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
5016 internal::Matcher<Expr>, InnerMatcher) {
5017 const Expr *const SubExpression =
5018 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
5019 return (SubExpression != nullptr &&
5020 InnerMatcher.matches(*SubExpression, Finder, Builder));
5023 /// Matches casts that has a given cast kind.
5025 /// Example: matches the implicit cast around \c 0
5026 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
5031 /// If the matcher is use from clang-query, CastKind parameter
5032 /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
5033 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
5034 return Node.getCastKind() == Kind;
5037 /// Matches casts whose destination type matches a given matcher.
5039 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
5040 /// actual casts "explicit" casts.)
5041 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
5042 internal::Matcher<QualType>, InnerMatcher) {
5043 const QualType NodeType = Node.getTypeAsWritten();
5044 return InnerMatcher.matches(NodeType, Finder, Builder);
5047 /// Matches implicit casts whose destination type matches a given
5050 /// FIXME: Unit test this matcher
5051 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
5052 internal::Matcher<QualType>, InnerMatcher) {
5053 return InnerMatcher.matches(Node.getType(), Finder, Builder);
5056 /// Matches TagDecl object that are spelled with "struct."
5058 /// Example matches S, but not C, U or E.
5065 AST_MATCHER(TagDecl, isStruct) {
5066 return Node.isStruct();
5069 /// Matches TagDecl object that are spelled with "union."
5071 /// Example matches U, but not C, S or E.
5078 AST_MATCHER(TagDecl, isUnion) {
5079 return Node.isUnion();
5082 /// Matches TagDecl object that are spelled with "class."
5084 /// Example matches C, but not S, U or E.
5091 AST_MATCHER(TagDecl, isClass) {
5092 return Node.isClass();
5095 /// Matches TagDecl object that are spelled with "enum."
5097 /// Example matches E, but not C, S or U.
5104 AST_MATCHER(TagDecl, isEnum) {
5105 return Node.isEnum();
5108 /// Matches the true branch expression of a conditional operator.
5110 /// Example 1 (conditional ternary operator): matches a
5112 /// condition ? a : b
5115 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
5119 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
5120 internal::Matcher<Expr>, InnerMatcher) {
5121 const Expr *Expression = Node.getTrueExpr();
5122 return (Expression != nullptr &&
5123 InnerMatcher.matches(*Expression, Finder, Builder));
5126 /// Matches the false branch expression of a conditional operator
5127 /// (binary or ternary).
5129 /// Example matches b
5131 /// condition ? a : b
5134 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
5135 internal::Matcher<Expr>, InnerMatcher) {
5136 const Expr *Expression = Node.getFalseExpr();
5137 return (Expression != nullptr &&
5138 InnerMatcher.matches(*Expression, Finder, Builder));
5141 /// Matches if a declaration has a body attached.
5143 /// Example matches A, va, fa
5146 /// class B; // Doesn't match, as it has no body.
5148 /// extern int vb; // Doesn't match, as it doesn't define the variable.
5150 /// void fb(); // Doesn't match, as it has no body.
5152 /// - (void)ma; // Doesn't match, interface is declaration.
5154 /// @implementation X
5159 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
5160 /// Matcher<ObjCMethodDecl>
5161 AST_POLYMORPHIC_MATCHER(isDefinition,
5162 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
5165 return Node.isThisDeclarationADefinition();
5168 /// Matches if a function declaration is variadic.
5170 /// Example matches f, but not g or h. The function i will not match, even when
5171 /// compiled in C mode.
5175 /// template <typename... Ts> void h(Ts...);
5178 AST_MATCHER(FunctionDecl, isVariadic) {
5179 return Node.isVariadic();
5182 /// Matches the class declaration that the given method declaration
5185 /// FIXME: Generalize this for other kinds of declarations.
5186 /// FIXME: What other kind of declarations would we need to generalize
5189 /// Example matches A() in the last line
5190 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
5191 /// ofClass(hasName("A"))))))
5199 AST_MATCHER_P(CXXMethodDecl, ofClass,
5200 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
5201 const CXXRecordDecl *Parent = Node.getParent();
5202 return (Parent != nullptr &&
5203 InnerMatcher.matches(*Parent, Finder, Builder));
5206 /// Matches each method overridden by the given method. This matcher may
5207 /// produce multiple matches.
5211 /// class A { virtual void f(); };
5212 /// class B : public A { void f(); };
5213 /// class C : public B { void f(); };
5215 /// cxxMethodDecl(ofClass(hasName("C")),
5216 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5217 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
5218 /// that B::f is not overridden by C::f).
5220 /// The check can produce multiple matches in case of multiple inheritance, e.g.
5222 /// class A1 { virtual void f(); };
5223 /// class A2 { virtual void f(); };
5224 /// class C : public A1, public A2 { void f(); };
5226 /// cxxMethodDecl(ofClass(hasName("C")),
5227 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
5228 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
5229 /// once with "b" binding "A2::f" and "d" binding "C::f".
5230 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
5231 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
5232 BoundNodesTreeBuilder Result;
5233 bool Matched = false;
5234 for (const auto *Overridden : Node.overridden_methods()) {
5235 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
5236 const bool OverriddenMatched =
5237 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
5238 if (OverriddenMatched) {
5240 Result.addMatch(OverriddenBuilder);
5243 *Builder = std::move(Result);
5247 /// Matches declarations of virtual methods and C++ base specifers that specify
5248 /// virtual inheritance.
5254 /// virtual void x(); // matches x
5261 /// class DirectlyDerived : virtual Base {}; // matches Base
5262 /// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
5265 /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
5266 AST_POLYMORPHIC_MATCHER(isVirtual,
5267 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
5268 CXXBaseSpecifier)) {
5269 return Node.isVirtual();
5272 /// Matches if the given method declaration has an explicit "virtual".
5278 /// virtual void x();
5280 /// class B : public A {
5285 /// matches A::x but not B::x
5286 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
5287 return Node.isVirtualAsWritten();
5290 /// Matches if the given method or class declaration is final.
5294 /// class A final {};
5297 /// virtual void f();
5304 /// matches A and C::f, but not B, C, or B::f
5305 AST_POLYMORPHIC_MATCHER(isFinal,
5306 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
5308 return Node.template hasAttr<FinalAttr>();
5311 /// Matches if the given method declaration is pure.
5317 /// virtual void x() = 0;
5321 AST_MATCHER(CXXMethodDecl, isPure) {
5322 return Node.isPure();
5325 /// Matches if the given method declaration is const.
5330 /// void foo() const;
5335 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
5336 AST_MATCHER(CXXMethodDecl, isConst) {
5337 return Node.isConst();
5340 /// Matches if the given method declaration declares a copy assignment
5346 /// A &operator=(const A &);
5347 /// A &operator=(A &&);
5351 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
5353 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
5354 return Node.isCopyAssignmentOperator();
5357 /// Matches if the given method declaration declares a move assignment
5363 /// A &operator=(const A &);
5364 /// A &operator=(A &&);
5368 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
5370 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
5371 return Node.isMoveAssignmentOperator();
5374 /// Matches if the given method declaration overrides another method.
5380 /// virtual void x();
5382 /// class B : public A {
5384 /// virtual void x();
5388 AST_MATCHER(CXXMethodDecl, isOverride) {
5389 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
5392 /// Matches method declarations that are user-provided.
5398 /// S(const S &) = default; // #2
5399 /// S(S &&) = delete; // #3
5402 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
5403 AST_MATCHER(CXXMethodDecl, isUserProvided) {
5404 return Node.isUserProvided();
5407 /// Matches member expressions that are called with '->' as opposed
5410 /// Member calls on the implicit this pointer match as called with '->'.
5415 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
5416 /// template <class T> void f() { this->f<T>(); f<T>(); }
5420 /// template <class T>
5422 /// void x() { this->m; }
5425 /// memberExpr(isArrow())
5426 /// matches this->x, x, y.x, a, this->b
5427 /// cxxDependentScopeMemberExpr(isArrow())
5429 /// unresolvedMemberExpr(isArrow())
5430 /// matches this->f<T>, f<T>
5431 AST_POLYMORPHIC_MATCHER(
5432 isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
5433 CXXDependentScopeMemberExpr)) {
5434 return Node.isArrow();
5437 /// Matches QualType nodes that are of integer type.
5445 /// functionDecl(hasAnyParameter(hasType(isInteger())))
5446 /// matches "a(int)", "b(long)", but not "c(double)".
5447 AST_MATCHER(QualType, isInteger) {
5448 return Node->isIntegerType();
5451 /// Matches QualType nodes that are of unsigned integer type.
5456 /// void b(unsigned long);
5459 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
5460 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
5461 AST_MATCHER(QualType, isUnsignedInteger) {
5462 return Node->isUnsignedIntegerType();
5465 /// Matches QualType nodes that are of signed integer type.
5470 /// void b(unsigned long);
5473 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
5474 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
5475 AST_MATCHER(QualType, isSignedInteger) {
5476 return Node->isSignedIntegerType();
5479 /// Matches QualType nodes that are of character type.
5484 /// void b(wchar_t);
5487 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
5488 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
5489 AST_MATCHER(QualType, isAnyCharacter) {
5490 return Node->isAnyCharacterType();
5493 /// Matches QualType nodes that are of any pointer type; this includes
5494 /// the Objective-C object pointer type, which is different despite being
5495 /// syntactically similar.
5499 /// int *i = nullptr;
5507 /// varDecl(hasType(isAnyPointer()))
5508 /// matches "int *i" and "Foo *f", but not "int j".
5509 AST_MATCHER(QualType, isAnyPointer) {
5510 return Node->isAnyPointerType();
5513 /// Matches QualType nodes that are const-qualified, i.e., that
5514 /// include "top-level" const.
5519 /// void b(int const);
5520 /// void c(const int);
5521 /// void d(const int*);
5522 /// void e(int const) {};
5524 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
5525 /// matches "void b(int const)", "void c(const int)" and
5526 /// "void e(int const) {}". It does not match d as there
5527 /// is no top-level const on the parameter type "const int *".
5528 AST_MATCHER(QualType, isConstQualified) {
5529 return Node.isConstQualified();
5532 /// Matches QualType nodes that are volatile-qualified, i.e., that
5533 /// include "top-level" volatile.
5538 /// void b(int volatile);
5539 /// void c(volatile int);
5540 /// void d(volatile int*);
5541 /// void e(int volatile) {};
5543 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
5544 /// matches "void b(int volatile)", "void c(volatile int)" and
5545 /// "void e(int volatile) {}". It does not match d as there
5546 /// is no top-level volatile on the parameter type "volatile int *".
5547 AST_MATCHER(QualType, isVolatileQualified) {
5548 return Node.isVolatileQualified();
5551 /// Matches QualType nodes that have local CV-qualifiers attached to
5552 /// the node, not hidden within a typedef.
5556 /// typedef const int const_int;
5559 /// int *volatile k;
5562 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
5563 /// \c i is const-qualified but the qualifier is not local.
5564 AST_MATCHER(QualType, hasLocalQualifiers) {
5565 return Node.hasLocalQualifiers();
5568 /// Matches a member expression where the member is matched by a
5573 /// struct { int first, second; } first, second;
5574 /// int i(second.first);
5575 /// int j(first.second);
5577 /// memberExpr(member(hasName("first")))
5578 /// matches second.first
5579 /// but not first.second (because the member name there is "second").
5580 AST_MATCHER_P(MemberExpr, member,
5581 internal::Matcher<ValueDecl>, InnerMatcher) {
5582 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
5585 /// Matches a member expression where the object expression is matched by a
5586 /// given matcher. Implicit object expressions are included; that is, it matches
5587 /// use of implicit `this`.
5593 /// int f(X x) { x.m; return m; }
5596 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
5597 /// matches `x.m`, but not `m`; however,
5598 /// memberExpr(hasObjectExpression(hasType(pointsTo(
5599 // cxxRecordDecl(hasName("X"))))))
5600 /// matches `m` (aka. `this->m`), but not `x.m`.
5601 AST_POLYMORPHIC_MATCHER_P(
5602 hasObjectExpression,
5603 AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
5604 CXXDependentScopeMemberExpr),
5605 internal::Matcher<Expr>, InnerMatcher) {
5606 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
5607 if (E->isImplicitAccess())
5609 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
5610 if (E->isImplicitAccess())
5612 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
5615 /// Matches any using shadow declaration.
5619 /// namespace X { void b(); }
5622 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
5623 /// matches \code using X::b \endcode
5624 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
5625 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
5626 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
5627 Node.shadow_end(), Finder, Builder);
5630 /// Matches a using shadow declaration where the target declaration is
5631 /// matched by the given matcher.
5635 /// namespace X { int a; void b(); }
5639 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
5640 /// matches \code using X::b \endcode
5641 /// but not \code using X::a \endcode
5642 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
5643 internal::Matcher<NamedDecl>, InnerMatcher) {
5644 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
5647 /// Matches template instantiations of function, class, or static
5648 /// member variable template instantiations.
5652 /// template <typename T> class X {}; class A {}; X<A> x;
5656 /// template <typename T> class X {}; class A {}; template class X<A>;
5660 /// template <typename T> class X {}; class A {}; extern template class X<A>;
5662 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5663 /// matches the template instantiation of X<A>.
5667 /// template <typename T> class X {}; class A {};
5668 /// template <> class X<A> {}; X<A> x;
5670 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5671 /// does not match, as X<A> is an explicit template specialization.
5673 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5674 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
5675 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5677 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
5678 Node.getTemplateSpecializationKind() ==
5679 TSK_ExplicitInstantiationDefinition ||
5680 Node.getTemplateSpecializationKind() ==
5681 TSK_ExplicitInstantiationDeclaration);
5684 /// Matches declarations that are template instantiations or are inside
5685 /// template instantiations.
5689 /// template<typename T> void A(T t) { T i; }
5693 /// functionDecl(isInstantiated())
5694 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
5695 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
5696 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5697 functionDecl(isTemplateInstantiation())));
5698 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
5701 /// Matches statements inside of a template instantiation.
5706 /// template<typename T> void A(T t) { T i; j += 42;}
5710 /// declStmt(isInTemplateInstantiation())
5711 /// matches 'int i;' and 'unsigned i'.
5712 /// unless(stmt(isInTemplateInstantiation()))
5713 /// will NOT match j += 42; as it's shared between the template definition and
5715 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
5717 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5718 functionDecl(isTemplateInstantiation())))));
5721 /// Matches explicit template specializations of function, class, or
5722 /// static member variable template instantiations.
5726 /// template<typename T> void A(T t) { }
5727 /// template<> void A(int N) { }
5729 /// functionDecl(isExplicitTemplateSpecialization())
5730 /// matches the specialization A<int>().
5732 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5733 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
5734 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5736 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
5739 /// Matches \c TypeLocs for which the given inner
5740 /// QualType-matcher matches.
5741 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
5742 internal::Matcher<QualType>, InnerMatcher, 0) {
5743 return internal::BindableMatcher<TypeLoc>(
5744 new internal::TypeLocTypeMatcher(InnerMatcher));
5747 /// Matches type \c bool.
5751 /// struct S { bool func(); };
5753 /// functionDecl(returns(booleanType()))
5754 /// matches "bool func();"
5755 AST_MATCHER(Type, booleanType) {
5756 return Node.isBooleanType();
5759 /// Matches type \c void.
5763 /// struct S { void func(); };
5765 /// functionDecl(returns(voidType()))
5766 /// matches "void func();"
5767 AST_MATCHER(Type, voidType) {
5768 return Node.isVoidType();
5771 template <typename NodeType>
5772 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
5774 /// Matches builtin Types.
5785 /// matches "int b", "float c" and "bool d"
5786 extern const AstTypeMatcher<BuiltinType> builtinType;
5788 /// Matches all kinds of arrays.
5792 /// int a[] = { 2, 3 };
5794 /// void f() { int c[a[0]]; }
5797 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
5798 extern const AstTypeMatcher<ArrayType> arrayType;
5800 /// Matches C99 complex types.
5804 /// _Complex float f;
5807 /// matches "_Complex float f"
5808 extern const AstTypeMatcher<ComplexType> complexType;
5810 /// Matches any real floating-point type (float, double, long double).
5817 /// realFloatingPointType()
5818 /// matches "float f" but not "int i"
5819 AST_MATCHER(Type, realFloatingPointType) {
5820 return Node.isRealFloatingType();
5823 /// Matches arrays and C99 complex types that have a specific element
5832 /// arrayType(hasElementType(builtinType()))
5833 /// matches "int b[7]"
5835 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5836 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5837 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5840 /// Matches C arrays with a specified constant size.
5846 /// int b[] = { 2, 3 };
5850 /// constantArrayType()
5851 /// matches "int a[2]"
5852 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5854 /// Matches nodes that have the specified size.
5860 /// int c[41], d[43];
5861 /// char *s = "abcd";
5862 /// wchar_t *ws = L"abcd";
5865 /// constantArrayType(hasSize(42))
5866 /// matches "int a[42]" and "int b[2 * 21]"
5867 /// stringLiteral(hasSize(4))
5868 /// matches "abcd", L"abcd"
5869 AST_POLYMORPHIC_MATCHER_P(hasSize,
5870 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5873 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5876 /// Matches C++ arrays whose size is a value-dependent expression.
5880 /// template<typename T, int Size>
5885 /// dependentSizedArrayType
5886 /// matches "T data[Size]"
5887 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5889 /// Matches C arrays with unspecified size.
5893 /// int a[] = { 2, 3 };
5895 /// void f(int c[]) { int d[a[0]]; };
5897 /// incompleteArrayType()
5898 /// matches "int a[]" and "int c[]"
5899 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5901 /// Matches C arrays with a specified size that is not an
5902 /// integer-constant-expression.
5907 /// int a[] = { 2, 3 }
5912 /// variableArrayType()
5913 /// matches "int c[a[0]]"
5914 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5916 /// Matches \c VariableArrayType nodes that have a specific size
5925 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5926 /// varDecl(hasName("b")))))))
5927 /// matches "int a[b]"
5928 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5929 internal::Matcher<Expr>, InnerMatcher) {
5930 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5933 /// Matches atomic types.
5940 /// matches "_Atomic(int) i"
5941 extern const AstTypeMatcher<AtomicType> atomicType;
5943 /// Matches atomic types with a specific value type.
5948 /// _Atomic(float) f;
5950 /// atomicType(hasValueType(isInteger()))
5951 /// matches "_Atomic(int) i"
5953 /// Usable as: Matcher<AtomicType>
5954 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5955 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5957 /// Matches types nodes representing C++11 auto types.
5962 /// int v[] = { 2, 3 }
5963 /// for (auto i : v) { }
5966 /// matches "auto n" and "auto i"
5967 extern const AstTypeMatcher<AutoType> autoType;
5969 /// Matches types nodes representing C++11 decltype(<expr>) types.
5975 /// decltype(i + j) result = i + j;
5978 /// matches "decltype(i + j)"
5979 extern const AstTypeMatcher<DecltypeType> decltypeType;
5981 /// Matches \c AutoType nodes where the deduced type is a specific type.
5983 /// Note: There is no \c TypeLoc for the deduced type and thus no
5984 /// \c getDeducedLoc() matcher.
5991 /// autoType(hasDeducedType(isInteger()))
5992 /// matches "auto a"
5994 /// Usable as: Matcher<AutoType>
5995 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5996 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5998 /// Matches \c DecltypeType nodes to find out the underlying type.
6002 /// decltype(1) a = 1;
6003 /// decltype(2.0) b = 2.0;
6005 /// decltypeType(hasUnderlyingType(isInteger()))
6006 /// matches the type of "a"
6008 /// Usable as: Matcher<DecltypeType>
6009 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
6010 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
6012 /// Matches \c FunctionType nodes.
6020 /// matches "int (*f)(int)" and the type of "g".
6021 extern const AstTypeMatcher<FunctionType> functionType;
6023 /// Matches \c FunctionProtoType nodes.
6030 /// functionProtoType()
6031 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
6032 /// In C mode, "g" is not matched because it does not contain a prototype.
6033 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
6035 /// Matches \c ParenType nodes.
6039 /// int (*ptr_to_array)[4];
6040 /// int *array_of_ptrs[4];
6043 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
6044 /// \c array_of_ptrs.
6045 extern const AstTypeMatcher<ParenType> parenType;
6047 /// Matches \c ParenType nodes where the inner type is a specific type.
6051 /// int (*ptr_to_array)[4];
6052 /// int (*ptr_to_func)(int);
6055 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
6056 /// \c ptr_to_func but not \c ptr_to_array.
6058 /// Usable as: Matcher<ParenType>
6059 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
6060 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
6062 /// Matches block pointer types, i.e. types syntactically represented as
6063 /// "void (^)(int)".
6065 /// The \c pointee is always required to be a \c FunctionType.
6066 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
6068 /// Matches member pointer types.
6071 /// struct A { int i; }
6072 /// A::* ptr = A::i;
6074 /// memberPointerType()
6075 /// matches "A::* ptr"
6076 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
6078 /// Matches pointer types, but does not match Objective-C object pointer
6092 /// matches "int *a", but does not match "Foo *f".
6093 extern const AstTypeMatcher<PointerType> pointerType;
6095 /// Matches an Objective-C object pointer type, which is different from
6096 /// a pointer type, despite being syntactically similar.
6107 /// matches "Foo *f", but does not match "int *a".
6108 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
6110 /// Matches both lvalue and rvalue reference types.
6123 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
6124 extern const AstTypeMatcher<ReferenceType> referenceType;
6126 /// Matches lvalue reference types.
6139 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
6140 /// matched since the type is deduced as int& by reference collapsing rules.
6141 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
6143 /// Matches rvalue reference types.
6156 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
6157 /// matched as it is deduced to int& by reference collapsing rules.
6158 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
6160 /// Narrows PointerType (and similar) matchers to those where the
6161 /// \c pointee matches a given matcher.
6169 /// pointerType(pointee(isConstQualified(), isInteger()))
6170 /// matches "int const *b"
6172 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
6173 /// Matcher<PointerType>, Matcher<ReferenceType>
6174 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
6175 pointee, getPointee,
6176 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
6177 PointerType, ReferenceType));
6179 /// Matches typedef types.
6186 /// matches "typedef int X"
6187 extern const AstTypeMatcher<TypedefType> typedefType;
6189 /// Matches enum types.
6193 /// enum C { Green };
6194 /// enum class S { Red };
6200 /// \c enumType() matches the type of the variable declarations of both \c c and
6202 extern const AstTypeMatcher<EnumType> enumType;
6204 /// Matches template specialization types.
6208 /// template <typename T>
6211 /// template class C<int>; // A
6212 /// C<char> var; // B
6215 /// \c templateSpecializationType() matches the type of the explicit
6216 /// instantiation in \c A and the type of the variable declaration in \c B.
6217 extern const AstTypeMatcher<TemplateSpecializationType>
6218 templateSpecializationType;
6220 /// Matches C++17 deduced template specialization types, e.g. deduced class
6225 /// template <typename T>
6226 /// class C { public: C(T); };
6230 /// \c deducedTemplateSpecializationType() matches the type in the declaration
6231 /// of the variable \c c.
6232 extern const AstTypeMatcher<DeducedTemplateSpecializationType>
6233 deducedTemplateSpecializationType;
6235 /// Matches types nodes representing unary type transformations.
6239 /// typedef __underlying_type(T) type;
6241 /// unaryTransformType()
6242 /// matches "__underlying_type(T)"
6243 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
6245 /// Matches record types (e.g. structs, classes).
6256 /// \c recordType() matches the type of the variable declarations of both \c c
6258 extern const AstTypeMatcher<RecordType> recordType;
6260 /// Matches tag types (record and enum types).
6271 /// \c tagType() matches the type of the variable declarations of both \c e
6273 extern const AstTypeMatcher<TagType> tagType;
6275 /// Matches types specified with an elaborated type keyword or with a
6291 /// \c elaboratedType() matches the type of the variable declarations of both
6293 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
6295 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
6296 /// matches \c InnerMatcher if the qualifier exists.
6308 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
6309 /// matches the type of the variable declaration of \c d.
6310 AST_MATCHER_P(ElaboratedType, hasQualifier,
6311 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
6312 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
6313 return InnerMatcher.matches(*Qualifier, Finder, Builder);
6318 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
6330 /// \c elaboratedType(namesType(recordType(
6331 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
6332 /// declaration of \c d.
6333 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
6335 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
6338 /// Matches types that represent the result of substituting a type for a
6339 /// template type parameter.
6343 /// template <typename T>
6349 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
6350 extern const AstTypeMatcher<SubstTemplateTypeParmType>
6351 substTemplateTypeParmType;
6353 /// Matches template type parameter substitutions that have a replacement
6354 /// type that matches the provided matcher.
6358 /// template <typename T>
6361 /// double j = F(i);
6364 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
6365 AST_TYPE_TRAVERSE_MATCHER(
6366 hasReplacementType, getReplacementType,
6367 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
6369 /// Matches template type parameter types.
6371 /// Example matches T, but not int.
6372 /// (matcher = templateTypeParmType())
6374 /// template <typename T> void f(int i);
6376 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
6378 /// Matches injected class name types.
6380 /// Example matches S s, but not S<T> s.
6381 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
6383 /// template <typename T> struct S {
6388 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
6390 /// Matches decayed type
6391 /// Example matches i[] in declaration of f.
6392 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
6393 /// Example matches i[1].
6394 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
6396 /// void f(int i[]) {
6400 extern const AstTypeMatcher<DecayedType> decayedType;
6402 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
6403 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
6405 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
6408 /// Matches declarations whose declaration context, interpreted as a
6409 /// Decl, matches \c InnerMatcher.
6420 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
6421 /// declaration of \c class \c D.
6422 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
6423 const DeclContext *DC = Node.getDeclContext();
6424 if (!DC) return false;
6425 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
6428 /// Matches nested name specifiers.
6433 /// struct A { static void f(); };
6435 /// void g() { A::f(); }
6439 /// nestedNameSpecifier()
6440 /// matches "ns::" and both "A::"
6441 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
6442 nestedNameSpecifier;
6444 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
6445 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
6446 nestedNameSpecifierLoc;
6448 /// Matches \c NestedNameSpecifierLocs for which the given inner
6449 /// NestedNameSpecifier-matcher matches.
6450 AST_MATCHER_FUNCTION_P_OVERLOAD(
6451 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
6452 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
6453 return internal::BindableMatcher<NestedNameSpecifierLoc>(
6454 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
6458 /// Matches nested name specifiers that specify a type matching the
6459 /// given \c QualType matcher without qualifiers.
6463 /// struct A { struct B { struct C {}; }; };
6466 /// nestedNameSpecifier(specifiesType(
6467 /// hasDeclaration(cxxRecordDecl(hasName("A")))
6470 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
6471 internal::Matcher<QualType>, InnerMatcher) {
6472 if (!Node.getAsType())
6474 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
6477 /// Matches nested name specifier locs that specify a type matching the
6478 /// given \c TypeLoc.
6482 /// struct A { struct B { struct C {}; }; };
6485 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
6486 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
6488 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
6489 internal::Matcher<TypeLoc>, InnerMatcher) {
6490 return Node && Node.getNestedNameSpecifier()->getAsType() &&
6491 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
6494 /// Matches on the prefix of a \c NestedNameSpecifier.
6498 /// struct A { struct B { struct C {}; }; };
6501 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
6503 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
6504 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
6506 const NestedNameSpecifier *NextNode = Node.getPrefix();
6509 return InnerMatcher.matches(*NextNode, Finder, Builder);
6512 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
6516 /// struct A { struct B { struct C {}; }; };
6519 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
6521 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
6522 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
6524 NestedNameSpecifierLoc NextNode = Node.getPrefix();
6527 return InnerMatcher.matches(NextNode, Finder, Builder);
6530 /// Matches nested name specifiers that specify a namespace matching the
6531 /// given namespace matcher.
6535 /// namespace ns { struct A {}; }
6538 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
6540 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
6541 internal::Matcher<NamespaceDecl>, InnerMatcher) {
6542 if (!Node.getAsNamespace())
6544 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
6547 /// Overloads for the \c equalsNode matcher.
6548 /// FIXME: Implement for other node types.
6551 /// Matches if a node equals another node.
6553 /// \c Decl has pointer identity in the AST.
6554 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
6555 return &Node == Other;
6557 /// Matches if a node equals another node.
6559 /// \c Stmt has pointer identity in the AST.
6560 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
6561 return &Node == Other;
6563 /// Matches if a node equals another node.
6565 /// \c Type has pointer identity in the AST.
6566 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
6567 return &Node == Other;
6572 /// Matches each case or default statement belonging to the given switch
6573 /// statement. This matcher may produce multiple matches.
6577 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
6579 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
6580 /// matches four times, with "c" binding each of "case 1:", "case 2:",
6581 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
6582 /// "switch (1)", "switch (2)" and "switch (2)".
6583 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
6585 BoundNodesTreeBuilder Result;
6586 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
6587 // iteration order. We should use the more general iterating matchers once
6588 // they are capable of expressing this matcher (for example, it should ignore
6589 // case statements belonging to nested switch statements).
6590 bool Matched = false;
6591 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
6592 SC = SC->getNextSwitchCase()) {
6593 BoundNodesTreeBuilder CaseBuilder(*Builder);
6594 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
6597 Result.addMatch(CaseBuilder);
6600 *Builder = std::move(Result);
6604 /// Matches each constructor initializer in a constructor definition.
6608 /// class A { A() : i(42), j(42) {} int i; int j; };
6610 /// cxxConstructorDecl(forEachConstructorInitializer(
6611 /// forField(decl().bind("x"))
6613 /// will trigger two matches, binding for 'i' and 'j' respectively.
6614 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
6615 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
6616 BoundNodesTreeBuilder Result;
6617 bool Matched = false;
6618 for (const auto *I : Node.inits()) {
6619 BoundNodesTreeBuilder InitBuilder(*Builder);
6620 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
6622 Result.addMatch(InitBuilder);
6625 *Builder = std::move(Result);
6629 /// Matches constructor declarations that are copy constructors.
6635 /// S(const S &); // #2
6639 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
6640 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
6641 return Node.isCopyConstructor();
6644 /// Matches constructor declarations that are move constructors.
6650 /// S(const S &); // #2
6654 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
6655 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
6656 return Node.isMoveConstructor();
6659 /// Matches constructor declarations that are default constructors.
6665 /// S(const S &); // #2
6669 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
6670 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
6671 return Node.isDefaultConstructor();
6674 /// Matches constructors that delegate to another constructor.
6681 /// S(S &&) : S() {} // #3
6683 /// S::S() : S(0) {} // #4
6685 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
6687 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
6688 return Node.isDelegatingConstructor();
6691 /// Matches constructor, conversion function, and deduction guide declarations
6692 /// that have an explicit specifier if this explicit specifier is resolved to
6697 /// template<bool b>
6700 /// explicit S(double); // #2
6701 /// operator int(); // #3
6702 /// explicit operator bool(); // #4
6703 /// explicit(false) S(bool) // # 7
6704 /// explicit(true) S(char) // # 8
6705 /// explicit(b) S(S) // # 9
6707 /// S(int) -> S<true> // #5
6708 /// explicit S(double) -> S<false> // #6
6710 /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
6711 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
6712 /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
6713 AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
6714 CXXConstructorDecl, CXXConversionDecl,
6715 CXXDeductionGuideDecl)) {
6716 return Node.isExplicit();
6719 /// Matches the expression in an explicit specifier if present in the given
6724 /// template<bool b>
6727 /// explicit S(double); // #2
6728 /// operator int(); // #3
6729 /// explicit operator bool(); // #4
6730 /// explicit(false) S(bool) // # 7
6731 /// explicit(true) S(char) // # 8
6732 /// explicit(b) S(S) // # 9
6734 /// S(int) -> S<true> // #5
6735 /// explicit S(double) -> S<false> // #6
6737 /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
6738 /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
6739 /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
6740 AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
6742 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
6745 return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
6748 /// Matches function and namespace declarations that are marked with
6749 /// the inline keyword.
6753 /// inline void f();
6756 /// inline namespace m {}
6759 /// functionDecl(isInline()) will match ::f().
6760 /// namespaceDecl(isInline()) will match n::m.
6761 AST_POLYMORPHIC_MATCHER(isInline,
6762 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
6764 // This is required because the spelling of the function used to determine
6765 // whether inline is specified or not differs between the polymorphic types.
6766 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
6767 return FD->isInlineSpecified();
6768 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
6769 return NSD->isInline();
6770 llvm_unreachable("Not a valid polymorphic type");
6773 /// Matches anonymous namespace declarations.
6778 /// namespace {} // #1
6781 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
6782 AST_MATCHER(NamespaceDecl, isAnonymous) {
6783 return Node.isAnonymousNamespace();
6786 /// Matches declarations in the namespace `std`, but not in nested namespaces.
6790 /// class vector {};
6792 /// class vector {};
6794 /// class vector {};
6798 /// inline namespace __1 {
6799 /// class vector {}; // #1
6800 /// namespace experimental {
6801 /// class vector {};
6806 /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
6807 AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
6809 /// If the given case statement does not use the GNU case range
6810 /// extension, matches the constant given in the statement.
6814 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
6816 /// caseStmt(hasCaseConstant(integerLiteral()))
6817 /// matches "case 1:"
6818 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
6823 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
6826 /// Matches declaration that has a given attribute.
6830 /// __attribute__((device)) void f() { ... }
6832 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
6833 /// f. If the matcher is used from clang-query, attr::Kind parameter should be
6834 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
6835 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
6836 for (const auto *Attr : Node.attrs()) {
6837 if (Attr->getKind() == AttrKind)
6843 /// Matches the return value expression of a return statement
6849 /// hasReturnValue(binaryOperator())
6850 /// matches 'return a + b'
6851 /// with binaryOperator()
6852 /// matching 'a + b'
6853 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
6855 if (const auto *RetValue = Node.getRetValue())
6856 return InnerMatcher.matches(*RetValue, Finder, Builder);
6860 /// Matches CUDA kernel call expression.
6862 /// Example matches,
6864 /// kernel<<<i,j>>>();
6866 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
6869 /// Matches expressions that resolve to a null pointer constant, such as
6870 /// GNU's __null, C++11's nullptr, or C's NULL macro.
6874 /// void *v1 = NULL;
6875 /// void *v2 = nullptr;
6876 /// void *v3 = __null; // GNU extension
6877 /// char *cp = (char *)0;
6881 /// expr(nullPointerConstant())
6882 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
6883 /// initializer for i.
6884 AST_MATCHER(Expr, nullPointerConstant) {
6885 return Node.isNullPointerConstant(Finder->getASTContext(),
6886 Expr::NPC_ValueDependentIsNull);
6889 /// Matches declaration of the function the statement belongs to
6893 /// F& operator=(const F& o) {
6894 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
6898 /// returnStmt(forFunction(hasName("operator=")))
6899 /// matches 'return *this'
6900 /// but does not match 'return v > 0'
6901 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
6903 const auto &Parents = Finder->getASTContext().getParents(Node);
6905 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
6906 while(!Stack.empty()) {
6907 const auto &CurNode = Stack.back();
6909 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6910 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6913 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6914 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6919 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6920 Stack.push_back(Parent);
6926 /// Matches a declaration that has external formal linkage.
6928 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6937 /// Example matches f() because it has external formal linkage despite being
6938 /// unique to the translation unit as though it has internal likage
6939 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6946 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6947 return Node.hasExternalFormalLinkage();
6950 /// Matches a declaration that has default arguments.
6952 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6954 /// void x(int val) {}
6955 /// void y(int val = 0) {}
6958 /// Deprecated. Use hasInitializer() instead to be able to
6959 /// match on the contents of the default argument. For example:
6962 /// void x(int val = 7) {}
6963 /// void y(int val = 42) {}
6965 /// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
6966 /// matches the parameter of y
6968 /// A matcher such as
6969 /// parmVarDecl(hasInitializer(anything()))
6970 /// is equivalent to parmVarDecl(hasDefaultArgument()).
6971 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6972 return Node.hasDefaultArg();
6975 /// Matches array new expressions.
6979 /// MyClass *p1 = new MyClass[10];
6981 /// cxxNewExpr(isArray())
6982 /// matches the expression 'new MyClass[10]'.
6983 AST_MATCHER(CXXNewExpr, isArray) {
6984 return Node.isArray();
6987 /// Matches placement new expression arguments.
6991 /// MyClass *p1 = new (Storage, 16) MyClass();
6993 /// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
6994 /// matches the expression 'new (Storage, 16) MyClass()'.
6995 AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
6996 internal::Matcher<Expr>, InnerMatcher) {
6997 return Node.getNumPlacementArgs() > Index &&
6998 InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
7001 /// Matches any placement new expression arguments.
7005 /// MyClass *p1 = new (Storage) MyClass();
7007 /// cxxNewExpr(hasAnyPlacementArg(anything()))
7008 /// matches the expression 'new (Storage, 16) MyClass()'.
7009 AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
7011 return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
7012 return InnerMatcher.matches(*Arg, Finder, Builder);
7016 /// Matches array new expressions with a given array size.
7020 /// MyClass *p1 = new MyClass[10];
7022 /// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
7023 /// matches the expression 'new MyClass[10]'.
7024 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
7025 return Node.isArray() && *Node.getArraySize() &&
7026 InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
7029 /// Matches a class declaration that is defined.
7031 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
7036 AST_MATCHER(CXXRecordDecl, hasDefinition) {
7037 return Node.hasDefinition();
7040 /// Matches C++11 scoped enum declaration.
7042 /// Example matches Y (matcher = enumDecl(isScoped()))
7045 /// enum class Y {};
7047 AST_MATCHER(EnumDecl, isScoped) {
7048 return Node.isScoped();
7051 /// Matches a function declared with a trailing return type.
7053 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
7056 /// auto Y() -> int {}
7058 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
7059 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
7060 return F->hasTrailingReturn();
7064 /// Matches expressions that match InnerMatcher that are possibly wrapped in an
7065 /// elidable constructor and other corresponding bookkeeping nodes.
7067 /// In C++17, elidable copy constructors are no longer being generated in the
7068 /// AST as it is not permitted by the standard. They are, however, part of the
7069 /// AST in C++14 and earlier. So, a matcher must abstract over these differences
7070 /// to work in all language modes. This matcher skips elidable constructor-call
7071 /// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
7072 /// various implicit nodes inside the constructor calls, all of which will not
7073 /// appear in the C++17 AST.
7085 /// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
7086 /// matches ``H D = G()`` in C++11 through C++17 (and beyond).
7087 AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
7088 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
7089 // E tracks the node that we are examining.
7090 const Expr *E = &Node;
7091 // If present, remove an outer `ExprWithCleanups` corresponding to the
7092 // underlying `CXXConstructExpr`. This check won't cover all cases of added
7093 // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
7094 // EWC is placed on the outermost node of the expression, which this may not
7095 // be), but, it still improves the coverage of this matcher.
7096 if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
7097 E = CleanupsExpr->getSubExpr();
7098 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
7099 if (CtorExpr->isElidable()) {
7100 if (const auto *MaterializeTemp =
7101 dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
7102 return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
7107 return InnerMatcher.matches(Node, Finder, Builder);
7110 //----------------------------------------------------------------------------//
7112 //----------------------------------------------------------------------------//
7114 /// Matches any ``#pragma omp`` executable directive.
7119 /// #pragma omp parallel
7120 /// #pragma omp parallel default(none)
7121 /// #pragma omp taskyield
7124 /// ``ompExecutableDirective()`` matches ``omp parallel``,
7125 /// ``omp parallel default(none)`` and ``omp taskyield``.
7126 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
7127 ompExecutableDirective;
7129 /// Matches standalone OpenMP directives,
7130 /// i.e., directives that can't have a structured block.
7135 /// #pragma omp parallel
7137 /// #pragma omp taskyield
7140 /// ``ompExecutableDirective(isStandaloneDirective()))`` matches
7141 /// ``omp taskyield``.
7142 AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
7143 return Node.isStandaloneDirective();
7146 /// Matches the structured-block of the OpenMP executable directive
7148 /// Prerequisite: the executable directive must not be standalone directive.
7149 /// If it is, it will never match.
7154 /// #pragma omp parallel
7156 /// #pragma omp parallel
7160 /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
7161 AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
7162 internal::Matcher<Stmt>, InnerMatcher) {
7163 if (Node.isStandaloneDirective())
7164 return false; // Standalone directives have no structured blocks.
7165 return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
7168 /// Matches any clause in an OpenMP directive.
7173 /// #pragma omp parallel
7174 /// #pragma omp parallel default(none)
7177 /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
7178 /// ``omp parallel default(none)``.
7179 AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
7180 internal::Matcher<OMPClause>, InnerMatcher) {
7181 ArrayRef<OMPClause *> Clauses = Node.clauses();
7182 return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
7183 Clauses.end(), Finder, Builder);
7186 /// Matches OpenMP ``default`` clause.
7191 /// #pragma omp parallel default(none)
7192 /// #pragma omp parallel default(shared)
7193 /// #pragma omp parallel default(firstprivate)
7194 /// #pragma omp parallel
7197 /// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and
7198 /// ``default(firstprivate)``
7199 extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
7202 /// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
7207 /// #pragma omp parallel
7208 /// #pragma omp parallel default(none)
7209 /// #pragma omp parallel default(shared)
7210 /// #pragma omp parallel default(firstprivate)
7213 /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
7214 AST_MATCHER(OMPDefaultClause, isNoneKind) {
7215 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
7218 /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
7223 /// #pragma omp parallel
7224 /// #pragma omp parallel default(none)
7225 /// #pragma omp parallel default(shared)
7226 /// #pragma omp parallel default(firstprivate)
7229 /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
7230 AST_MATCHER(OMPDefaultClause, isSharedKind) {
7231 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
7234 /// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
7240 /// #pragma omp parallel
7241 /// #pragma omp parallel default(none)
7242 /// #pragma omp parallel default(shared)
7243 /// #pragma omp parallel default(firstprivate)
7246 /// ``ompDefaultClause(isFirstPrivateKind())`` matches only
7247 /// ``default(firstprivate)``.
7248 AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
7249 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
7252 /// Matches if the OpenMP directive is allowed to contain the specified OpenMP
7258 /// #pragma omp parallel
7259 /// #pragma omp parallel for
7263 /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
7264 /// ``omp parallel`` and ``omp parallel for``.
7266 /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
7267 /// should be passed as a quoted string. e.g.,
7268 /// ``isAllowedToContainClauseKind("OMPC_default").``
7269 AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
7270 OpenMPClauseKind, CKind) {
7271 return llvm::omp::isAllowedClauseForDirective(
7272 Node.getDirectiveKind(), CKind,
7273 Finder->getASTContext().getLangOpts().OpenMP);
7276 //----------------------------------------------------------------------------//
7277 // End OpenMP handling.
7278 //----------------------------------------------------------------------------//
7280 } // namespace ast_matchers
7281 } // namespace clang
7283 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H