clang 19.0.0git
ASTMatchers.h
Go to the documentation of this file.
1//===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements matchers to be used together with the MatchFinder to
10// match AST nodes.
11//
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.
14//
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'.
19//
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
23// access.
24//
25// For example, when we're interested in child classes of a certain class, we
26// would write:
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
31// matched.
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
34// class declaration.
35//
36// See ASTMatchersInternal.h for a more in-depth explanation of the
37// implementation details of the matcher framework.
38//
39// See ASTMatchFinder.h for how to use the generated matchers to run over
40// an AST.
41//
42//===----------------------------------------------------------------------===//
43
44#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
45#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
46
49#include "clang/AST/Attr.h"
51#include "clang/AST/Decl.h"
52#include "clang/AST/DeclCXX.h"
54#include "clang/AST/DeclObjC.h"
56#include "clang/AST/Expr.h"
57#include "clang/AST/ExprCXX.h"
58#include "clang/AST/ExprObjC.h"
64#include "clang/AST/Stmt.h"
65#include "clang/AST/StmtCXX.h"
66#include "clang/AST/StmtObjC.h"
70#include "clang/AST/Type.h"
71#include "clang/AST/TypeLoc.h"
78#include "clang/Basic/LLVM.h"
82#include "llvm/ADT/ArrayRef.h"
83#include "llvm/ADT/SmallVector.h"
84#include "llvm/ADT/StringExtras.h"
85#include "llvm/ADT/StringRef.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/Regex.h"
90#include <cassert>
91#include <cstddef>
92#include <iterator>
93#include <limits>
94#include <optional>
95#include <string>
96#include <utility>
97#include <vector>
98
99namespace clang {
100namespace ast_matchers {
101
102/// Maps string IDs to AST nodes matched by parts of a matcher.
103///
104/// The bound nodes are generated by calling \c bind("id") on the node matchers
105/// of the nodes we want to access later.
106///
107/// The instances of BoundNodes are created by \c MatchFinder when the user's
108/// callbacks are executed every time a match is found.
110public:
111 /// Returns the AST node bound to \c ID.
112 ///
113 /// Returns NULL if there was no node bound to \c ID or if there is a node but
114 /// it cannot be converted to the specified type.
115 template <typename T>
116 const T *getNodeAs(StringRef ID) const {
117 return MyBoundNodes.getNodeAs<T>(ID);
118 }
119
120 /// Type of mapping from binding identifiers to bound nodes. This type
121 /// is an associative container with a key type of \c std::string and a value
122 /// type of \c clang::DynTypedNode
123 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
124
125 /// Retrieve mapping from binding identifiers to bound nodes.
126 const IDToNodeMap &getMap() const {
127 return MyBoundNodes.getMap();
128 }
129
130private:
132
133 /// Create BoundNodes from a pre-filled map of bindings.
134 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
135 : MyBoundNodes(MyBoundNodes) {}
136
137 internal::BoundNodesMap MyBoundNodes;
138};
139
140/// Types of matchers for the top-level classes in the AST class
141/// hierarchy.
142/// @{
143using DeclarationMatcher = internal::Matcher<Decl>;
144using StatementMatcher = internal::Matcher<Stmt>;
145using TypeMatcher = internal::Matcher<QualType>;
146using TypeLocMatcher = internal::Matcher<TypeLoc>;
147using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
148using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
149using CXXBaseSpecifierMatcher = internal::Matcher<CXXBaseSpecifier>;
150using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
151using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
152using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
153using LambdaCaptureMatcher = internal::Matcher<LambdaCapture>;
154using AttrMatcher = internal::Matcher<Attr>;
155/// @}
156
157/// Matches any node.
158///
159/// Useful when another matcher requires a child matcher, but there's no
160/// additional constraint. This will often be used with an explicit conversion
161/// to an \c internal::Matcher<> type such as \c TypeMatcher.
162///
163/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
164/// \code
165/// "int* p" and "void f()" in
166/// int* p;
167/// void f();
168/// \endcode
169///
170/// Usable as: Any Matcher
171inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
172
173/// Matches the top declaration context.
174///
175/// Given
176/// \code
177/// int X;
178/// namespace NS {
179/// int Y;
180/// } // namespace NS
181/// \endcode
182/// decl(hasDeclContext(translationUnitDecl()))
183/// matches "int X", but not "int Y".
184extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
186
187/// Matches typedef declarations.
188///
189/// Given
190/// \code
191/// typedef int X;
192/// using Y = int;
193/// \endcode
194/// typedefDecl()
195/// matches "typedef int X", but not "using Y = int"
196extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
198
199/// Matches typedef name declarations.
200///
201/// Given
202/// \code
203/// typedef int X;
204/// using Y = int;
205/// \endcode
206/// typedefNameDecl()
207/// matches "typedef int X" and "using Y = int"
208extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
210
211/// Matches type alias declarations.
212///
213/// Given
214/// \code
215/// typedef int X;
216/// using Y = int;
217/// \endcode
218/// typeAliasDecl()
219/// matches "using Y = int", but not "typedef int X"
220extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
222
223/// Matches type alias template declarations.
224///
225/// typeAliasTemplateDecl() matches
226/// \code
227/// template <typename T>
228/// using Y = X<T>;
229/// \endcode
230extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
232
233/// Matches AST nodes that were expanded within the main-file.
234///
235/// Example matches X but not Y
236/// (matcher = cxxRecordDecl(isExpansionInMainFile())
237/// \code
238/// #include <Y.h>
239/// class X {};
240/// \endcode
241/// Y.h:
242/// \code
243/// class Y {};
244/// \endcode
245///
246/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
247AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
249 auto &SourceManager = Finder->getASTContext().getSourceManager();
251 SourceManager.getExpansionLoc(Node.getBeginLoc()));
252}
253
254/// Matches AST nodes that were expanded within system-header-files.
255///
256/// Example matches Y but not X
257/// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
258/// \code
259/// #include <SystemHeader.h>
260/// class X {};
261/// \endcode
262/// SystemHeader.h:
263/// \code
264/// class Y {};
265/// \endcode
266///
267/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
268AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
270 auto &SourceManager = Finder->getASTContext().getSourceManager();
271 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
272 if (ExpansionLoc.isInvalid()) {
273 return false;
274 }
275 return SourceManager.isInSystemHeader(ExpansionLoc);
276}
277
278/// Matches AST nodes that were expanded within files whose name is
279/// partially matching a given regex.
280///
281/// Example matches Y but not X
282/// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
283/// \code
284/// #include "ASTMatcher.h"
285/// class X {};
286/// \endcode
287/// ASTMatcher.h:
288/// \code
289/// class Y {};
290/// \endcode
291///
292/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
293AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
295 TypeLoc),
296 RegExp) {
297 auto &SourceManager = Finder->getASTContext().getSourceManager();
298 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
299 if (ExpansionLoc.isInvalid()) {
300 return false;
301 }
302 auto FileEntry =
304 if (!FileEntry) {
305 return false;
306 }
307
308 auto Filename = FileEntry->getName();
309 return RegExp->match(Filename);
310}
311
312/// Matches statements that are (transitively) expanded from the named macro.
313/// Does not match if only part of the statement is expanded from that macro or
314/// if different parts of the statement are expanded from different
315/// appearances of the macro.
316AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
318 std::string, MacroName) {
319 // Verifies that the statement' beginning and ending are both expanded from
320 // the same instance of the given macro.
321 auto& Context = Finder->getASTContext();
322 std::optional<SourceLocation> B =
323 internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
324 if (!B) return false;
325 std::optional<SourceLocation> E =
326 internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
327 if (!E) return false;
328 return *B == *E;
329}
330
331/// Matches declarations.
332///
333/// Examples matches \c X, \c C, and the friend declaration inside \c C;
334/// \code
335/// void X();
336/// class C {
337/// friend X;
338/// };
339/// \endcode
340extern const internal::VariadicAllOfMatcher<Decl> decl;
341
342/// Matches decomposition-declarations.
343///
344/// Examples matches the declaration node with \c foo and \c bar, but not
345/// \c number.
346/// (matcher = declStmt(has(decompositionDecl())))
347///
348/// \code
349/// int number = 42;
350/// auto [foo, bar] = std::make_pair{42, 42};
351/// \endcode
352extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl>
354
355/// Matches binding declarations
356/// Example matches \c foo and \c bar
357/// (matcher = bindingDecl()
358///
359/// \code
360/// auto [foo, bar] = std::make_pair{42, 42};
361/// \endcode
362extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl>
364
365/// Matches a declaration of a linkage specification.
366///
367/// Given
368/// \code
369/// extern "C" {}
370/// \endcode
371/// linkageSpecDecl()
372/// matches "extern "C" {}"
373extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
375
376/// Matches a declaration of anything that could have a name.
377///
378/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
379/// \code
380/// typedef int X;
381/// struct S {
382/// union {
383/// int i;
384/// } U;
385/// };
386/// \endcode
387extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
388
389/// Matches a declaration of label.
390///
391/// Given
392/// \code
393/// goto FOO;
394/// FOO: bar();
395/// \endcode
396/// labelDecl()
397/// matches 'FOO:'
398extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
399
400/// Matches a declaration of a namespace.
401///
402/// Given
403/// \code
404/// namespace {}
405/// namespace test {}
406/// \endcode
407/// namespaceDecl()
408/// matches "namespace {}" and "namespace test {}"
409extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
411
412/// Matches a declaration of a namespace alias.
413///
414/// Given
415/// \code
416/// namespace test {}
417/// namespace alias = ::test;
418/// \endcode
419/// namespaceAliasDecl()
420/// matches "namespace alias" but not "namespace test"
421extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
423
424/// Matches class, struct, and union declarations.
425///
426/// Example matches \c X, \c Z, \c U, and \c S
427/// \code
428/// class X;
429/// template<class T> class Z {};
430/// struct S {};
431/// union U {};
432/// \endcode
433extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
434
435/// Matches C++ class declarations.
436///
437/// Example matches \c X, \c Z
438/// \code
439/// class X;
440/// template<class T> class Z {};
441/// \endcode
442extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
444
445/// Matches C++ class template declarations.
446///
447/// Example matches \c Z
448/// \code
449/// template<class T> class Z {};
450/// \endcode
451extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
453
454/// Matches C++ class template specializations.
455///
456/// Given
457/// \code
458/// template<typename T> class A {};
459/// template<> class A<double> {};
460/// A<int> a;
461/// \endcode
462/// classTemplateSpecializationDecl()
463/// matches the specializations \c A<int> and \c A<double>
464extern const internal::VariadicDynCastAllOfMatcher<
467
468/// Matches C++ class template partial specializations.
469///
470/// Given
471/// \code
472/// template<class T1, class T2, int I>
473/// class A {};
474///
475/// template<class T, int I>
476/// class A<T, T*, I> {};
477///
478/// template<>
479/// class A<int, int, 1> {};
480/// \endcode
481/// classTemplatePartialSpecializationDecl()
482/// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
483extern const internal::VariadicDynCastAllOfMatcher<
486
487/// Matches declarator declarations (field, variable, function
488/// and non-type template parameter declarations).
489///
490/// Given
491/// \code
492/// class X { int y; };
493/// \endcode
494/// declaratorDecl()
495/// matches \c int y.
496extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
498
499/// Matches parameter variable declarations.
500///
501/// Given
502/// \code
503/// void f(int x);
504/// \endcode
505/// parmVarDecl()
506/// matches \c int x.
507extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
509
510/// Matches C++ access specifier declarations.
511///
512/// Given
513/// \code
514/// class C {
515/// public:
516/// int a;
517/// };
518/// \endcode
519/// accessSpecDecl()
520/// matches 'public:'
521extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
523
524/// Matches class bases.
525///
526/// Examples matches \c public virtual B.
527/// \code
528/// class B {};
529/// class C : public virtual B {};
530/// \endcode
531extern const internal::VariadicAllOfMatcher<CXXBaseSpecifier> cxxBaseSpecifier;
532
533/// Matches constructor initializers.
534///
535/// Examples matches \c i(42).
536/// \code
537/// class C {
538/// C() : i(42) {}
539/// int i;
540/// };
541/// \endcode
542extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
544
545/// Matches template arguments.
546///
547/// Given
548/// \code
549/// template <typename T> struct C {};
550/// C<int> c;
551/// \endcode
552/// templateArgument()
553/// matches 'int' in C<int>.
554extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
555
556/// Matches template arguments (with location info).
557///
558/// Given
559/// \code
560/// template <typename T> struct C {};
561/// C<int> c;
562/// \endcode
563/// templateArgumentLoc()
564/// matches 'int' in C<int>.
565extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
567
568/// Matches template name.
569///
570/// Given
571/// \code
572/// template <typename T> class X { };
573/// X<int> xi;
574/// \endcode
575/// templateName()
576/// matches 'X' in X<int>.
577extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
578
579/// Matches non-type template parameter declarations.
580///
581/// Given
582/// \code
583/// template <typename T, int N> struct C {};
584/// \endcode
585/// nonTypeTemplateParmDecl()
586/// matches 'N', but not 'T'.
587extern const internal::VariadicDynCastAllOfMatcher<Decl,
590
591/// Matches template type parameter declarations.
592///
593/// Given
594/// \code
595/// template <typename T, int N> struct C {};
596/// \endcode
597/// templateTypeParmDecl()
598/// matches 'T', but not 'N'.
599extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
601
602/// Matches template template parameter declarations.
603///
604/// Given
605/// \code
606/// template <template <typename> class Z, int N> struct C {};
607/// \endcode
608/// templateTypeParmDecl()
609/// matches 'Z', but not 'N'.
610extern const internal::VariadicDynCastAllOfMatcher<Decl,
613
614/// Matches public C++ declarations and C++ base specifers that specify public
615/// inheritance.
616///
617/// Examples:
618/// \code
619/// class C {
620/// public: int a; // fieldDecl(isPublic()) matches 'a'
621/// protected: int b;
622/// private: int c;
623/// };
624/// \endcode
625///
626/// \code
627/// class Base {};
628/// class Derived1 : public Base {}; // matches 'Base'
629/// struct Derived2 : Base {}; // matches 'Base'
630/// \endcode
634 return getAccessSpecifier(Node) == AS_public;
635}
636
637/// Matches protected C++ declarations and C++ base specifers that specify
638/// protected inheritance.
639///
640/// Examples:
641/// \code
642/// class C {
643/// public: int a;
644/// protected: int b; // fieldDecl(isProtected()) matches 'b'
645/// private: int c;
646/// };
647/// \endcode
648///
649/// \code
650/// class Base {};
651/// class Derived : protected Base {}; // matches 'Base'
652/// \endcode
656 return getAccessSpecifier(Node) == AS_protected;
657}
658
659/// Matches private C++ declarations and C++ base specifers that specify private
660/// inheritance.
661///
662/// Examples:
663/// \code
664/// class C {
665/// public: int a;
666/// protected: int b;
667/// private: int c; // fieldDecl(isPrivate()) matches 'c'
668/// };
669/// \endcode
670///
671/// \code
672/// struct Base {};
673/// struct Derived1 : private Base {}; // matches 'Base'
674/// class Derived2 : Base {}; // matches 'Base'
675/// \endcode
679 return getAccessSpecifier(Node) == AS_private;
680}
681
682/// Matches non-static data members that are bit-fields.
683///
684/// Given
685/// \code
686/// class C {
687/// int a : 2;
688/// int b;
689/// };
690/// \endcode
691/// fieldDecl(isBitField())
692/// matches 'int a;' but not 'int b;'.
693AST_MATCHER(FieldDecl, isBitField) {
694 return Node.isBitField();
695}
696
697/// Matches non-static data members that are bit-fields of the specified
698/// bit width.
699///
700/// Given
701/// \code
702/// class C {
703/// int a : 2;
704/// int b : 4;
705/// int c : 2;
706/// };
707/// \endcode
708/// fieldDecl(hasBitWidth(2))
709/// matches 'int a;' and 'int c;' but not 'int b;'.
710AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
711 return Node.isBitField() &&
712 Node.getBitWidthValue(Finder->getASTContext()) == Width;
713}
714
715/// Matches non-static data members that have an in-class initializer.
716///
717/// Given
718/// \code
719/// class C {
720/// int a = 2;
721/// int b = 3;
722/// int c;
723/// };
724/// \endcode
725/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
726/// matches 'int a;' but not 'int b;'.
727/// fieldDecl(hasInClassInitializer(anything()))
728/// matches 'int a;' and 'int b;' but not 'int c;'.
729AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
730 InnerMatcher) {
731 const Expr *Initializer = Node.getInClassInitializer();
732 return (Initializer != nullptr &&
733 InnerMatcher.matches(*Initializer, Finder, Builder));
734}
735
736/// Determines whether the function is "main", which is the entry point
737/// into an executable program.
739 return Node.isMain();
740}
741
742/// Matches the specialized template of a specialization declaration.
743///
744/// Given
745/// \code
746/// template<typename T> class A {}; #1
747/// template<> class A<int> {}; #2
748/// \endcode
749/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
750/// matches '#2' with classTemplateDecl() matching the class template
751/// declaration of 'A' at #1.
753 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
754 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
755 return (Decl != nullptr &&
756 InnerMatcher.matches(*Decl, Finder, Builder));
757}
758
759/// Matches an entity that has been implicitly added by the compiler (e.g.
760/// implicit default/copy constructors).
763 LambdaCapture)) {
764 return Node.isImplicit();
765}
766
767/// Matches classTemplateSpecializations, templateSpecializationType and
768/// functionDecl that have at least one TemplateArgument matching the given
769/// InnerMatcher.
770///
771/// Given
772/// \code
773/// template<typename T> class A {};
774/// template<> class A<double> {};
775/// A<int> a;
776///
777/// template<typename T> f() {};
778/// void func() { f<int>(); };
779/// \endcode
780///
781/// \endcode
782/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
783/// refersToType(asString("int"))))
784/// matches the specialization \c A<int>
785///
786/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
787/// matches the specialization \c f<int>
789 hasAnyTemplateArgument,
793 internal::Matcher<TemplateArgument>, InnerMatcher) {
795 internal::getTemplateSpecializationArgs(Node);
796 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
797 Builder) != List.end();
798}
799
800/// Causes all nested matchers to be matched with the specified traversal kind.
801///
802/// Given
803/// \code
804/// void foo()
805/// {
806/// int i = 3.0;
807/// }
808/// \endcode
809/// The matcher
810/// \code
811/// traverse(TK_IgnoreUnlessSpelledInSource,
812/// varDecl(hasInitializer(floatLiteral().bind("init")))
813/// )
814/// \endcode
815/// matches the variable declaration with "init" bound to the "3.0".
816template <typename T>
817internal::Matcher<T> traverse(TraversalKind TK,
818 const internal::Matcher<T> &InnerMatcher) {
819 return internal::DynTypedMatcher::constructRestrictedWrapper(
820 new internal::TraversalMatcher<T>(TK, InnerMatcher),
821 InnerMatcher.getID().first)
822 .template unconditionalConvertTo<T>();
823}
824
825template <typename T>
826internal::BindableMatcher<T>
827traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
828 return internal::BindableMatcher<T>(
829 internal::DynTypedMatcher::constructRestrictedWrapper(
830 new internal::TraversalMatcher<T>(TK, InnerMatcher),
831 InnerMatcher.getID().first)
832 .template unconditionalConvertTo<T>());
833}
834
835template <typename... T>
836internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
838 const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
839 return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
840 TK, InnerMatcher);
841}
842
843template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
844 typename T, typename ToTypes>
845internal::TraversalWrapper<
846 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
847traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
848 ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
849 return internal::TraversalWrapper<
850 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
851 ToTypes>>(TK, InnerMatcher);
852}
853
854template <template <typename T, typename... P> class MatcherT, typename... P,
855 typename ReturnTypesF>
856internal::TraversalWrapper<
857 internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>
858traverse(TraversalKind TK,
859 const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>
860 &InnerMatcher) {
861 return internal::TraversalWrapper<
862 internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK,
863 InnerMatcher);
864}
865
866template <typename... T>
867internal::Matcher<typename internal::GetClade<T...>::Type>
868traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
869 return traverse(TK, InnerMatcher.with());
870}
871
872/// Matches expressions that match InnerMatcher after any implicit AST
873/// nodes are stripped off.
874///
875/// Parentheses and explicit casts are not discarded.
876/// Given
877/// \code
878/// class C {};
879/// C a = C();
880/// C b;
881/// C c = b;
882/// \endcode
883/// The matchers
884/// \code
885/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
886/// \endcode
887/// would match the declarations for a, b, and c.
888/// While
889/// \code
890/// varDecl(hasInitializer(cxxConstructExpr()))
891/// \endcode
892/// only match the declarations for b and c.
893AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
894 InnerMatcher) {
895 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
896}
897
898/// Matches expressions that match InnerMatcher after any implicit casts
899/// are stripped off.
900///
901/// Parentheses and explicit casts are not discarded.
902/// Given
903/// \code
904/// int arr[5];
905/// int a = 0;
906/// char b = 0;
907/// const int c = a;
908/// int *d = arr;
909/// long e = (long) 0l;
910/// \endcode
911/// The matchers
912/// \code
913/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
914/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
915/// \endcode
916/// would match the declarations for a, b, c, and d, but not e.
917/// While
918/// \code
919/// varDecl(hasInitializer(integerLiteral()))
920/// varDecl(hasInitializer(declRefExpr()))
921/// \endcode
922/// only match the declarations for a.
923AST_MATCHER_P(Expr, ignoringImpCasts,
924 internal::Matcher<Expr>, InnerMatcher) {
925 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
926}
927
928/// Matches expressions that match InnerMatcher after parentheses and
929/// casts are stripped off.
930///
931/// Implicit and non-C Style casts are also discarded.
932/// Given
933/// \code
934/// int a = 0;
935/// char b = (0);
936/// void* c = reinterpret_cast<char*>(0);
937/// char d = char(0);
938/// \endcode
939/// The matcher
940/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
941/// would match the declarations for a, b, c, and d.
942/// while
943/// varDecl(hasInitializer(integerLiteral()))
944/// only match the declaration for a.
945AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
946 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
947}
948
949/// Matches expressions that match InnerMatcher after implicit casts and
950/// parentheses are stripped off.
951///
952/// Explicit casts are not discarded.
953/// Given
954/// \code
955/// int arr[5];
956/// int a = 0;
957/// char b = (0);
958/// const int c = a;
959/// int *d = (arr);
960/// long e = ((long) 0l);
961/// \endcode
962/// The matchers
963/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
964/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
965/// would match the declarations for a, b, c, and d, but not e.
966/// while
967/// varDecl(hasInitializer(integerLiteral()))
968/// varDecl(hasInitializer(declRefExpr()))
969/// would only match the declaration for a.
970AST_MATCHER_P(Expr, ignoringParenImpCasts,
971 internal::Matcher<Expr>, InnerMatcher) {
972 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
973}
974
975/// Matches types that match InnerMatcher after any parens are stripped.
976///
977/// Given
978/// \code
979/// void (*fp)(void);
980/// \endcode
981/// The matcher
982/// \code
983/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
984/// \endcode
985/// would match the declaration for fp.
986AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
987 InnerMatcher, 0) {
988 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
989}
990
991/// Overload \c ignoringParens for \c Expr.
992///
993/// Given
994/// \code
995/// const char* str = ("my-string");
996/// \endcode
997/// The matcher
998/// \code
999/// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
1000/// \endcode
1001/// would match the implicit cast resulting from the assignment.
1002AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
1003 InnerMatcher, 1) {
1004 const Expr *E = Node.IgnoreParens();
1005 return InnerMatcher.matches(*E, Finder, Builder);
1006}
1007
1008/// Matches expressions that are instantiation-dependent even if it is
1009/// neither type- nor value-dependent.
1010///
1011/// In the following example, the expression sizeof(sizeof(T() + T()))
1012/// is instantiation-dependent (since it involves a template parameter T),
1013/// but is neither type- nor value-dependent, since the type of the inner
1014/// sizeof is known (std::size_t) and therefore the size of the outer
1015/// sizeof is known.
1016/// \code
1017/// template<typename T>
1018/// void f(T x, T y) { sizeof(sizeof(T() + T()); }
1019/// \endcode
1020/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
1021AST_MATCHER(Expr, isInstantiationDependent) {
1022 return Node.isInstantiationDependent();
1023}
1024
1025/// Matches expressions that are type-dependent because the template type
1026/// is not yet instantiated.
1027///
1028/// For example, the expressions "x" and "x + y" are type-dependent in
1029/// the following code, but "y" is not type-dependent:
1030/// \code
1031/// template<typename T>
1032/// void add(T x, int y) {
1033/// x + y;
1034/// }
1035/// \endcode
1036/// expr(isTypeDependent()) matches x + y
1037AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
1038
1039/// Matches expression that are value-dependent because they contain a
1040/// non-type template parameter.
1041///
1042/// For example, the array bound of "Chars" in the following example is
1043/// value-dependent.
1044/// \code
1045/// template<int Size> int f() { return Size; }
1046/// \endcode
1047/// expr(isValueDependent()) matches return Size
1048AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
1049
1050/// Matches classTemplateSpecializations, templateSpecializationType and
1051/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
1052///
1053/// Given
1054/// \code
1055/// template<typename T, typename U> class A {};
1056/// A<bool, int> b;
1057/// A<int, bool> c;
1058///
1059/// template<typename T> void f() {}
1060/// void func() { f<int>(); };
1061/// \endcode
1062/// classTemplateSpecializationDecl(hasTemplateArgument(
1063/// 1, refersToType(asString("int"))))
1064/// matches the specialization \c A<bool, int>
1065///
1066/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1067/// matches the specialization \c f<int>
1069 hasTemplateArgument,
1072 FunctionDecl),
1073 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1075 internal::getTemplateSpecializationArgs(Node);
1076 if (List.size() <= N)
1077 return false;
1078 return InnerMatcher.matches(List[N], Finder, Builder);
1079}
1080
1081/// Matches if the number of template arguments equals \p N.
1082///
1083/// Given
1084/// \code
1085/// template<typename T> struct C {};
1086/// C<int> c;
1087/// \endcode
1088/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1089/// matches C<int>.
1091 templateArgumentCountIs,
1094 unsigned, N) {
1095 return internal::getTemplateSpecializationArgs(Node).size() == N;
1096}
1097
1098/// Matches a TemplateArgument that refers to a certain type.
1099///
1100/// Given
1101/// \code
1102/// struct X {};
1103/// template<typename T> struct A {};
1104/// A<X> a;
1105/// \endcode
1106/// classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
1107/// recordType(hasDeclaration(recordDecl(hasName("X")))))))
1108/// matches the specialization of \c struct A generated by \c A<X>.
1110 internal::Matcher<QualType>, InnerMatcher) {
1111 if (Node.getKind() != TemplateArgument::Type)
1112 return false;
1113 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1114}
1115
1116/// Matches a TemplateArgument that refers to a certain template.
1117///
1118/// Given
1119/// \code
1120/// template<template <typename> class S> class X {};
1121/// template<typename T> class Y {};
1122/// X<Y> xi;
1123/// \endcode
1124/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1125/// refersToTemplate(templateName())))
1126/// matches the specialization \c X<Y>
1128 internal::Matcher<TemplateName>, InnerMatcher) {
1129 if (Node.getKind() != TemplateArgument::Template)
1130 return false;
1131 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1132}
1133
1134/// Matches a canonical TemplateArgument that refers to a certain
1135/// declaration.
1136///
1137/// Given
1138/// \code
1139/// struct B { int next; };
1140/// template<int(B::*next_ptr)> struct A {};
1141/// A<&B::next> a;
1142/// \endcode
1143/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1144/// refersToDeclaration(fieldDecl(hasName("next")))))
1145/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1146/// \c B::next
1147AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1148 internal::Matcher<Decl>, InnerMatcher) {
1149 if (Node.getKind() == TemplateArgument::Declaration)
1150 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1151 return false;
1152}
1153
1154/// Matches a sugar TemplateArgument that refers to a certain expression.
1155///
1156/// Given
1157/// \code
1158/// struct B { int next; };
1159/// template<int(B::*next_ptr)> struct A {};
1160/// A<&B::next> a;
1161/// \endcode
1162/// templateSpecializationType(hasAnyTemplateArgument(
1163/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1164/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1165/// \c B::next
1166AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1167 if (Node.getKind() == TemplateArgument::Expression)
1168 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1169 return false;
1170}
1171
1172/// Matches a TemplateArgument that is an integral value.
1173///
1174/// Given
1175/// \code
1176/// template<int T> struct C {};
1177/// C<42> c;
1178/// \endcode
1179/// classTemplateSpecializationDecl(
1180/// hasAnyTemplateArgument(isIntegral()))
1181/// matches the implicit instantiation of C in C<42>
1182/// with isIntegral() matching 42.
1184 return Node.getKind() == TemplateArgument::Integral;
1185}
1186
1187/// Matches a TemplateArgument that refers to an integral type.
1188///
1189/// Given
1190/// \code
1191/// template<int T> struct C {};
1192/// C<42> c;
1193/// \endcode
1194/// classTemplateSpecializationDecl(
1195/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1196/// matches the implicit instantiation of C in C<42>.
1197AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1198 internal::Matcher<QualType>, InnerMatcher) {
1199 if (Node.getKind() != TemplateArgument::Integral)
1200 return false;
1201 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1202}
1203
1204/// Matches a TemplateArgument of integral type with a given value.
1205///
1206/// Note that 'Value' is a string as the template argument's value is
1207/// an arbitrary precision integer. 'Value' must be euqal to the canonical
1208/// representation of that integral value in base 10.
1209///
1210/// Given
1211/// \code
1212/// template<int T> struct C {};
1213/// C<42> c;
1214/// \endcode
1215/// classTemplateSpecializationDecl(
1216/// hasAnyTemplateArgument(equalsIntegralValue("42")))
1217/// matches the implicit instantiation of C in C<42>.
1218AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1219 std::string, Value) {
1220 if (Node.getKind() != TemplateArgument::Integral)
1221 return false;
1222 return toString(Node.getAsIntegral(), 10) == Value;
1223}
1224
1225/// Matches an Objective-C autorelease pool statement.
1226///
1227/// Given
1228/// \code
1229/// @autoreleasepool {
1230/// int x = 0;
1231/// }
1232/// \endcode
1233/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1234/// inside the autorelease pool.
1235extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1237
1238/// Matches any value declaration.
1239///
1240/// Example matches A, B, C and F
1241/// \code
1242/// enum X { A, B, C };
1243/// void F();
1244/// \endcode
1245extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1246
1247/// Matches C++ constructor declarations.
1248///
1249/// Example matches Foo::Foo() and Foo::Foo(int)
1250/// \code
1251/// class Foo {
1252/// public:
1253/// Foo();
1254/// Foo(int);
1255/// int DoSomething();
1256/// };
1257/// \endcode
1258extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1260
1261/// Matches explicit C++ destructor declarations.
1262///
1263/// Example matches Foo::~Foo()
1264/// \code
1265/// class Foo {
1266/// public:
1267/// virtual ~Foo();
1268/// };
1269/// \endcode
1270extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1272
1273/// Matches enum declarations.
1274///
1275/// Example matches X
1276/// \code
1277/// enum X {
1278/// A, B, C
1279/// };
1280/// \endcode
1281extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1282
1283/// Matches enum constants.
1284///
1285/// Example matches A, B, C
1286/// \code
1287/// enum X {
1288/// A, B, C
1289/// };
1290/// \endcode
1291extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1293
1294/// Matches tag declarations.
1295///
1296/// Example matches X, Z, U, S, E
1297/// \code
1298/// class X;
1299/// template<class T> class Z {};
1300/// struct S {};
1301/// union U {};
1302/// enum E {
1303/// A, B, C
1304/// };
1305/// \endcode
1306extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1307
1308/// Matches method declarations.
1309///
1310/// Example matches y
1311/// \code
1312/// class X { void y(); };
1313/// \endcode
1314extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1316
1317/// Matches conversion operator declarations.
1318///
1319/// Example matches the operator.
1320/// \code
1321/// class X { operator int() const; };
1322/// \endcode
1323extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1325
1326/// Matches user-defined and implicitly generated deduction guide.
1327///
1328/// Example matches the deduction guide.
1329/// \code
1330/// template<typename T>
1331/// class X { X(int) };
1332/// X(int) -> X<int>;
1333/// \endcode
1334extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1336
1337/// Matches concept declarations.
1338///
1339/// Example matches integral
1340/// \code
1341/// template<typename T>
1342/// concept integral = std::is_integral_v<T>;
1343/// \endcode
1344extern const internal::VariadicDynCastAllOfMatcher<Decl, ConceptDecl>
1346
1347/// Matches variable declarations.
1348///
1349/// Note: this does not match declarations of member variables, which are
1350/// "field" declarations in Clang parlance.
1351///
1352/// Example matches a
1353/// \code
1354/// int a;
1355/// \endcode
1356extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1357
1358/// Matches field declarations.
1359///
1360/// Given
1361/// \code
1362/// class X { int m; };
1363/// \endcode
1364/// fieldDecl()
1365/// matches 'm'.
1366extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1367
1368/// Matches indirect field declarations.
1369///
1370/// Given
1371/// \code
1372/// struct X { struct { int a; }; };
1373/// \endcode
1374/// indirectFieldDecl()
1375/// matches 'a'.
1376extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1378
1379/// Matches function declarations.
1380///
1381/// Example matches f
1382/// \code
1383/// void f();
1384/// \endcode
1385extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1387
1388/// Matches C++ function template declarations.
1389///
1390/// Example matches f
1391/// \code
1392/// template<class T> void f(T t) {}
1393/// \endcode
1394extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1396
1397/// Matches friend declarations.
1398///
1399/// Given
1400/// \code
1401/// class X { friend void foo(); };
1402/// \endcode
1403/// friendDecl()
1404/// matches 'friend void foo()'.
1405extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1406
1407/// Matches statements.
1408///
1409/// Given
1410/// \code
1411/// { ++a; }
1412/// \endcode
1413/// stmt()
1414/// matches both the compound statement '{ ++a; }' and '++a'.
1415extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1416
1417/// Matches declaration statements.
1418///
1419/// Given
1420/// \code
1421/// int a;
1422/// \endcode
1423/// declStmt()
1424/// matches 'int a'.
1425extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1426
1427/// Matches member expressions.
1428///
1429/// Given
1430/// \code
1431/// class Y {
1432/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1433/// int a; static int b;
1434/// };
1435/// \endcode
1436/// memberExpr()
1437/// matches this->x, x, y.x, a, this->b
1438extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1439
1440/// Matches unresolved member expressions.
1441///
1442/// Given
1443/// \code
1444/// struct X {
1445/// template <class T> void f();
1446/// void g();
1447/// };
1448/// template <class T> void h() { X x; x.f<T>(); x.g(); }
1449/// \endcode
1450/// unresolvedMemberExpr()
1451/// matches x.f<T>
1452extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1454
1455/// Matches member expressions where the actual member referenced could not be
1456/// resolved because the base expression or the member name was dependent.
1457///
1458/// Given
1459/// \code
1460/// template <class T> void f() { T t; t.g(); }
1461/// \endcode
1462/// cxxDependentScopeMemberExpr()
1463/// matches t.g
1464extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1467
1468/// Matches call expressions.
1469///
1470/// Example matches x.y() and y()
1471/// \code
1472/// X x;
1473/// x.y();
1474/// y();
1475/// \endcode
1476extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1477
1478/// Matches call expressions which were resolved using ADL.
1479///
1480/// Example matches y(x) but not y(42) or NS::y(x).
1481/// \code
1482/// namespace NS {
1483/// struct X {};
1484/// void y(X);
1485/// }
1486///
1487/// void y(...);
1488///
1489/// void test() {
1490/// NS::X x;
1491/// y(x); // Matches
1492/// NS::y(x); // Doesn't match
1493/// y(42); // Doesn't match
1494/// using NS::y;
1495/// y(x); // Found by both unqualified lookup and ADL, doesn't match
1496// }
1497/// \endcode
1498AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1499
1500/// Matches lambda expressions.
1501///
1502/// Example matches [&](){return 5;}
1503/// \code
1504/// [&](){return 5;}
1505/// \endcode
1506extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1507
1508/// Matches member call expressions.
1509///
1510/// Example matches x.y()
1511/// \code
1512/// X x;
1513/// x.y();
1514/// \endcode
1515extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1517
1518/// Matches ObjectiveC Message invocation expressions.
1519///
1520/// The innermost message send invokes the "alloc" class method on the
1521/// NSString class, while the outermost message send invokes the
1522/// "initWithString" instance method on the object returned from
1523/// NSString's "alloc". This matcher should match both message sends.
1524/// \code
1525/// [[NSString alloc] initWithString:@"Hello"]
1526/// \endcode
1527extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1529
1530/// Matches ObjectiveC String literal expressions.
1531///
1532/// Example matches @"abcd"
1533/// \code
1534/// NSString *s = @"abcd";
1535/// \endcode
1536extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
1538
1539/// Matches Objective-C interface declarations.
1540///
1541/// Example matches Foo
1542/// \code
1543/// @interface Foo
1544/// @end
1545/// \endcode
1546extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1548
1549/// Matches Objective-C implementation declarations.
1550///
1551/// Example matches Foo
1552/// \code
1553/// @implementation Foo
1554/// @end
1555/// \endcode
1556extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1558
1559/// Matches Objective-C protocol declarations.
1560///
1561/// Example matches FooDelegate
1562/// \code
1563/// @protocol FooDelegate
1564/// @end
1565/// \endcode
1566extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1568
1569/// Matches Objective-C category declarations.
1570///
1571/// Example matches Foo (Additions)
1572/// \code
1573/// @interface Foo (Additions)
1574/// @end
1575/// \endcode
1576extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1578
1579/// Matches Objective-C category definitions.
1580///
1581/// Example matches Foo (Additions)
1582/// \code
1583/// @implementation Foo (Additions)
1584/// @end
1585/// \endcode
1586extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1588
1589/// Matches Objective-C method declarations.
1590///
1591/// Example matches both declaration and definition of -[Foo method]
1592/// \code
1593/// @interface Foo
1594/// - (void)method;
1595/// @end
1596///
1597/// @implementation Foo
1598/// - (void)method {}
1599/// @end
1600/// \endcode
1601extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1603
1604/// Matches block declarations.
1605///
1606/// Example matches the declaration of the nameless block printing an input
1607/// integer.
1608///
1609/// \code
1610/// myFunc(^(int p) {
1611/// printf("%d", p);
1612/// })
1613/// \endcode
1614extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1615 blockDecl;
1616
1617/// Matches Objective-C instance variable declarations.
1618///
1619/// Example matches _enabled
1620/// \code
1621/// @implementation Foo {
1622/// BOOL _enabled;
1623/// }
1624/// @end
1625/// \endcode
1626extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1628
1629/// Matches Objective-C property declarations.
1630///
1631/// Example matches enabled
1632/// \code
1633/// @interface Foo
1634/// @property BOOL enabled;
1635/// @end
1636/// \endcode
1637extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1639
1640/// Matches Objective-C \@throw statements.
1641///
1642/// Example matches \@throw
1643/// \code
1644/// @throw obj;
1645/// \endcode
1646extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1648
1649/// Matches Objective-C @try statements.
1650///
1651/// Example matches @try
1652/// \code
1653/// @try {}
1654/// @catch (...) {}
1655/// \endcode
1656extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1658
1659/// Matches Objective-C @catch statements.
1660///
1661/// Example matches @catch
1662/// \code
1663/// @try {}
1664/// @catch (...) {}
1665/// \endcode
1666extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1668
1669/// Matches Objective-C @finally statements.
1670///
1671/// Example matches @finally
1672/// \code
1673/// @try {}
1674/// @finally {}
1675/// \endcode
1676extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1678
1679/// Matches expressions that introduce cleanups to be run at the end
1680/// of the sub-expression's evaluation.
1681///
1682/// Example matches std::string()
1683/// \code
1684/// const std::string str = std::string();
1685/// \endcode
1686extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1688
1689/// Matches init list expressions.
1690///
1691/// Given
1692/// \code
1693/// int a[] = { 1, 2 };
1694/// struct B { int x, y; };
1695/// B b = { 5, 6 };
1696/// \endcode
1697/// initListExpr()
1698/// matches "{ 1, 2 }" and "{ 5, 6 }"
1699extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1701
1702/// Matches the syntactic form of init list expressions
1703/// (if expression have it).
1704AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1705 internal::Matcher<Expr>, InnerMatcher) {
1706 const Expr *SyntForm = Node.getSyntacticForm();
1707 return (SyntForm != nullptr &&
1708 InnerMatcher.matches(*SyntForm, Finder, Builder));
1709}
1710
1711/// Matches C++ initializer list expressions.
1712///
1713/// Given
1714/// \code
1715/// std::vector<int> a({ 1, 2, 3 });
1716/// std::vector<int> b = { 4, 5 };
1717/// int c[] = { 6, 7 };
1718/// std::pair<int, int> d = { 8, 9 };
1719/// \endcode
1720/// cxxStdInitializerListExpr()
1721/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1722extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1725
1726/// Matches implicit initializers of init list expressions.
1727///
1728/// Given
1729/// \code
1730/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1731/// \endcode
1732/// implicitValueInitExpr()
1733/// matches "[0].y" (implicitly)
1734extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1736
1737/// Matches paren list expressions.
1738/// ParenListExprs don't have a predefined type and are used for late parsing.
1739/// In the final AST, they can be met in template declarations.
1740///
1741/// Given
1742/// \code
1743/// template<typename T> class X {
1744/// void f() {
1745/// X x(*this);
1746/// int a = 0, b = 1; int i = (a, b);
1747/// }
1748/// };
1749/// \endcode
1750/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1751/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1752extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1754
1755/// Matches substitutions of non-type template parameters.
1756///
1757/// Given
1758/// \code
1759/// template <int N>
1760/// struct A { static const int n = N; };
1761/// struct B : public A<42> {};
1762/// \endcode
1763/// substNonTypeTemplateParmExpr()
1764/// matches "N" in the right-hand side of "static const int n = N;"
1765extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1768
1769/// Matches using declarations.
1770///
1771/// Given
1772/// \code
1773/// namespace X { int x; }
1774/// using X::x;
1775/// \endcode
1776/// usingDecl()
1777/// matches \code using X::x \endcode
1778extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1779
1780/// Matches using-enum declarations.
1781///
1782/// Given
1783/// \code
1784/// namespace X { enum x {...}; }
1785/// using enum X::x;
1786/// \endcode
1787/// usingEnumDecl()
1788/// matches \code using enum X::x \endcode
1789extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1791
1792/// Matches using namespace declarations.
1793///
1794/// Given
1795/// \code
1796/// namespace X { int x; }
1797/// using namespace X;
1798/// \endcode
1799/// usingDirectiveDecl()
1800/// matches \code using namespace X \endcode
1801extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1803
1804/// Matches reference to a name that can be looked up during parsing
1805/// but could not be resolved to a specific declaration.
1806///
1807/// Given
1808/// \code
1809/// template<typename T>
1810/// T foo() { T a; return a; }
1811/// template<typename T>
1812/// void bar() {
1813/// foo<T>();
1814/// }
1815/// \endcode
1816/// unresolvedLookupExpr()
1817/// matches \code foo<T>() \endcode
1818extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1820
1821/// Matches unresolved using value declarations.
1822///
1823/// Given
1824/// \code
1825/// template<typename X>
1826/// class C : private X {
1827/// using X::x;
1828/// };
1829/// \endcode
1830/// unresolvedUsingValueDecl()
1831/// matches \code using X::x \endcode
1832extern const internal::VariadicDynCastAllOfMatcher<Decl,
1835
1836/// Matches unresolved using value declarations that involve the
1837/// typename.
1838///
1839/// Given
1840/// \code
1841/// template <typename T>
1842/// struct Base { typedef T Foo; };
1843///
1844/// template<typename T>
1845/// struct S : private Base<T> {
1846/// using typename Base<T>::Foo;
1847/// };
1848/// \endcode
1849/// unresolvedUsingTypenameDecl()
1850/// matches \code using Base<T>::Foo \endcode
1851extern const internal::VariadicDynCastAllOfMatcher<Decl,
1854
1855/// Matches a constant expression wrapper.
1856///
1857/// Example matches the constant in the case statement:
1858/// (matcher = constantExpr())
1859/// \code
1860/// switch (a) {
1861/// case 37: break;
1862/// }
1863/// \endcode
1864extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1866
1867/// Matches parentheses used in expressions.
1868///
1869/// Example matches (foo() + 1)
1870/// \code
1871/// int foo() { return 1; }
1872/// int a = (foo() + 1);
1873/// \endcode
1874extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1875
1876/// Matches constructor call expressions (including implicit ones).
1877///
1878/// Example matches string(ptr, n) and ptr within arguments of f
1879/// (matcher = cxxConstructExpr())
1880/// \code
1881/// void f(const string &a, const string &b);
1882/// char *ptr;
1883/// int n;
1884/// f(string(ptr, n), ptr);
1885/// \endcode
1886extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1888
1889/// Matches unresolved constructor call expressions.
1890///
1891/// Example matches T(t) in return statement of f
1892/// (matcher = cxxUnresolvedConstructExpr())
1893/// \code
1894/// template <typename T>
1895/// void f(const T& t) { return T(t); }
1896/// \endcode
1897extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1900
1901/// Matches implicit and explicit this expressions.
1902///
1903/// Example matches the implicit this expression in "return i".
1904/// (matcher = cxxThisExpr())
1905/// \code
1906/// struct foo {
1907/// int i;
1908/// int f() { return i; }
1909/// };
1910/// \endcode
1911extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1913
1914/// Matches nodes where temporaries are created.
1915///
1916/// Example matches FunctionTakesString(GetStringByValue())
1917/// (matcher = cxxBindTemporaryExpr())
1918/// \code
1919/// FunctionTakesString(GetStringByValue());
1920/// FunctionTakesStringByPointer(GetStringPointer());
1921/// \endcode
1922extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1924
1925/// Matches nodes where temporaries are materialized.
1926///
1927/// Example: Given
1928/// \code
1929/// struct T {void func();};
1930/// T f();
1931/// void g(T);
1932/// \endcode
1933/// materializeTemporaryExpr() matches 'f()' in these statements
1934/// \code
1935/// T u(f());
1936/// g(f());
1937/// f().func();
1938/// \endcode
1939/// but does not match
1940/// \code
1941/// f();
1942/// \endcode
1943extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1946
1947/// Matches new expressions.
1948///
1949/// Given
1950/// \code
1951/// new X;
1952/// \endcode
1953/// cxxNewExpr()
1954/// matches 'new X'.
1955extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1956
1957/// Matches delete expressions.
1958///
1959/// Given
1960/// \code
1961/// delete X;
1962/// \endcode
1963/// cxxDeleteExpr()
1964/// matches 'delete X'.
1965extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1967
1968/// Matches noexcept expressions.
1969///
1970/// Given
1971/// \code
1972/// bool a() noexcept;
1973/// bool b() noexcept(true);
1974/// bool c() noexcept(false);
1975/// bool d() noexcept(noexcept(a()));
1976/// bool e = noexcept(b()) || noexcept(c());
1977/// \endcode
1978/// cxxNoexceptExpr()
1979/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1980/// doesn't match the noexcept specifier in the declarations a, b, c or d.
1981extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1983
1984/// Matches a loop initializing the elements of an array in a number of contexts:
1985/// * in the implicit copy/move constructor for a class with an array member
1986/// * when a lambda-expression captures an array by value
1987/// * when a decomposition declaration decomposes an array
1988///
1989/// Given
1990/// \code
1991/// void testLambdaCapture() {
1992/// int a[10];
1993/// auto Lam1 = [a]() {
1994/// return;
1995/// };
1996/// }
1997/// \endcode
1998/// arrayInitLoopExpr() matches the implicit loop that initializes each element of
1999/// the implicit array field inside the lambda object, that represents the array `a`
2000/// captured by value.
2001extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitLoopExpr>
2003
2004/// The arrayInitIndexExpr consists of two subexpressions: a common expression
2005/// (the source array) that is evaluated once up-front, and a per-element initializer
2006/// that runs once for each array element. Within the per-element initializer,
2007/// the current index may be obtained via an ArrayInitIndexExpr.
2008///
2009/// Given
2010/// \code
2011/// void testStructBinding() {
2012/// int a[2] = {1, 2};
2013/// auto [x, y] = a;
2014/// }
2015/// \endcode
2016/// arrayInitIndexExpr() matches the array index that implicitly iterates
2017/// over the array `a` to copy each element to the anonymous array
2018/// that backs the structured binding `[x, y]` elements of which are
2019/// referred to by their aliases `x` and `y`.
2020extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitIndexExpr>
2022
2023/// Matches array subscript expressions.
2024///
2025/// Given
2026/// \code
2027/// int i = a[1];
2028/// \endcode
2029/// arraySubscriptExpr()
2030/// matches "a[1]"
2031extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
2033
2034/// Matches the value of a default argument at the call site.
2035///
2036/// Example matches the CXXDefaultArgExpr placeholder inserted for the
2037/// default value of the second parameter in the call expression f(42)
2038/// (matcher = cxxDefaultArgExpr())
2039/// \code
2040/// void f(int x, int y = 0);
2041/// f(42);
2042/// \endcode
2043extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
2045
2046/// Matches overloaded operator calls.
2047///
2048/// Note that if an operator isn't overloaded, it won't match. Instead, use
2049/// binaryOperator matcher.
2050/// Currently it does not match operators such as new delete.
2051/// FIXME: figure out why these do not match?
2052///
2053/// Example matches both operator<<((o << b), c) and operator<<(o, b)
2054/// (matcher = cxxOperatorCallExpr())
2055/// \code
2056/// ostream &operator<< (ostream &out, int i) { };
2057/// ostream &o; int b = 1, c = 1;
2058/// o << b << c;
2059/// \endcode
2060/// See also the binaryOperation() matcher for more-general matching of binary
2061/// uses of this AST node.
2062extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2064
2065/// Matches C++17 fold expressions.
2066///
2067/// Example matches `(0 + ... + args)`:
2068/// \code
2069/// template <typename... Args>
2070/// auto sum(Args... args) {
2071/// return (0 + ... + args);
2072/// }
2073/// \endcode
2074extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFoldExpr>
2076
2077/// Matches rewritten binary operators
2078///
2079/// Example matches use of "<":
2080/// \code
2081/// #include <compare>
2082/// struct HasSpaceshipMem {
2083/// int a;
2084/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2085/// };
2086/// void compare() {
2087/// HasSpaceshipMem hs1, hs2;
2088/// if (hs1 < hs2)
2089/// return;
2090/// }
2091/// \endcode
2092/// See also the binaryOperation() matcher for more-general matching
2093/// of this AST node.
2094extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2097
2098/// Matches expressions.
2099///
2100/// Example matches x()
2101/// \code
2102/// void f() { x(); }
2103/// \endcode
2104extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2105
2106/// Matches expressions that refer to declarations.
2107///
2108/// Example matches x in if (x)
2109/// \code
2110/// bool x;
2111/// if (x) {}
2112/// \endcode
2113extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2115
2116/// Matches a reference to an ObjCIvar.
2117///
2118/// Example: matches "a" in "init" method:
2119/// \code
2120/// @implementation A {
2121/// NSString *a;
2122/// }
2123/// - (void) init {
2124/// a = @"hello";
2125/// }
2126/// \endcode
2127extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2129
2130/// Matches a reference to a block.
2131///
2132/// Example: matches "^{}":
2133/// \code
2134/// void f() { ^{}(); }
2135/// \endcode
2136extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2137
2138/// Matches if statements.
2139///
2140/// Example matches 'if (x) {}'
2141/// \code
2142/// if (x) {}
2143/// \endcode
2144extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2145
2146/// Matches for statements.
2147///
2148/// Example matches 'for (;;) {}'
2149/// \code
2150/// for (;;) {}
2151/// int i[] = {1, 2, 3}; for (auto a : i);
2152/// \endcode
2153extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2154
2155/// Matches the increment statement of a for loop.
2156///
2157/// Example:
2158/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2159/// matches '++x' in
2160/// \code
2161/// for (x; x < N; ++x) { }
2162/// \endcode
2163AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2164 InnerMatcher) {
2165 const Stmt *const Increment = Node.getInc();
2166 return (Increment != nullptr &&
2167 InnerMatcher.matches(*Increment, Finder, Builder));
2168}
2169
2170/// Matches the initialization statement of a for loop.
2171///
2172/// Example:
2173/// forStmt(hasLoopInit(declStmt()))
2174/// matches 'int x = 0' in
2175/// \code
2176/// for (int x = 0; x < N; ++x) { }
2177/// \endcode
2178AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2179 InnerMatcher) {
2180 const Stmt *const Init = Node.getInit();
2181 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2182}
2183
2184/// Matches range-based for statements.
2185///
2186/// cxxForRangeStmt() matches 'for (auto a : i)'
2187/// \code
2188/// int i[] = {1, 2, 3}; for (auto a : i);
2189/// for(int j = 0; j < 5; ++j);
2190/// \endcode
2191extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2193
2194/// Matches the initialization statement of a for loop.
2195///
2196/// Example:
2197/// forStmt(hasLoopVariable(anything()))
2198/// matches 'int x' in
2199/// \code
2200/// for (int x : a) { }
2201/// \endcode
2202AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2203 InnerMatcher) {
2204 const VarDecl *const Var = Node.getLoopVariable();
2205 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2206}
2207
2208/// Matches the range initialization statement of a for loop.
2209///
2210/// Example:
2211/// forStmt(hasRangeInit(anything()))
2212/// matches 'a' in
2213/// \code
2214/// for (int x : a) { }
2215/// \endcode
2216AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2217 InnerMatcher) {
2218 const Expr *const Init = Node.getRangeInit();
2219 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2220}
2221
2222/// Matches while statements.
2223///
2224/// Given
2225/// \code
2226/// while (true) {}
2227/// \endcode
2228/// whileStmt()
2229/// matches 'while (true) {}'.
2230extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2231
2232/// Matches do statements.
2233///
2234/// Given
2235/// \code
2236/// do {} while (true);
2237/// \endcode
2238/// doStmt()
2239/// matches 'do {} while(true)'
2240extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2241
2242/// Matches break statements.
2243///
2244/// Given
2245/// \code
2246/// while (true) { break; }
2247/// \endcode
2248/// breakStmt()
2249/// matches 'break'
2250extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2251
2252/// Matches continue statements.
2253///
2254/// Given
2255/// \code
2256/// while (true) { continue; }
2257/// \endcode
2258/// continueStmt()
2259/// matches 'continue'
2260extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2262
2263/// Matches co_return statements.
2264///
2265/// Given
2266/// \code
2267/// while (true) { co_return; }
2268/// \endcode
2269/// coreturnStmt()
2270/// matches 'co_return'
2271extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2273
2274/// Matches return statements.
2275///
2276/// Given
2277/// \code
2278/// return 1;
2279/// \endcode
2280/// returnStmt()
2281/// matches 'return 1'
2282extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2283
2284/// Matches goto statements.
2285///
2286/// Given
2287/// \code
2288/// goto FOO;
2289/// FOO: bar();
2290/// \endcode
2291/// gotoStmt()
2292/// matches 'goto FOO'
2293extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2294
2295/// Matches label statements.
2296///
2297/// Given
2298/// \code
2299/// goto FOO;
2300/// FOO: bar();
2301/// \endcode
2302/// labelStmt()
2303/// matches 'FOO:'
2304extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2305
2306/// Matches address of label statements (GNU extension).
2307///
2308/// Given
2309/// \code
2310/// FOO: bar();
2311/// void *ptr = &&FOO;
2312/// goto *bar;
2313/// \endcode
2314/// addrLabelExpr()
2315/// matches '&&FOO'
2316extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2318
2319/// Matches switch statements.
2320///
2321/// Given
2322/// \code
2323/// switch(a) { case 42: break; default: break; }
2324/// \endcode
2325/// switchStmt()
2326/// matches 'switch(a)'.
2327extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2328
2329/// Matches case and default statements inside switch statements.
2330///
2331/// Given
2332/// \code
2333/// switch(a) { case 42: break; default: break; }
2334/// \endcode
2335/// switchCase()
2336/// matches 'case 42:' and 'default:'.
2337extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2338
2339/// Matches case statements inside switch statements.
2340///
2341/// Given
2342/// \code
2343/// switch(a) { case 42: break; default: break; }
2344/// \endcode
2345/// caseStmt()
2346/// matches 'case 42:'.
2347extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2348
2349/// Matches default statements inside switch statements.
2350///
2351/// Given
2352/// \code
2353/// switch(a) { case 42: break; default: break; }
2354/// \endcode
2355/// defaultStmt()
2356/// matches 'default:'.
2357extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2359
2360/// Matches compound statements.
2361///
2362/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2363/// \code
2364/// for (;;) {{}}
2365/// \endcode
2366extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2368
2369/// Matches catch statements.
2370///
2371/// \code
2372/// try {} catch(int i) {}
2373/// \endcode
2374/// cxxCatchStmt()
2375/// matches 'catch(int i)'
2376extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2378
2379/// Matches try statements.
2380///
2381/// \code
2382/// try {} catch(int i) {}
2383/// \endcode
2384/// cxxTryStmt()
2385/// matches 'try {}'
2386extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2387
2388/// Matches throw expressions.
2389///
2390/// \code
2391/// try { throw 5; } catch(int i) {}
2392/// \endcode
2393/// cxxThrowExpr()
2394/// matches 'throw 5'
2395extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2397
2398/// Matches null statements.
2399///
2400/// \code
2401/// foo();;
2402/// \endcode
2403/// nullStmt()
2404/// matches the second ';'
2405extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2406
2407/// Matches asm statements.
2408///
2409/// \code
2410/// int i = 100;
2411/// __asm("mov al, 2");
2412/// \endcode
2413/// asmStmt()
2414/// matches '__asm("mov al, 2")'
2415extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2416
2417/// Matches bool literals.
2418///
2419/// Example matches true
2420/// \code
2421/// true
2422/// \endcode
2423extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2425
2426/// Matches string literals (also matches wide string literals).
2427///
2428/// Example matches "abcd", L"abcd"
2429/// \code
2430/// char *s = "abcd";
2431/// wchar_t *ws = L"abcd";
2432/// \endcode
2433extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2435
2436/// Matches character literals (also matches wchar_t).
2437///
2438/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2439/// though.
2440///
2441/// Example matches 'a', L'a'
2442/// \code
2443/// char ch = 'a';
2444/// wchar_t chw = L'a';
2445/// \endcode
2446extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2448
2449/// Matches integer literals of all sizes / encodings, e.g.
2450/// 1, 1L, 0x1 and 1U.
2451///
2452/// Does not match character-encoded integers such as L'a'.
2453extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2455
2456/// Matches float literals of all sizes / encodings, e.g.
2457/// 1.0, 1.0f, 1.0L and 1e10.
2458///
2459/// Does not match implicit conversions such as
2460/// \code
2461/// float a = 10;
2462/// \endcode
2463extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2465
2466/// Matches imaginary literals, which are based on integer and floating
2467/// point literals e.g.: 1i, 1.0i
2468extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2470
2471/// Matches fixed point literals
2472extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2474
2475/// Matches user defined literal operator call.
2476///
2477/// Example match: "foo"_suffix
2478extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2480
2481/// Matches compound (i.e. non-scalar) literals
2482///
2483/// Example match: {1}, (1, 2)
2484/// \code
2485/// int array[4] = {1};
2486/// vector int myvec = (vector int)(1, 2);
2487/// \endcode
2488extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2490
2491/// Matches co_await expressions.
2492///
2493/// Given
2494/// \code
2495/// co_await 1;
2496/// \endcode
2497/// coawaitExpr()
2498/// matches 'co_await 1'
2499extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2501/// Matches co_await expressions where the type of the promise is dependent
2502extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2504/// Matches co_yield expressions.
2505///
2506/// Given
2507/// \code
2508/// co_yield 1;
2509/// \endcode
2510/// coyieldExpr()
2511/// matches 'co_yield 1'
2512extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2514
2515/// Matches coroutine body statements.
2516///
2517/// coroutineBodyStmt() matches the coroutine below
2518/// \code
2519/// generator<int> gen() {
2520/// co_return;
2521/// }
2522/// \endcode
2523extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoroutineBodyStmt>
2525
2526/// Matches nullptr literal.
2527extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2529
2530/// Matches GNU __builtin_choose_expr.
2531extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2532 chooseExpr;
2533
2534/// Matches builtin function __builtin_convertvector.
2535extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConvertVectorExpr>
2537
2538/// Matches GNU __null expression.
2539extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2541
2542/// Matches C11 _Generic expression.
2543extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2545
2546/// Matches atomic builtins.
2547/// Example matches __atomic_load_n(ptr, 1)
2548/// \code
2549/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2550/// \endcode
2551extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2552
2553/// Matches statement expression (GNU extension).
2554///
2555/// Example match: ({ int X = 4; X; })
2556/// \code
2557/// int C = ({ int X = 4; X; });
2558/// \endcode
2559extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2560
2561/// Matches binary operator expressions.
2562///
2563/// Example matches a || b
2564/// \code
2565/// !(a || b)
2566/// \endcode
2567/// See also the binaryOperation() matcher for more-general matching.
2568extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2570
2571/// Matches unary operator expressions.
2572///
2573/// Example matches !a
2574/// \code
2575/// !a || b
2576/// \endcode
2577extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2579
2580/// Matches conditional operator expressions.
2581///
2582/// Example matches a ? b : c
2583/// \code
2584/// (a ? b : c) + 42
2585/// \endcode
2586extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2588
2589/// Matches binary conditional operator expressions (GNU extension).
2590///
2591/// Example matches a ?: b
2592/// \code
2593/// (a ?: b) + 42;
2594/// \endcode
2595extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2598
2599/// Matches opaque value expressions. They are used as helpers
2600/// to reference another expressions and can be met
2601/// in BinaryConditionalOperators, for example.
2602///
2603/// Example matches 'a'
2604/// \code
2605/// (a ?: c) + 42;
2606/// \endcode
2607extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2609
2610/// Matches a C++ static_assert declaration.
2611///
2612/// Example:
2613/// staticAssertDecl()
2614/// matches
2615/// static_assert(sizeof(S) == sizeof(int))
2616/// in
2617/// \code
2618/// struct S {
2619/// int x;
2620/// };
2621/// static_assert(sizeof(S) == sizeof(int));
2622/// \endcode
2623extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2625
2626/// Matches a reinterpret_cast expression.
2627///
2628/// Either the source expression or the destination type can be matched
2629/// using has(), but hasDestinationType() is more specific and can be
2630/// more readable.
2631///
2632/// Example matches reinterpret_cast<char*>(&p) in
2633/// \code
2634/// void* p = reinterpret_cast<char*>(&p);
2635/// \endcode
2636extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2638
2639/// Matches a C++ static_cast expression.
2640///
2641/// \see hasDestinationType
2642/// \see reinterpretCast
2643///
2644/// Example:
2645/// cxxStaticCastExpr()
2646/// matches
2647/// static_cast<long>(8)
2648/// in
2649/// \code
2650/// long eight(static_cast<long>(8));
2651/// \endcode
2652extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2654
2655/// Matches a dynamic_cast expression.
2656///
2657/// Example:
2658/// cxxDynamicCastExpr()
2659/// matches
2660/// dynamic_cast<D*>(&b);
2661/// in
2662/// \code
2663/// struct B { virtual ~B() {} }; struct D : B {};
2664/// B b;
2665/// D* p = dynamic_cast<D*>(&b);
2666/// \endcode
2667extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2669
2670/// Matches a const_cast expression.
2671///
2672/// Example: Matches const_cast<int*>(&r) in
2673/// \code
2674/// int n = 42;
2675/// const int &r(n);
2676/// int* p = const_cast<int*>(&r);
2677/// \endcode
2678extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2680
2681/// Matches a C-style cast expression.
2682///
2683/// Example: Matches (int) 2.2f in
2684/// \code
2685/// int i = (int) 2.2f;
2686/// \endcode
2687extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2689
2690/// Matches explicit cast expressions.
2691///
2692/// Matches any cast expression written in user code, whether it be a
2693/// C-style cast, a functional-style cast, or a keyword cast.
2694///
2695/// Does not match implicit conversions.
2696///
2697/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2698/// Clang uses the term "cast" to apply to implicit conversions as well as to
2699/// actual cast expressions.
2700///
2701/// \see hasDestinationType.
2702///
2703/// Example: matches all five of the casts in
2704/// \code
2705/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2706/// \endcode
2707/// but does not match the implicit conversion in
2708/// \code
2709/// long ell = 42;
2710/// \endcode
2711extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2713
2714/// Matches the implicit cast nodes of Clang's AST.
2715///
2716/// This matches many different places, including function call return value
2717/// eliding, as well as any type conversions.
2718extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2720
2721/// Matches any cast nodes of Clang's AST.
2722///
2723/// Example: castExpr() matches each of the following:
2724/// \code
2725/// (int) 3;
2726/// const_cast<Expr *>(SubExpr);
2727/// char c = 0;
2728/// \endcode
2729/// but does not match
2730/// \code
2731/// int i = (0);
2732/// int k = 0;
2733/// \endcode
2734extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2735
2736/// Matches functional cast expressions
2737///
2738/// Example: Matches Foo(bar);
2739/// \code
2740/// Foo f = bar;
2741/// Foo g = (Foo) bar;
2742/// Foo h = Foo(bar);
2743/// \endcode
2744extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2746
2747/// Matches functional cast expressions having N != 1 arguments
2748///
2749/// Example: Matches Foo(bar, bar)
2750/// \code
2751/// Foo h = Foo(bar, bar);
2752/// \endcode
2753extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2755
2756/// Matches predefined identifier expressions [C99 6.4.2.2].
2757///
2758/// Example: Matches __func__
2759/// \code
2760/// printf("%s", __func__);
2761/// \endcode
2762extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2764
2765/// Matches C99 designated initializer expressions [C99 6.7.8].
2766///
2767/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2768/// \code
2769/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2770/// \endcode
2771extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2773
2774/// Matches designated initializer expressions that contain
2775/// a specific number of designators.
2776///
2777/// Example: Given
2778/// \code
2779/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2780/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2781/// \endcode
2782/// designatorCountIs(2)
2783/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2784/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2785AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2786 return Node.size() == N;
2787}
2788
2789/// Matches \c QualTypes in the clang AST.
2790extern const internal::VariadicAllOfMatcher<QualType> qualType;
2791
2792/// Matches \c Types in the clang AST.
2793extern const internal::VariadicAllOfMatcher<Type> type;
2794
2795/// Matches \c TypeLocs in the clang AST.
2796extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2797
2798/// Matches if any of the given matchers matches.
2799///
2800/// Unlike \c anyOf, \c eachOf will generate a match result for each
2801/// matching submatcher.
2802///
2803/// For example, in:
2804/// \code
2805/// class A { int a; int b; };
2806/// \endcode
2807/// The matcher:
2808/// \code
2809/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2810/// has(fieldDecl(hasName("b")).bind("v"))))
2811/// \endcode
2812/// will generate two results binding "v", the first of which binds
2813/// the field declaration of \c a, the second the field declaration of
2814/// \c b.
2815///
2816/// Usable as: Any Matcher
2817extern const internal::VariadicOperatorMatcherFunc<
2818 2, std::numeric_limits<unsigned>::max()>
2819 eachOf;
2820
2821/// Matches if any of the given matchers matches.
2822///
2823/// Usable as: Any Matcher
2824extern const internal::VariadicOperatorMatcherFunc<
2825 2, std::numeric_limits<unsigned>::max()>
2826 anyOf;
2827
2828/// Matches if all given matchers match.
2829///
2830/// Usable as: Any Matcher
2831extern const internal::VariadicOperatorMatcherFunc<
2832 2, std::numeric_limits<unsigned>::max()>
2833 allOf;
2834
2835/// Matches any node regardless of the submatcher.
2836///
2837/// However, \c optionally will retain any bindings generated by the submatcher.
2838/// Useful when additional information which may or may not present about a main
2839/// matching node is desired.
2840///
2841/// For example, in:
2842/// \code
2843/// class Foo {
2844/// int bar;
2845/// }
2846/// \endcode
2847/// The matcher:
2848/// \code
2849/// cxxRecordDecl(
2850/// optionally(has(
2851/// fieldDecl(hasName("bar")).bind("var")
2852/// ))).bind("record")
2853/// \endcode
2854/// will produce a result binding for both "record" and "var".
2855/// The matcher will produce a "record" binding for even if there is no data
2856/// member named "bar" in that class.
2857///
2858/// Usable as: Any Matcher
2859extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2860
2861/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2862///
2863/// Given
2864/// \code
2865/// Foo x = bar;
2866/// int y = sizeof(x) + alignof(x);
2867/// \endcode
2868/// unaryExprOrTypeTraitExpr()
2869/// matches \c sizeof(x) and \c alignof(x)
2870extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2873
2874/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2875///
2876/// Given
2877/// \code
2878/// if (true);
2879/// for (; true; );
2880/// \endcode
2881/// with the matcher
2882/// \code
2883/// mapAnyOf(ifStmt, forStmt).with(
2884/// hasCondition(cxxBoolLiteralExpr(equals(true)))
2885/// ).bind("trueCond")
2886/// \endcode
2887/// matches the \c if and the \c for. It is equivalent to:
2888/// \code
2889/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2890/// anyOf(
2891/// ifStmt(trueCond).bind("trueCond"),
2892/// forStmt(trueCond).bind("trueCond")
2893/// );
2894/// \endcode
2895///
2896/// The with() chain-call accepts zero or more matchers which are combined
2897/// as-if with allOf() in each of the node matchers.
2898/// Usable as: Any Matcher
2899template <typename T, typename... U>
2900auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2901 return internal::MapAnyOfHelper<U...>();
2902}
2903
2904/// Matches nodes which can be used with binary operators.
2905///
2906/// The code
2907/// \code
2908/// var1 != var2;
2909/// \endcode
2910/// might be represented in the clang AST as a binaryOperator, a
2911/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2912///
2913/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2914/// least one is a class type (cxxOperatorCallExpr)
2915/// * whether the code appears in a template declaration, if at least one of the
2916/// vars is a dependent-type (binaryOperator)
2917/// * whether the code relies on a rewritten binary operator, such as a
2918/// spaceship operator or an inverted equality operator
2919/// (cxxRewrittenBinaryOperator)
2920///
2921/// This matcher elides details in places where the matchers for the nodes are
2922/// compatible.
2923///
2924/// Given
2925/// \code
2926/// binaryOperation(
2927/// hasOperatorName("!="),
2928/// hasLHS(expr().bind("lhs")),
2929/// hasRHS(expr().bind("rhs"))
2930/// )
2931/// \endcode
2932/// matches each use of "!=" in:
2933/// \code
2934/// struct S{
2935/// bool operator!=(const S&) const;
2936/// };
2937///
2938/// void foo()
2939/// {
2940/// 1 != 2;
2941/// S() != S();
2942/// }
2943///
2944/// template<typename T>
2945/// void templ()
2946/// {
2947/// 1 != 2;
2948/// T() != S();
2949/// }
2950/// struct HasOpEq
2951/// {
2952/// bool operator==(const HasOpEq &) const;
2953/// };
2954///
2955/// void inverse()
2956/// {
2957/// HasOpEq s1;
2958/// HasOpEq s2;
2959/// if (s1 != s2)
2960/// return;
2961/// }
2962///
2963/// struct HasSpaceship
2964/// {
2965/// bool operator<=>(const HasOpEq &) const;
2966/// };
2967///
2968/// void use_spaceship()
2969/// {
2970/// HasSpaceship s1;
2971/// HasSpaceship s2;
2972/// if (s1 != s2)
2973/// return;
2974/// }
2975/// \endcode
2976extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2979
2980/// Matches function calls and constructor calls
2981///
2982/// Because CallExpr and CXXConstructExpr do not share a common
2983/// base class with API accessing arguments etc, AST Matchers for code
2984/// which should match both are typically duplicated. This matcher
2985/// removes the need for duplication.
2986///
2987/// Given code
2988/// \code
2989/// struct ConstructorTakesInt
2990/// {
2991/// ConstructorTakesInt(int i) {}
2992/// };
2993///
2994/// void callTakesInt(int i)
2995/// {
2996/// }
2997///
2998/// void doCall()
2999/// {
3000/// callTakesInt(42);
3001/// }
3002///
3003/// void doConstruct()
3004/// {
3005/// ConstructorTakesInt cti(42);
3006/// }
3007/// \endcode
3008///
3009/// The matcher
3010/// \code
3011/// invocation(hasArgument(0, integerLiteral(equals(42))))
3012/// \endcode
3013/// matches the expression in both doCall and doConstruct
3014extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
3015
3016/// Matches unary expressions that have a specific type of argument.
3017///
3018/// Given
3019/// \code
3020/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
3021/// \endcode
3022/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
3023/// matches \c sizeof(a) and \c alignof(c)
3025 internal::Matcher<QualType>, InnerMatcher) {
3026 const QualType ArgumentType = Node.getTypeOfArgument();
3027 return InnerMatcher.matches(ArgumentType, Finder, Builder);
3028}
3029
3030/// Matches unary expressions of a certain kind.
3031///
3032/// Given
3033/// \code
3034/// int x;
3035/// int s = sizeof(x) + alignof(x)
3036/// \endcode
3037/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
3038/// matches \c sizeof(x)
3039///
3040/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
3041/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
3043 return Node.getKind() == Kind;
3044}
3045
3046/// Same as unaryExprOrTypeTraitExpr, but only matching
3047/// alignof.
3048inline internal::BindableMatcher<Stmt> alignOfExpr(
3049 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3051 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
3052 InnerMatcher)));
3053}
3054
3055/// Same as unaryExprOrTypeTraitExpr, but only matching
3056/// sizeof.
3057inline internal::BindableMatcher<Stmt> sizeOfExpr(
3058 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3060 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
3061}
3062
3063/// Matches NamedDecl nodes that have the specified name.
3064///
3065/// Supports specifying enclosing namespaces or classes by prefixing the name
3066/// with '<enclosing>::'.
3067/// Does not match typedefs of an underlying type with the given name.
3068///
3069/// Example matches X (Name == "X")
3070/// \code
3071/// class X;
3072/// \endcode
3073///
3074/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
3075/// \code
3076/// namespace a { namespace b { class X; } }
3077/// \endcode
3078inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3079 return internal::Matcher<NamedDecl>(
3080 new internal::HasNameMatcher({std::string(Name)}));
3081}
3082
3083/// Matches NamedDecl nodes that have any of the specified names.
3084///
3085/// This matcher is only provided as a performance optimization of hasName.
3086/// \code
3087/// hasAnyName(a, b, c)
3088/// \endcode
3089/// is equivalent to, but faster than
3090/// \code
3091/// anyOf(hasName(a), hasName(b), hasName(c))
3092/// \endcode
3093extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3095 hasAnyName;
3096
3097/// Matches NamedDecl nodes whose fully qualified names contain
3098/// a substring matched by the given RegExp.
3099///
3100/// Supports specifying enclosing namespaces or classes by
3101/// prefixing the name with '<enclosing>::'. Does not match typedefs
3102/// of an underlying type with the given name.
3103///
3104/// Example matches X (regexp == "::X")
3105/// \code
3106/// class X;
3107/// \endcode
3108///
3109/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3110/// \code
3111/// namespace foo { namespace bar { class X; } }
3112/// \endcode
3113AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3114 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3115 return RegExp->match(FullNameString);
3116}
3117
3118/// Matches overloaded operator names.
3119///
3120/// Matches overloaded operator names specified in strings without the
3121/// "operator" prefix: e.g. "<<".
3122///
3123/// Given:
3124/// \code
3125/// class A { int operator*(); };
3126/// const A &operator<<(const A &a, const A &b);
3127/// A a;
3128/// a << a; // <-- This matches
3129/// \endcode
3130///
3131/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3132/// specified line and
3133/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3134/// matches the declaration of \c A.
3135///
3136/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3137inline internal::PolymorphicMatcher<
3138 internal::HasOverloadedOperatorNameMatcher,
3140 std::vector<std::string>>
3142 return internal::PolymorphicMatcher<
3143 internal::HasOverloadedOperatorNameMatcher,
3145 std::vector<std::string>>({std::string(Name)});
3146}
3147
3148/// Matches overloaded operator names.
3149///
3150/// Matches overloaded operator names specified in strings without the
3151/// "operator" prefix: e.g. "<<".
3152///
3153/// hasAnyOverloadedOperatorName("+", "-")
3154/// Is equivalent to
3155/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3156extern const internal::VariadicFunction<
3157 internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3160 std::vector<std::string>>,
3163
3164/// Matches template-dependent, but known, member names.
3165///
3166/// In template declarations, dependent members are not resolved and so can
3167/// not be matched to particular named declarations.
3168///
3169/// This matcher allows to match on the known name of members.
3170///
3171/// Given
3172/// \code
3173/// template <typename T>
3174/// struct S {
3175/// void mem();
3176/// };
3177/// template <typename T>
3178/// void x() {
3179/// S<T> s;
3180/// s.mem();
3181/// }
3182/// \endcode
3183/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3184AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3185 return Node.getMember().getAsString() == N;
3186}
3187
3188/// Matches template-dependent, but known, member names against an already-bound
3189/// node
3190///
3191/// In template declarations, dependent members are not resolved and so can
3192/// not be matched to particular named declarations.
3193///
3194/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3195/// and CXXMethodDecl nodes.
3196///
3197/// Given
3198/// \code
3199/// template <typename T>
3200/// struct S {
3201/// void mem();
3202/// };
3203/// template <typename T>
3204/// void x() {
3205/// S<T> s;
3206/// s.mem();
3207/// }
3208/// \endcode
3209/// The matcher
3210/// @code
3211/// \c cxxDependentScopeMemberExpr(
3212/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3213/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3214/// cxxMethodDecl(hasName("mem")).bind("templMem")
3215/// )))))
3216/// )))),
3217/// memberHasSameNameAsBoundNode("templMem")
3218/// )
3219/// @endcode
3220/// first matches and binds the @c mem member of the @c S template, then
3221/// compares its name to the usage in @c s.mem() in the @c x function template
3222AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3223 std::string, BindingID) {
3224 auto MemberName = Node.getMember().getAsString();
3225
3226 return Builder->removeBindings(
3227 [this, MemberName](const BoundNodesMap &Nodes) {
3228 const auto &BN = Nodes.getNode(this->BindingID);
3229 if (const auto *ND = BN.get<NamedDecl>()) {
3230 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3231 return true;
3232 return ND->getName() != MemberName;
3233 }
3234 return true;
3235 });
3236}
3237
3238/// Matches C++ classes that are directly or indirectly derived from a class
3239/// matching \c Base, or Objective-C classes that directly or indirectly
3240/// subclass a class matching \c Base.
3241///
3242/// Note that a class is not considered to be derived from itself.
3243///
3244/// Example matches Y, Z, C (Base == hasName("X"))
3245/// \code
3246/// class X;
3247/// class Y : public X {}; // directly derived
3248/// class Z : public Y {}; // indirectly derived
3249/// typedef X A;
3250/// typedef A B;
3251/// class C : public B {}; // derived from a typedef of X
3252/// \endcode
3253///
3254/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3255/// \code
3256/// class Foo;
3257/// typedef Foo X;
3258/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3259/// \endcode
3260///
3261/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3262/// \code
3263/// @interface NSObject @end
3264/// @interface Bar : NSObject @end
3265/// \endcode
3266///
3267/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3269 isDerivedFrom,
3271 internal::Matcher<NamedDecl>, Base) {
3272 // Check if the node is a C++ struct/union/class.
3273 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3274 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3275
3276 // The node must be an Objective-C class.
3277 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3278 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3279 /*Directly=*/false);
3280}
3281
3282/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3284 isDerivedFrom,
3286 std::string, BaseName, 1) {
3287 if (BaseName.empty())
3288 return false;
3289
3290 const auto M = isDerivedFrom(hasName(BaseName));
3291
3292 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3293 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3294
3295 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3296 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3297}
3298
3299/// Matches C++ classes that have a direct or indirect base matching \p
3300/// BaseSpecMatcher.
3301///
3302/// Example:
3303/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3304/// \code
3305/// class Foo;
3306/// class Bar : Foo {};
3307/// class Baz : Bar {};
3308/// class SpecialBase;
3309/// class Proxy : SpecialBase {}; // matches Proxy
3310/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3311/// \endcode
3312///
3313// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3314AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3315 BaseSpecMatcher) {
3316 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3317}
3318
3319/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3320///
3321/// Example:
3322/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3323/// \code
3324/// class Foo;
3325/// class Bar : Foo {};
3326/// class Baz : Bar {};
3327/// class SpecialBase;
3328/// class Proxy : SpecialBase {}; // matches Proxy
3329/// class IndirectlyDerived : Proxy {}; // doesn't match
3330/// \endcode
3331AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3332 BaseSpecMatcher) {
3333 return Node.hasDefinition() &&
3334 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3335 return BaseSpecMatcher.matches(Base, Finder, Builder);
3336 });
3337}
3338
3339/// Similar to \c isDerivedFrom(), but also matches classes that directly
3340/// match \c Base.
3342 isSameOrDerivedFrom,
3344 internal::Matcher<NamedDecl>, Base, 0) {
3345 const auto M = anyOf(Base, isDerivedFrom(Base));
3346
3347 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3348 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3349
3350 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3351 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3352}
3353
3354/// Overloaded method as shortcut for
3355/// \c isSameOrDerivedFrom(hasName(...)).
3357 isSameOrDerivedFrom,
3359 std::string, BaseName, 1) {
3360 if (BaseName.empty())
3361 return false;
3362
3363 const auto M = isSameOrDerivedFrom(hasName(BaseName));
3364
3365 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3366 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3367
3368 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3369 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3370}
3371
3372/// Matches C++ or Objective-C classes that are directly derived from a class
3373/// matching \c Base.
3374///
3375/// Note that a class is not considered to be derived from itself.
3376///
3377/// Example matches Y, C (Base == hasName("X"))
3378/// \code
3379/// class X;
3380/// class Y : public X {}; // directly derived
3381/// class Z : public Y {}; // indirectly derived
3382/// typedef X A;
3383/// typedef A B;
3384/// class C : public B {}; // derived from a typedef of X
3385/// \endcode
3386///
3387/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3388/// \code
3389/// class Foo;
3390/// typedef Foo X;
3391/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3392/// \endcode
3394 isDirectlyDerivedFrom,
3396 internal::Matcher<NamedDecl>, Base, 0) {
3397 // Check if the node is a C++ struct/union/class.
3398 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3399 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3400
3401 // The node must be an Objective-C class.
3402 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3403 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3404 /*Directly=*/true);
3405}
3406
3407/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3409 isDirectlyDerivedFrom,
3411 std::string, BaseName, 1) {
3412 if (BaseName.empty())
3413 return false;
3414 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3415
3416 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3417 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3418
3419 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3420 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3421}
3422/// Matches the first method of a class or struct that satisfies \c
3423/// InnerMatcher.
3424///
3425/// Given:
3426/// \code
3427/// class A { void func(); };
3428/// class B { void member(); };
3429/// \endcode
3430///
3431/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3432/// \c A but not \c B.
3433AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3434 InnerMatcher) {
3435 BoundNodesTreeBuilder Result(*Builder);
3436 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3437 Node.method_end(), Finder, &Result);
3438 if (MatchIt == Node.method_end())
3439 return false;
3440
3441 if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3442 return false;
3443 *Builder = std::move(Result);
3444 return true;
3445}
3446
3447/// Matches the generated class of lambda expressions.
3448///
3449/// Given:
3450/// \code
3451/// auto x = []{};
3452/// \endcode
3453///
3454/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3455/// \c decltype(x)
3457 return Node.isLambda();
3458}
3459
3460/// Matches AST nodes that have child AST nodes that match the
3461/// provided matcher.
3462///
3463/// Example matches X, Y
3464/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3465/// \code
3466/// class X {}; // Matches X, because X::X is a class of name X inside X.
3467/// class Y { class X {}; };
3468/// class Z { class Y { class X {}; }; }; // Does not match Z.
3469/// \endcode
3470///
3471/// ChildT must be an AST base type.
3472///
3473/// Usable as: Any Matcher
3474/// Note that has is direct matcher, so it also matches things like implicit
3475/// casts and paren casts. If you are matching with expr then you should
3476/// probably consider using ignoringParenImpCasts like:
3477/// has(ignoringParenImpCasts(expr())).
3478extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3479
3480/// Matches AST nodes that have descendant AST nodes that match the
3481/// provided matcher.
3482///
3483/// Example matches X, Y, Z
3484/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3485/// \code
3486/// class X {}; // Matches X, because X::X is a class of name X inside X.
3487/// class Y { class X {}; };
3488/// class Z { class Y { class X {}; }; };
3489/// \endcode
3490///
3491/// DescendantT must be an AST base type.
3492///
3493/// Usable as: Any Matcher
3494extern const internal::ArgumentAdaptingMatcherFunc<
3495 internal::HasDescendantMatcher>
3497
3498/// Matches AST nodes that have child AST nodes that match the
3499/// provided matcher.
3500///
3501/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3502/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3503/// \code
3504/// class X {};
3505/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3506/// // inside Y.
3507/// class Z { class Y { class X {}; }; }; // Does not match Z.
3508/// \endcode
3509///
3510/// ChildT must be an AST base type.
3511///
3512/// As opposed to 'has', 'forEach' will cause a match for each result that
3513/// matches instead of only on the first one.
3514///
3515/// Usable as: Any Matcher
3516extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3517 forEach;
3518
3519/// Matches AST nodes that have descendant AST nodes that match the
3520/// provided matcher.
3521///
3522/// Example matches X, A, A::X, B, B::C, B::C::X
3523/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3524/// \code
3525/// class X {};
3526/// class A { class X {}; }; // Matches A, because A::X is a class of name
3527/// // X inside A.
3528/// class B { class C { class X {}; }; };
3529/// \endcode
3530///
3531/// DescendantT must be an AST base type.
3532///
3533/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3534/// each result that matches instead of only on the first one.
3535///
3536/// Note: Recursively combined ForEachDescendant can cause many matches:
3537/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3538/// forEachDescendant(cxxRecordDecl())
3539/// )))
3540/// will match 10 times (plus injected class name matches) on:
3541/// \code
3542/// class A { class B { class C { class D { class E {}; }; }; }; };
3543/// \endcode
3544///
3545/// Usable as: Any Matcher
3546extern const internal::ArgumentAdaptingMatcherFunc<
3547 internal::ForEachDescendantMatcher>
3549
3550/// Matches if the node or any descendant matches.
3551///
3552/// Generates results for each match.
3553///
3554/// For example, in:
3555/// \code
3556/// class A { class B {}; class C {}; };
3557/// \endcode
3558/// The matcher:
3559/// \code
3560/// cxxRecordDecl(hasName("::A"),
3561/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3562/// \endcode
3563/// will generate results for \c A, \c B and \c C.
3564///
3565/// Usable as: Any Matcher
3566template <typename T>
3567internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3568 return eachOf(Matcher, forEachDescendant(Matcher));
3569}
3570
3571/// Matches AST nodes that have a parent that matches the provided
3572/// matcher.
3573///
3574/// Given
3575/// \code
3576/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3577/// \endcode
3578/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3579///
3580/// Usable as: Any Matcher
3581extern const internal::ArgumentAdaptingMatcherFunc<
3582 internal::HasParentMatcher,
3583 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3584 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3585 hasParent;
3586
3587/// Matches AST nodes that have an ancestor that matches the provided
3588/// matcher.
3589///
3590/// Given
3591/// \code
3592/// void f() { if (true) { int x = 42; } }
3593/// void g() { for (;;) { int x = 43; } }
3594/// \endcode
3595/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3596///
3597/// Usable as: Any Matcher
3598extern const internal::ArgumentAdaptingMatcherFunc<
3599 internal::HasAncestorMatcher,
3600 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3601 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3603
3604/// Matches if the provided matcher does not match.
3605///
3606/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3607/// \code
3608/// class X {};
3609/// class Y {};
3610/// \endcode
3611///
3612/// Usable as: Any Matcher
3613extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3614
3615/// Matches a node if the declaration associated with that node
3616/// matches the given matcher.
3617///
3618/// The associated declaration is:
3619/// - for type nodes, the declaration of the underlying type
3620/// - for CallExpr, the declaration of the callee
3621/// - for MemberExpr, the declaration of the referenced member
3622/// - for CXXConstructExpr, the declaration of the constructor
3623/// - for CXXNewExpr, the declaration of the operator new
3624/// - for ObjCIvarExpr, the declaration of the ivar
3625///
3626/// For type nodes, hasDeclaration will generally match the declaration of the
3627/// sugared type. Given
3628/// \code
3629/// class X {};
3630/// typedef X Y;
3631/// Y y;
3632/// \endcode
3633/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3634/// typedefDecl. A common use case is to match the underlying, desugared type.
3635/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3636/// \code
3637/// varDecl(hasType(hasUnqualifiedDesugaredType(
3638/// recordType(hasDeclaration(decl())))))
3639/// \endcode
3640/// In this matcher, the decl will match the CXXRecordDecl of class X.
3641///
3642/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3643/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3644/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3645/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3646/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3647/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3648/// Matcher<UnresolvedUsingType>
3649inline internal::PolymorphicMatcher<
3650 internal::HasDeclarationMatcher,
3651 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3652hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3653 return internal::PolymorphicMatcher<
3654 internal::HasDeclarationMatcher,
3655 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3656 InnerMatcher);
3657}
3658
3659/// Matches a \c NamedDecl whose underlying declaration matches the given
3660/// matcher.
3661///
3662/// Given
3663/// \code
3664/// namespace N { template<class T> void f(T t); }
3665/// template <class T> void g() { using N::f; f(T()); }
3666/// \endcode
3667/// \c unresolvedLookupExpr(hasAnyDeclaration(
3668/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3669/// matches the use of \c f in \c g() .
3670AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3671 InnerMatcher) {
3672 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3673
3674 return UnderlyingDecl != nullptr &&
3675 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3676}
3677
3678/// Matches on the implicit object argument of a member call expression, after
3679/// stripping off any parentheses or implicit casts.
3680///
3681/// Given
3682/// \code
3683/// class Y { public: void m(); };
3684/// Y g();
3685/// class X : public Y {};
3686/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3687/// \endcode
3688/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3689/// matches `y.m()` and `(g()).m()`.
3690/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3691/// matches `x.m()`.
3692/// cxxMemberCallExpr(on(callExpr()))
3693/// matches `(g()).m()`.
3694///
3695/// FIXME: Overload to allow directly matching types?
3696AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3697 InnerMatcher) {
3698 const Expr *ExprNode = Node.getImplicitObjectArgument()
3699 ->IgnoreParenImpCasts();
3700 return (ExprNode != nullptr &&
3701 InnerMatcher.matches(*ExprNode, Finder, Builder));
3702}
3703
3704
3705/// Matches on the receiver of an ObjectiveC Message expression.
3706///
3707/// Example
3708/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3709/// matches the [webView ...] message invocation.
3710/// \code
3711/// NSString *webViewJavaScript = ...
3712/// UIWebView *webView = ...
3713/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3714/// \endcode
3715AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3716 InnerMatcher) {
3717 const QualType TypeDecl = Node.getReceiverType();
3718 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3719}
3720
3721/// Returns true when the Objective-C method declaration is a class method.
3722///
3723/// Example
3724/// matcher = objcMethodDecl(isClassMethod())
3725/// matches
3726/// \code
3727/// @interface I + (void)foo; @end
3728/// \endcode
3729/// but not
3730/// \code
3731/// @interface I - (void)bar; @end
3732/// \endcode
3734 return Node.isClassMethod();
3735}
3736
3737/// Returns true when the Objective-C method declaration is an instance method.
3738///
3739/// Example
3740/// matcher = objcMethodDecl(isInstanceMethod())
3741/// matches
3742/// \code
3743/// @interface I - (void)bar; @end
3744/// \endcode
3745/// but not
3746/// \code
3747/// @interface I + (void)foo; @end
3748/// \endcode
3750 return Node.isInstanceMethod();
3751}
3752
3753/// Returns true when the Objective-C message is sent to a class.
3754///
3755/// Example
3756/// matcher = objcMessageExpr(isClassMessage())
3757/// matches
3758/// \code
3759/// [NSString stringWithFormat:@"format"];
3760/// \endcode
3761/// but not
3762/// \code
3763/// NSString *x = @"hello";
3764/// [x containsString:@"h"];
3765/// \endcode
3767 return Node.isClassMessage();
3768}
3769
3770/// Returns true when the Objective-C message is sent to an instance.
3771///
3772/// Example
3773/// matcher = objcMessageExpr(isInstanceMessage())
3774/// matches
3775/// \code
3776/// NSString *x = @"hello";
3777/// [x containsString:@"h"];
3778/// \endcode
3779/// but not
3780/// \code
3781/// [NSString stringWithFormat:@"format"];
3782/// \endcode
3783AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3784 return Node.isInstanceMessage();
3785}
3786
3787/// Matches if the Objective-C message is sent to an instance,
3788/// and the inner matcher matches on that instance.
3789///
3790/// For example the method call in
3791/// \code
3792/// NSString *x = @"hello";
3793/// [x containsString:@"h"];
3794/// \endcode
3795/// is matched by
3796/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3797AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3798 InnerMatcher) {
3799 const Expr *ReceiverNode = Node.getInstanceReceiver();
3800 return (ReceiverNode != nullptr &&
3801 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3802 Builder));
3803}
3804
3805/// Matches when BaseName == Selector.getAsString()
3806///
3807/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3808/// matches the outer message expr in the code below, but NOT the message
3809/// invocation for self.bodyView.
3810/// \code
3811/// [self.bodyView loadHTMLString:html baseURL:NULL];
3812/// \endcode
3813AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3814 Selector Sel = Node.getSelector();
3815 return BaseName == Sel.getAsString();
3816}
3817
3818/// Matches when at least one of the supplied string equals to the
3819/// Selector.getAsString()
3820///
3821/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3822/// matches both of the expressions below:
3823/// \code
3824/// [myObj methodA:argA];
3825/// [myObj methodB:argB];
3826/// \endcode
3827extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3828 StringRef,
3831
3832/// Matches ObjC selectors whose name contains
3833/// a substring matched by the given RegExp.
3834/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3835/// matches the outer message expr in the code below, but NOT the message
3836/// invocation for self.bodyView.
3837/// \code
3838/// [self.bodyView loadHTMLString:html baseURL:NULL];
3839/// \endcode
3840AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3841 std::string SelectorString = Node.getSelector().getAsString();
3842 return RegExp->match(SelectorString);
3843}
3844
3845/// Matches when the selector is the empty selector
3846///
3847/// Matches only when the selector of the objCMessageExpr is NULL. This may
3848/// represent an error condition in the tree!
3849AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3850 return Node.getSelector().isNull();
3851}
3852
3853/// Matches when the selector is a Unary Selector
3854///
3855/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3856/// matches self.bodyView in the code below, but NOT the outer message
3857/// invocation of "loadHTMLString:baseURL:".
3858/// \code
3859/// [self.bodyView loadHTMLString:html baseURL:NULL];
3860/// \endcode
3861AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3862 return Node.getSelector().isUnarySelector();
3863}
3864
3865/// Matches when the selector is a keyword selector
3866///
3867/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3868/// message expression in
3869///
3870/// \code
3871/// UIWebView *webView = ...;
3872/// CGRect bodyFrame = webView.frame;
3873/// bodyFrame.size.height = self.bodyContentHeight;
3874/// webView.frame = bodyFrame;
3875/// // ^---- matches here
3876/// \endcode
3877AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3878 return Node.getSelector().isKeywordSelector();
3879}
3880
3881/// Matches when the selector has the specified number of arguments
3882///
3883/// matcher = objCMessageExpr(numSelectorArgs(0));
3884/// matches self.bodyView in the code below
3885///
3886/// matcher = objCMessageExpr(numSelectorArgs(2));
3887/// matches the invocation of "loadHTMLString:baseURL:" but not that
3888/// of self.bodyView
3889/// \code
3890/// [self.bodyView loadHTMLString:html baseURL:NULL];
3891/// \endcode
3892AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3893 return Node.getSelector().getNumArgs() == N;
3894}
3895
3896/// Matches if the call or fold expression's callee expression matches.
3897///
3898/// Given
3899/// \code
3900/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3901/// void f() { f(); }
3902/// \endcode
3903/// callExpr(callee(expr()))
3904/// matches this->x(), x(), y.x(), f()
3905/// with callee(...)
3906/// matching this->x, x, y.x, f respectively
3907///
3908/// Given
3909/// \code
3910/// template <typename... Args>
3911/// auto sum(Args... args) {
3912/// return (0 + ... + args);
3913/// }
3914///
3915/// template <typename... Args>
3916/// auto multiply(Args... args) {
3917/// return (args * ... * 1);
3918/// }
3919/// \endcode
3920/// cxxFoldExpr(callee(expr()))
3921/// matches (args * ... * 1)
3922/// with callee(...)
3923/// matching *
3924///
3925/// Note: Callee cannot take the more general internal::Matcher<Expr>
3926/// because this introduces ambiguous overloads with calls to Callee taking a
3927/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3928/// implemented in terms of implicit casts.
3931 CXXFoldExpr),
3932 internal::Matcher<Stmt>, InnerMatcher, 0) {
3933 const auto *ExprNode = Node.getCallee();
3934 return (ExprNode != nullptr &&
3935 InnerMatcher.matches(*ExprNode, Finder, Builder));
3936}
3937
3938/// Matches 1) if the call expression's callee's declaration matches the
3939/// given matcher; or 2) if the Obj-C message expression's callee's method
3940/// declaration matches the given matcher.
3941///
3942/// Example matches y.x() (matcher = callExpr(callee(
3943/// cxxMethodDecl(hasName("x")))))
3944/// \code
3945/// class Y { public: void x(); };
3946/// void z() { Y y; y.x(); }
3947/// \endcode
3948///
3949/// Example 2. Matches [I foo] with
3950/// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3951///
3952/// \code
3953/// @interface I: NSObject
3954/// +(void)foo;
3955/// @end
3956/// ...
3957/// [I foo]
3958/// \endcode
3961 internal::Matcher<Decl>, InnerMatcher, 1) {
3962 if (isa<CallExpr>(&Node))
3963 return callExpr(hasDeclaration(InnerMatcher))
3964 .matches(Node, Finder, Builder);
3965 else {
3966 // The dynamic cast below is guaranteed to succeed as there are only 2
3967 // supported return types.
3968 const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
3969 const Decl *DeclNode = MsgNode->getMethodDecl();
3970 return (DeclNode != nullptr &&
3971 InnerMatcher.matches(*DeclNode, Finder, Builder));
3972 }
3973}
3974
3975/// Matches if the expression's or declaration's type matches a type
3976/// matcher.
3977///
3978/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3979/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3980/// and U (matcher = typedefDecl(hasType(asString("int")))
3981/// and friend class X (matcher = friendDecl(hasType("X"))
3982/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3983/// asString("class X")))
3984/// \code
3985/// class X {};
3986/// void y(X &x) { x; X z; }
3987/// typedef int U;
3988/// class Y { friend class X; };
3989/// class Z : public virtual X {};
3990/// \endcode
3992 hasType,
3995 internal::Matcher<QualType>, InnerMatcher, 0) {
3996 QualType QT = internal::getUnderlyingType(Node);
3997 if (!QT.isNull())
3998 return InnerMatcher.matches(QT, Finder, Builder);
3999 return false;
4000}
4001
4002/// Overloaded to match the declaration of the expression's or value
4003/// declaration's type.
4004///
4005/// In case of a value declaration (for example a variable declaration),
4006/// this resolves one layer of indirection. For example, in the value
4007/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
4008/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
4009/// declaration of x.
4010///
4011/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4012/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4013/// and friend class X (matcher = friendDecl(hasType("X"))
4014/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4015/// cxxRecordDecl(hasName("X"))))
4016/// \code
4017/// class X {};
4018/// void y(X &x) { x; X z; }
4019/// class Y { friend class X; };
4020/// class Z : public virtual X {};
4021/// \endcode
4022///
4023/// Example matches class Derived
4024/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
4025/// \code
4026/// class Base {};
4027/// class Derived : Base {};
4028/// \endcode
4029///
4030/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
4031/// Matcher<CXXBaseSpecifier>
4033 hasType,
4036 internal::Matcher<Decl>, InnerMatcher, 1) {
4037 QualType QT = internal::getUnderlyingType(Node);
4038 if (!QT.isNull())
4039 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
4040 return false;
4041}
4042
4043/// Matches if the type location of a node matches the inner matcher.
4044///
4045/// Examples:
4046/// \code
4047/// int x;
4048/// \endcode
4049/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
4050/// matches int x
4051///
4052/// \code
4053/// auto x = int(3);
4054/// \endcode
4055/// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
4056/// matches int(3)
4057///
4058/// \code
4059/// struct Foo { Foo(int, int); };
4060/// auto x = Foo(1, 2);
4061/// \endcode
4062/// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
4063/// matches Foo(1, 2)
4064///
4065/// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
4066/// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
4067/// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
4068/// Matcher<CXXUnresolvedConstructExpr>,
4069/// Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>,
4070/// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
4071/// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
4072/// Matcher<TypedefNameDecl>
4074 hasTypeLoc,
4081 internal::Matcher<TypeLoc>, Inner) {
4082 TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
4083 if (source == nullptr) {
4084 // This happens for example for implicit destructors.
4085 return false;
4086 }
4087 return Inner.matches(source->getTypeLoc(), Finder, Builder);
4088}
4089
4090/// Matches if the matched type is represented by the given string.
4091///
4092/// Given
4093/// \code
4094/// class Y { public: void x(); };
4095/// void z() { Y* y; y->x(); }
4096/// \endcode
4097/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
4098/// matches y->x()
4099AST_MATCHER_P(QualType, asString, std::string, Name) {
4100 return Name == Node.getAsString();
4101}
4102
4103/// Matches if the matched type is a pointer type and the pointee type
4104/// matches the specified matcher.
4105///
4106/// Example matches y->x()
4107/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
4108/// cxxRecordDecl(hasName("Y")))))))
4109/// \code
4110/// class Y { public: void x(); };
4111/// void z() { Y *y; y->x(); }
4112/// \endcode
4114 QualType, pointsTo, internal::Matcher<QualType>,
4115 InnerMatcher) {
4116 return (!Node.isNull() && Node->isAnyPointerType() &&
4117 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4118}
4119
4120/// Overloaded to match the pointee type's declaration.
4121AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
4122 InnerMatcher, 1) {
4123 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
4124 .matches(Node, Finder, Builder);
4125}
4126
4127/// Matches if the matched type matches the unqualified desugared
4128/// type of the matched node.
4129///
4130/// For example, in:
4131/// \code
4132/// class A {};
4133/// using B = A;
4134/// \endcode
4135/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4136/// both B and A.
4137AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4138 InnerMatcher) {
4139 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4140 Builder);
4141}
4142
4143/// Matches if the matched type is a reference type and the referenced
4144/// type matches the specified matcher.
4145///
4146/// Example matches X &x and const X &y
4147/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4148/// \code
4149/// class X {
4150/// void a(X b) {
4151/// X &x = b;
4152/// const X &y = b;
4153/// }
4154/// };
4155/// \endcode
4156AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4157 InnerMatcher) {
4158 return (!Node.isNull() && Node->isReferenceType() &&
4159 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4160}
4161
4162/// Matches QualTypes whose canonical type matches InnerMatcher.
4163///
4164/// Given:
4165/// \code
4166/// typedef int &int_ref;
4167/// int a;
4168/// int_ref b = a;
4169/// \endcode
4170///
4171/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4172/// declaration of b but \c
4173/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4174AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4175 InnerMatcher) {
4176 if (Node.isNull())
4177 return false;
4178 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4179}
4180
4181/// Overloaded to match the referenced type's declaration.
4182AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4183 InnerMatcher, 1) {
4184 return references(qualType(hasDeclaration(InnerMatcher)))
4185 .matches(Node, Finder, Builder);
4186}
4187
4188/// Matches on the implicit object argument of a member call expression. Unlike
4189/// `on`, matches the argument directly without stripping away anything.
4190///
4191/// Given
4192/// \code
4193/// class Y { public: void m(); };
4194/// Y g();
4195/// class X : public Y { void g(); };
4196/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4197/// \endcode
4198/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4199/// cxxRecordDecl(hasName("Y")))))
4200/// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
4201/// cxxMemberCallExpr(on(callExpr()))
4202/// does not match `(g()).m()`, because the parens are not ignored.
4203///
4204/// FIXME: Overload to allow directly matching types?
4205AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4206 internal::Matcher<Expr>, InnerMatcher) {
4207 const Expr *ExprNode = Node.getImplicitObjectArgument();
4208 return (ExprNode != nullptr &&
4209 InnerMatcher.matches(*ExprNode, Finder, Builder));
4210}
4211
4212/// Matches if the type of the expression's implicit object argument either
4213/// matches the InnerMatcher, or is a pointer to a type that matches the
4214/// InnerMatcher.
4215///
4216/// Given
4217/// \code
4218/// class Y { public: void m(); };
4219/// class X : public Y { void g(); };
4220/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4221/// \endcode
4222/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4223/// cxxRecordDecl(hasName("Y")))))
4224/// matches `y.m()`, `p->m()` and `x.m()`.
4225/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4226/// cxxRecordDecl(hasName("X")))))
4227/// matches `x.g()`.
4229 internal::Matcher<QualType>, InnerMatcher, 0) {
4230 return onImplicitObjectArgument(
4231 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4232 .matches(Node, Finder, Builder);
4233}
4234
4235/// Overloaded to match the type's declaration.
4237 internal::Matcher<Decl>, InnerMatcher, 1) {
4238 return onImplicitObjectArgument(
4239 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4240 .matches(Node, Finder, Builder);
4241}
4242
4243/// Matches a DeclRefExpr that refers to a declaration that matches the
4244/// specified matcher.
4245///
4246/// Example matches x in if(x)
4247/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4248/// \code
4249/// bool x;
4250/// if (x) {}
4251/// \endcode
4252AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4253 InnerMatcher) {
4254 const Decl *DeclNode = Node.getDecl();
4255 return (DeclNode != nullptr &&
4256 InnerMatcher.matches(*DeclNode, Finder, Builder));
4257}
4258
4259/// Matches if a node refers to a declaration through a specific
4260/// using shadow declaration.
4261///
4262/// Examples:
4263/// \code
4264/// namespace a { int f(); }
4265/// using a::f;
4266/// int x = f();
4267/// \endcode
4268/// declRefExpr(throughUsingDecl(anything()))
4269/// matches \c f
4270///
4271/// \code
4272/// namespace a { class X{}; }
4273/// using a::X;
4274/// X x;
4275/// \endcode
4276/// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4277/// matches \c X
4278///
4279/// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4282 UsingType),
4283 internal::Matcher<UsingShadowDecl>, Inner) {
4284 const NamedDecl *FoundDecl = Node.getFoundDecl();
4285 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4286 return Inner.matches(*UsingDecl, Finder, Builder);
4287 return false;
4288}
4289
4290/// Matches an \c OverloadExpr if any of the declarations in the set of
4291/// overloads matches the given matcher.
4292///
4293/// Given
4294/// \code
4295/// template <typename T> void foo(T);
4296/// template <typename T> void bar(T);
4297/// template <typename T> void baz(T t) {
4298/// foo(t);
4299/// bar(t);
4300/// }
4301/// \endcode
4302/// unresolvedLookupExpr(hasAnyDeclaration(
4303/// functionTemplateDecl(hasName("foo"))))
4304/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4305AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4306 InnerMatcher) {
4307 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4308 Node.decls_end(), Finder,
4309 Builder) != Node.decls_end();
4310}
4311
4312/// Matches the Decl of a DeclStmt which has a single declaration.
4313///
4314/// Given
4315/// \code
4316/// int a, b;
4317/// int c;
4318/// \endcode
4319/// declStmt(hasSingleDecl(anything()))
4320/// matches 'int c;' but not 'int a, b;'.
4321AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4322 if (Node.isSingleDecl()) {
4323 const Decl *FoundDecl = Node.getSingleDecl();
4324 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4325 }
4326 return false;
4327}
4328
4329/// Matches a variable declaration that has an initializer expression
4330/// that matches the given matcher.
4331///
4332/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4333/// \code
4334/// bool y() { return true; }
4335/// bool x = y();
4336/// \endcode
4338 VarDecl, hasInitializer, internal::Matcher<Expr>,
4339 InnerMatcher) {
4340 const Expr *Initializer = Node.getAnyInitializer();
4341 return (Initializer != nullptr &&
4342 InnerMatcher.matches(*Initializer, Finder, Builder));
4343}
4344
4345/// Matches a variable serving as the implicit variable for a lambda init-
4346/// capture.
4347///
4348/// Example matches x (matcher = varDecl(isInitCapture()))
4349/// \code
4350/// auto f = [x=3]() { return x; };
4351/// \endcode
4352AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4353
4354/// Matches each lambda capture in a lambda expression.
4355///
4356/// Given
4357/// \code
4358/// int main() {
4359/// int x, y;
4360/// float z;
4361/// auto f = [=]() { return x + y + z; };
4362/// }
4363/// \endcode
4364/// lambdaExpr(forEachLambdaCapture(
4365/// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4366/// will trigger two matches, binding for 'x' and 'y' respectively.
4367AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4368 internal::Matcher<LambdaCapture>, InnerMatcher) {
4369 BoundNodesTreeBuilder Result;
4370 bool Matched = false;
4371 for (const auto &Capture : Node.captures()) {
4372 if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4373 continue;
4374 BoundNodesTreeBuilder CaptureBuilder(*Builder);
4375 if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4376 Matched = true;
4377 Result.addMatch(CaptureBuilder);
4378 }
4379 }
4380 *Builder = std::move(Result);
4381 return Matched;
4382}
4383
4384/// \brief Matches a static variable with local scope.
4385///
4386/// Example matches y (matcher = varDecl(isStaticLocal()))
4387/// \code
4388/// void f() {
4389/// int x;
4390/// static int y;
4391/// }
4392/// static int z;
4393/// \endcode
4394AST_MATCHER(VarDecl, isStaticLocal) {
4395 return Node.isStaticLocal();
4396}
4397
4398/// Matches a variable declaration that has function scope and is a
4399/// non-static local variable.
4400///
4401/// Example matches x (matcher = varDecl(hasLocalStorage())
4402/// \code
4403/// void f() {
4404/// int x;
4405/// static int y;
4406/// }
4407/// int z;
4408/// \endcode
4409AST_MATCHER(VarDecl, hasLocalStorage) {
4410 return Node.hasLocalStorage();
4411}
4412
4413/// Matches a variable declaration that does not have local storage.
4414///
4415/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4416/// \code
4417/// void f() {
4418/// int x;
4419/// static int y;
4420/// }
4421/// int z;
4422/// \endcode
4423AST_MATCHER(VarDecl, hasGlobalStorage) {
4424 return Node.hasGlobalStorage();
4425}
4426
4427/// Matches a variable declaration that has automatic storage duration.
4428///
4429/// Example matches x, but not y, z, or a.
4430/// (matcher = varDecl(hasAutomaticStorageDuration())
4431/// \code
4432/// void f() {
4433/// int x;
4434/// static int y;
4435/// thread_local int z;
4436/// }
4437/// int a;
4438/// \endcode
4439AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4440 return Node.getStorageDuration() == SD_Automatic;
4441}
4442
4443/// Matches a variable declaration that has static storage duration.
4444/// It includes the variable declared at namespace scope and those declared
4445/// with "static" and "extern" storage class specifiers.
4446///
4447/// \code
4448/// void f() {
4449/// int x;
4450/// static int y;
4451/// thread_local int z;
4452/// }
4453/// int a;
4454/// static int b;
4455/// extern int c;
4456/// varDecl(hasStaticStorageDuration())
4457/// matches the function declaration y, a, b and c.
4458/// \endcode
4459AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4460 return Node.getStorageDuration() == SD_Static;
4461}
4462
4463/// Matches a variable declaration that has thread storage duration.
4464///
4465/// Example matches z, but not x, z, or a.
4466/// (matcher = varDecl(hasThreadStorageDuration())
4467/// \code
4468/// void f() {
4469/// int x;
4470/// static int y;
4471/// thread_local int z;
4472/// }
4473/// int a;
4474/// \endcode
4475AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4476 return Node.getStorageDuration() == SD_Thread;
4477}
4478
4479/// Matches a variable declaration that is an exception variable from
4480/// a C++ catch block, or an Objective-C \@catch statement.
4481///
4482/// Example matches x (matcher = varDecl(isExceptionVariable())
4483/// \code
4484/// void f(int y) {
4485/// try {
4486/// } catch (int x) {
4487/// }
4488/// }
4489/// \endcode
4490AST_MATCHER(VarDecl, isExceptionVariable) {
4491 return Node.isExceptionVariable();
4492}
4493
4494/// Checks that a call expression or a constructor call expression has
4495/// a specific number of arguments (including absent default arguments).
4496///
4497/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4498/// \code
4499/// void f(int x, int y);
4500/// f(0, 0);
4501/// \endcode
4506 unsigned, N) {
4507 unsigned NumArgs = Node.getNumArgs();
4508 if (!Finder->isTraversalIgnoringImplicitNodes())
4509 return NumArgs == N;
4510 while (NumArgs) {
4511 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4512 break;
4513 --NumArgs;
4514 }
4515 return NumArgs == N;
4516}
4517
4518/// Checks that a call expression or a constructor call expression has at least
4519/// the specified number of arguments (including absent default arguments).
4520///
4521/// Example matches f(0, 0) and g(0, 0, 0)
4522/// (matcher = callExpr(argumentCountAtLeast(2)))
4523/// \code
4524/// void f(int x, int y);
4525/// void g(int x, int y, int z);
4526/// f(0, 0);
4527/// g(0, 0, 0);
4528/// \endcode
4529AST_POLYMORPHIC_MATCHER_P(argumentCountAtLeast,
4533 unsigned, N) {
4534 unsigned NumArgs = Node.getNumArgs();
4535 if (!Finder->isTraversalIgnoringImplicitNodes())
4536 return NumArgs >= N;
4537 while (NumArgs) {
4538 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4539 break;
4540 --NumArgs;
4541 }
4542 return NumArgs >= N;
4543}
4544
4545/// Matches the n'th argument of a call expression or a constructor
4546/// call expression.
4547///
4548/// Example matches y in x(y)
4549/// (matcher = callExpr(hasArgument(0, declRefExpr())))
4550/// \code
4551/// void x(int) { int y; x(y); }
4552/// \endcode
4557 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4558 if (N >= Node.getNumArgs())
4559 return false;
4560 const Expr *Arg = Node.getArg(N);
4561 if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4562 return false;
4563 return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4564}
4565
4566/// Matches the operand that does not contain the parameter pack.
4567///
4568/// Example matches `(0 + ... + args)` and `(args * ... * 1)`
4569/// (matcher = cxxFoldExpr(hasFoldInit(expr())))
4570/// with hasFoldInit(...)
4571/// matching `0` and `1` respectively
4572/// \code
4573/// template <typename... Args>
4574/// auto sum(Args... args) {
4575/// return (0 + ... + args);
4576/// }
4577///
4578/// template <typename... Args>
4579/// auto multiply(Args... args) {
4580/// return (args * ... * 1);
4581/// }
4582/// \endcode
4583AST_MATCHER_P(CXXFoldExpr, hasFoldInit, internal::Matcher<Expr>, InnerMacher) {
4584 const auto *const Init = Node.getInit();
4585 return Init && InnerMacher.matches(*Init, Finder, Builder);
4586}
4587
4588/// Matches the operand that contains the parameter pack.
4589///
4590/// Example matches `(0 + ... + args)`
4591/// (matcher = cxxFoldExpr(hasPattern(expr())))
4592/// with hasPattern(...)
4593/// matching `args`
4594/// \code
4595/// template <typename... Args>
4596/// auto sum(Args... args) {
4597/// return (0 + ... + args);
4598/// }
4599///
4600/// template <typename... Args>
4601/// auto multiply(Args... args) {
4602/// return (args * ... * 1);
4603/// }
4604/// \endcode
4605AST_MATCHER_P(CXXFoldExpr, hasPattern, internal::Matcher<Expr>, InnerMacher) {
4606 const Expr *const Pattern = Node.getPattern();
4607 return Pattern && InnerMacher.matches(*Pattern, Finder, Builder);
4608}
4609
4610/// Matches right-folding fold expressions.
4611///
4612/// Example matches `(args * ... * 1)`
4613/// (matcher = cxxFoldExpr(isRightFold()))
4614/// \code
4615/// template <typename... Args>
4616/// auto sum(Args... args) {
4617/// return (0 + ... + args);
4618/// }
4619///
4620/// template <typename... Args>
4621/// auto multiply(Args... args) {
4622/// return (args * ... * 1);
4623/// }
4624/// \endcode
4625AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
4626
4627/// Matches left-folding fold expressions.
4628///
4629/// Example matches `(0 + ... + args)`
4630/// (matcher = cxxFoldExpr(isLeftFold()))
4631/// \code
4632/// template <typename... Args>
4633/// auto sum(Args... args) {
4634/// return (0 + ... + args);
4635/// }
4636///
4637/// template <typename... Args>
4638/// auto multiply(Args... args) {
4639/// return (args * ... * 1);
4640/// }
4641/// \endcode
4642AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
4643
4644/// Matches unary fold expressions, i.e. fold expressions without an
4645/// initializer.
4646///
4647/// Example matches `(args * ...)`
4648/// (matcher = cxxFoldExpr(isUnaryFold()))
4649/// \code
4650/// template <typename... Args>
4651/// auto sum(Args... args) {
4652/// return (0 + ... + args);
4653/// }
4654///
4655/// template <typename... Args>
4656/// auto multiply(Args... args) {
4657/// return (args * ...);
4658/// }
4659/// \endcode
4660AST_MATCHER(CXXFoldExpr, isUnaryFold) { return Node.getInit() == nullptr; }
4661
4662/// Matches binary fold expressions, i.e. fold expressions with an initializer.
4663///
4664/// Example matches `(0 + ... + args)`
4665/// (matcher = cxxFoldExpr(isBinaryFold()))
4666/// \code
4667/// template <typename... Args>
4668/// auto sum(Args... args) {
4669/// return (0 + ... + args);
4670/// }
4671///
4672/// template <typename... Args>
4673/// auto multiply(Args... args) {
4674/// return (args * ...);
4675/// }
4676/// \endcode
4677AST_MATCHER(CXXFoldExpr, isBinaryFold) { return Node.getInit() != nullptr; }
4678
4679/// Matches the n'th item of an initializer list expression.
4680///
4681/// Example matches y.
4682/// (matcher = initListExpr(hasInit(0, expr())))
4683/// \code
4684/// int x{y}.
4685/// \endcode
4686AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N, internal::Matcher<Expr>,
4687 InnerMatcher) {
4688 return N < Node.getNumInits() &&
4689 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4690}
4691
4692/// Matches declaration statements that contain a specific number of
4693/// declarations.
4694///
4695/// Example: Given
4696/// \code
4697/// int a, b;
4698/// int c;
4699/// int d = 2, e;
4700/// \endcode
4701/// declCountIs(2)
4702/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4703AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4704 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4705}
4706
4707/// Matches the n'th declaration of a declaration statement.
4708///
4709/// Note that this does not work for global declarations because the AST
4710/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4711/// DeclStmt's.
4712/// Example: Given non-global declarations
4713/// \code
4714/// int a, b = 0;
4715/// int c;
4716/// int d = 2, e;
4717/// \endcode
4718/// declStmt(containsDeclaration(
4719/// 0, varDecl(hasInitializer(anything()))))
4720/// matches only 'int d = 2, e;', and
4721/// declStmt(containsDeclaration(1, varDecl()))
4722/// \code
4723/// matches 'int a, b = 0' as well as 'int d = 2, e;'
4724/// but 'int c;' is not matched.
4725/// \endcode
4726AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4727 internal::Matcher<Decl>, InnerMatcher) {
4728 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4729 if (N >= NumDecls)
4730 return false;
4731 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4732 std::advance(Iterator, N);
4733 return InnerMatcher.matches(**Iterator, Finder, Builder);
4734}
4735
4736/// Matches a C++ catch statement that has a catch-all handler.
4737///
4738/// Given
4739/// \code
4740/// try {
4741/// // ...
4742/// } catch (int) {
4743/// // ...
4744/// } catch (...) {
4745/// // ...
4746/// }
4747/// \endcode
4748/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4750 return Node.getExceptionDecl() == nullptr;
4751}
4752
4753/// Matches a constructor initializer.
4754///
4755/// Given
4756/// \code
4757/// struct Foo {
4758/// Foo() : foo_(1) { }
4759/// int foo_;
4760/// };
4761/// \endcode
4762/// cxxRecordDecl(has(cxxConstructorDecl(
4763/// hasAnyConstructorInitializer(anything())
4764/// )))
4765/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4766AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4767 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4768 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4769 Node.init_end(), Finder, Builder);
4770 if (MatchIt == Node.init_end())
4771 return false;
4772 return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4773}
4774
4775/// Matches the field declaration of a constructor initializer.
4776///
4777/// Given
4778/// \code
4779/// struct Foo {
4780/// Foo() : foo_(1) { }
4781/// int foo_;
4782/// };
4783/// \endcode
4784/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4785/// forField(hasName("foo_"))))))
4786/// matches Foo
4787/// with forField matching foo_
4789 internal::Matcher<FieldDecl>, InnerMatcher) {
4790 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4791 return (NodeAsDecl != nullptr &&
4792 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4793}
4794
4795/// Matches the initializer expression of a constructor initializer.
4796///
4797/// Given
4798/// \code
4799/// struct Foo {
4800/// Foo() : foo_(1) { }
4801/// int foo_;
4802/// };
4803/// \endcode
4804/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4805/// withInitializer(integerLiteral(equals(1)))))))
4806/// matches Foo
4807/// with withInitializer matching (1)
4809 internal::Matcher<Expr>, InnerMatcher) {
4810 const Expr* NodeAsExpr = Node.getInit();
4811 return (NodeAsExpr != nullptr &&
4812 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4813}
4814
4815/// Matches a constructor initializer if it is explicitly written in
4816/// code (as opposed to implicitly added by the compiler).
4817///
4818/// Given
4819/// \code
4820/// struct Foo {
4821/// Foo() { }
4822/// Foo(int) : foo_("A") { }
4823/// string foo_;
4824/// };
4825/// \endcode
4826/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4827/// will match Foo(int), but not Foo()
4829 return Node.isWritten();
4830}
4831
4832/// Matches a constructor initializer if it is initializing a base, as
4833/// opposed to a member.
4834///
4835/// Given
4836/// \code
4837/// struct B {};
4838/// struct D : B {
4839/// int I;
4840/// D(int i) : I(i) {}
4841/// };
4842/// struct E : B {
4843/// E() : B() {}
4844/// };
4845/// \endcode
4846/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4847/// will match E(), but not match D(int).
4848AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4849 return Node.isBaseInitializer();
4850}
4851
4852/// Matches a constructor initializer if it is initializing a member, as
4853/// opposed to a base.
4854///
4855/// Given
4856/// \code
4857/// struct B {};
4858/// struct D : B {
4859/// int I;
4860/// D(int i) : I(i) {}
4861/// };
4862/// struct E : B {
4863/// E() : B() {}
4864/// };
4865/// \endcode
4866/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4867/// will match D(int), but not match E().
4868AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4869 return Node.isMemberInitializer();
4870}
4871
4872/// Matches any argument of a call expression or a constructor call
4873/// expression, or an ObjC-message-send expression.
4874///
4875/// Given
4876/// \code
4877/// void x(int, int, int) { int y; x(1, y, 42); }
4878/// \endcode
4879/// callExpr(hasAnyArgument(declRefExpr()))
4880/// matches x(1, y, 42)
4881/// with hasAnyArgument(...)
4882/// matching y
4883///
4884/// For ObjectiveC, given
4885/// \code
4886/// @interface I - (void) f:(int) y; @end
4887/// void foo(I *i) { [i f:12]; }
4888/// \endcode
4889/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4890/// matches [i f:12]
4895 internal::Matcher<Expr>, InnerMatcher) {
4896 for (const Expr *Arg : Node.arguments()) {
4897 if (Finder->isTraversalIgnoringImplicitNodes() &&
4898 isa<CXXDefaultArgExpr>(Arg))
4899 break;
4900 BoundNodesTreeBuilder Result(*Builder);
4901 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4902 *Builder = std::move(Result);
4903 return true;
4904 }
4905 }
4906 return false;
4907}
4908
4909/// Matches lambda captures.
4910///
4911/// Given
4912/// \code
4913/// int main() {
4914/// int x;
4915/// auto f = [x](){};
4916/// auto g = [x = 1](){};
4917/// }
4918/// \endcode
4919/// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4920/// `lambdaCapture()` matches `x` and `x=1`.
4921extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4922
4923/// Matches any capture in a lambda expression.
4924///
4925/// Given
4926/// \code
4927/// void foo() {
4928/// int t = 5;
4929/// auto f = [=](){ return t; };
4930/// }
4931/// \endcode
4932/// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4933/// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4934/// both match `[=](){ return t; }`.
4935AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4936 InnerMatcher) {
4937 for (const LambdaCapture &Capture : Node.captures()) {
4938 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4939 if (InnerMatcher.matches(Capture, Finder, &Result)) {
4940 *Builder = std::move(Result);
4941 return true;
4942 }
4943 }
4944 return false;
4945}
4946
4947/// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4948/// `VarDecl` can be a separate variable that is captured by value or
4949/// reference, or a synthesized variable if the capture has an initializer.
4950///
4951/// Given
4952/// \code
4953/// void foo() {
4954/// int x;
4955/// auto f = [x](){};
4956/// auto g = [x = 1](){};
4957/// }
4958/// \endcode
4959/// In the matcher
4960/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4961/// capturesVar(hasName("x")) matches `x` and `x = 1`.
4962AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
4963 InnerMatcher) {
4964 if (!Node.capturesVariable())
4965 return false;
4966 auto *capturedVar = Node.getCapturedVar();
4967 return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
4968}
4969
4970/// Matches a `LambdaCapture` that refers to 'this'.
4971///
4972/// Given
4973/// \code
4974/// class C {
4975/// int cc;
4976/// int f() {
4977/// auto l = [this]() { return cc; };
4978/// return l();
4979/// }
4980/// };
4981/// \endcode
4982/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
4983/// matches `[this]() { return cc; }`.
4984AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
4985
4986/// Matches a constructor call expression which uses list initialization.
4987AST_MATCHER(CXXConstructExpr, isListInitialization) {
4988 return Node.isListInitialization();
4989}
4990
4991/// Matches a constructor call expression which requires
4992/// zero initialization.
4993///
4994/// Given
4995/// \code
4996/// void foo() {
4997/// struct point { double x; double y; };
4998/// point pt[2] = { { 1.0, 2.0 } };
4999/// }
5000/// \endcode
5001/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
5002/// will match the implicit array filler for pt[1].
5003AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
5004 return Node.requiresZeroInitialization();
5005}
5006
5007/// Matches the n'th parameter of a function or an ObjC method
5008/// declaration or a block.
5009///
5010/// Given
5011/// \code
5012/// class X { void f(int x) {} };
5013/// \endcode
5014/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
5015/// matches f(int x) {}
5016/// with hasParameter(...)
5017/// matching int x
5018///
5019/// For ObjectiveC, given
5020/// \code
5021/// @interface I - (void) f:(int) y; @end
5022/// \endcode
5023//
5024/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
5025/// matches the declaration of method f with hasParameter
5026/// matching y.
5030 BlockDecl),
5031 unsigned, N, internal::Matcher<ParmVarDecl>,
5032 InnerMatcher) {
5033 return (N < Node.parameters().size()
5034 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
5035}
5036
5037/// Matches if the given method declaration declares a member function with an
5038/// explicit object parameter.
5039///
5040/// Given
5041/// \code
5042/// struct A {
5043/// int operator-(this A, int);
5044/// void fun(this A &&self);
5045/// static int operator()(int);
5046/// int operator+(int);
5047/// };
5048/// \endcode
5049///
5050/// cxxMethodDecl(isExplicitObjectMemberFunction()) matches the first two
5051/// methods but not the last two.
5052AST_MATCHER(CXXMethodDecl, isExplicitObjectMemberFunction) {
5053 return Node.isExplicitObjectMemberFunction();
5054}
5055
5056/// Matches all arguments and their respective ParmVarDecl.
5057///
5058/// Given
5059/// \code
5060/// void f(int i);
5061/// int y;
5062/// f(y);
5063/// \endcode
5064/// callExpr(
5065/// forEachArgumentWithParam(
5066/// declRefExpr(to(varDecl(hasName("y")))),
5067/// parmVarDecl(hasType(isInteger()))
5068/// ))
5069/// matches f(y);
5070/// with declRefExpr(...)
5071/// matching int y
5072/// and parmVarDecl(...)
5073/// matching int i
5074AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
5077 internal::Matcher<Expr>, ArgMatcher,
5078 internal::Matcher<ParmVarDecl>, ParamMatcher) {
5079 BoundNodesTreeBuilder Result;
5080 // The first argument of an overloaded member operator is the implicit object
5081 // argument of the method which should not be matched against a parameter, so
5082 // we skip over it here.
5083 BoundNodesTreeBuilder Matches;
5084 unsigned ArgIndex =
5086 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5087 .matches(Node, Finder, &Matches)
5088 ? 1
5089 : 0;
5090 int ParamIndex = 0;
5091 bool Matched = false;
5092 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
5093 BoundNodesTreeBuilder ArgMatches(*Builder);
5094 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
5095 Finder, &ArgMatches)) {
5096 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5098 hasParameter(ParamIndex, ParamMatcher)))),
5099 callExpr(callee(functionDecl(
5100 hasParameter(ParamIndex, ParamMatcher))))))
5101 .matches(Node, Finder, &ParamMatches)) {
5102 Result.addMatch(ParamMatches);
5103 Matched = true;
5104 }
5105 }
5106 ++ParamIndex;
5107 }
5108 *Builder = std::move(Result);
5109 return Matched;
5110}
5111
5112/// Matches all arguments and their respective types for a \c CallExpr or
5113/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
5114/// it works on calls through function pointers as well.
5115///
5116/// The difference is, that function pointers do not provide access to a
5117/// \c ParmVarDecl, but only the \c QualType for each argument.
5118///
5119/// Given
5120/// \code
5121/// void f(int i);
5122/// int y;
5123/// f(y);
5124/// void (*f_ptr)(int) = f;
5125/// f_ptr(y);
5126/// \endcode
5127/// callExpr(
5128/// forEachArgumentWithParamType(
5129/// declRefExpr(to(varDecl(hasName("y")))),
5130/// qualType(isInteger()).bind("type)
5131/// ))
5132/// matches f(y) and f_ptr(y)
5133/// with declRefExpr(...)
5134/// matching int y
5135/// and qualType(...)
5136/// matching int
5137AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
5140 internal::Matcher<Expr>, ArgMatcher,
5141 internal::Matcher<QualType>, ParamMatcher) {
5142 BoundNodesTreeBuilder Result;
5143 // The first argument of an overloaded member operator is the implicit object
5144 // argument of the method which should not be matched against a parameter, so
5145 // we skip over it here.
5146 BoundNodesTreeBuilder Matches;
5147 unsigned ArgIndex =
5149 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5150 .matches(Node, Finder, &Matches)
5151 ? 1
5152 : 0;
5153 const FunctionProtoType *FProto = nullptr;
5154
5155 if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
5156 if (const auto *Value =
5157 dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
5159
5160 // This does not necessarily lead to a `FunctionProtoType`,
5161 // e.g. K&R functions do not have a function prototype.
5162 if (QT->isFunctionPointerType())
5163 FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
5164
5165 if (QT->isMemberFunctionPointerType()) {
5166 const auto *MP = QT->getAs<MemberPointerType>();
5167 assert(MP && "Must be member-pointer if its a memberfunctionpointer");
5168 FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
5169 assert(FProto &&
5170 "The call must have happened through a member function "
5171 "pointer");
5172 }
5173 }
5174 }
5175
5176 unsigned ParamIndex = 0;
5177 bool Matched = false;
5178 unsigned NumArgs = Node.getNumArgs();
5179 if (FProto && FProto->isVariadic())
5180 NumArgs = std::min(NumArgs, FProto->getNumParams());
5181
5182 for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
5183 BoundNodesTreeBuilder ArgMatches(*Builder);
5184 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
5185 &ArgMatches)) {
5186 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5187
5188 // This test is cheaper compared to the big matcher in the next if.
5189 // Therefore, please keep this order.
5190 if (FProto && FProto->getNumParams() > ParamIndex) {
5191 QualType ParamType = FProto->getParamType(ParamIndex);
5192 if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
5193 Result.addMatch(ParamMatches);
5194 Matched = true;
5195 continue;
5196 }
5197 }
5199 hasParameter(ParamIndex, hasType(ParamMatcher))))),
5200 callExpr(callee(functionDecl(
5201 hasParameter(ParamIndex, hasType(ParamMatcher)))))))
5202 .matches(Node, Finder, &ParamMatches)) {
5203 Result.addMatch(ParamMatches);
5204 Matched = true;
5205 continue;
5206 }
5207 }
5208 }
5209 *Builder = std::move(Result);
5210 return Matched;
5211}
5212
5213/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
5214/// list. The parameter list could be that of either a block, function, or
5215/// objc-method.
5216///
5217///
5218/// Given
5219///
5220/// \code
5221/// void f(int a, int b, int c) {
5222/// }
5223/// \endcode
5224///
5225/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
5226///
5227/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
5228AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
5229 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
5230
5231 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
5232 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5233 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
5234 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5235 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
5236 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5237
5238 return false;
5239}
5240
5241/// Matches any parameter of a function or an ObjC method declaration or a
5242/// block.
5243///
5244/// Does not match the 'this' parameter of a method.
5245///
5246/// Given
5247/// \code
5248/// class X { void f(int x, int y, int z) {} };
5249/// \endcode
5250/// cxxMethodDecl(hasAnyParameter(hasName("y")))
5251/// matches f(int x, int y, int z) {}
5252/// with hasAnyParameter(...)
5253/// matching int y
5254///
5255/// For ObjectiveC, given
5256/// \code
5257/// @interface I - (void) f:(int) y; @end
5258/// \endcode
5259//
5260/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5261/// matches the declaration of method f with hasParameter
5262/// matching y.
5263///
5264/// For blocks, given
5265/// \code
5266/// b = ^(int y) { printf("%d", y) };
5267/// \endcode
5268///
5269/// the matcher blockDecl(hasAnyParameter(hasName("y")))
5270/// matches the declaration of the block b with hasParameter
5271/// matching y.
5275 BlockDecl),
5276 internal::Matcher<ParmVarDecl>,
5277 InnerMatcher) {
5278 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5279 Node.param_end(), Finder,
5280 Builder) != Node.param_end();
5281}
5282
5283/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5284/// specific parameter count.
5285///
5286/// Given
5287/// \code
5288/// void f(int i) {}
5289/// void g(int i, int j) {}
5290/// void h(int i, int j);
5291/// void j(int i);
5292/// void k(int x, int y, int z, ...);
5293/// \endcode
5294/// functionDecl(parameterCountIs(2))
5295/// matches \c g and \c h
5296/// functionProtoType(parameterCountIs(2))
5297/// matches \c g and \c h
5298/// functionProtoType(parameterCountIs(3))
5299/// matches \c k
5303 unsigned, N) {
5304 return Node.getNumParams() == N;
5305}
5306
5307/// Matches classTemplateSpecialization, templateSpecializationType and
5308/// functionDecl nodes where the template argument matches the inner matcher.
5309/// This matcher may produce multiple matches.
5310///
5311/// Given
5312/// \code
5313/// template <typename T, unsigned N, unsigned M>
5314/// struct Matrix {};
5315///
5316/// constexpr unsigned R = 2;
5317/// Matrix<int, R * 2, R * 4> M;
5318///
5319/// template <typename T, typename U>
5320/// void f(T&& t, U&& u) {}
5321///
5322/// bool B = false;
5323/// f(R, B);
5324/// \endcode
5325/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5326/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5327/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5328/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5329/// and 'bool'
5331 forEachTemplateArgument,
5334 internal::Matcher<TemplateArgument>, InnerMatcher) {
5335 ArrayRef<TemplateArgument> TemplateArgs =
5336 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5337 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5338 bool Matched = false;
5339 for (const auto &Arg : TemplateArgs) {
5340 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5341 if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5342 Matched = true;
5343 Result.addMatch(ArgBuilder);
5344 }
5345 }
5346 *Builder = std::move(Result);
5347 return Matched;
5348}
5349
5350/// Matches \c FunctionDecls that have a noreturn attribute.
5351///
5352/// Given
5353/// \code
5354/// void nope();
5355/// [[noreturn]] void a();
5356/// __attribute__((noreturn)) void b();
5357/// struct c { [[noreturn]] c(); };
5358/// \endcode
5359/// functionDecl(isNoReturn())
5360/// matches all of those except
5361/// \code
5362/// void nope();
5363/// \endcode
5364AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5365
5366/// Matches the return type of a function declaration.
5367///
5368/// Given:
5369/// \code
5370/// class X { int f() { return 1; } };
5371/// \endcode
5372/// cxxMethodDecl(returns(asString("int")))
5373/// matches int f() { return 1; }
5375 internal::Matcher<QualType>, InnerMatcher) {
5376 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5377}
5378
5379/// Matches extern "C" function or variable declarations.
5380///
5381/// Given:
5382/// \code
5383/// extern "C" void f() {}
5384/// extern "C" { void g() {} }
5385/// void h() {}
5386/// extern "C" int x = 1;
5387/// extern "C" int y = 2;
5388/// int z = 3;
5389/// \endcode
5390/// functionDecl(isExternC())
5391/// matches the declaration of f and g, but not the declaration of h.
5392/// varDecl(isExternC())
5393/// matches the declaration of x and y, but not the declaration of z.
5395 VarDecl)) {
5396 return Node.isExternC();
5397}
5398
5399/// Matches variable/function declarations that have "static" storage
5400/// class specifier ("static" keyword) written in the source.
5401///
5402/// Given:
5403/// \code
5404/// static void f() {}
5405/// static int i = 0;
5406/// extern int j;
5407/// int k;
5408/// \endcode
5409/// functionDecl(isStaticStorageClass())
5410/// matches the function declaration f.
5411/// varDecl(isStaticStorageClass())
5412/// matches the variable declaration i.
5413AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5415 VarDecl)) {
5416 return Node.getStorageClass() == SC_Static;
5417}
5418
5419/// Matches deleted function declarations.
5420///
5421/// Given:
5422/// \code
5423/// void Func();
5424/// void DeletedFunc() = delete;
5425/// \endcode
5426/// functionDecl(isDeleted())
5427/// matches the declaration of DeletedFunc, but not Func.
5429 return Node.isDeleted();
5430}
5431
5432/// Matches defaulted function declarations.
5433///
5434/// Given:
5435/// \code
5436/// class A { ~A(); };
5437/// class B { ~B() = default; };
5438/// \endcode
5439/// functionDecl(isDefaulted())
5440/// matches the declaration of ~B, but not ~A.
5442 return Node.isDefaulted();
5443}
5444
5445/// Matches weak function declarations.
5446///
5447/// Given:
5448/// \code
5449/// void foo() __attribute__((__weakref__("__foo")));
5450/// void bar();
5451/// \endcode
5452/// functionDecl(isWeak())
5453/// matches the weak declaration "foo", but not "bar".
5454AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5455
5456/// Matches functions that have a dynamic exception specification.
5457///
5458/// Given:
5459/// \code
5460/// void f();
5461/// void g() noexcept;
5462/// void h() noexcept(true);
5463/// void i() noexcept(false);
5464/// void j() throw();
5465/// void k() throw(int);
5466/// void l() throw(...);
5467/// \endcode
5468/// functionDecl(hasDynamicExceptionSpec()) and
5469/// functionProtoType(hasDynamicExceptionSpec())
5470/// match the declarations of j, k, and l, but not f, g, h, or i.
5471AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5474 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5475 return FnTy->hasDynamicExceptionSpec();
5476 return false;
5477}
5478
5479/// Matches functions that have a non-throwing exception specification.
5480///
5481/// Given:
5482/// \code
5483/// void f();
5484/// void g() noexcept;
5485/// void h() throw();
5486/// void i() throw(int);
5487/// void j() noexcept(false);
5488/// \endcode
5489/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5490/// match the declarations of g, and h, but not f, i or j.
5494 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5495
5496 // If the function does not have a prototype, then it is assumed to be a
5497 // throwing function (as it would if the function did not have any exception
5498 // specification).
5499 if (!FnTy)
5500 return false;
5501
5502 // Assume the best for any unresolved exception specification.
5504 return true;
5505
5506 return FnTy->isNothrow();
5507}
5508
5509/// Matches consteval function declarations and if consteval/if ! consteval
5510/// statements.
5511///
5512/// Given:
5513/// \code
5514/// consteval int a();
5515/// void b() { if consteval {} }
5516/// void c() { if ! consteval {} }
5517/// void d() { if ! consteval {} else {} }
5518/// \endcode
5519/// functionDecl(isConsteval())
5520/// matches the declaration of "int a()".
5521/// ifStmt(isConsteval())
5522/// matches the if statement in "void b()", "void c()", "void d()".
5525 return Node.isConsteval();
5526}
5527
5528/// Matches constexpr variable and function declarations,
5529/// and if constexpr.
5530///
5531/// Given:
5532/// \code
5533/// constexpr int foo = 42;
5534/// constexpr int bar();
5535/// void baz() { if constexpr(1 > 0) {} }
5536/// \endcode
5537/// varDecl(isConstexpr())
5538/// matches the declaration of foo.
5539/// functionDecl(isConstexpr())
5540/// matches the declaration of bar.
5541/// ifStmt(isConstexpr())
5542/// matches the if statement in baz.
5546 IfStmt)) {
5547 return Node.isConstexpr();
5548}
5549
5550/// Matches constinit variable declarations.
5551///
5552/// Given:
5553/// \code
5554/// constinit int foo = 42;
5555/// constinit const char* bar = "bar";
5556/// int baz = 42;
5557/// [[clang::require_constant_initialization]] int xyz = 42;
5558/// \endcode
5559/// varDecl(isConstinit())
5560/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5561AST_MATCHER(VarDecl, isConstinit) {
5562 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5563 return CIA->isConstinit();
5564 return false;
5565}
5566
5567/// Matches selection statements with initializer.
5568///
5569/// Given:
5570/// \code
5571/// void foo() {
5572/// if (int i = foobar(); i > 0) {}
5573/// switch (int i = foobar(); i) {}
5574/// for (auto& a = get_range(); auto& x : a) {}
5575/// }
5576/// void bar() {
5577/// if (foobar() > 0) {}
5578/// switch (foobar()) {}
5579/// for (auto& x : get_range()) {}
5580/// }
5581/// \endcode
5582/// ifStmt(hasInitStatement(anything()))
5583/// matches the if statement in foo but not in bar.
5584/// switchStmt(hasInitStatement(anything()))
5585/// matches the switch statement in foo but not in bar.
5586/// cxxForRangeStmt(hasInitStatement(anything()))
5587/// matches the range for statement in foo but not in bar.
5591 internal::Matcher<Stmt>, InnerMatcher) {
5592 const Stmt *Init = Node.getInit();
5593 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5594}
5595
5596/// Matches the condition expression of an if statement, for loop,
5597/// switch statement or conditional operator.
5598///
5599/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5600/// \code
5601/// if (true) {}
5602/// \endcode
5604 hasCondition,
5607 internal::Matcher<Expr>, InnerMatcher) {
5608 const Expr *const Condition = Node.getCond();
5609 return (Condition != nullptr &&
5610 InnerMatcher.matches(*Condition, Finder, Builder));
5611}
5612
5613/// Matches the then-statement of an if statement.
5614///
5615/// Examples matches the if statement
5616/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5617/// \code
5618/// if (false) true; else false;
5619/// \endcode
5620AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5621 const Stmt *const Then = Node.getThen();
5622 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5623}
5624
5625/// Matches the else-statement of an if statement.
5626///
5627/// Examples matches the if statement
5628/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5629/// \code
5630/// if (false) false; else true;
5631/// \endcode
5632AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5633 const Stmt *const Else = Node.getElse();
5634 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5635}
5636
5637/// Matches if a node equals a previously bound node.
5638///
5639/// Matches a node if it equals the node previously bound to \p ID.
5640///
5641/// Given
5642/// \code
5643/// class X { int a; int b; };
5644/// \endcode
5645/// cxxRecordDecl(
5646/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5647/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5648/// matches the class \c X, as \c a and \c b have the same type.
5649///
5650/// Note that when multiple matches are involved via \c forEach* matchers,
5651/// \c equalsBoundNodes acts as a filter.
5652/// For example:
5653/// compoundStmt(
5654/// forEachDescendant(varDecl().bind("d")),
5655/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5656/// will trigger a match for each combination of variable declaration
5657/// and reference to that variable declaration within a compound statement.
5660 QualType),
5661 std::string, ID) {
5662 // FIXME: Figure out whether it makes sense to allow this
5663 // on any other node types.
5664 // For *Loc it probably does not make sense, as those seem
5665 // unique. For NestedNameSepcifier it might make sense, as
5666 // those also have pointer identity, but I'm not sure whether
5667 // they're ever reused.
5668 internal::NotEqualsBoundNodePredicate Predicate;
5669 Predicate.ID = ID;
5670 Predicate.Node = DynTypedNode::create(Node);
5671 return Builder->removeBindings(Predicate);
5672}
5673
5674/// Matches the condition variable statement in an if statement.
5675///
5676/// Given
5677/// \code
5678/// if (A* a = GetAPointer()) {}
5679/// \endcode
5680/// hasConditionVariableStatement(...)
5681/// matches 'A* a = GetAPointer()'.
5682AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5683 internal::Matcher<DeclStmt>, InnerMatcher) {
5684 const DeclStmt* const DeclarationStatement =
5685 Node.getConditionVariableDeclStmt();
5686 return DeclarationStatement != nullptr &&
5687 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5688}
5689
5690/// Matches the index expression of an array subscript expression.
5691///
5692/// Given
5693/// \code
5694/// int i[5];
5695/// void f() { i[1] = 42; }
5696/// \endcode
5697/// arraySubscriptExpression(hasIndex(integerLiteral()))
5698/// matches \c i[1] with the \c integerLiteral() matching \c 1
5700 internal::Matcher<Expr>, InnerMatcher) {
5701 if (const Expr* Expression = Node.getIdx())
5702 return InnerMatcher.matches(*Expression, Finder, Builder);
5703 return false;
5704}
5705
5706/// Matches the base expression of an array subscript expression.
5707///
5708/// Given
5709/// \code
5710/// int i[5];
5711/// void f() { i[1] = 42; }
5712/// \endcode
5713/// arraySubscriptExpression(hasBase(implicitCastExpr(
5714/// hasSourceExpression(declRefExpr()))))
5715/// matches \c i[1] with the \c declRefExpr() matching \c i
5717 internal::Matcher<Expr>, InnerMatcher) {
5718 if (const Expr* Expression = Node.getBase())
5719 return InnerMatcher.matches(*Expression, Finder, Builder);
5720 return false;
5721}
5722
5723/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5724/// definition that has a given body. Note that in case of functions or
5725/// coroutines this matcher only matches the definition itself and not the
5726/// other declarations of the same function or coroutine.
5727///
5728/// Given
5729/// \code
5730/// for (;;) {}
5731/// \endcode
5732/// forStmt(hasBody(compoundStmt()))
5733/// matches 'for (;;) {}'
5734/// with compoundStmt()
5735/// matching '{}'
5736///
5737/// Given
5738/// \code
5739/// void f();
5740/// void f() {}
5741/// \endcode
5742/// functionDecl(hasBody(compoundStmt()))
5743/// matches 'void f() {}'
5744/// with compoundStmt()
5745/// matching '{}'
5746/// but does not match 'void f();'
5748 hasBody,
5751 internal::Matcher<Stmt>, InnerMatcher) {
5752 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5753 return false;
5754 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5755 return (Statement != nullptr &&
5756 InnerMatcher.matches(*Statement, Finder, Builder));
5757}
5758
5759/// Matches a function declaration that has a given body present in the AST.
5760/// Note that this matcher matches all the declarations of a function whose
5761/// body is present in the AST.
5762///
5763/// Given
5764/// \code
5765/// void f();
5766/// void f() {}
5767/// void g();
5768/// \endcode
5769/// functionDecl(hasAnyBody(compoundStmt()))
5770/// matches both 'void f();'
5771/// and 'void f() {}'
5772/// with compoundStmt()
5773/// matching '{}'
5774/// but does not match 'void g();'
5776 internal::Matcher<Stmt>, InnerMatcher) {
5777 const Stmt *const Statement = Node.getBody();
5778 return (Statement != nullptr &&
5779 InnerMatcher.matches(*Statement, Finder, Builder));
5780}
5781
5782
5783/// Matches compound statements where at least one substatement matches
5784/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5785///
5786/// Given
5787/// \code
5788/// { {}; 1+2; }
5789/// \endcode
5790/// hasAnySubstatement(compoundStmt())
5791/// matches '{ {}; 1+2; }'
5792/// with compoundStmt()
5793/// matching '{}'
5794AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5796 StmtExpr),
5797 internal::Matcher<Stmt>, InnerMatcher) {
5798 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5799 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5800 CS->body_end(), Finder,
5801 Builder) != CS->body_end();
5802}
5803
5804/// Checks that a compound statement contains a specific number of
5805/// child statements.
5806///
5807/// Example: Given
5808/// \code
5809/// { for (;;) {} }
5810/// \endcode
5811/// compoundStmt(statementCountIs(0)))
5812/// matches '{}'
5813/// but does not match the outer compound statement.
5814AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5815 return Node.size() == N;
5816}
5817
5818/// Matches literals that are equal to the given value of type ValueT.
5819///
5820/// Given
5821/// \code
5822/// f('\0', false, 3.14, 42);
5823/// \endcode
5824/// characterLiteral(equals(0))
5825/// matches '\0'
5826/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5827/// match false
5828/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5829/// match 3.14
5830/// integerLiteral(equals(42))
5831/// matches 42
5832///
5833/// Note that you cannot directly match a negative numeric literal because the
5834/// minus sign is not part of the literal: It is a unary operator whose operand
5835/// is the positive numeric literal. Instead, you must use a unaryOperator()
5836/// matcher to match the minus sign:
5837///
5838/// unaryOperator(hasOperatorName("-"),
5839/// hasUnaryOperand(integerLiteral(equals(13))))
5840///
5841/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5842/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5843template <typename ValueT>
5844internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5845 void(internal::AllNodeBaseTypes), ValueT>
5846equals(const ValueT &Value) {
5847 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5848 void(internal::AllNodeBaseTypes), ValueT>(
5849 Value);
5850}
5851
5856 bool, Value, 0) {
5857 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5858 .matchesNode(Node);
5859}
5860
5865 unsigned, Value, 1) {
5866 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5867 .matchesNode(Node);
5868}
5869
5875 double, Value, 2) {
5876 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5877 .matchesNode(Node);
5878}
5879
5880/// Matches the operator Name of operator expressions and fold expressions
5881/// (binary or unary).
5882///
5883/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5884/// \code
5885/// !(a || b)
5886/// \endcode
5887///
5888/// Example matches `(0 + ... + args)`
5889/// (matcher = cxxFoldExpr(hasOperatorName("+")))
5890/// \code
5891/// template <typename... Args>
5892/// auto sum(Args... args) {
5893/// return (0 + ... + args);
5894/// }
5895/// \endcode
5897 hasOperatorName,
5901 std::string, Name) {
5902 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5903 return *OpName == Name;
5904 return false;
5905}
5906
5907/// Matches operator expressions (binary or unary) that have any of the
5908/// specified names.
5909///
5910/// hasAnyOperatorName("+", "-")
5911/// Is equivalent to
5912/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5913extern const internal::VariadicFunction<
5914 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5918 std::vector<std::string>>,
5921
5922/// Matches all kinds of assignment operators.
5923///
5924/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5925/// \code
5926/// if (a == b)
5927/// a += b;
5928/// \endcode
5929///
5930/// Example 2: matches s1 = s2
5931/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5932/// \code
5933/// struct S { S& operator=(const S&); };
5934/// void x() { S s1, s2; s1 = s2; }
5935/// \endcode
5937 isAssignmentOperator,
5940 return Node.isAssignmentOp();
5941}
5942
5943/// Matches comparison operators.
5944///
5945/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5946/// \code
5947/// if (a == b)
5948/// a += b;
5949/// \endcode
5950///
5951/// Example 2: matches s1 < s2
5952/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5953/// \code
5954/// struct S { bool operator<(const S& other); };
5955/// void x(S s1, S s2) { bool b1 = s1 < s2; }
5956/// \endcode
5958 isComparisonOperator,
5961 return Node.isComparisonOp();
5962}
5963
5964/// Matches the left hand side of binary operator expressions.
5965///
5966/// Example matches a (matcher = binaryOperator(hasLHS()))
5967/// \code
5968/// a || b
5969/// \endcode
5971 hasLHS,
5975 internal::Matcher<Expr>, InnerMatcher) {
5976 const Expr *LeftHandSide = internal::getLHS(Node);
5977 return (LeftHandSide != nullptr &&
5978 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
5979}
5980
5981/// Matches the right hand side of binary operator expressions.
5982///
5983/// Example matches b (matcher = binaryOperator(hasRHS()))
5984/// \code
5985/// a || b
5986/// \endcode
5988 hasRHS,
5992 internal::Matcher<Expr>, InnerMatcher) {
5993 const Expr *RightHandSide = internal::getRHS(Node);
5994 return (RightHandSide != nullptr &&
5995 InnerMatcher.matches(*RightHandSide, Finder, Builder));
5996}
5997
5998/// Matches if either the left hand side or the right hand side of a
5999/// binary operator or fold expression matches.
6001 hasEitherOperand,
6004 internal::Matcher<Expr>, InnerMatcher) {
6005 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6006 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
6007 .matches(Node, Finder, Builder);
6008}
6009
6010/// Matches if both matchers match with opposite sides of the binary operator
6011/// or fold expression.
6012///
6013/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
6014/// integerLiteral(equals(2)))
6015/// \code
6016/// 1 + 2 // Match
6017/// 2 + 1 // Match
6018/// 1 + 1 // No match
6019/// 2 + 2 // No match
6020/// \endcode
6022 hasOperands,
6025 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
6026 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6027 anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
6028 allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
6029 .matches(Node, Finder, Builder);
6030}
6031
6032/// Matches if the operand of a unary operator matches.
6033///
6034/// Example matches true (matcher = hasUnaryOperand(
6035/// cxxBoolLiteral(equals(true))))
6036/// \co