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/Decl.h"
51 #include "clang/AST/DeclCXX.h"
52 #include "clang/AST/DeclFriend.h"
53 #include "clang/AST/DeclObjC.h"
54 #include "clang/AST/DeclTemplate.h"
55 #include "clang/AST/Expr.h"
56 #include "clang/AST/ExprCXX.h"
57 #include "clang/AST/ExprObjC.h"
58 #include "clang/AST/NestedNameSpecifier.h"
59 #include "clang/AST/OpenMPClause.h"
60 #include "clang/AST/OperationKinds.h"
61 #include "clang/AST/Stmt.h"
62 #include "clang/AST/StmtCXX.h"
63 #include "clang/AST/StmtObjC.h"
64 #include "clang/AST/StmtOpenMP.h"
65 #include "clang/AST/TemplateBase.h"
66 #include "clang/AST/TemplateName.h"
67 #include "clang/AST/Type.h"
68 #include "clang/AST/TypeLoc.h"
69 #include "clang/ASTMatchers/ASTMatchersInternal.h"
70 #include "clang/ASTMatchers/ASTMatchersMacros.h"
71 #include "clang/Basic/AttrKinds.h"
72 #include "clang/Basic/ExceptionSpecificationType.h"
73 #include "clang/Basic/IdentifierTable.h"
74 #include "clang/Basic/LLVM.h"
75 #include "clang/Basic/SourceManager.h"
76 #include "clang/Basic/Specifiers.h"
77 #include "clang/Basic/TypeTraits.h"
78 #include "llvm/ADT/ArrayRef.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringRef.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Regex.h"
94 namespace ast_matchers {
96 /// Maps string IDs to AST nodes matched by parts of a matcher.
98 /// The bound nodes are generated by calling \c bind("id") on the node matchers
99 /// of the nodes we want to access later.
101 /// The instances of BoundNodes are created by \c MatchFinder when the user's
102 /// callbacks are executed every time a match is found.
105 /// Returns the AST node bound to \c ID.
107 /// Returns NULL if there was no node bound to \c ID or if there is a node but
108 /// it cannot be converted to the specified type.
109 template <typename T>
110 const T *getNodeAs(StringRef ID) const {
111 return MyBoundNodes.getNodeAs<T>(ID);
114 /// Type of mapping from binding identifiers to bound nodes. This type
115 /// is an associative container with a key type of \c std::string and a value
116 /// type of \c clang::ast_type_traits::DynTypedNode
117 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
119 /// Retrieve mapping from binding identifiers to bound nodes.
120 const IDToNodeMap &getMap() const {
121 return MyBoundNodes.getMap();
125 friend class internal::BoundNodesTreeBuilder;
127 /// Create BoundNodes from a pre-filled map of bindings.
128 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
129 : MyBoundNodes(MyBoundNodes) {}
131 internal::BoundNodesMap MyBoundNodes;
134 /// Types of matchers for the top-level classes in the AST class
137 using DeclarationMatcher = internal::Matcher<Decl>;
138 using StatementMatcher = internal::Matcher<Stmt>;
139 using TypeMatcher = internal::Matcher<QualType>;
140 using TypeLocMatcher = internal::Matcher<TypeLoc>;
141 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
142 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
143 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
146 /// Matches any node.
148 /// Useful when another matcher requires a child matcher, but there's no
149 /// additional constraint. This will often be used with an explicit conversion
150 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
152 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
154 /// "int* p" and "void f()" in
159 /// Usable as: Any Matcher
160 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
162 /// Matches the top declaration context.
169 /// } // namespace NS
171 /// decl(hasDeclContext(translationUnitDecl()))
172 /// matches "int X", but not "int Y".
173 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
176 /// Matches typedef declarations.
184 /// matches "typedef int X", but not "using Y = int"
185 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
188 /// Matches typedef name declarations.
195 /// typedefNameDecl()
196 /// matches "typedef int X" and "using Y = int"
197 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
200 /// Matches type alias declarations.
208 /// matches "using Y = int", but not "typedef int X"
209 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
212 /// Matches type alias template declarations.
214 /// typeAliasTemplateDecl() matches
216 /// template <typename T>
219 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
220 typeAliasTemplateDecl;
222 /// Matches AST nodes that were expanded within the main-file.
224 /// Example matches X but not Y
225 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
235 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
236 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
237 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
238 auto &SourceManager = Finder->getASTContext().getSourceManager();
239 return SourceManager.isInMainFile(
240 SourceManager.getExpansionLoc(Node.getBeginLoc()));
243 /// Matches AST nodes that were expanded within system-header-files.
245 /// Example matches Y but not X
246 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
248 /// #include <SystemHeader.h>
256 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
257 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
258 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
259 auto &SourceManager = Finder->getASTContext().getSourceManager();
260 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
261 if (ExpansionLoc.isInvalid()) {
264 return SourceManager.isInSystemHeader(ExpansionLoc);
267 /// Matches AST nodes that were expanded within files whose name is
268 /// partially matching a given regex.
270 /// Example matches Y but not X
271 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
273 /// #include "ASTMatcher.h"
281 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
282 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
283 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
284 std::string, RegExp) {
285 auto &SourceManager = Finder->getASTContext().getSourceManager();
286 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
287 if (ExpansionLoc.isInvalid()) {
291 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
296 auto Filename = FileEntry->getName();
297 llvm::Regex RE(RegExp);
298 return RE.match(Filename);
301 /// Matches declarations.
303 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
310 extern const internal::VariadicAllOfMatcher<Decl> decl;
312 /// Matches a declaration of a linkage specification.
318 /// linkageSpecDecl()
319 /// matches "extern "C" {}"
320 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
323 /// Matches a declaration of anything that could have a name.
325 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
334 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
336 /// Matches a declaration of label.
345 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
347 /// Matches a declaration of a namespace.
352 /// namespace test {}
355 /// matches "namespace {}" and "namespace test {}"
356 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
359 /// Matches a declaration of a namespace alias.
363 /// namespace test {}
364 /// namespace alias = ::test;
366 /// namespaceAliasDecl()
367 /// matches "namespace alias" but not "namespace test"
368 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
371 /// Matches class, struct, and union declarations.
373 /// Example matches \c X, \c Z, \c U, and \c S
376 /// template<class T> class Z {};
380 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
382 /// Matches C++ class declarations.
384 /// Example matches \c X, \c Z
387 /// template<class T> class Z {};
389 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
392 /// Matches C++ class template declarations.
394 /// Example matches \c Z
396 /// template<class T> class Z {};
398 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
401 /// Matches C++ class template specializations.
405 /// template<typename T> class A {};
406 /// template<> class A<double> {};
409 /// classTemplateSpecializationDecl()
410 /// matches the specializations \c A<int> and \c A<double>
411 extern const internal::VariadicDynCastAllOfMatcher<
412 Decl, ClassTemplateSpecializationDecl>
413 classTemplateSpecializationDecl;
415 /// Matches C++ class template partial specializations.
419 /// template<class T1, class T2, int I>
422 /// template<class T, int I>
423 /// class A<T, T*, I> {};
426 /// class A<int, int, 1> {};
428 /// classTemplatePartialSpecializationDecl()
429 /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
430 extern const internal::VariadicDynCastAllOfMatcher<
431 Decl, ClassTemplatePartialSpecializationDecl>
432 classTemplatePartialSpecializationDecl;
434 /// Matches declarator declarations (field, variable, function
435 /// and non-type template parameter declarations).
439 /// class X { int y; };
442 /// matches \c int y.
443 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
446 /// Matches parameter variable declarations.
453 /// matches \c int x.
454 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
457 /// Matches C++ access specifier declarations.
467 /// matches 'public:'
468 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
471 /// Matches constructor initializers.
473 /// Examples matches \c i(42).
480 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
483 /// Matches template arguments.
487 /// template <typename T> struct C {};
490 /// templateArgument()
491 /// matches 'int' in C<int>.
492 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
494 /// Matches template name.
498 /// template <typename T> class X { };
502 /// matches 'X' in X<int>.
503 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
505 /// Matches non-type template parameter declarations.
509 /// template <typename T, int N> struct C {};
511 /// nonTypeTemplateParmDecl()
512 /// matches 'N', but not 'T'.
513 extern const internal::VariadicDynCastAllOfMatcher<Decl,
514 NonTypeTemplateParmDecl>
515 nonTypeTemplateParmDecl;
517 /// Matches template type parameter declarations.
521 /// template <typename T, int N> struct C {};
523 /// templateTypeParmDecl()
524 /// matches 'T', but not 'N'.
525 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
526 templateTypeParmDecl;
528 /// Matches public C++ declarations.
534 /// protected: int b;
538 /// fieldDecl(isPublic())
540 AST_MATCHER(Decl, isPublic) {
541 return Node.getAccess() == AS_public;
544 /// Matches protected C++ declarations.
550 /// protected: int b;
554 /// fieldDecl(isProtected())
556 AST_MATCHER(Decl, isProtected) {
557 return Node.getAccess() == AS_protected;
560 /// Matches private C++ declarations.
566 /// protected: int b;
570 /// fieldDecl(isPrivate())
572 AST_MATCHER(Decl, isPrivate) {
573 return Node.getAccess() == AS_private;
576 /// Matches non-static data members that are bit-fields.
585 /// fieldDecl(isBitField())
586 /// matches 'int a;' but not 'int b;'.
587 AST_MATCHER(FieldDecl, isBitField) {
588 return Node.isBitField();
591 /// Matches non-static data members that are bit-fields of the specified
602 /// fieldDecl(hasBitWidth(2))
603 /// matches 'int a;' and 'int c;' but not 'int b;'.
604 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
605 return Node.isBitField() &&
606 Node.getBitWidthValue(Finder->getASTContext()) == Width;
609 /// Matches non-static data members that have an in-class initializer.
619 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
620 /// matches 'int a;' but not 'int b;'.
621 /// fieldDecl(hasInClassInitializer(anything()))
622 /// matches 'int a;' and 'int b;' but not 'int c;'.
623 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
625 const Expr *Initializer = Node.getInClassInitializer();
626 return (Initializer != nullptr &&
627 InnerMatcher.matches(*Initializer, Finder, Builder));
630 /// Determines whether the function is "main", which is the entry point
631 /// into an executable program.
632 AST_MATCHER(FunctionDecl, isMain) {
633 return Node.isMain();
636 /// Matches the specialized template of a specialization declaration.
640 /// template<typename T> class A {}; #1
641 /// template<> class A<int> {}; #2
643 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
644 /// matches '#2' with classTemplateDecl() matching the class template
645 /// declaration of 'A' at #1.
646 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
647 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
648 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
649 return (Decl != nullptr &&
650 InnerMatcher.matches(*Decl, Finder, Builder));
653 /// Matches a declaration that has been implicitly added
654 /// by the compiler (eg. implicit default/copy constructors).
655 AST_MATCHER(Decl, isImplicit) {
656 return Node.isImplicit();
659 /// Matches classTemplateSpecializations, templateSpecializationType and
660 /// functionDecl that have at least one TemplateArgument matching the given
665 /// template<typename T> class A {};
666 /// template<> class A<double> {};
669 /// template<typename T> f() {};
670 /// void func() { f<int>(); };
674 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
675 /// refersToType(asString("int"))))
676 /// matches the specialization \c A<int>
678 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
679 /// matches the specialization \c f<int>
680 AST_POLYMORPHIC_MATCHER_P(
681 hasAnyTemplateArgument,
682 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
683 TemplateSpecializationType,
685 internal::Matcher<TemplateArgument>, InnerMatcher) {
686 ArrayRef<TemplateArgument> List =
687 internal::getTemplateSpecializationArgs(Node);
688 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
692 /// Matches expressions that match InnerMatcher after any implicit AST
693 /// nodes are stripped off.
695 /// Parentheses and explicit casts are not discarded.
705 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
707 /// would match the declarations for a, b, and c.
710 /// varDecl(hasInitializer(cxxConstructExpr()))
712 /// only match the declarations for b and c.
713 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
715 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
718 /// Matches expressions that match InnerMatcher after any implicit casts
719 /// are stripped off.
721 /// Parentheses and explicit casts are not discarded.
729 /// long e = (long) 0l;
733 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
734 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
736 /// would match the declarations for a, b, c, and d, but not e.
739 /// varDecl(hasInitializer(integerLiteral()))
740 /// varDecl(hasInitializer(declRefExpr()))
742 /// only match the declarations for b, c, and d.
743 AST_MATCHER_P(Expr, ignoringImpCasts,
744 internal::Matcher<Expr>, InnerMatcher) {
745 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
748 /// Matches expressions that match InnerMatcher after parentheses and
749 /// casts are stripped off.
751 /// Implicit and non-C Style casts are also discarded.
756 /// void* c = reinterpret_cast<char*>(0);
757 /// char d = char(0);
760 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
761 /// would match the declarations for a, b, c, and d.
763 /// varDecl(hasInitializer(integerLiteral()))
764 /// only match the declaration for a.
765 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
766 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
769 /// Matches expressions that match InnerMatcher after implicit casts and
770 /// parentheses are stripped off.
772 /// Explicit casts are not discarded.
780 /// long e = ((long) 0l);
783 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
784 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
785 /// would match the declarations for a, b, c, and d, but not e.
787 /// varDecl(hasInitializer(integerLiteral()))
788 /// varDecl(hasInitializer(declRefExpr()))
789 /// would only match the declaration for a.
790 AST_MATCHER_P(Expr, ignoringParenImpCasts,
791 internal::Matcher<Expr>, InnerMatcher) {
792 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
795 /// Matches types that match InnerMatcher after any parens are stripped.
799 /// void (*fp)(void);
803 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
805 /// would match the declaration for fp.
806 AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
808 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
811 /// Overload \c ignoringParens for \c Expr.
815 /// const char* str = ("my-string");
819 /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
821 /// would match the implicit cast resulting from the assignment.
822 AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
824 const Expr *E = Node.IgnoreParens();
825 return InnerMatcher.matches(*E, Finder, Builder);
828 /// Matches expressions that are instantiation-dependent even if it is
829 /// neither type- nor value-dependent.
831 /// In the following example, the expression sizeof(sizeof(T() + T()))
832 /// is instantiation-dependent (since it involves a template parameter T),
833 /// but is neither type- nor value-dependent, since the type of the inner
834 /// sizeof is known (std::size_t) and therefore the size of the outer
837 /// template<typename T>
838 /// void f(T x, T y) { sizeof(sizeof(T() + T()); }
840 /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
841 AST_MATCHER(Expr, isInstantiationDependent) {
842 return Node.isInstantiationDependent();
845 /// Matches expressions that are type-dependent because the template type
846 /// is not yet instantiated.
848 /// For example, the expressions "x" and "x + y" are type-dependent in
849 /// the following code, but "y" is not type-dependent:
851 /// template<typename T>
852 /// void add(T x, int y) {
856 /// expr(isTypeDependent()) matches x + y
857 AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
859 /// Matches expression that are value-dependent because they contain a
860 /// non-type template parameter.
862 /// For example, the array bound of "Chars" in the following example is
865 /// template<int Size> int f() { return Size; }
867 /// expr(isValueDependent()) matches return Size
868 AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
870 /// Matches classTemplateSpecializations, templateSpecializationType and
871 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
875 /// template<typename T, typename U> class A {};
879 /// template<typename T> void f() {}
880 /// void func() { f<int>(); };
882 /// classTemplateSpecializationDecl(hasTemplateArgument(
883 /// 1, refersToType(asString("int"))))
884 /// matches the specialization \c A<bool, int>
886 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
887 /// matches the specialization \c f<int>
888 AST_POLYMORPHIC_MATCHER_P2(
890 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
891 TemplateSpecializationType,
893 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
894 ArrayRef<TemplateArgument> List =
895 internal::getTemplateSpecializationArgs(Node);
896 if (List.size() <= N)
898 return InnerMatcher.matches(List[N], Finder, Builder);
901 /// Matches if the number of template arguments equals \p N.
905 /// template<typename T> struct C {};
908 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
910 AST_POLYMORPHIC_MATCHER_P(
911 templateArgumentCountIs,
912 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
913 TemplateSpecializationType),
915 return internal::getTemplateSpecializationArgs(Node).size() == N;
918 /// Matches a TemplateArgument that refers to a certain type.
923 /// template<typename T> struct A {};
926 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
927 /// refersToType(class(hasName("X")))))
928 /// matches the specialization \c A<X>
929 AST_MATCHER_P(TemplateArgument, refersToType,
930 internal::Matcher<QualType>, InnerMatcher) {
931 if (Node.getKind() != TemplateArgument::Type)
933 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
936 /// Matches a TemplateArgument that refers to a certain template.
940 /// template<template <typename> class S> class X {};
941 /// template<typename T> class Y {};
944 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
945 /// refersToTemplate(templateName())))
946 /// matches the specialization \c X<Y>
947 AST_MATCHER_P(TemplateArgument, refersToTemplate,
948 internal::Matcher<TemplateName>, InnerMatcher) {
949 if (Node.getKind() != TemplateArgument::Template)
951 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
954 /// Matches a canonical TemplateArgument that refers to a certain
959 /// struct B { int next; };
960 /// template<int(B::*next_ptr)> struct A {};
963 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
964 /// refersToDeclaration(fieldDecl(hasName("next")))))
965 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
967 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
968 internal::Matcher<Decl>, InnerMatcher) {
969 if (Node.getKind() == TemplateArgument::Declaration)
970 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
974 /// Matches a sugar TemplateArgument that refers to a certain expression.
978 /// struct B { int next; };
979 /// template<int(B::*next_ptr)> struct A {};
982 /// templateSpecializationType(hasAnyTemplateArgument(
983 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
984 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
986 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
987 if (Node.getKind() == TemplateArgument::Expression)
988 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
992 /// Matches a TemplateArgument that is an integral value.
996 /// template<int T> struct C {};
999 /// classTemplateSpecializationDecl(
1000 /// hasAnyTemplateArgument(isIntegral()))
1001 /// matches the implicit instantiation of C in C<42>
1002 /// with isIntegral() matching 42.
1003 AST_MATCHER(TemplateArgument, isIntegral) {
1004 return Node.getKind() == TemplateArgument::Integral;
1007 /// Matches a TemplateArgument that referes to an integral type.
1011 /// template<int T> struct C {};
1014 /// classTemplateSpecializationDecl(
1015 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1016 /// matches the implicit instantiation of C in C<42>.
1017 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1018 internal::Matcher<QualType>, InnerMatcher) {
1019 if (Node.getKind() != TemplateArgument::Integral)
1021 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1024 /// Matches a TemplateArgument of integral type with a given value.
1026 /// Note that 'Value' is a string as the template argument's value is
1027 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
1028 /// representation of that integral value in base 10.
1032 /// template<int T> struct C {};
1035 /// classTemplateSpecializationDecl(
1036 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
1037 /// matches the implicit instantiation of C in C<42>.
1038 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1039 std::string, Value) {
1040 if (Node.getKind() != TemplateArgument::Integral)
1042 return Node.getAsIntegral().toString(10) == Value;
1045 /// Matches an Objective-C autorelease pool statement.
1049 /// @autoreleasepool {
1053 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1054 /// inside the autorelease pool.
1055 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1056 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1058 /// Matches any value declaration.
1060 /// Example matches A, B, C and F
1062 /// enum X { A, B, C };
1065 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1067 /// Matches C++ constructor declarations.
1069 /// Example matches Foo::Foo() and Foo::Foo(int)
1075 /// int DoSomething();
1078 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1081 /// Matches explicit C++ destructor declarations.
1083 /// Example matches Foo::~Foo()
1090 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1093 /// Matches enum declarations.
1095 /// Example matches X
1101 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1103 /// Matches enum constants.
1105 /// Example matches A, B, C
1111 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1114 /// Matches method declarations.
1116 /// Example matches y
1118 /// class X { void y(); };
1120 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1123 /// Matches conversion operator declarations.
1125 /// Example matches the operator.
1127 /// class X { operator int() const; };
1129 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1132 /// Matches user-defined and implicitly generated deduction guide.
1134 /// Example matches the deduction guide.
1136 /// template<typename T>
1137 /// class X { X(int) };
1138 /// X(int) -> X<int>;
1140 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1141 cxxDeductionGuideDecl;
1143 /// Matches variable declarations.
1145 /// Note: this does not match declarations of member variables, which are
1146 /// "field" declarations in Clang parlance.
1148 /// Example matches a
1152 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1154 /// Matches field declarations.
1158 /// class X { int m; };
1162 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1164 /// Matches indirect field declarations.
1168 /// struct X { struct { int a; }; };
1170 /// indirectFieldDecl()
1172 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1175 /// Matches function declarations.
1177 /// Example matches f
1181 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1184 /// Matches C++ function template declarations.
1186 /// Example matches f
1188 /// template<class T> void f(T t) {}
1190 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1191 functionTemplateDecl;
1193 /// Matches friend declarations.
1197 /// class X { friend void foo(); };
1200 /// matches 'friend void foo()'.
1201 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1203 /// Matches statements.
1210 /// matches both the compound statement '{ ++a; }' and '++a'.
1211 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1213 /// Matches declaration statements.
1220 /// matches 'int a'.
1221 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1223 /// Matches member expressions.
1228 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1229 /// int a; static int b;
1233 /// matches this->x, x, y.x, a, this->b
1234 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1236 /// Matches unresolved member expressions.
1241 /// template <class T> void f();
1244 /// template <class T> void h() { X x; x.f<T>(); x.g(); }
1246 /// unresolvedMemberExpr()
1248 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1249 unresolvedMemberExpr;
1251 /// Matches member expressions where the actual member referenced could not be
1252 /// resolved because the base expression or the member name was dependent.
1256 /// template <class T> void f() { T t; t.g(); }
1258 /// cxxDependentScopeMemberExpr()
1260 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1261 CXXDependentScopeMemberExpr>
1262 cxxDependentScopeMemberExpr;
1264 /// Matches call expressions.
1266 /// Example matches x.y() and y()
1272 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1274 /// Matches call expressions which were resolved using ADL.
1276 /// Example matches y(x) but not y(42) or NS::y(x).
1287 /// y(x); // Matches
1288 /// NS::y(x); // Doesn't match
1289 /// y(42); // Doesn't match
1291 /// y(x); // Found by both unqualified lookup and ADL, doesn't match
1294 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1296 /// Matches lambda expressions.
1298 /// Example matches [&](){return 5;}
1300 /// [&](){return 5;}
1302 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1304 /// Matches member call expressions.
1306 /// Example matches x.y()
1311 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1314 /// Matches ObjectiveC Message invocation expressions.
1316 /// The innermost message send invokes the "alloc" class method on the
1317 /// NSString class, while the outermost message send invokes the
1318 /// "initWithString" instance method on the object returned from
1319 /// NSString's "alloc". This matcher should match both message sends.
1321 /// [[NSString alloc] initWithString:@"Hello"]
1323 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1326 /// Matches Objective-C interface declarations.
1328 /// Example matches Foo
1333 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1336 /// Matches Objective-C implementation declarations.
1338 /// Example matches Foo
1340 /// @implementation Foo
1343 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1344 objcImplementationDecl;
1346 /// Matches Objective-C protocol declarations.
1348 /// Example matches FooDelegate
1350 /// @protocol FooDelegate
1353 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1356 /// Matches Objective-C category declarations.
1358 /// Example matches Foo (Additions)
1360 /// @interface Foo (Additions)
1363 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1366 /// Matches Objective-C category definitions.
1368 /// Example matches Foo (Additions)
1370 /// @implementation Foo (Additions)
1373 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1374 objcCategoryImplDecl;
1376 /// Matches Objective-C method declarations.
1378 /// Example matches both declaration and definition of -[Foo method]
1384 /// @implementation Foo
1385 /// - (void)method {}
1388 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1391 /// Matches block declarations.
1393 /// Example matches the declaration of the nameless block printing an input
1397 /// myFunc(^(int p) {
1398 /// printf("%d", p);
1401 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1404 /// Matches Objective-C instance variable declarations.
1406 /// Example matches _enabled
1408 /// @implementation Foo {
1413 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1416 /// Matches Objective-C property declarations.
1418 /// Example matches enabled
1421 /// @property BOOL enabled;
1424 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1427 /// Matches Objective-C \@throw statements.
1429 /// Example matches \@throw
1433 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1436 /// Matches Objective-C @try statements.
1438 /// Example matches @try
1443 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1446 /// Matches Objective-C @catch statements.
1448 /// Example matches @catch
1453 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1456 /// Matches Objective-C @finally statements.
1458 /// Example matches @finally
1463 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1466 /// Matches expressions that introduce cleanups to be run at the end
1467 /// of the sub-expression's evaluation.
1469 /// Example matches std::string()
1471 /// const std::string str = std::string();
1473 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1476 /// Matches init list expressions.
1480 /// int a[] = { 1, 2 };
1481 /// struct B { int x, y; };
1485 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1486 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1489 /// Matches the syntactic form of init list expressions
1490 /// (if expression have it).
1491 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1492 internal::Matcher<Expr>, InnerMatcher) {
1493 const Expr *SyntForm = Node.getSyntacticForm();
1494 return (SyntForm != nullptr &&
1495 InnerMatcher.matches(*SyntForm, Finder, Builder));
1498 /// Matches C++ initializer list expressions.
1502 /// std::vector<int> a({ 1, 2, 3 });
1503 /// std::vector<int> b = { 4, 5 };
1504 /// int c[] = { 6, 7 };
1505 /// std::pair<int, int> d = { 8, 9 };
1507 /// cxxStdInitializerListExpr()
1508 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1509 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1510 CXXStdInitializerListExpr>
1511 cxxStdInitializerListExpr;
1513 /// Matches implicit initializers of init list expressions.
1517 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1519 /// implicitValueInitExpr()
1520 /// matches "[0].y" (implicitly)
1521 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1522 implicitValueInitExpr;
1524 /// Matches paren list expressions.
1525 /// ParenListExprs don't have a predefined type and are used for late parsing.
1526 /// In the final AST, they can be met in template declarations.
1530 /// template<typename T> class X {
1533 /// int a = 0, b = 1; int i = (a, b);
1537 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1538 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1539 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1542 /// Matches substitutions of non-type template parameters.
1546 /// template <int N>
1547 /// struct A { static const int n = N; };
1548 /// struct B : public A<42> {};
1550 /// substNonTypeTemplateParmExpr()
1551 /// matches "N" in the right-hand side of "static const int n = N;"
1552 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1553 SubstNonTypeTemplateParmExpr>
1554 substNonTypeTemplateParmExpr;
1556 /// Matches using declarations.
1560 /// namespace X { int x; }
1564 /// matches \code using X::x \endcode
1565 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1567 /// Matches using namespace declarations.
1571 /// namespace X { int x; }
1572 /// using namespace X;
1574 /// usingDirectiveDecl()
1575 /// matches \code using namespace X \endcode
1576 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1579 /// Matches reference to a name that can be looked up during parsing
1580 /// but could not be resolved to a specific declaration.
1584 /// template<typename T>
1585 /// T foo() { T a; return a; }
1586 /// template<typename T>
1591 /// unresolvedLookupExpr()
1592 /// matches \code foo<T>() \endcode
1593 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1594 unresolvedLookupExpr;
1596 /// Matches unresolved using value declarations.
1600 /// template<typename X>
1601 /// class C : private X {
1605 /// unresolvedUsingValueDecl()
1606 /// matches \code using X::x \endcode
1607 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1608 UnresolvedUsingValueDecl>
1609 unresolvedUsingValueDecl;
1611 /// Matches unresolved using value declarations that involve the
1616 /// template <typename T>
1617 /// struct Base { typedef T Foo; };
1619 /// template<typename T>
1620 /// struct S : private Base<T> {
1621 /// using typename Base<T>::Foo;
1624 /// unresolvedUsingTypenameDecl()
1625 /// matches \code using Base<T>::Foo \endcode
1626 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1627 UnresolvedUsingTypenameDecl>
1628 unresolvedUsingTypenameDecl;
1630 /// Matches a constant expression wrapper.
1632 /// Example matches the constant in the case statement:
1633 /// (matcher = constantExpr())
1639 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1642 /// Matches parentheses used in expressions.
1644 /// Example matches (foo() + 1)
1646 /// int foo() { return 1; }
1647 /// int a = (foo() + 1);
1649 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1651 /// Matches constructor call expressions (including implicit ones).
1653 /// Example matches string(ptr, n) and ptr within arguments of f
1654 /// (matcher = cxxConstructExpr())
1656 /// void f(const string &a, const string &b);
1659 /// f(string(ptr, n), ptr);
1661 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1664 /// Matches unresolved constructor call expressions.
1666 /// Example matches T(t) in return statement of f
1667 /// (matcher = cxxUnresolvedConstructExpr())
1669 /// template <typename T>
1670 /// void f(const T& t) { return T(t); }
1672 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1673 CXXUnresolvedConstructExpr>
1674 cxxUnresolvedConstructExpr;
1676 /// Matches implicit and explicit this expressions.
1678 /// Example matches the implicit this expression in "return i".
1679 /// (matcher = cxxThisExpr())
1683 /// int f() { return i; }
1686 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1689 /// Matches nodes where temporaries are created.
1691 /// Example matches FunctionTakesString(GetStringByValue())
1692 /// (matcher = cxxBindTemporaryExpr())
1694 /// FunctionTakesString(GetStringByValue());
1695 /// FunctionTakesStringByPointer(GetStringPointer());
1697 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1698 cxxBindTemporaryExpr;
1700 /// Matches nodes where temporaries are materialized.
1704 /// struct T {void func();};
1708 /// materializeTemporaryExpr() matches 'f()' in these statements
1714 /// but does not match
1718 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1719 MaterializeTemporaryExpr>
1720 materializeTemporaryExpr;
1722 /// Matches new expressions.
1729 /// matches 'new X'.
1730 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1732 /// Matches delete expressions.
1739 /// matches 'delete X'.
1740 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1743 /// Matches array subscript expressions.
1749 /// arraySubscriptExpr()
1751 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1754 /// Matches the value of a default argument at the call site.
1756 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1757 /// default value of the second parameter in the call expression f(42)
1758 /// (matcher = cxxDefaultArgExpr())
1760 /// void f(int x, int y = 0);
1763 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1766 /// Matches overloaded operator calls.
1768 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1769 /// binaryOperator matcher.
1770 /// Currently it does not match operators such as new delete.
1771 /// FIXME: figure out why these do not match?
1773 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1774 /// (matcher = cxxOperatorCallExpr())
1776 /// ostream &operator<< (ostream &out, int i) { };
1777 /// ostream &o; int b = 1, c = 1;
1780 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1781 cxxOperatorCallExpr;
1783 /// Matches expressions.
1785 /// Example matches x()
1787 /// void f() { x(); }
1789 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1791 /// Matches expressions that refer to declarations.
1793 /// Example matches x in if (x)
1798 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1801 /// Matches a reference to an ObjCIvar.
1803 /// Example: matches "a" in "init" method:
1805 /// @implementation A {
1812 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1815 /// Matches a reference to a block.
1817 /// Example: matches "^{}":
1819 /// void f() { ^{}(); }
1821 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
1823 /// Matches if statements.
1825 /// Example matches 'if (x) {}'
1829 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1831 /// Matches for statements.
1833 /// Example matches 'for (;;) {}'
1836 /// int i[] = {1, 2, 3}; for (auto a : i);
1838 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1840 /// Matches the increment statement of a for loop.
1843 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1844 /// matches '++x' in
1846 /// for (x; x < N; ++x) { }
1848 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1850 const Stmt *const Increment = Node.getInc();
1851 return (Increment != nullptr &&
1852 InnerMatcher.matches(*Increment, Finder, Builder));
1855 /// Matches the initialization statement of a for loop.
1858 /// forStmt(hasLoopInit(declStmt()))
1859 /// matches 'int x = 0' in
1861 /// for (int x = 0; x < N; ++x) { }
1863 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1865 const Stmt *const Init = Node.getInit();
1866 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1869 /// Matches range-based for statements.
1871 /// cxxForRangeStmt() matches 'for (auto a : i)'
1873 /// int i[] = {1, 2, 3}; for (auto a : i);
1874 /// for(int j = 0; j < 5; ++j);
1876 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1879 /// Matches the initialization statement of a for loop.
1882 /// forStmt(hasLoopVariable(anything()))
1883 /// matches 'int x' in
1885 /// for (int x : a) { }
1887 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1889 const VarDecl *const Var = Node.getLoopVariable();
1890 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1893 /// Matches the range initialization statement of a for loop.
1896 /// forStmt(hasRangeInit(anything()))
1899 /// for (int x : a) { }
1901 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1903 const Expr *const Init = Node.getRangeInit();
1904 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1907 /// Matches while statements.
1914 /// matches 'while (true) {}'.
1915 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1917 /// Matches do statements.
1921 /// do {} while (true);
1924 /// matches 'do {} while(true)'
1925 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1927 /// Matches break statements.
1931 /// while (true) { break; }
1935 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1937 /// Matches continue statements.
1941 /// while (true) { continue; }
1944 /// matches 'continue'
1945 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1948 /// Matches return statements.
1955 /// matches 'return 1'
1956 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1958 /// Matches goto statements.
1966 /// matches 'goto FOO'
1967 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1969 /// Matches label statements.
1978 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1980 /// Matches address of label statements (GNU extension).
1985 /// void *ptr = &&FOO;
1990 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
1993 /// Matches switch statements.
1997 /// switch(a) { case 42: break; default: break; }
2000 /// matches 'switch(a)'.
2001 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2003 /// Matches case and default statements inside switch statements.
2007 /// switch(a) { case 42: break; default: break; }
2010 /// matches 'case 42:' and 'default:'.
2011 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2013 /// Matches case statements inside switch statements.
2017 /// switch(a) { case 42: break; default: break; }
2020 /// matches 'case 42:'.
2021 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2023 /// Matches default statements inside switch statements.
2027 /// switch(a) { case 42: break; default: break; }
2030 /// matches 'default:'.
2031 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2034 /// Matches compound statements.
2036 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2040 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2043 /// Matches catch statements.
2046 /// try {} catch(int i) {}
2049 /// matches 'catch(int i)'
2050 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2053 /// Matches try statements.
2056 /// try {} catch(int i) {}
2059 /// matches 'try {}'
2060 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2062 /// Matches throw expressions.
2065 /// try { throw 5; } catch(int i) {}
2068 /// matches 'throw 5'
2069 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2072 /// Matches null statements.
2078 /// matches the second ';'
2079 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2081 /// Matches asm statements.
2085 /// __asm("mov al, 2");
2088 /// matches '__asm("mov al, 2")'
2089 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2091 /// Matches bool literals.
2093 /// Example matches true
2097 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2100 /// Matches string literals (also matches wide string literals).
2102 /// Example matches "abcd", L"abcd"
2104 /// char *s = "abcd";
2105 /// wchar_t *ws = L"abcd";
2107 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2110 /// Matches character literals (also matches wchar_t).
2112 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2115 /// Example matches 'a', L'a'
2118 /// wchar_t chw = L'a';
2120 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2123 /// Matches integer literals of all sizes / encodings, e.g.
2124 /// 1, 1L, 0x1 and 1U.
2126 /// Does not match character-encoded integers such as L'a'.
2127 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2130 /// Matches float literals of all sizes / encodings, e.g.
2131 /// 1.0, 1.0f, 1.0L and 1e10.
2133 /// Does not match implicit conversions such as
2137 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2140 /// Matches imaginary literals, which are based on integer and floating
2141 /// point literals e.g.: 1i, 1.0i
2142 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2145 /// Matches user defined literal operator call.
2147 /// Example match: "foo"_suffix
2148 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2151 /// Matches compound (i.e. non-scalar) literals
2153 /// Example match: {1}, (1, 2)
2155 /// int array[4] = {1};
2156 /// vector int myvec = (vector int)(1, 2);
2158 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2159 compoundLiteralExpr;
2161 /// Matches nullptr literal.
2162 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2163 cxxNullPtrLiteralExpr;
2165 /// Matches GNU __builtin_choose_expr.
2166 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2169 /// Matches GNU __null expression.
2170 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2173 /// Matches atomic builtins.
2174 /// Example matches __atomic_load_n(ptr, 1)
2176 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2178 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2180 /// Matches statement expression (GNU extension).
2182 /// Example match: ({ int X = 4; X; })
2184 /// int C = ({ int X = 4; X; });
2186 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2188 /// Matches binary operator expressions.
2190 /// Example matches a || b
2194 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2197 /// Matches unary operator expressions.
2199 /// Example matches !a
2203 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2206 /// Matches conditional operator expressions.
2208 /// Example matches a ? b : c
2210 /// (a ? b : c) + 42
2212 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2213 conditionalOperator;
2215 /// Matches binary conditional operator expressions (GNU extension).
2217 /// Example matches a ?: b
2221 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2222 BinaryConditionalOperator>
2223 binaryConditionalOperator;
2225 /// Matches opaque value expressions. They are used as helpers
2226 /// to reference another expressions and can be met
2227 /// in BinaryConditionalOperators, for example.
2229 /// Example matches 'a'
2233 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2236 /// Matches a C++ static_assert declaration.
2239 /// staticAssertExpr()
2241 /// static_assert(sizeof(S) == sizeof(int))
2247 /// static_assert(sizeof(S) == sizeof(int));
2249 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2252 /// Matches a reinterpret_cast expression.
2254 /// Either the source expression or the destination type can be matched
2255 /// using has(), but hasDestinationType() is more specific and can be
2258 /// Example matches reinterpret_cast<char*>(&p) in
2260 /// void* p = reinterpret_cast<char*>(&p);
2262 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2263 cxxReinterpretCastExpr;
2265 /// Matches a C++ static_cast expression.
2267 /// \see hasDestinationType
2268 /// \see reinterpretCast
2271 /// cxxStaticCastExpr()
2273 /// static_cast<long>(8)
2276 /// long eight(static_cast<long>(8));
2278 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2281 /// Matches a dynamic_cast expression.
2284 /// cxxDynamicCastExpr()
2286 /// dynamic_cast<D*>(&b);
2289 /// struct B { virtual ~B() {} }; struct D : B {};
2291 /// D* p = dynamic_cast<D*>(&b);
2293 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2296 /// Matches a const_cast expression.
2298 /// Example: Matches const_cast<int*>(&r) in
2301 /// const int &r(n);
2302 /// int* p = const_cast<int*>(&r);
2304 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2307 /// Matches a C-style cast expression.
2309 /// Example: Matches (int) 2.2f in
2311 /// int i = (int) 2.2f;
2313 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2316 /// Matches explicit cast expressions.
2318 /// Matches any cast expression written in user code, whether it be a
2319 /// C-style cast, a functional-style cast, or a keyword cast.
2321 /// Does not match implicit conversions.
2323 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2324 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2325 /// actual cast expressions.
2327 /// \see hasDestinationType.
2329 /// Example: matches all five of the casts in
2331 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2333 /// but does not match the implicit conversion in
2337 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2340 /// Matches the implicit cast nodes of Clang's AST.
2342 /// This matches many different places, including function call return value
2343 /// eliding, as well as any type conversions.
2344 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2347 /// Matches any cast nodes of Clang's AST.
2349 /// Example: castExpr() matches each of the following:
2352 /// const_cast<Expr *>(SubExpr);
2355 /// but does not match
2360 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2362 /// Matches functional cast expressions
2364 /// Example: Matches Foo(bar);
2367 /// Foo g = (Foo) bar;
2368 /// Foo h = Foo(bar);
2370 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2371 cxxFunctionalCastExpr;
2373 /// Matches functional cast expressions having N != 1 arguments
2375 /// Example: Matches Foo(bar, bar)
2377 /// Foo h = Foo(bar, bar);
2379 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2380 cxxTemporaryObjectExpr;
2382 /// Matches predefined identifier expressions [C99 6.4.2.2].
2384 /// Example: Matches __func__
2386 /// printf("%s", __func__);
2388 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2391 /// Matches C99 designated initializer expressions [C99 6.7.8].
2393 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2395 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2397 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2400 /// Matches designated initializer expressions that contain
2401 /// a specific number of designators.
2405 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2406 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2408 /// designatorCountIs(2)
2409 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2410 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2411 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2412 return Node.size() == N;
2415 /// Matches \c QualTypes in the clang AST.
2416 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2418 /// Matches \c Types in the clang AST.
2419 extern const internal::VariadicAllOfMatcher<Type> type;
2421 /// Matches \c TypeLocs in the clang AST.
2422 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2424 /// Matches if any of the given matchers matches.
2426 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2427 /// matching submatcher.
2429 /// For example, in:
2431 /// class A { int a; int b; };
2435 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2436 /// has(fieldDecl(hasName("b")).bind("v"))))
2438 /// will generate two results binding "v", the first of which binds
2439 /// the field declaration of \c a, the second the field declaration of
2442 /// Usable as: Any Matcher
2443 extern const internal::VariadicOperatorMatcherFunc<
2444 2, std::numeric_limits<unsigned>::max()>
2447 /// Matches if any of the given matchers matches.
2449 /// Usable as: Any Matcher
2450 extern const internal::VariadicOperatorMatcherFunc<
2451 2, std::numeric_limits<unsigned>::max()>
2454 /// Matches if all given matchers match.
2456 /// Usable as: Any Matcher
2457 extern const internal::VariadicOperatorMatcherFunc<
2458 2, std::numeric_limits<unsigned>::max()>
2461 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2466 /// int y = sizeof(x) + alignof(x);
2468 /// unaryExprOrTypeTraitExpr()
2469 /// matches \c sizeof(x) and \c alignof(x)
2470 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2471 UnaryExprOrTypeTraitExpr>
2472 unaryExprOrTypeTraitExpr;
2474 /// Matches unary expressions that have a specific type of argument.
2478 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2480 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2481 /// matches \c sizeof(a) and \c alignof(c)
2482 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2483 internal::Matcher<QualType>, InnerMatcher) {
2484 const QualType ArgumentType = Node.getTypeOfArgument();
2485 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2488 /// Matches unary expressions of a certain kind.
2493 /// int s = sizeof(x) + alignof(x)
2495 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2496 /// matches \c sizeof(x)
2498 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2499 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2500 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2501 return Node.getKind() == Kind;
2504 /// Same as unaryExprOrTypeTraitExpr, but only matching
2506 inline internal::Matcher<Stmt> alignOfExpr(
2507 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2508 return stmt(unaryExprOrTypeTraitExpr(
2509 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2513 /// Same as unaryExprOrTypeTraitExpr, but only matching
2515 inline internal::Matcher<Stmt> sizeOfExpr(
2516 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2517 return stmt(unaryExprOrTypeTraitExpr(
2518 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2521 /// Matches NamedDecl nodes that have the specified name.
2523 /// Supports specifying enclosing namespaces or classes by prefixing the name
2524 /// with '<enclosing>::'.
2525 /// Does not match typedefs of an underlying type with the given name.
2527 /// Example matches X (Name == "X")
2532 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2534 /// namespace a { namespace b { class X; } }
2536 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2537 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2540 /// Matches NamedDecl nodes that have any of the specified names.
2542 /// This matcher is only provided as a performance optimization of hasName.
2544 /// hasAnyName(a, b, c)
2546 /// is equivalent to, but faster than
2548 /// anyOf(hasName(a), hasName(b), hasName(c))
2550 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2551 internal::hasAnyNameFunc>
2554 /// Matches NamedDecl nodes whose fully qualified names contain
2555 /// a substring matched by the given RegExp.
2557 /// Supports specifying enclosing namespaces or classes by
2558 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2559 /// of an underlying type with the given name.
2561 /// Example matches X (regexp == "::X")
2566 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2568 /// namespace foo { namespace bar { class X; } }
2570 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2571 assert(!RegExp.empty());
2572 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2573 llvm::Regex RE(RegExp);
2574 return RE.match(FullNameString);
2577 /// Matches overloaded operator names.
2579 /// Matches overloaded operator names specified in strings without the
2580 /// "operator" prefix: e.g. "<<".
2584 /// class A { int operator*(); };
2585 /// const A &operator<<(const A &a, const A &b);
2587 /// a << a; // <-- This matches
2590 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2591 /// specified line and
2592 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2593 /// matches the declaration of \c A.
2595 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2596 inline internal::PolymorphicMatcherWithParam1<
2597 internal::HasOverloadedOperatorNameMatcher, StringRef,
2598 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2599 hasOverloadedOperatorName(StringRef Name) {
2600 return internal::PolymorphicMatcherWithParam1<
2601 internal::HasOverloadedOperatorNameMatcher, StringRef,
2602 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2605 /// Matches C++ classes that are directly or indirectly derived from a class
2606 /// matching \c Base, or Objective-C classes that directly or indirectly
2607 /// subclass a class matching \c Base.
2609 /// Note that a class is not considered to be derived from itself.
2611 /// Example matches Y, Z, C (Base == hasName("X"))
2614 /// class Y : public X {}; // directly derived
2615 /// class Z : public Y {}; // indirectly derived
2618 /// class C : public B {}; // derived from a typedef of X
2621 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2625 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2628 /// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
2630 /// @interface NSObject @end
2631 /// @interface Bar : NSObject @end
2634 /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
2635 AST_POLYMORPHIC_MATCHER_P(
2637 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2638 internal::Matcher<NamedDecl>, Base) {
2639 // Check if the node is a C++ struct/union/class.
2640 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2641 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
2643 // The node must be an Objective-C class.
2644 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2645 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
2646 /*Directly=*/false);
2649 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2650 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2652 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2653 std::string, BaseName, 1) {
2654 if (BaseName.empty())
2657 const auto M = isDerivedFrom(hasName(BaseName));
2659 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2660 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2662 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2663 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2666 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2668 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2669 isSameOrDerivedFrom,
2670 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2671 internal::Matcher<NamedDecl>, Base, 0) {
2672 const auto M = anyOf(Base, isDerivedFrom(Base));
2674 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2675 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2677 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2678 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2681 /// Overloaded method as shortcut for
2682 /// \c isSameOrDerivedFrom(hasName(...)).
2683 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2684 isSameOrDerivedFrom,
2685 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2686 std::string, BaseName, 1) {
2687 if (BaseName.empty())
2690 const auto M = isSameOrDerivedFrom(hasName(BaseName));
2692 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2693 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2695 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2696 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2699 /// Matches C++ or Objective-C classes that are directly derived from a class
2700 /// matching \c Base.
2702 /// Note that a class is not considered to be derived from itself.
2704 /// Example matches Y, C (Base == hasName("X"))
2707 /// class Y : public X {}; // directly derived
2708 /// class Z : public Y {}; // indirectly derived
2711 /// class C : public B {}; // derived from a typedef of X
2714 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2718 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2720 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2721 isDirectlyDerivedFrom,
2722 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2723 internal::Matcher<NamedDecl>, Base, 0) {
2724 // Check if the node is a C++ struct/union/class.
2725 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2726 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
2728 // The node must be an Objective-C class.
2729 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2730 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
2734 /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
2735 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2736 isDirectlyDerivedFrom,
2737 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
2738 std::string, BaseName, 1) {
2739 if (BaseName.empty())
2741 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
2743 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
2744 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
2746 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
2747 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
2749 /// Matches the first method of a class or struct that satisfies \c
2754 /// class A { void func(); };
2755 /// class B { void member(); };
2758 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2759 /// \c A but not \c B.
2760 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2762 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2763 Node.method_end(), Finder, Builder);
2766 /// Matches the generated class of lambda expressions.
2773 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2775 AST_MATCHER(CXXRecordDecl, isLambda) {
2776 return Node.isLambda();
2779 /// Matches AST nodes that have child AST nodes that match the
2780 /// provided matcher.
2782 /// Example matches X, Y
2783 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2785 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2786 /// class Y { class X {}; };
2787 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2790 /// ChildT must be an AST base type.
2792 /// Usable as: Any Matcher
2793 /// Note that has is direct matcher, so it also matches things like implicit
2794 /// casts and paren casts. If you are matching with expr then you should
2795 /// probably consider using ignoringParenImpCasts like:
2796 /// has(ignoringParenImpCasts(expr())).
2797 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2799 /// Matches AST nodes that have descendant AST nodes that match the
2800 /// provided matcher.
2802 /// Example matches X, Y, Z
2803 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2805 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2806 /// class Y { class X {}; };
2807 /// class Z { class Y { class X {}; }; };
2810 /// DescendantT must be an AST base type.
2812 /// Usable as: Any Matcher
2813 extern const internal::ArgumentAdaptingMatcherFunc<
2814 internal::HasDescendantMatcher>
2817 /// Matches AST nodes that have child AST nodes that match the
2818 /// provided matcher.
2820 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2821 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2824 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
2826 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2829 /// ChildT must be an AST base type.
2831 /// As opposed to 'has', 'forEach' will cause a match for each result that
2832 /// matches instead of only on the first one.
2834 /// Usable as: Any Matcher
2835 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2838 /// Matches AST nodes that have descendant AST nodes that match the
2839 /// provided matcher.
2841 /// Example matches X, A, A::X, B, B::C, B::C::X
2842 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2845 /// class A { class X {}; }; // Matches A, because A::X is a class of name
2847 /// class B { class C { class X {}; }; };
2850 /// DescendantT must be an AST base type.
2852 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2853 /// each result that matches instead of only on the first one.
2855 /// Note: Recursively combined ForEachDescendant can cause many matches:
2856 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2857 /// forEachDescendant(cxxRecordDecl())
2859 /// will match 10 times (plus injected class name matches) on:
2861 /// class A { class B { class C { class D { class E {}; }; }; }; };
2864 /// Usable as: Any Matcher
2865 extern const internal::ArgumentAdaptingMatcherFunc<
2866 internal::ForEachDescendantMatcher>
2869 /// Matches if the node or any descendant matches.
2871 /// Generates results for each match.
2873 /// For example, in:
2875 /// class A { class B {}; class C {}; };
2879 /// cxxRecordDecl(hasName("::A"),
2880 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2882 /// will generate results for \c A, \c B and \c C.
2884 /// Usable as: Any Matcher
2885 template <typename T>
2886 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2887 return eachOf(Matcher, forEachDescendant(Matcher));
2890 /// Matches AST nodes that have a parent that matches the provided
2895 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2897 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2899 /// Usable as: Any Matcher
2900 extern const internal::ArgumentAdaptingMatcherFunc<
2901 internal::HasParentMatcher,
2902 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2903 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2906 /// Matches AST nodes that have an ancestor that matches the provided
2911 /// void f() { if (true) { int x = 42; } }
2912 /// void g() { for (;;) { int x = 43; } }
2914 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2916 /// Usable as: Any Matcher
2917 extern const internal::ArgumentAdaptingMatcherFunc<
2918 internal::HasAncestorMatcher,
2919 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2920 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2923 /// Matches if the provided matcher does not match.
2925 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2931 /// Usable as: Any Matcher
2932 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2934 /// Matches a node if the declaration associated with that node
2935 /// matches the given matcher.
2937 /// The associated declaration is:
2938 /// - for type nodes, the declaration of the underlying type
2939 /// - for CallExpr, the declaration of the callee
2940 /// - for MemberExpr, the declaration of the referenced member
2941 /// - for CXXConstructExpr, the declaration of the constructor
2942 /// - for CXXNewExpr, the declaration of the operator new
2943 /// - for ObjCIvarExpr, the declaration of the ivar
2945 /// For type nodes, hasDeclaration will generally match the declaration of the
2946 /// sugared type. Given
2952 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2953 /// typedefDecl. A common use case is to match the underlying, desugared type.
2954 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2956 /// varDecl(hasType(hasUnqualifiedDesugaredType(
2957 /// recordType(hasDeclaration(decl())))))
2959 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2961 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2962 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2963 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2964 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2965 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2966 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2967 /// Matcher<UnresolvedUsingType>
2968 inline internal::PolymorphicMatcherWithParam1<
2969 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2970 void(internal::HasDeclarationSupportedTypes)>
2971 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2972 return internal::PolymorphicMatcherWithParam1<
2973 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2974 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2977 /// Matches a \c NamedDecl whose underlying declaration matches the given
2982 /// namespace N { template<class T> void f(T t); }
2983 /// template <class T> void g() { using N::f; f(T()); }
2985 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2986 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2987 /// matches the use of \c f in \c g() .
2988 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2990 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2992 return UnderlyingDecl != nullptr &&
2993 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2996 /// Matches on the implicit object argument of a member call expression, after
2997 /// stripping off any parentheses or implicit casts.
3001 /// class Y { public: void m(); };
3003 /// class X : public Y {};
3004 /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3006 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3007 /// matches `y.m()` and `(g()).m()`.
3008 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3009 /// matches `x.m()`.
3010 /// cxxMemberCallExpr(on(callExpr()))
3011 /// matches `(g()).m()`.
3013 /// FIXME: Overload to allow directly matching types?
3014 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3016 const Expr *ExprNode = Node.getImplicitObjectArgument()
3017 ->IgnoreParenImpCasts();
3018 return (ExprNode != nullptr &&
3019 InnerMatcher.matches(*ExprNode, Finder, Builder));
3023 /// Matches on the receiver of an ObjectiveC Message expression.
3026 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3027 /// matches the [webView ...] message invocation.
3029 /// NSString *webViewJavaScript = ...
3030 /// UIWebView *webView = ...
3031 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3033 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3035 const QualType TypeDecl = Node.getReceiverType();
3036 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3039 /// Returns true when the Objective-C method declaration is a class method.
3042 /// matcher = objcMethodDecl(isClassMethod())
3045 /// @interface I + (void)foo; @end
3049 /// @interface I - (void)bar; @end
3051 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
3052 return Node.isClassMethod();
3055 /// Returns true when the Objective-C method declaration is an instance method.
3058 /// matcher = objcMethodDecl(isInstanceMethod())
3061 /// @interface I - (void)bar; @end
3065 /// @interface I + (void)foo; @end
3067 AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
3068 return Node.isInstanceMethod();
3071 /// Returns true when the Objective-C message is sent to a class.
3074 /// matcher = objcMessageExpr(isClassMessage())
3077 /// [NSString stringWithFormat:@"format"];
3081 /// NSString *x = @"hello";
3082 /// [x containsString:@"h"];
3084 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
3085 return Node.isClassMessage();
3088 /// Returns true when the Objective-C message is sent to an instance.
3091 /// matcher = objcMessageExpr(isInstanceMessage())
3094 /// NSString *x = @"hello";
3095 /// [x containsString:@"h"];
3099 /// [NSString stringWithFormat:@"format"];
3101 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3102 return Node.isInstanceMessage();
3105 /// Matches if the Objective-C message is sent to an instance,
3106 /// and the inner matcher matches on that instance.
3108 /// For example the method call in
3110 /// NSString *x = @"hello";
3111 /// [x containsString:@"h"];
3114 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3115 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3117 const Expr *ReceiverNode = Node.getInstanceReceiver();
3118 return (ReceiverNode != nullptr &&
3119 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3123 /// Matches when BaseName == Selector.getAsString()
3125 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3126 /// matches the outer message expr in the code below, but NOT the message
3127 /// invocation for self.bodyView.
3129 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3131 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3132 Selector Sel = Node.getSelector();
3133 return BaseName.compare(Sel.getAsString()) == 0;
3137 /// Matches when at least one of the supplied string equals to the
3138 /// Selector.getAsString()
3140 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3141 /// matches both of the expressions below:
3143 /// [myObj methodA:argA];
3144 /// [myObj methodB:argB];
3146 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3148 internal::hasAnySelectorFunc>
3151 /// Matches ObjC selectors whose name contains
3152 /// a substring matched by the given RegExp.
3153 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3154 /// matches the outer message expr in the code below, but NOT the message
3155 /// invocation for self.bodyView.
3157 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3159 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
3160 assert(!RegExp.empty());
3161 std::string SelectorString = Node.getSelector().getAsString();
3162 llvm::Regex RE(RegExp);
3163 return RE.match(SelectorString);
3166 /// Matches when the selector is the empty selector
3168 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3169 /// represent an error condition in the tree!
3170 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3171 return Node.getSelector().isNull();
3174 /// Matches when the selector is a Unary Selector
3176 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3177 /// matches self.bodyView in the code below, but NOT the outer message
3178 /// invocation of "loadHTMLString:baseURL:".
3180 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3182 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3183 return Node.getSelector().isUnarySelector();
3186 /// Matches when the selector is a keyword selector
3188 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3189 /// message expression in
3192 /// UIWebView *webView = ...;
3193 /// CGRect bodyFrame = webView.frame;
3194 /// bodyFrame.size.height = self.bodyContentHeight;
3195 /// webView.frame = bodyFrame;
3196 /// // ^---- matches here
3198 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3199 return Node.getSelector().isKeywordSelector();
3202 /// Matches when the selector has the specified number of arguments
3204 /// matcher = objCMessageExpr(numSelectorArgs(0));
3205 /// matches self.bodyView in the code below
3207 /// matcher = objCMessageExpr(numSelectorArgs(2));
3208 /// matches the invocation of "loadHTMLString:baseURL:" but not that
3209 /// of self.bodyView
3211 /// [self.bodyView loadHTMLString:html baseURL:NULL];
3213 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3214 return Node.getSelector().getNumArgs() == N;
3217 /// Matches if the call expression's callee expression matches.
3221 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3222 /// void f() { f(); }
3224 /// callExpr(callee(expr()))
3225 /// matches this->x(), x(), y.x(), f()
3226 /// with callee(...)
3227 /// matching this->x, x, y.x, f respectively
3229 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3230 /// because this introduces ambiguous overloads with calls to Callee taking a
3231 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3232 /// implemented in terms of implicit casts.
3233 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3235 const Expr *ExprNode = Node.getCallee();
3236 return (ExprNode != nullptr &&
3237 InnerMatcher.matches(*ExprNode, Finder, Builder));
3240 /// Matches if the call expression's callee's declaration matches the
3243 /// Example matches y.x() (matcher = callExpr(callee(
3244 /// cxxMethodDecl(hasName("x")))))
3246 /// class Y { public: void x(); };
3247 /// void z() { Y y; y.x(); }
3249 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3251 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3254 /// Matches if the expression's or declaration's type matches a type
3257 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3258 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3259 /// and U (matcher = typedefDecl(hasType(asString("int")))
3260 /// and friend class X (matcher = friendDecl(hasType("X"))
3263 /// void y(X &x) { x; X z; }
3265 /// class Y { friend class X; };
3267 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3269 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3271 internal::Matcher<QualType>, InnerMatcher, 0) {
3272 QualType QT = internal::getUnderlyingType(Node);
3274 return InnerMatcher.matches(QT, Finder, Builder);
3278 /// Overloaded to match the declaration of the expression's or value
3279 /// declaration's type.
3281 /// In case of a value declaration (for example a variable declaration),
3282 /// this resolves one layer of indirection. For example, in the value
3283 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3284 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3285 /// declaration of x.
3287 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3288 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3289 /// and friend class X (matcher = friendDecl(hasType("X"))
3292 /// void y(X &x) { x; X z; }
3293 /// class Y { friend class X; };
3296 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
3297 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3298 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
3299 internal::Matcher<Decl>, InnerMatcher, 1) {
3300 QualType QT = internal::getUnderlyingType(Node);
3302 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3306 /// Matches if the type location of the declarator decl's type matches
3307 /// the inner matcher.
3313 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3315 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3316 if (!Node.getTypeSourceInfo())
3317 // This happens for example for implicit destructors.
3319 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3322 /// Matches if the matched type is represented by the given string.
3326 /// class Y { public: void x(); };
3327 /// void z() { Y* y; y->x(); }
3329 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3331 AST_MATCHER_P(QualType, asString, std::string, Name) {
3332 return Name == Node.getAsString();
3335 /// Matches if the matched type is a pointer type and the pointee type
3336 /// matches the specified matcher.
3338 /// Example matches y->x()
3339 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3340 /// cxxRecordDecl(hasName("Y")))))))
3342 /// class Y { public: void x(); };
3343 /// void z() { Y *y; y->x(); }
3346 QualType, pointsTo, internal::Matcher<QualType>,
3348 return (!Node.isNull() && Node->isAnyPointerType() &&
3349 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3352 /// Overloaded to match the pointee type's declaration.
3353 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3355 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3356 .matches(Node, Finder, Builder);
3359 /// Matches if the matched type matches the unqualified desugared
3360 /// type of the matched node.
3362 /// For example, in:
3367 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3369 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3371 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3375 /// Matches if the matched type is a reference type and the referenced
3376 /// type matches the specified matcher.
3378 /// Example matches X &x and const X &y
3379 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3388 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3390 return (!Node.isNull() && Node->isReferenceType() &&
3391 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3394 /// Matches QualTypes whose canonical type matches InnerMatcher.
3398 /// typedef int &int_ref;
3403 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3404 /// declaration of b but \c
3405 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3406 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3410 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3413 /// Overloaded to match the referenced type's declaration.
3414 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3416 return references(qualType(hasDeclaration(InnerMatcher)))
3417 .matches(Node, Finder, Builder);
3420 /// Matches on the implicit object argument of a member call expression. Unlike
3421 /// `on`, matches the argument directly without stripping away anything.
3425 /// class Y { public: void m(); };
3427 /// class X : public Y { void g(); };
3428 /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
3430 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
3431 /// cxxRecordDecl(hasName("Y")))))
3432 /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
3433 /// cxxMemberCallExpr(on(callExpr()))
3434 /// does not match `(g()).m()`, because the parens are not ignored.
3436 /// FIXME: Overload to allow directly matching types?
3437 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3438 internal::Matcher<Expr>, InnerMatcher) {
3439 const Expr *ExprNode = Node.getImplicitObjectArgument();
3440 return (ExprNode != nullptr &&
3441 InnerMatcher.matches(*ExprNode, Finder, Builder));
3444 /// Matches if the type of the expression's implicit object argument either
3445 /// matches the InnerMatcher, or is a pointer to a type that matches the
3450 /// class Y { public: void m(); };
3451 /// class X : public Y { void g(); };
3452 /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
3454 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3455 /// cxxRecordDecl(hasName("Y")))))
3456 /// matches `y.m()`, `p->m()` and `x.m()`.
3457 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3458 /// cxxRecordDecl(hasName("X")))))
3459 /// matches `x.g()`.
3460 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3461 internal::Matcher<QualType>, InnerMatcher, 0) {
3462 return onImplicitObjectArgument(
3463 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3464 .matches(Node, Finder, Builder);
3467 /// Overloaded to match the type's declaration.
3468 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3469 internal::Matcher<Decl>, InnerMatcher, 1) {
3470 return onImplicitObjectArgument(
3471 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3472 .matches(Node, Finder, Builder);
3475 /// Matches a DeclRefExpr that refers to a declaration that matches the
3476 /// specified matcher.
3478 /// Example matches x in if(x)
3479 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3484 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3486 const Decl *DeclNode = Node.getDecl();
3487 return (DeclNode != nullptr &&
3488 InnerMatcher.matches(*DeclNode, Finder, Builder));
3491 /// Matches a \c DeclRefExpr that refers to a declaration through a
3492 /// specific using shadow declaration.
3496 /// namespace a { void f() {} }
3499 /// f(); // Matches this ..
3500 /// a::f(); // .. but not this.
3503 /// declRefExpr(throughUsingDecl(anything()))
3505 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3506 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3507 const NamedDecl *FoundDecl = Node.getFoundDecl();
3508 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3509 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3513 /// Matches an \c OverloadExpr if any of the declarations in the set of
3514 /// overloads matches the given matcher.
3518 /// template <typename T> void foo(T);
3519 /// template <typename T> void bar(T);
3520 /// template <typename T> void baz(T t) {
3525 /// unresolvedLookupExpr(hasAnyDeclaration(
3526 /// functionTemplateDecl(hasName("foo"))))
3527 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3528 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3530 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3531 Node.decls_end(), Finder, Builder);
3534 /// Matches the Decl of a DeclStmt which has a single declaration.
3541 /// declStmt(hasSingleDecl(anything()))
3542 /// matches 'int c;' but not 'int a, b;'.
3543 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3544 if (Node.isSingleDecl()) {
3545 const Decl *FoundDecl = Node.getSingleDecl();
3546 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3551 /// Matches a variable declaration that has an initializer expression
3552 /// that matches the given matcher.
3554 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3556 /// bool y() { return true; }
3560 VarDecl, hasInitializer, internal::Matcher<Expr>,
3562 const Expr *Initializer = Node.getAnyInitializer();
3563 return (Initializer != nullptr &&
3564 InnerMatcher.matches(*Initializer, Finder, Builder));
3567 /// \brief Matches a static variable with local scope.
3569 /// Example matches y (matcher = varDecl(isStaticLocal()))
3577 AST_MATCHER(VarDecl, isStaticLocal) {
3578 return Node.isStaticLocal();
3581 /// Matches a variable declaration that has function scope and is a
3582 /// non-static local variable.
3584 /// Example matches x (matcher = varDecl(hasLocalStorage())
3592 AST_MATCHER(VarDecl, hasLocalStorage) {
3593 return Node.hasLocalStorage();
3596 /// Matches a variable declaration that does not have local storage.
3598 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3606 AST_MATCHER(VarDecl, hasGlobalStorage) {
3607 return Node.hasGlobalStorage();
3610 /// Matches a variable declaration that has automatic storage duration.
3612 /// Example matches x, but not y, z, or a.
3613 /// (matcher = varDecl(hasAutomaticStorageDuration())
3618 /// thread_local int z;
3622 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3623 return Node.getStorageDuration() == SD_Automatic;
3626 /// Matches a variable declaration that has static storage duration.
3627 /// It includes the variable declared at namespace scope and those declared
3628 /// with "static" and "extern" storage class specifiers.
3634 /// thread_local int z;
3639 /// varDecl(hasStaticStorageDuration())
3640 /// matches the function declaration y, a, b and c.
3642 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3643 return Node.getStorageDuration() == SD_Static;
3646 /// Matches a variable declaration that has thread storage duration.
3648 /// Example matches z, but not x, z, or a.
3649 /// (matcher = varDecl(hasThreadStorageDuration())
3654 /// thread_local int z;
3658 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3659 return Node.getStorageDuration() == SD_Thread;
3662 /// Matches a variable declaration that is an exception variable from
3663 /// a C++ catch block, or an Objective-C \@catch statement.
3665 /// Example matches x (matcher = varDecl(isExceptionVariable())
3669 /// } catch (int x) {
3673 AST_MATCHER(VarDecl, isExceptionVariable) {
3674 return Node.isExceptionVariable();
3677 /// Checks that a call expression or a constructor call expression has
3678 /// a specific number of arguments (including absent default arguments).
3680 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3682 /// void f(int x, int y);
3685 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3686 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3690 return Node.getNumArgs() == N;
3693 /// Matches the n'th argument of a call expression or a constructor
3694 /// call expression.
3696 /// Example matches y in x(y)
3697 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3699 /// void x(int) { int y; x(y); }
3701 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3702 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3705 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3706 return (N < Node.getNumArgs() &&
3707 InnerMatcher.matches(
3708 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3711 /// Matches the n'th item of an initializer list expression.
3713 /// Example matches y.
3714 /// (matcher = initListExpr(hasInit(0, expr())))
3718 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
3719 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
3720 return N < Node.getNumInits() &&
3721 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
3724 /// Matches declaration statements that contain a specific number of
3734 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3735 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3736 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3739 /// Matches the n'th declaration of a declaration statement.
3741 /// Note that this does not work for global declarations because the AST
3742 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3744 /// Example: Given non-global declarations
3750 /// declStmt(containsDeclaration(
3751 /// 0, varDecl(hasInitializer(anything()))))
3752 /// matches only 'int d = 2, e;', and
3753 /// declStmt(containsDeclaration(1, varDecl()))
3755 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3756 /// but 'int c;' is not matched.
3758 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3759 internal::Matcher<Decl>, InnerMatcher) {
3760 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3763 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3764 std::advance(Iterator, N);
3765 return InnerMatcher.matches(**Iterator, Finder, Builder);
3768 /// Matches a C++ catch statement that has a catch-all handler.
3780 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3781 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3782 return Node.getExceptionDecl() == nullptr;
3785 /// Matches a constructor initializer.
3790 /// Foo() : foo_(1) { }
3794 /// cxxRecordDecl(has(cxxConstructorDecl(
3795 /// hasAnyConstructorInitializer(anything())
3797 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3798 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3799 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3800 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3801 Node.init_end(), Finder, Builder);
3804 /// Matches the field declaration of a constructor initializer.
3809 /// Foo() : foo_(1) { }
3813 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3814 /// forField(hasName("foo_"))))))
3816 /// with forField matching foo_
3817 AST_MATCHER_P(CXXCtorInitializer, forField,
3818 internal::Matcher<FieldDecl>, InnerMatcher) {
3819 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3820 return (NodeAsDecl != nullptr &&
3821 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3824 /// Matches the initializer expression of a constructor initializer.
3829 /// Foo() : foo_(1) { }
3833 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3834 /// withInitializer(integerLiteral(equals(1)))))))
3836 /// with withInitializer matching (1)
3837 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3838 internal::Matcher<Expr>, InnerMatcher) {
3839 const Expr* NodeAsExpr = Node.getInit();
3840 return (NodeAsExpr != nullptr &&
3841 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3844 /// Matches a constructor initializer if it is explicitly written in
3845 /// code (as opposed to implicitly added by the compiler).
3851 /// Foo(int) : foo_("A") { }
3855 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3856 /// will match Foo(int), but not Foo()
3857 AST_MATCHER(CXXCtorInitializer, isWritten) {
3858 return Node.isWritten();
3861 /// Matches a constructor initializer if it is initializing a base, as
3862 /// opposed to a member.
3869 /// D(int i) : I(i) {}
3875 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3876 /// will match E(), but not match D(int).
3877 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3878 return Node.isBaseInitializer();
3881 /// Matches a constructor initializer if it is initializing a member, as
3882 /// opposed to a base.
3889 /// D(int i) : I(i) {}
3895 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3896 /// will match D(int), but not match E().
3897 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3898 return Node.isMemberInitializer();
3901 /// Matches any argument of a call expression or a constructor call
3902 /// expression, or an ObjC-message-send expression.
3906 /// void x(int, int, int) { int y; x(1, y, 42); }
3908 /// callExpr(hasAnyArgument(declRefExpr()))
3909 /// matches x(1, y, 42)
3910 /// with hasAnyArgument(...)
3913 /// For ObjectiveC, given
3915 /// @interface I - (void) f:(int) y; @end
3916 /// void foo(I *i) { [i f:12]; }
3918 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3919 /// matches [i f:12]
3920 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3921 AST_POLYMORPHIC_SUPPORTED_TYPES(
3922 CallExpr, CXXConstructExpr,
3923 CXXUnresolvedConstructExpr, ObjCMessageExpr),
3924 internal::Matcher<Expr>, InnerMatcher) {
3925 for (const Expr *Arg : Node.arguments()) {
3926 BoundNodesTreeBuilder Result(*Builder);
3927 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3928 *Builder = std::move(Result);
3935 /// Matches a constructor call expression which uses list initialization.
3936 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3937 return Node.isListInitialization();
3940 /// Matches a constructor call expression which requires
3941 /// zero initialization.
3946 /// struct point { double x; double y; };
3947 /// point pt[2] = { { 1.0, 2.0 } };
3950 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3951 /// will match the implicit array filler for pt[1].
3952 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3953 return Node.requiresZeroInitialization();
3956 /// Matches the n'th parameter of a function or an ObjC method
3957 /// declaration or a block.
3961 /// class X { void f(int x) {} };
3963 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3964 /// matches f(int x) {}
3965 /// with hasParameter(...)
3968 /// For ObjectiveC, given
3970 /// @interface I - (void) f:(int) y; @end
3973 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3974 /// matches the declaration of method f with hasParameter
3976 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3977 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3980 unsigned, N, internal::Matcher<ParmVarDecl>,
3982 return (N < Node.parameters().size()
3983 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3986 /// Matches all arguments and their respective ParmVarDecl.
3995 /// forEachArgumentWithParam(
3996 /// declRefExpr(to(varDecl(hasName("y")))),
3997 /// parmVarDecl(hasType(isInteger()))
4000 /// with declRefExpr(...)
4002 /// and parmVarDecl(...)
4004 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4005 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
4007 internal::Matcher<Expr>, ArgMatcher,
4008 internal::Matcher<ParmVarDecl>, ParamMatcher) {
4009 BoundNodesTreeBuilder Result;
4010 // The first argument of an overloaded member operator is the implicit object
4011 // argument of the method which should not be matched against a parameter, so
4012 // we skip over it here.
4013 BoundNodesTreeBuilder Matches;
4014 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4015 .matches(Node, Finder, &Matches)
4019 bool Matched = false;
4020 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
4021 BoundNodesTreeBuilder ArgMatches(*Builder);
4022 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4023 Finder, &ArgMatches)) {
4024 BoundNodesTreeBuilder ParamMatches(ArgMatches);
4025 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4026 hasParameter(ParamIndex, ParamMatcher)))),
4027 callExpr(callee(functionDecl(
4028 hasParameter(ParamIndex, ParamMatcher))))))
4029 .matches(Node, Finder, &ParamMatches)) {
4030 Result.addMatch(ParamMatches);
4036 *Builder = std::move(Result);
4040 /// Matches any parameter of a function or an ObjC method declaration or a
4043 /// Does not match the 'this' parameter of a method.
4047 /// class X { void f(int x, int y, int z) {} };
4049 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
4050 /// matches f(int x, int y, int z) {}
4051 /// with hasAnyParameter(...)
4054 /// For ObjectiveC, given
4056 /// @interface I - (void) f:(int) y; @end
4059 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
4060 /// matches the declaration of method f with hasParameter
4063 /// For blocks, given
4065 /// b = ^(int y) { printf("%d", y) };
4068 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
4069 /// matches the declaration of the block b with hasParameter
4071 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
4072 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4075 internal::Matcher<ParmVarDecl>,
4077 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
4078 Node.param_end(), Finder, Builder);
4081 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
4082 /// specific parameter count.
4086 /// void f(int i) {}
4087 /// void g(int i, int j) {}
4088 /// void h(int i, int j);
4090 /// void k(int x, int y, int z, ...);
4092 /// functionDecl(parameterCountIs(2))
4093 /// matches \c g and \c h
4094 /// functionProtoType(parameterCountIs(2))
4095 /// matches \c g and \c h
4096 /// functionProtoType(parameterCountIs(3))
4098 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
4099 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4102 return Node.getNumParams() == N;
4105 /// Matches \c FunctionDecls that have a noreturn attribute.
4110 /// [[noreturn]] void a();
4111 /// __attribute__((noreturn)) void b();
4112 /// struct c { [[noreturn]] c(); };
4114 /// functionDecl(isNoReturn())
4115 /// matches all of those except
4119 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
4121 /// Matches the return type of a function declaration.
4125 /// class X { int f() { return 1; } };
4127 /// cxxMethodDecl(returns(asString("int")))
4128 /// matches int f() { return 1; }
4129 AST_MATCHER_P(FunctionDecl, returns,
4130 internal::Matcher<QualType>, InnerMatcher) {
4131 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
4134 /// Matches extern "C" function or variable declarations.
4138 /// extern "C" void f() {}
4139 /// extern "C" { void g() {} }
4141 /// extern "C" int x = 1;
4142 /// extern "C" int y = 2;
4145 /// functionDecl(isExternC())
4146 /// matches the declaration of f and g, but not the declaration of h.
4147 /// varDecl(isExternC())
4148 /// matches the declaration of x and y, but not the declaration of z.
4149 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4151 return Node.isExternC();
4154 /// Matches variable/function declarations that have "static" storage
4155 /// class specifier ("static" keyword) written in the source.
4159 /// static void f() {}
4160 /// static int i = 0;
4164 /// functionDecl(isStaticStorageClass())
4165 /// matches the function declaration f.
4166 /// varDecl(isStaticStorageClass())
4167 /// matches the variable declaration i.
4168 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
4169 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4171 return Node.getStorageClass() == SC_Static;
4174 /// Matches deleted function declarations.
4179 /// void DeletedFunc() = delete;
4181 /// functionDecl(isDeleted())
4182 /// matches the declaration of DeletedFunc, but not Func.
4183 AST_MATCHER(FunctionDecl, isDeleted) {
4184 return Node.isDeleted();
4187 /// Matches defaulted function declarations.
4191 /// class A { ~A(); };
4192 /// class B { ~B() = default; };
4194 /// functionDecl(isDefaulted())
4195 /// matches the declaration of ~B, but not ~A.
4196 AST_MATCHER(FunctionDecl, isDefaulted) {
4197 return Node.isDefaulted();
4200 /// Matches functions that have a dynamic exception specification.
4205 /// void g() noexcept;
4206 /// void h() noexcept(true);
4207 /// void i() noexcept(false);
4208 /// void j() throw();
4209 /// void k() throw(int);
4210 /// void l() throw(...);
4212 /// functionDecl(hasDynamicExceptionSpec()) and
4213 /// functionProtoType(hasDynamicExceptionSpec())
4214 /// match the declarations of j, k, and l, but not f, g, h, or i.
4215 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
4216 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4217 FunctionProtoType)) {
4218 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
4219 return FnTy->hasDynamicExceptionSpec();
4223 /// Matches functions that have a non-throwing exception specification.
4228 /// void g() noexcept;
4229 /// void h() throw();
4230 /// void i() throw(int);
4231 /// void j() noexcept(false);
4233 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
4234 /// match the declarations of g, and h, but not f, i or j.
4235 AST_POLYMORPHIC_MATCHER(isNoThrow,
4236 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4237 FunctionProtoType)) {
4238 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
4240 // If the function does not have a prototype, then it is assumed to be a
4241 // throwing function (as it would if the function did not have any exception
4246 // Assume the best for any unresolved exception specification.
4247 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
4250 return FnTy->isNothrow();
4253 /// Matches constexpr variable and function declarations,
4254 /// and if constexpr.
4258 /// constexpr int foo = 42;
4259 /// constexpr int bar();
4260 /// void baz() { if constexpr(1 > 0) {} }
4262 /// varDecl(isConstexpr())
4263 /// matches the declaration of foo.
4264 /// functionDecl(isConstexpr())
4265 /// matches the declaration of bar.
4266 /// ifStmt(isConstexpr())
4267 /// matches the if statement in baz.
4268 AST_POLYMORPHIC_MATCHER(isConstexpr,
4269 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
4272 return Node.isConstexpr();
4275 /// Matches the condition expression of an if statement, for loop,
4276 /// switch statement or conditional operator.
4278 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
4282 AST_POLYMORPHIC_MATCHER_P(
4284 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
4285 SwitchStmt, AbstractConditionalOperator),
4286 internal::Matcher<Expr>, InnerMatcher) {
4287 const Expr *const Condition = Node.getCond();
4288 return (Condition != nullptr &&
4289 InnerMatcher.matches(*Condition, Finder, Builder));
4292 /// Matches the then-statement of an if statement.
4294 /// Examples matches the if statement
4295 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
4297 /// if (false) true; else false;
4299 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
4300 const Stmt *const Then = Node.getThen();
4301 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
4304 /// Matches the else-statement of an if statement.
4306 /// Examples matches the if statement
4307 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
4309 /// if (false) false; else true;
4311 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
4312 const Stmt *const Else = Node.getElse();
4313 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
4316 /// Matches if a node equals a previously bound node.
4318 /// Matches a node if it equals the node previously bound to \p ID.
4322 /// class X { int a; int b; };
4325 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4326 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
4327 /// matches the class \c X, as \c a and \c b have the same type.
4329 /// Note that when multiple matches are involved via \c forEach* matchers,
4330 /// \c equalsBoundNodes acts as a filter.
4333 /// forEachDescendant(varDecl().bind("d")),
4334 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
4335 /// will trigger a match for each combination of variable declaration
4336 /// and reference to that variable declaration within a compound statement.
4337 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
4338 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
4341 // FIXME: Figure out whether it makes sense to allow this
4342 // on any other node types.
4343 // For *Loc it probably does not make sense, as those seem
4344 // unique. For NestedNameSepcifier it might make sense, as
4345 // those also have pointer identity, but I'm not sure whether
4346 // they're ever reused.
4347 internal::NotEqualsBoundNodePredicate Predicate;
4349 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
4350 return Builder->removeBindings(Predicate);
4353 /// Matches the condition variable statement in an if statement.
4357 /// if (A* a = GetAPointer()) {}
4359 /// hasConditionVariableStatement(...)
4360 /// matches 'A* a = GetAPointer()'.
4361 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
4362 internal::Matcher<DeclStmt>, InnerMatcher) {
4363 const DeclStmt* const DeclarationStatement =
4364 Node.getConditionVariableDeclStmt();
4365 return DeclarationStatement != nullptr &&
4366 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
4369 /// Matches the index expression of an array subscript expression.
4374 /// void f() { i[1] = 42; }
4376 /// arraySubscriptExpression(hasIndex(integerLiteral()))
4377 /// matches \c i[1] with the \c integerLiteral() matching \c 1
4378 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
4379 internal::Matcher<Expr>, InnerMatcher) {
4380 if (const Expr* Expression = Node.getIdx())
4381 return InnerMatcher.matches(*Expression, Finder, Builder);
4385 /// Matches the base expression of an array subscript expression.
4390 /// void f() { i[1] = 42; }
4392 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4393 /// hasSourceExpression(declRefExpr()))))
4394 /// matches \c i[1] with the \c declRefExpr() matching \c i
4395 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4396 internal::Matcher<Expr>, InnerMatcher) {
4397 if (const Expr* Expression = Node.getBase())
4398 return InnerMatcher.matches(*Expression, Finder, Builder);
4402 /// Matches a 'for', 'while', 'do while' statement or a function
4403 /// definition that has a given body.
4409 /// hasBody(compoundStmt())
4410 /// matches 'for (;;) {}'
4411 /// with compoundStmt()
4413 AST_POLYMORPHIC_MATCHER_P(hasBody,
4414 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4418 internal::Matcher<Stmt>, InnerMatcher) {
4419 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4420 return (Statement != nullptr &&
4421 InnerMatcher.matches(*Statement, Finder, Builder));
4424 /// Matches compound statements where at least one substatement matches
4425 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4431 /// hasAnySubstatement(compoundStmt())
4432 /// matches '{ {}; 1+2; }'
4433 /// with compoundStmt()
4435 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4436 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4438 internal::Matcher<Stmt>, InnerMatcher) {
4439 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4440 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4441 CS->body_end(), Finder, Builder);
4444 /// Checks that a compound statement contains a specific number of
4445 /// child statements.
4451 /// compoundStmt(statementCountIs(0)))
4453 /// but does not match the outer compound statement.
4454 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4455 return Node.size() == N;
4458 /// Matches literals that are equal to the given value of type ValueT.
4462 /// f('\0', false, 3.14, 42);
4464 /// characterLiteral(equals(0))
4466 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4468 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4470 /// integerLiteral(equals(42))
4473 /// Note that you cannot directly match a negative numeric literal because the
4474 /// minus sign is not part of the literal: It is a unary operator whose operand
4475 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4476 /// matcher to match the minus sign:
4478 /// unaryOperator(hasOperatorName("-"),
4479 /// hasUnaryOperand(integerLiteral(equals(13))))
4481 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4482 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4483 template <typename ValueT>
4484 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
4485 equals(const ValueT &Value) {
4486 return internal::PolymorphicMatcherWithParam1<
4487 internal::ValueEqualsMatcher,
4491 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4492 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4496 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4500 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4501 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4504 unsigned, Value, 1) {
4505 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4509 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4510 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4515 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4519 /// Matches the operator Name of operator expressions (binary or
4522 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4526 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4527 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4529 std::string, Name) {
4530 return Name == Node.getOpcodeStr(Node.getOpcode());
4533 /// Matches all kinds of assignment operators.
4535 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4541 /// Example 2: matches s1 = s2
4542 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4544 /// struct S { S& operator=(const S&); };
4545 /// void x() { S s1, s2; s1 = s2; })
4547 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4548 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4549 CXXOperatorCallExpr)) {
4550 return Node.isAssignmentOp();
4553 /// Matches the left hand side of binary operator expressions.
4555 /// Example matches a (matcher = binaryOperator(hasLHS()))
4559 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4560 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4561 ArraySubscriptExpr),
4562 internal::Matcher<Expr>, InnerMatcher) {
4563 const Expr *LeftHandSide = Node.getLHS();
4564 return (LeftHandSide != nullptr &&
4565 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4568 /// Matches the right hand side of binary operator expressions.
4570 /// Example matches b (matcher = binaryOperator(hasRHS()))
4574 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4575 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4576 ArraySubscriptExpr),
4577 internal::Matcher<Expr>, InnerMatcher) {
4578 const Expr *RightHandSide = Node.getRHS();
4579 return (RightHandSide != nullptr &&
4580 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4583 /// Matches if either the left hand side or the right hand side of a
4584 /// binary operator matches.
4585 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4586 const internal::Matcher<Expr> &InnerMatcher) {
4587 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4590 /// Matches if the operand of a unary operator matches.
4592 /// Example matches true (matcher = hasUnaryOperand(
4593 /// cxxBoolLiteral(equals(true))))
4597 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4598 internal::Matcher<Expr>, InnerMatcher) {
4599 const Expr * const Operand = Node.getSubExpr();
4600 return (Operand != nullptr &&
4601 InnerMatcher.matches(*Operand, Finder, Builder));
4604 /// Matches if the cast's source expression
4605 /// or opaque value's source expression matches the given matcher.
4607 /// Example 1: matches "a string"
4608 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4610 /// class URL { URL(string); };
4611 /// URL url = "a string";
4614 /// Example 2: matches 'b' (matcher =
4615 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4619 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4620 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4622 internal::Matcher<Expr>, InnerMatcher) {
4623 const Expr *const SubExpression =
4624 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4625 return (SubExpression != nullptr &&
4626 InnerMatcher.matches(*SubExpression, Finder, Builder));
4629 /// Matches casts that has a given cast kind.
4631 /// Example: matches the implicit cast around \c 0
4632 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4637 /// If the matcher is use from clang-query, CastKind parameter
4638 /// should be passed as a quoted string. e.g., ofKind("CK_NullToPointer").
4639 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4640 return Node.getCastKind() == Kind;
4643 /// Matches casts whose destination type matches a given matcher.
4645 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4646 /// actual casts "explicit" casts.)
4647 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4648 internal::Matcher<QualType>, InnerMatcher) {
4649 const QualType NodeType = Node.getTypeAsWritten();
4650 return InnerMatcher.matches(NodeType, Finder, Builder);
4653 /// Matches implicit casts whose destination type matches a given
4656 /// FIXME: Unit test this matcher
4657 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4658 internal::Matcher<QualType>, InnerMatcher) {
4659 return InnerMatcher.matches(Node.getType(), Finder, Builder);
4662 /// Matches RecordDecl object that are spelled with "struct."
4664 /// Example matches S, but not C or U.
4670 AST_MATCHER(RecordDecl, isStruct) {
4671 return Node.isStruct();
4674 /// Matches RecordDecl object that are spelled with "union."
4676 /// Example matches U, but not C or S.
4682 AST_MATCHER(RecordDecl, isUnion) {
4683 return Node.isUnion();
4686 /// Matches RecordDecl object that are spelled with "class."
4688 /// Example matches C, but not S or U.
4694 AST_MATCHER(RecordDecl, isClass) {
4695 return Node.isClass();
4698 /// Matches the true branch expression of a conditional operator.
4700 /// Example 1 (conditional ternary operator): matches a
4702 /// condition ? a : b
4705 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4709 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4710 internal::Matcher<Expr>, InnerMatcher) {
4711 const Expr *Expression = Node.getTrueExpr();
4712 return (Expression != nullptr &&
4713 InnerMatcher.matches(*Expression, Finder, Builder));
4716 /// Matches the false branch expression of a conditional operator
4717 /// (binary or ternary).
4719 /// Example matches b
4721 /// condition ? a : b
4724 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4725 internal::Matcher<Expr>, InnerMatcher) {
4726 const Expr *Expression = Node.getFalseExpr();
4727 return (Expression != nullptr &&
4728 InnerMatcher.matches(*Expression, Finder, Builder));
4731 /// Matches if a declaration has a body attached.
4733 /// Example matches A, va, fa
4736 /// class B; // Doesn't match, as it has no body.
4738 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4740 /// void fb(); // Doesn't match, as it has no body.
4742 /// - (void)ma; // Doesn't match, interface is declaration.
4744 /// @implementation X
4749 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4750 /// Matcher<ObjCMethodDecl>
4751 AST_POLYMORPHIC_MATCHER(isDefinition,
4752 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4755 return Node.isThisDeclarationADefinition();
4758 /// Matches if a function declaration is variadic.
4760 /// Example matches f, but not g or h. The function i will not match, even when
4761 /// compiled in C mode.
4765 /// template <typename... Ts> void h(Ts...);
4768 AST_MATCHER(FunctionDecl, isVariadic) {
4769 return Node.isVariadic();
4772 /// Matches the class declaration that the given method declaration
4775 /// FIXME: Generalize this for other kinds of declarations.
4776 /// FIXME: What other kind of declarations would we need to generalize
4779 /// Example matches A() in the last line
4780 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4781 /// ofClass(hasName("A"))))))
4789 AST_MATCHER_P(CXXMethodDecl, ofClass,
4790 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4791 const CXXRecordDecl *Parent = Node.getParent();
4792 return (Parent != nullptr &&
4793 InnerMatcher.matches(*Parent, Finder, Builder));
4796 /// Matches each method overridden by the given method. This matcher may
4797 /// produce multiple matches.
4801 /// class A { virtual void f(); };
4802 /// class B : public A { void f(); };
4803 /// class C : public B { void f(); };
4805 /// cxxMethodDecl(ofClass(hasName("C")),
4806 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4807 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4808 /// that B::f is not overridden by C::f).
4810 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4812 /// class A1 { virtual void f(); };
4813 /// class A2 { virtual void f(); };
4814 /// class C : public A1, public A2 { void f(); };
4816 /// cxxMethodDecl(ofClass(hasName("C")),
4817 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4818 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4819 /// once with "b" binding "A2::f" and "d" binding "C::f".
4820 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4821 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4822 BoundNodesTreeBuilder Result;
4823 bool Matched = false;
4824 for (const auto *Overridden : Node.overridden_methods()) {
4825 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4826 const bool OverriddenMatched =
4827 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4828 if (OverriddenMatched) {
4830 Result.addMatch(OverriddenBuilder);
4833 *Builder = std::move(Result);
4837 /// Matches if the given method declaration is virtual.
4843 /// virtual void x();
4847 AST_MATCHER(CXXMethodDecl, isVirtual) {
4848 return Node.isVirtual();
4851 /// Matches if the given method declaration has an explicit "virtual".
4857 /// virtual void x();
4859 /// class B : public A {
4864 /// matches A::x but not B::x
4865 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4866 return Node.isVirtualAsWritten();
4869 /// Matches if the given method or class declaration is final.
4873 /// class A final {};
4876 /// virtual void f();
4883 /// matches A and C::f, but not B, C, or B::f
4884 AST_POLYMORPHIC_MATCHER(isFinal,
4885 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4887 return Node.template hasAttr<FinalAttr>();
4890 /// Matches if the given method declaration is pure.
4896 /// virtual void x() = 0;
4900 AST_MATCHER(CXXMethodDecl, isPure) {
4901 return Node.isPure();
4904 /// Matches if the given method declaration is const.
4909 /// void foo() const;
4914 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4915 AST_MATCHER(CXXMethodDecl, isConst) {
4916 return Node.isConst();
4919 /// Matches if the given method declaration declares a copy assignment
4925 /// A &operator=(const A &);
4926 /// A &operator=(A &&);
4930 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4932 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4933 return Node.isCopyAssignmentOperator();
4936 /// Matches if the given method declaration declares a move assignment
4942 /// A &operator=(const A &);
4943 /// A &operator=(A &&);
4947 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4949 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4950 return Node.isMoveAssignmentOperator();
4953 /// Matches if the given method declaration overrides another method.
4959 /// virtual void x();
4961 /// class B : public A {
4963 /// virtual void x();
4967 AST_MATCHER(CXXMethodDecl, isOverride) {
4968 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4971 /// Matches method declarations that are user-provided.
4977 /// S(const S &) = default; // #2
4978 /// S(S &&) = delete; // #3
4981 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4982 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4983 return Node.isUserProvided();
4986 /// Matches member expressions that are called with '->' as opposed
4989 /// Member calls on the implicit this pointer match as called with '->'.
4994 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4995 /// template <class T> void f() { this->f<T>(); f<T>(); }
4999 /// template <class T>
5001 /// void x() { this->m; }
5004 /// memberExpr(isArrow())
5005 /// matches this->x, x, y.x, a, this->b
5006 /// cxxDependentScopeMemberExpr(isArrow())
5008 /// unresolvedMemberExpr(isArrow())
5009 /// matches this->f<T>, f<T>
5010 AST_POLYMORPHIC_MATCHER(
5011 isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
5012 CXXDependentScopeMemberExpr)) {
5013 return Node.isArrow();
5016 /// Matches QualType nodes that are of integer type.
5024 /// functionDecl(hasAnyParameter(hasType(isInteger())))
5025 /// matches "a(int)", "b(long)", but not "c(double)".
5026 AST_MATCHER(QualType, isInteger) {
5027 return Node->isIntegerType();
5030 /// Matches QualType nodes that are of unsigned integer type.
5035 /// void b(unsigned long);
5038 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
5039 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
5040 AST_MATCHER(QualType, isUnsignedInteger) {
5041 return Node->isUnsignedIntegerType();
5044 /// Matches QualType nodes that are of signed integer type.
5049 /// void b(unsigned long);
5052 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
5053 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
5054 AST_MATCHER(QualType, isSignedInteger) {
5055 return Node->isSignedIntegerType();
5058 /// Matches QualType nodes that are of character type.
5063 /// void b(wchar_t);
5066 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
5067 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
5068 AST_MATCHER(QualType, isAnyCharacter) {
5069 return Node->isAnyCharacterType();
5072 /// Matches QualType nodes that are of any pointer type; this includes
5073 /// the Objective-C object pointer type, which is different despite being
5074 /// syntactically similar.
5078 /// int *i = nullptr;
5086 /// varDecl(hasType(isAnyPointer()))
5087 /// matches "int *i" and "Foo *f", but not "int j".
5088 AST_MATCHER(QualType, isAnyPointer) {
5089 return Node->isAnyPointerType();
5092 /// Matches QualType nodes that are const-qualified, i.e., that
5093 /// include "top-level" const.
5098 /// void b(int const);
5099 /// void c(const int);
5100 /// void d(const int*);
5101 /// void e(int const) {};
5103 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
5104 /// matches "void b(int const)", "void c(const int)" and
5105 /// "void e(int const) {}". It does not match d as there
5106 /// is no top-level const on the parameter type "const int *".
5107 AST_MATCHER(QualType, isConstQualified) {
5108 return Node.isConstQualified();
5111 /// Matches QualType nodes that are volatile-qualified, i.e., that
5112 /// include "top-level" volatile.
5117 /// void b(int volatile);
5118 /// void c(volatile int);
5119 /// void d(volatile int*);
5120 /// void e(int volatile) {};
5122 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
5123 /// matches "void b(int volatile)", "void c(volatile int)" and
5124 /// "void e(int volatile) {}". It does not match d as there
5125 /// is no top-level volatile on the parameter type "volatile int *".
5126 AST_MATCHER(QualType, isVolatileQualified) {
5127 return Node.isVolatileQualified();
5130 /// Matches QualType nodes that have local CV-qualifiers attached to
5131 /// the node, not hidden within a typedef.
5135 /// typedef const int const_int;
5138 /// int *volatile k;
5141 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
5142 /// \c i is const-qualified but the qualifier is not local.
5143 AST_MATCHER(QualType, hasLocalQualifiers) {
5144 return Node.hasLocalQualifiers();
5147 /// Matches a member expression where the member is matched by a
5152 /// struct { int first, second; } first, second;
5153 /// int i(second.first);
5154 /// int j(first.second);
5156 /// memberExpr(member(hasName("first")))
5157 /// matches second.first
5158 /// but not first.second (because the member name there is "second").
5159 AST_MATCHER_P(MemberExpr, member,
5160 internal::Matcher<ValueDecl>, InnerMatcher) {
5161 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
5164 /// Matches a member expression where the object expression is matched by a
5165 /// given matcher. Implicit object expressions are included; that is, it matches
5166 /// use of implicit `this`.
5172 /// int f(X x) { x.m; return m; }
5175 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
5176 /// matches `x.m`, but not `m`; however,
5177 /// memberExpr(hasObjectExpression(hasType(pointsTo(
5178 // cxxRecordDecl(hasName("X"))))))
5179 /// matches `m` (aka. `this->m`), but not `x.m`.
5180 AST_POLYMORPHIC_MATCHER_P(
5181 hasObjectExpression,
5182 AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
5183 CXXDependentScopeMemberExpr),
5184 internal::Matcher<Expr>, InnerMatcher) {
5185 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
5186 if (E->isImplicitAccess())
5188 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
5189 if (E->isImplicitAccess())
5191 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
5194 /// Matches any using shadow declaration.
5198 /// namespace X { void b(); }
5201 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
5202 /// matches \code using X::b \endcode
5203 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
5204 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
5205 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
5206 Node.shadow_end(), Finder, Builder);
5209 /// Matches a using shadow declaration where the target declaration is
5210 /// matched by the given matcher.
5214 /// namespace X { int a; void b(); }
5218 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
5219 /// matches \code using X::b \endcode
5220 /// but not \code using X::a \endcode
5221 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
5222 internal::Matcher<NamedDecl>, InnerMatcher) {
5223 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
5226 /// Matches template instantiations of function, class, or static
5227 /// member variable template instantiations.
5231 /// template <typename T> class X {}; class A {}; X<A> x;
5235 /// template <typename T> class X {}; class A {}; template class X<A>;
5239 /// template <typename T> class X {}; class A {}; extern template class X<A>;
5241 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5242 /// matches the template instantiation of X<A>.
5246 /// template <typename T> class X {}; class A {};
5247 /// template <> class X<A> {}; X<A> x;
5249 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5250 /// does not match, as X<A> is an explicit template specialization.
5252 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5253 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
5254 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5256 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
5257 Node.getTemplateSpecializationKind() ==
5258 TSK_ExplicitInstantiationDefinition ||
5259 Node.getTemplateSpecializationKind() ==
5260 TSK_ExplicitInstantiationDeclaration);
5263 /// Matches declarations that are template instantiations or are inside
5264 /// template instantiations.
5268 /// template<typename T> void A(T t) { T i; }
5272 /// functionDecl(isInstantiated())
5273 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
5274 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
5275 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5276 functionDecl(isTemplateInstantiation())));
5277 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
5280 /// Matches statements inside of a template instantiation.
5285 /// template<typename T> void A(T t) { T i; j += 42;}
5289 /// declStmt(isInTemplateInstantiation())
5290 /// matches 'int i;' and 'unsigned i'.
5291 /// unless(stmt(isInTemplateInstantiation()))
5292 /// will NOT match j += 42; as it's shared between the template definition and
5294 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
5296 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5297 functionDecl(isTemplateInstantiation())))));
5300 /// Matches explicit template specializations of function, class, or
5301 /// static member variable template instantiations.
5305 /// template<typename T> void A(T t) { }
5306 /// template<> void A(int N) { }
5308 /// functionDecl(isExplicitTemplateSpecialization())
5309 /// matches the specialization A<int>().
5311 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5312 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
5313 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5315 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
5318 /// Matches \c TypeLocs for which the given inner
5319 /// QualType-matcher matches.
5320 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
5321 internal::Matcher<QualType>, InnerMatcher, 0) {
5322 return internal::BindableMatcher<TypeLoc>(
5323 new internal::TypeLocTypeMatcher(InnerMatcher));
5326 /// Matches type \c bool.
5330 /// struct S { bool func(); };
5332 /// functionDecl(returns(booleanType()))
5333 /// matches "bool func();"
5334 AST_MATCHER(Type, booleanType) {
5335 return Node.isBooleanType();
5338 /// Matches type \c void.
5342 /// struct S { void func(); };
5344 /// functionDecl(returns(voidType()))
5345 /// matches "void func();"
5346 AST_MATCHER(Type, voidType) {
5347 return Node.isVoidType();
5350 template <typename NodeType>
5351 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
5353 /// Matches builtin Types.
5364 /// matches "int b", "float c" and "bool d"
5365 extern const AstTypeMatcher<BuiltinType> builtinType;
5367 /// Matches all kinds of arrays.
5371 /// int a[] = { 2, 3 };
5373 /// void f() { int c[a[0]]; }
5376 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
5377 extern const AstTypeMatcher<ArrayType> arrayType;
5379 /// Matches C99 complex types.
5383 /// _Complex float f;
5386 /// matches "_Complex float f"
5387 extern const AstTypeMatcher<ComplexType> complexType;
5389 /// Matches any real floating-point type (float, double, long double).
5396 /// realFloatingPointType()
5397 /// matches "float f" but not "int i"
5398 AST_MATCHER(Type, realFloatingPointType) {
5399 return Node.isRealFloatingType();
5402 /// Matches arrays and C99 complex types that have a specific element
5411 /// arrayType(hasElementType(builtinType()))
5412 /// matches "int b[7]"
5414 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5415 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5416 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5419 /// Matches C arrays with a specified constant size.
5425 /// int b[] = { 2, 3 };
5429 /// constantArrayType()
5430 /// matches "int a[2]"
5431 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5433 /// Matches nodes that have the specified size.
5439 /// int c[41], d[43];
5440 /// char *s = "abcd";
5441 /// wchar_t *ws = L"abcd";
5444 /// constantArrayType(hasSize(42))
5445 /// matches "int a[42]" and "int b[2 * 21]"
5446 /// stringLiteral(hasSize(4))
5447 /// matches "abcd", L"abcd"
5448 AST_POLYMORPHIC_MATCHER_P(hasSize,
5449 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5452 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5455 /// Matches C++ arrays whose size is a value-dependent expression.
5459 /// template<typename T, int Size>
5464 /// dependentSizedArrayType
5465 /// matches "T data[Size]"
5466 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5468 /// Matches C arrays with unspecified size.
5472 /// int a[] = { 2, 3 };
5474 /// void f(int c[]) { int d[a[0]]; };
5476 /// incompleteArrayType()
5477 /// matches "int a[]" and "int c[]"
5478 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5480 /// Matches C arrays with a specified size that is not an
5481 /// integer-constant-expression.
5486 /// int a[] = { 2, 3 }
5491 /// variableArrayType()
5492 /// matches "int c[a[0]]"
5493 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5495 /// Matches \c VariableArrayType nodes that have a specific size
5504 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5505 /// varDecl(hasName("b")))))))
5506 /// matches "int a[b]"
5507 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5508 internal::Matcher<Expr>, InnerMatcher) {
5509 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5512 /// Matches atomic types.
5519 /// matches "_Atomic(int) i"
5520 extern const AstTypeMatcher<AtomicType> atomicType;
5522 /// Matches atomic types with a specific value type.
5527 /// _Atomic(float) f;
5529 /// atomicType(hasValueType(isInteger()))
5530 /// matches "_Atomic(int) i"
5532 /// Usable as: Matcher<AtomicType>
5533 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5534 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5536 /// Matches types nodes representing C++11 auto types.
5541 /// int v[] = { 2, 3 }
5542 /// for (auto i : v) { }
5545 /// matches "auto n" and "auto i"
5546 extern const AstTypeMatcher<AutoType> autoType;
5548 /// Matches types nodes representing C++11 decltype(<expr>) types.
5554 /// decltype(i + j) result = i + j;
5557 /// matches "decltype(i + j)"
5558 extern const AstTypeMatcher<DecltypeType> decltypeType;
5560 /// Matches \c AutoType nodes where the deduced type is a specific type.
5562 /// Note: There is no \c TypeLoc for the deduced type and thus no
5563 /// \c getDeducedLoc() matcher.
5570 /// autoType(hasDeducedType(isInteger()))
5571 /// matches "auto a"
5573 /// Usable as: Matcher<AutoType>
5574 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5575 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5577 /// Matches \c DecltypeType nodes to find out the underlying type.
5581 /// decltype(1) a = 1;
5582 /// decltype(2.0) b = 2.0;
5584 /// decltypeType(hasUnderlyingType(isInteger()))
5585 /// matches the type of "a"
5587 /// Usable as: Matcher<DecltypeType>
5588 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
5589 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
5591 /// Matches \c FunctionType nodes.
5599 /// matches "int (*f)(int)" and the type of "g".
5600 extern const AstTypeMatcher<FunctionType> functionType;
5602 /// Matches \c FunctionProtoType nodes.
5609 /// functionProtoType()
5610 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
5611 /// In C mode, "g" is not matched because it does not contain a prototype.
5612 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
5614 /// Matches \c ParenType nodes.
5618 /// int (*ptr_to_array)[4];
5619 /// int *array_of_ptrs[4];
5622 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
5623 /// \c array_of_ptrs.
5624 extern const AstTypeMatcher<ParenType> parenType;
5626 /// Matches \c ParenType nodes where the inner type is a specific type.
5630 /// int (*ptr_to_array)[4];
5631 /// int (*ptr_to_func)(int);
5634 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5635 /// \c ptr_to_func but not \c ptr_to_array.
5637 /// Usable as: Matcher<ParenType>
5638 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5639 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5641 /// Matches block pointer types, i.e. types syntactically represented as
5642 /// "void (^)(int)".
5644 /// The \c pointee is always required to be a \c FunctionType.
5645 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5647 /// Matches member pointer types.
5650 /// struct A { int i; }
5651 /// A::* ptr = A::i;
5653 /// memberPointerType()
5654 /// matches "A::* ptr"
5655 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5657 /// Matches pointer types, but does not match Objective-C object pointer
5671 /// matches "int *a", but does not match "Foo *f".
5672 extern const AstTypeMatcher<PointerType> pointerType;
5674 /// Matches an Objective-C object pointer type, which is different from
5675 /// a pointer type, despite being syntactically similar.
5686 /// matches "Foo *f", but does not match "int *a".
5687 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5689 /// Matches both lvalue and rvalue reference types.
5702 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5703 extern const AstTypeMatcher<ReferenceType> referenceType;
5705 /// Matches lvalue reference types.
5718 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5719 /// matched since the type is deduced as int& by reference collapsing rules.
5720 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5722 /// Matches rvalue reference types.
5735 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5736 /// matched as it is deduced to int& by reference collapsing rules.
5737 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5739 /// Narrows PointerType (and similar) matchers to those where the
5740 /// \c pointee matches a given matcher.
5748 /// pointerType(pointee(isConstQualified(), isInteger()))
5749 /// matches "int const *b"
5751 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5752 /// Matcher<PointerType>, Matcher<ReferenceType>
5753 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5754 pointee, getPointee,
5755 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5756 PointerType, ReferenceType));
5758 /// Matches typedef types.
5765 /// matches "typedef int X"
5766 extern const AstTypeMatcher<TypedefType> typedefType;
5768 /// Matches enum types.
5772 /// enum C { Green };
5773 /// enum class S { Red };
5779 /// \c enumType() matches the type of the variable declarations of both \c c and
5781 extern const AstTypeMatcher<EnumType> enumType;
5783 /// Matches template specialization types.
5787 /// template <typename T>
5790 /// template class C<int>; // A
5791 /// C<char> var; // B
5794 /// \c templateSpecializationType() matches the type of the explicit
5795 /// instantiation in \c A and the type of the variable declaration in \c B.
5796 extern const AstTypeMatcher<TemplateSpecializationType>
5797 templateSpecializationType;
5799 /// Matches types nodes representing unary type transformations.
5803 /// typedef __underlying_type(T) type;
5805 /// unaryTransformType()
5806 /// matches "__underlying_type(T)"
5807 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5809 /// Matches record types (e.g. structs, classes).
5820 /// \c recordType() matches the type of the variable declarations of both \c c
5822 extern const AstTypeMatcher<RecordType> recordType;
5824 /// Matches tag types (record and enum types).
5835 /// \c tagType() matches the type of the variable declarations of both \c e
5837 extern const AstTypeMatcher<TagType> tagType;
5839 /// Matches types specified with an elaborated type keyword or with a
5855 /// \c elaboratedType() matches the type of the variable declarations of both
5857 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5859 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5860 /// matches \c InnerMatcher if the qualifier exists.
5872 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5873 /// matches the type of the variable declaration of \c d.
5874 AST_MATCHER_P(ElaboratedType, hasQualifier,
5875 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5876 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5877 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5882 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5894 /// \c elaboratedType(namesType(recordType(
5895 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5896 /// declaration of \c d.
5897 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5899 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5902 /// Matches types that represent the result of substituting a type for a
5903 /// template type parameter.
5907 /// template <typename T>
5913 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5914 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5915 substTemplateTypeParmType;
5917 /// Matches template type parameter substitutions that have a replacement
5918 /// type that matches the provided matcher.
5922 /// template <typename T>
5925 /// double j = F(i);
5928 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5929 AST_TYPE_TRAVERSE_MATCHER(
5930 hasReplacementType, getReplacementType,
5931 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5933 /// Matches template type parameter types.
5935 /// Example matches T, but not int.
5936 /// (matcher = templateTypeParmType())
5938 /// template <typename T> void f(int i);
5940 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5942 /// Matches injected class name types.
5944 /// Example matches S s, but not S<T> s.
5945 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5947 /// template <typename T> struct S {
5952 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5954 /// Matches decayed type
5955 /// Example matches i[] in declaration of f.
5956 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5957 /// Example matches i[1].
5958 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5960 /// void f(int i[]) {
5964 extern const AstTypeMatcher<DecayedType> decayedType;
5966 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
5967 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5969 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5972 /// Matches declarations whose declaration context, interpreted as a
5973 /// Decl, matches \c InnerMatcher.
5984 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5985 /// declaration of \c class \c D.
5986 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5987 const DeclContext *DC = Node.getDeclContext();
5988 if (!DC) return false;
5989 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5992 /// Matches nested name specifiers.
5997 /// struct A { static void f(); };
5999 /// void g() { A::f(); }
6003 /// nestedNameSpecifier()
6004 /// matches "ns::" and both "A::"
6005 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
6006 nestedNameSpecifier;
6008 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
6009 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
6010 nestedNameSpecifierLoc;
6012 /// Matches \c NestedNameSpecifierLocs for which the given inner
6013 /// NestedNameSpecifier-matcher matches.
6014 AST_MATCHER_FUNCTION_P_OVERLOAD(
6015 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
6016 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
6017 return internal::BindableMatcher<NestedNameSpecifierLoc>(
6018 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
6022 /// Matches nested name specifiers that specify a type matching the
6023 /// given \c QualType matcher without qualifiers.
6027 /// struct A { struct B { struct C {}; }; };
6030 /// nestedNameSpecifier(specifiesType(
6031 /// hasDeclaration(cxxRecordDecl(hasName("A")))
6034 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
6035 internal::Matcher<QualType>, InnerMatcher) {
6036 if (!Node.getAsType())
6038 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
6041 /// Matches nested name specifier locs that specify a type matching the
6042 /// given \c TypeLoc.
6046 /// struct A { struct B { struct C {}; }; };
6049 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
6050 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
6052 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
6053 internal::Matcher<TypeLoc>, InnerMatcher) {
6054 return Node && Node.getNestedNameSpecifier()->getAsType() &&
6055 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
6058 /// Matches on the prefix of a \c NestedNameSpecifier.
6062 /// struct A { struct B { struct C {}; }; };
6065 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
6067 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
6068 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
6070 const NestedNameSpecifier *NextNode = Node.getPrefix();
6073 return InnerMatcher.matches(*NextNode, Finder, Builder);
6076 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
6080 /// struct A { struct B { struct C {}; }; };
6083 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
6085 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
6086 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
6088 NestedNameSpecifierLoc NextNode = Node.getPrefix();
6091 return InnerMatcher.matches(NextNode, Finder, Builder);
6094 /// Matches nested name specifiers that specify a namespace matching the
6095 /// given namespace matcher.
6099 /// namespace ns { struct A {}; }
6102 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
6104 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
6105 internal::Matcher<NamespaceDecl>, InnerMatcher) {
6106 if (!Node.getAsNamespace())
6108 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
6111 /// Overloads for the \c equalsNode matcher.
6112 /// FIXME: Implement for other node types.
6115 /// Matches if a node equals another node.
6117 /// \c Decl has pointer identity in the AST.
6118 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
6119 return &Node == Other;
6121 /// Matches if a node equals another node.
6123 /// \c Stmt has pointer identity in the AST.
6124 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
6125 return &Node == Other;
6127 /// Matches if a node equals another node.
6129 /// \c Type has pointer identity in the AST.
6130 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
6131 return &Node == Other;
6136 /// Matches each case or default statement belonging to the given switch
6137 /// statement. This matcher may produce multiple matches.
6141 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
6143 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
6144 /// matches four times, with "c" binding each of "case 1:", "case 2:",
6145 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
6146 /// "switch (1)", "switch (2)" and "switch (2)".
6147 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
6149 BoundNodesTreeBuilder Result;
6150 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
6151 // iteration order. We should use the more general iterating matchers once
6152 // they are capable of expressing this matcher (for example, it should ignore
6153 // case statements belonging to nested switch statements).
6154 bool Matched = false;
6155 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
6156 SC = SC->getNextSwitchCase()) {
6157 BoundNodesTreeBuilder CaseBuilder(*Builder);
6158 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
6161 Result.addMatch(CaseBuilder);
6164 *Builder = std::move(Result);
6168 /// Matches each constructor initializer in a constructor definition.
6172 /// class A { A() : i(42), j(42) {} int i; int j; };
6174 /// cxxConstructorDecl(forEachConstructorInitializer(
6175 /// forField(decl().bind("x"))
6177 /// will trigger two matches, binding for 'i' and 'j' respectively.
6178 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
6179 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
6180 BoundNodesTreeBuilder Result;
6181 bool Matched = false;
6182 for (const auto *I : Node.inits()) {
6183 BoundNodesTreeBuilder InitBuilder(*Builder);
6184 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
6186 Result.addMatch(InitBuilder);
6189 *Builder = std::move(Result);
6193 /// Matches constructor declarations that are copy constructors.
6199 /// S(const S &); // #2
6203 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
6204 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
6205 return Node.isCopyConstructor();
6208 /// Matches constructor declarations that are move constructors.
6214 /// S(const S &); // #2
6218 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
6219 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
6220 return Node.isMoveConstructor();
6223 /// Matches constructor declarations that are default constructors.
6229 /// S(const S &); // #2
6233 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
6234 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
6235 return Node.isDefaultConstructor();
6238 /// Matches constructors that delegate to another constructor.
6245 /// S(S &&) : S() {} // #3
6247 /// S::S() : S(0) {} // #4
6249 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
6251 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
6252 return Node.isDelegatingConstructor();
6255 /// Matches constructor, conversion function, and deduction guide declarations
6256 /// that have an explicit specifier if this explicit specifier is resolved to
6261 /// template<bool b>
6264 /// explicit S(double); // #2
6265 /// operator int(); // #3
6266 /// explicit operator bool(); // #4
6267 /// explicit(false) S(bool) // # 7
6268 /// explicit(true) S(char) // # 8
6269 /// explicit(b) S(S) // # 9
6271 /// S(int) -> S<true> // #5
6272 /// explicit S(double) -> S<false> // #6
6274 /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
6275 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
6276 /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
6277 AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
6278 CXXConstructorDecl, CXXConversionDecl,
6279 CXXDeductionGuideDecl)) {
6280 return Node.isExplicit();
6283 /// Matches the expression in an explicit specifier if present in the given
6288 /// template<bool b>
6291 /// explicit S(double); // #2
6292 /// operator int(); // #3
6293 /// explicit operator bool(); // #4
6294 /// explicit(false) S(bool) // # 7
6295 /// explicit(true) S(char) // # 8
6296 /// explicit(b) S(S) // # 9
6298 /// S(int) -> S<true> // #5
6299 /// explicit S(double) -> S<false> // #6
6301 /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
6302 /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
6303 /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
6304 AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
6306 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
6309 return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
6312 /// Matches function and namespace declarations that are marked with
6313 /// the inline keyword.
6317 /// inline void f();
6320 /// inline namespace m {}
6323 /// functionDecl(isInline()) will match ::f().
6324 /// namespaceDecl(isInline()) will match n::m.
6325 AST_POLYMORPHIC_MATCHER(isInline,
6326 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
6328 // This is required because the spelling of the function used to determine
6329 // whether inline is specified or not differs between the polymorphic types.
6330 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
6331 return FD->isInlineSpecified();
6332 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
6333 return NSD->isInline();
6334 llvm_unreachable("Not a valid polymorphic type");
6337 /// Matches anonymous namespace declarations.
6342 /// namespace {} // #1
6345 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
6346 AST_MATCHER(NamespaceDecl, isAnonymous) {
6347 return Node.isAnonymousNamespace();
6350 /// Matches declarations in the namespace `std`, but not in nested namespaces.
6354 /// class vector {};
6356 /// class vector {};
6358 /// class vector {};
6362 /// inline namespace __1 {
6363 /// class vector {}; // #1
6364 /// namespace experimental {
6365 /// class vector {};
6370 /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
6371 AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
6373 /// If the given case statement does not use the GNU case range
6374 /// extension, matches the constant given in the statement.
6378 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
6380 /// caseStmt(hasCaseConstant(integerLiteral()))
6381 /// matches "case 1:"
6382 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
6387 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
6390 /// Matches declaration that has a given attribute.
6394 /// __attribute__((device)) void f() { ... }
6396 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
6397 /// f. If the matcher is used from clang-query, attr::Kind parameter should be
6398 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
6399 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
6400 for (const auto *Attr : Node.attrs()) {
6401 if (Attr->getKind() == AttrKind)
6407 /// Matches the return value expression of a return statement
6413 /// hasReturnValue(binaryOperator())
6414 /// matches 'return a + b'
6415 /// with binaryOperator()
6416 /// matching 'a + b'
6417 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
6419 if (const auto *RetValue = Node.getRetValue())
6420 return InnerMatcher.matches(*RetValue, Finder, Builder);
6424 /// Matches CUDA kernel call expression.
6426 /// Example matches,
6428 /// kernel<<<i,j>>>();
6430 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
6433 /// Matches expressions that resolve to a null pointer constant, such as
6434 /// GNU's __null, C++11's nullptr, or C's NULL macro.
6438 /// void *v1 = NULL;
6439 /// void *v2 = nullptr;
6440 /// void *v3 = __null; // GNU extension
6441 /// char *cp = (char *)0;
6445 /// expr(nullPointerConstant())
6446 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
6447 /// initializer for i.
6448 AST_MATCHER(Expr, nullPointerConstant) {
6449 return Node.isNullPointerConstant(Finder->getASTContext(),
6450 Expr::NPC_ValueDependentIsNull);
6453 /// Matches declaration of the function the statement belongs to
6457 /// F& operator=(const F& o) {
6458 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
6462 /// returnStmt(forFunction(hasName("operator=")))
6463 /// matches 'return *this'
6464 /// but does not match 'return v > 0'
6465 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
6467 const auto &Parents = Finder->getASTContext().getParents(Node);
6469 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
6471 while(!Stack.empty()) {
6472 const auto &CurNode = Stack.back();
6474 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6475 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6478 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6479 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6484 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6485 Stack.push_back(Parent);
6491 /// Matches a declaration that has external formal linkage.
6493 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6502 /// Example matches f() because it has external formal linkage despite being
6503 /// unique to the translation unit as though it has internal likage
6504 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6511 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6512 return Node.hasExternalFormalLinkage();
6515 /// Matches a declaration that has default arguments.
6517 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6519 /// void x(int val) {}
6520 /// void y(int val = 0) {}
6522 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6523 return Node.hasDefaultArg();
6526 /// Matches array new expressions.
6530 /// MyClass *p1 = new MyClass[10];
6532 /// cxxNewExpr(isArray())
6533 /// matches the expression 'new MyClass[10]'.
6534 AST_MATCHER(CXXNewExpr, isArray) {
6535 return Node.isArray();
6538 /// Matches array new expressions with a given array size.
6542 /// MyClass *p1 = new MyClass[10];
6544 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
6545 /// matches the expression 'new MyClass[10]'.
6546 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
6547 return Node.isArray() && *Node.getArraySize() &&
6548 InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
6551 /// Matches a class declaration that is defined.
6553 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
6558 AST_MATCHER(CXXRecordDecl, hasDefinition) {
6559 return Node.hasDefinition();
6562 /// Matches C++11 scoped enum declaration.
6564 /// Example matches Y (matcher = enumDecl(isScoped()))
6567 /// enum class Y {};
6569 AST_MATCHER(EnumDecl, isScoped) {
6570 return Node.isScoped();
6573 /// Matches a function declared with a trailing return type.
6575 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
6578 /// auto Y() -> int {}
6580 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
6581 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
6582 return F->hasTrailingReturn();
6586 /// Matches expressions that match InnerMatcher that are possibly wrapped in an
6587 /// elidable constructor and other corresponding bookkeeping nodes.
6589 /// In C++17, elidable copy constructors are no longer being generated in the
6590 /// AST as it is not permitted by the standard. They are, however, part of the
6591 /// AST in C++14 and earlier. So, a matcher must abstract over these differences
6592 /// to work in all language modes. This matcher skips elidable constructor-call
6593 /// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
6594 /// various implicit nodes inside the constructor calls, all of which will not
6595 /// appear in the C++17 AST.
6607 /// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
6608 /// matches ``H D = G()`` in C++11 through C++17 (and beyond).
6609 AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
6610 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
6611 // E tracks the node that we are examining.
6612 const Expr *E = &Node;
6613 // If present, remove an outer `ExprWithCleanups` corresponding to the
6614 // underlying `CXXConstructExpr`. This check won't cover all cases of added
6615 // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
6616 // EWC is placed on the outermost node of the expression, which this may not
6617 // be), but, it still improves the coverage of this matcher.
6618 if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
6619 E = CleanupsExpr->getSubExpr();
6620 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
6621 if (CtorExpr->isElidable()) {
6622 if (const auto *MaterializeTemp =
6623 dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
6624 return InnerMatcher.matches(*MaterializeTemp->GetTemporaryExpr(),
6629 return InnerMatcher.matches(Node, Finder, Builder);
6632 //----------------------------------------------------------------------------//
6634 //----------------------------------------------------------------------------//
6636 /// Matches any ``#pragma omp`` executable directive.
6641 /// #pragma omp parallel
6642 /// #pragma omp parallel default(none)
6643 /// #pragma omp taskyield
6646 /// ``ompExecutableDirective()`` matches ``omp parallel``,
6647 /// ``omp parallel default(none)`` and ``omp taskyield``.
6648 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
6649 ompExecutableDirective;
6651 /// Matches standalone OpenMP directives,
6652 /// i.e., directives that can't have a structured block.
6657 /// #pragma omp parallel
6659 /// #pragma omp taskyield
6662 /// ``ompExecutableDirective(isStandaloneDirective()))`` matches
6663 /// ``omp taskyield``.
6664 AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
6665 return Node.isStandaloneDirective();
6668 /// Matches the Stmt AST node that is marked as being the structured-block
6669 /// of an OpenMP executable directive.
6674 /// #pragma omp parallel
6678 /// ``stmt(isOMPStructuredBlock()))`` matches ``{}``.
6679 AST_MATCHER(Stmt, isOMPStructuredBlock) { return Node.isOMPStructuredBlock(); }
6681 /// Matches the structured-block of the OpenMP executable directive
6683 /// Prerequisite: the executable directive must not be standalone directive.
6684 /// If it is, it will never match.
6689 /// #pragma omp parallel
6691 /// #pragma omp parallel
6695 /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
6696 AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
6697 internal::Matcher<Stmt>, InnerMatcher) {
6698 if (Node.isStandaloneDirective())
6699 return false; // Standalone directives have no structured blocks.
6700 return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
6703 /// Matches any clause in an OpenMP directive.
6708 /// #pragma omp parallel
6709 /// #pragma omp parallel default(none)
6712 /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
6713 /// ``omp parallel default(none)``.
6714 AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
6715 internal::Matcher<OMPClause>, InnerMatcher) {
6716 ArrayRef<OMPClause *> Clauses = Node.clauses();
6717 return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
6718 Clauses.end(), Finder, Builder);
6721 /// Matches OpenMP ``default`` clause.
6726 /// #pragma omp parallel default(none)
6727 /// #pragma omp parallel default(shared)
6728 /// #pragma omp parallel
6731 /// ``ompDefaultClause()`` matches ``default(none)`` and ``default(shared)``.
6732 extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
6735 /// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
6740 /// #pragma omp parallel
6741 /// #pragma omp parallel default(none)
6742 /// #pragma omp parallel default(shared)
6745 /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
6746 AST_MATCHER(OMPDefaultClause, isNoneKind) {
6747 return Node.getDefaultKind() == OMPC_DEFAULT_none;
6750 /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
6755 /// #pragma omp parallel
6756 /// #pragma omp parallel default(none)
6757 /// #pragma omp parallel default(shared)
6760 /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
6761 AST_MATCHER(OMPDefaultClause, isSharedKind) {
6762 return Node.getDefaultKind() == OMPC_DEFAULT_shared;
6765 /// Matches if the OpenMP directive is allowed to contain the specified OpenMP
6771 /// #pragma omp parallel
6772 /// #pragma omp parallel for
6776 /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
6777 /// ``omp parallel`` and ``omp parallel for``.
6779 /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
6780 /// should be passed as a quoted string. e.g.,
6781 /// ``isAllowedToContainClauseKind("OMPC_default").``
6782 AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
6783 OpenMPClauseKind, CKind) {
6784 return isAllowedClauseForDirective(Node.getDirectiveKind(), CKind);
6787 //----------------------------------------------------------------------------//
6788 // End OpenMP handling.
6789 //----------------------------------------------------------------------------//
6791 } // namespace ast_matchers
6792 } // namespace clang
6794 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H