clang 20.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 templateSpecializationTypes, class template specializations,
768/// variable template specializations, and function template specializations
769/// that have at least one TemplateArgument matching the given 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 templateSpecializationType, class template specializations,
1051/// variable template specializations, and function template specializations
1052/// where the n'th TemplateArgument matches the given InnerMatcher.
1053///
1054/// Given
1055/// \code
1056/// template<typename T, typename U> class A {};
1057/// A<bool, int> b;
1058/// A<int, bool> c;
1059///
1060/// template<typename T> void f() {}
1061/// void func() { f<int>(); };
1062/// \endcode
1063/// classTemplateSpecializationDecl(hasTemplateArgument(
1064/// 1, refersToType(asString("int"))))
1065/// matches the specialization \c A<bool, int>
1066///
1067/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1068/// matches the specialization \c f<int>
1070 hasTemplateArgument,
1074 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1076 internal::getTemplateSpecializationArgs(Node);
1077 if (List.size() <= N)
1078 return false;
1079 return InnerMatcher.matches(List[N], Finder, Builder);
1080}
1081
1082/// Matches if the number of template arguments equals \p N.
1083///
1084/// Given
1085/// \code
1086/// template<typename T> struct C {};
1087/// C<int> c;
1088/// \endcode
1089/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1090/// matches C<int>.
1092 templateArgumentCountIs,
1095 unsigned, N) {
1096 return internal::getTemplateSpecializationArgs(Node).size() == N;
1097}
1098
1099/// Matches a TemplateArgument that refers to a certain type.
1100///
1101/// Given
1102/// \code
1103/// struct X {};
1104/// template<typename T> struct A {};
1105/// A<X> a;
1106/// \endcode
1107/// classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
1108/// recordType(hasDeclaration(recordDecl(hasName("X")))))))
1109/// matches the specialization of \c struct A generated by \c A<X>.
1111 internal::Matcher<QualType>, InnerMatcher) {
1112 if (Node.getKind() != TemplateArgument::Type)
1113 return false;
1114 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1115}
1116
1117/// Matches a TemplateArgument that refers to a certain template.
1118///
1119/// Given
1120/// \code
1121/// template<template <typename> class S> class X {};
1122/// template<typename T> class Y {};
1123/// X<Y> xi;
1124/// \endcode
1125/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1126/// refersToTemplate(templateName())))
1127/// matches the specialization \c X<Y>
1129 internal::Matcher<TemplateName>, InnerMatcher) {
1130 if (Node.getKind() != TemplateArgument::Template)
1131 return false;
1132 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1133}
1134
1135/// Matches a canonical TemplateArgument that refers to a certain
1136/// declaration.
1137///
1138/// Given
1139/// \code
1140/// struct B { int next; };
1141/// template<int(B::*next_ptr)> struct A {};
1142/// A<&B::next> a;
1143/// \endcode
1144/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1145/// refersToDeclaration(fieldDecl(hasName("next")))))
1146/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1147/// \c B::next
1148AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1149 internal::Matcher<Decl>, InnerMatcher) {
1150 if (Node.getKind() == TemplateArgument::Declaration)
1151 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1152 return false;
1153}
1154
1155/// Matches a sugar TemplateArgument that refers to a certain expression.
1156///
1157/// Given
1158/// \code
1159/// struct B { int next; };
1160/// template<int(B::*next_ptr)> struct A {};
1161/// A<&B::next> a;
1162/// \endcode
1163/// templateSpecializationType(hasAnyTemplateArgument(
1164/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1165/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1166/// \c B::next
1167AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1168 if (Node.getKind() == TemplateArgument::Expression)
1169 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1170 return false;
1171}
1172
1173/// Matches a TemplateArgument that is an integral value.
1174///
1175/// Given
1176/// \code
1177/// template<int T> struct C {};
1178/// C<42> c;
1179/// \endcode
1180/// classTemplateSpecializationDecl(
1181/// hasAnyTemplateArgument(isIntegral()))
1182/// matches the implicit instantiation of C in C<42>
1183/// with isIntegral() matching 42.
1185 return Node.getKind() == TemplateArgument::Integral;
1186}
1187
1188/// Matches a TemplateArgument that refers to an integral type.
1189///
1190/// Given
1191/// \code
1192/// template<int T> struct C {};
1193/// C<42> c;
1194/// \endcode
1195/// classTemplateSpecializationDecl(
1196/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1197/// matches the implicit instantiation of C in C<42>.
1198AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1199 internal::Matcher<QualType>, InnerMatcher) {
1200 if (Node.getKind() != TemplateArgument::Integral)
1201 return false;
1202 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1203}
1204
1205/// Matches a TemplateArgument of integral type with a given value.
1206///
1207/// Note that 'Value' is a string as the template argument's value is
1208/// an arbitrary precision integer. 'Value' must be euqal to the canonical
1209/// representation of that integral value in base 10.
1210///
1211/// Given
1212/// \code
1213/// template<int T> struct C {};
1214/// C<42> c;
1215/// \endcode
1216/// classTemplateSpecializationDecl(
1217/// hasAnyTemplateArgument(equalsIntegralValue("42")))
1218/// matches the implicit instantiation of C in C<42>.
1219AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1220 std::string, Value) {
1221 if (Node.getKind() != TemplateArgument::Integral)
1222 return false;
1223 return toString(Node.getAsIntegral(), 10) == Value;
1224}
1225
1226/// Matches an Objective-C autorelease pool statement.
1227///
1228/// Given
1229/// \code
1230/// @autoreleasepool {
1231/// int x = 0;
1232/// }
1233/// \endcode
1234/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1235/// inside the autorelease pool.
1236extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1238
1239/// Matches any value declaration.
1240///
1241/// Example matches A, B, C and F
1242/// \code
1243/// enum X { A, B, C };
1244/// void F();
1245/// \endcode
1246extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1247
1248/// Matches C++ constructor declarations.
1249///
1250/// Example matches Foo::Foo() and Foo::Foo(int)
1251/// \code
1252/// class Foo {
1253/// public:
1254/// Foo();
1255/// Foo(int);
1256/// int DoSomething();
1257/// };
1258/// \endcode
1259extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1261
1262/// Matches explicit C++ destructor declarations.
1263///
1264/// Example matches Foo::~Foo()
1265/// \code
1266/// class Foo {
1267/// public:
1268/// virtual ~Foo();
1269/// };
1270/// \endcode
1271extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1273
1274/// Matches enum declarations.
1275///
1276/// Example matches X
1277/// \code
1278/// enum X {
1279/// A, B, C
1280/// };
1281/// \endcode
1282extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1283
1284/// Matches enum constants.
1285///
1286/// Example matches A, B, C
1287/// \code
1288/// enum X {
1289/// A, B, C
1290/// };
1291/// \endcode
1292extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1294
1295/// Matches tag declarations.
1296///
1297/// Example matches X, Z, U, S, E
1298/// \code
1299/// class X;
1300/// template<class T> class Z {};
1301/// struct S {};
1302/// union U {};
1303/// enum E {
1304/// A, B, C
1305/// };
1306/// \endcode
1307extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1308
1309/// Matches method declarations.
1310///
1311/// Example matches y
1312/// \code
1313/// class X { void y(); };
1314/// \endcode
1315extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1317
1318/// Matches conversion operator declarations.
1319///
1320/// Example matches the operator.
1321/// \code
1322/// class X { operator int() const; };
1323/// \endcode
1324extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1326
1327/// Matches user-defined and implicitly generated deduction guide.
1328///
1329/// Example matches the deduction guide.
1330/// \code
1331/// template<typename T>
1332/// class X { X(int) };
1333/// X(int) -> X<int>;
1334/// \endcode
1335extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1337
1338/// Matches concept declarations.
1339///
1340/// Example matches integral
1341/// \code
1342/// template<typename T>
1343/// concept integral = std::is_integral_v<T>;
1344/// \endcode
1345extern const internal::VariadicDynCastAllOfMatcher<Decl, ConceptDecl>
1347
1348/// Matches variable declarations.
1349///
1350/// Note: this does not match declarations of member variables, which are
1351/// "field" declarations in Clang parlance.
1352///
1353/// Example matches a
1354/// \code
1355/// int a;
1356/// \endcode
1357extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1358
1359/// Matches field declarations.
1360///
1361/// Given
1362/// \code
1363/// class X { int m; };
1364/// \endcode
1365/// fieldDecl()
1366/// matches 'm'.
1367extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1368
1369/// Matches indirect field declarations.
1370///
1371/// Given
1372/// \code
1373/// struct X { struct { int a; }; };
1374/// \endcode
1375/// indirectFieldDecl()
1376/// matches 'a'.
1377extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1379
1380/// Matches function declarations.
1381///
1382/// Example matches f
1383/// \code
1384/// void f();
1385/// \endcode
1386extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1388
1389/// Matches C++ function template declarations.
1390///
1391/// Example matches f
1392/// \code
1393/// template<class T> void f(T t) {}
1394/// \endcode
1395extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1397
1398/// Matches friend declarations.
1399///
1400/// Given
1401/// \code
1402/// class X { friend void foo(); };
1403/// \endcode
1404/// friendDecl()
1405/// matches 'friend void foo()'.
1406extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1407
1408/// Matches statements.
1409///
1410/// Given
1411/// \code
1412/// { ++a; }
1413/// \endcode
1414/// stmt()
1415/// matches both the compound statement '{ ++a; }' and '++a'.
1416extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1417
1418/// Matches declaration statements.
1419///
1420/// Given
1421/// \code
1422/// int a;
1423/// \endcode
1424/// declStmt()
1425/// matches 'int a'.
1426extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1427
1428/// Matches member expressions.
1429///
1430/// Given
1431/// \code
1432/// class Y {
1433/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1434/// int a; static int b;
1435/// };
1436/// \endcode
1437/// memberExpr()
1438/// matches this->x, x, y.x, a, this->b
1439extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1440
1441/// Matches unresolved member expressions.
1442///
1443/// Given
1444/// \code
1445/// struct X {
1446/// template <class T> void f();
1447/// void g();
1448/// };
1449/// template <class T> void h() { X x; x.f<T>(); x.g(); }
1450/// \endcode
1451/// unresolvedMemberExpr()
1452/// matches x.f<T>
1453extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1455
1456/// Matches member expressions where the actual member referenced could not be
1457/// resolved because the base expression or the member name was dependent.
1458///
1459/// Given
1460/// \code
1461/// template <class T> void f() { T t; t.g(); }
1462/// \endcode
1463/// cxxDependentScopeMemberExpr()
1464/// matches t.g
1465extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1468
1469/// Matches call expressions.
1470///
1471/// Example matches x.y() and y()
1472/// \code
1473/// X x;
1474/// x.y();
1475/// y();
1476/// \endcode
1477extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1478
1479/// Matches call expressions which were resolved using ADL.
1480///
1481/// Example matches y(x) but not y(42) or NS::y(x).
1482/// \code
1483/// namespace NS {
1484/// struct X {};
1485/// void y(X);
1486/// }
1487///
1488/// void y(...);
1489///
1490/// void test() {
1491/// NS::X x;
1492/// y(x); // Matches
1493/// NS::y(x); // Doesn't match
1494/// y(42); // Doesn't match
1495/// using NS::y;
1496/// y(x); // Found by both unqualified lookup and ADL, doesn't match
1497// }
1498/// \endcode
1499AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1500
1501/// Matches lambda expressions.
1502///
1503/// Example matches [&](){return 5;}
1504/// \code
1505/// [&](){return 5;}
1506/// \endcode
1507extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1508
1509/// Matches member call expressions.
1510///
1511/// Example matches x.y()
1512/// \code
1513/// X x;
1514/// x.y();
1515/// \endcode
1516extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1518
1519/// Matches ObjectiveC Message invocation expressions.
1520///
1521/// The innermost message send invokes the "alloc" class method on the
1522/// NSString class, while the outermost message send invokes the
1523/// "initWithString" instance method on the object returned from
1524/// NSString's "alloc". This matcher should match both message sends.
1525/// \code
1526/// [[NSString alloc] initWithString:@"Hello"]
1527/// \endcode
1528extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1530
1531/// Matches ObjectiveC String literal expressions.
1532///
1533/// Example matches @"abcd"
1534/// \code
1535/// NSString *s = @"abcd";
1536/// \endcode
1537extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
1539
1540/// Matches Objective-C interface declarations.
1541///
1542/// Example matches Foo
1543/// \code
1544/// @interface Foo
1545/// @end
1546/// \endcode
1547extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1549
1550/// Matches Objective-C implementation declarations.
1551///
1552/// Example matches Foo
1553/// \code
1554/// @implementation Foo
1555/// @end
1556/// \endcode
1557extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1559
1560/// Matches Objective-C protocol declarations.
1561///
1562/// Example matches FooDelegate
1563/// \code
1564/// @protocol FooDelegate
1565/// @end
1566/// \endcode
1567extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1569
1570/// Matches Objective-C category declarations.
1571///
1572/// Example matches Foo (Additions)
1573/// \code
1574/// @interface Foo (Additions)
1575/// @end
1576/// \endcode
1577extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1579
1580/// Matches Objective-C category definitions.
1581///
1582/// Example matches Foo (Additions)
1583/// \code
1584/// @implementation Foo (Additions)
1585/// @end
1586/// \endcode
1587extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1589
1590/// Matches Objective-C method declarations.
1591///
1592/// Example matches both declaration and definition of -[Foo method]
1593/// \code
1594/// @interface Foo
1595/// - (void)method;
1596/// @end
1597///
1598/// @implementation Foo
1599/// - (void)method {}
1600/// @end
1601/// \endcode
1602extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1604
1605/// Matches block declarations.
1606///
1607/// Example matches the declaration of the nameless block printing an input
1608/// integer.
1609///
1610/// \code
1611/// myFunc(^(int p) {
1612/// printf("%d", p);
1613/// })
1614/// \endcode
1615extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1616 blockDecl;
1617
1618/// Matches Objective-C instance variable declarations.
1619///
1620/// Example matches _enabled
1621/// \code
1622/// @implementation Foo {
1623/// BOOL _enabled;
1624/// }
1625/// @end
1626/// \endcode
1627extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1629
1630/// Matches Objective-C property declarations.
1631///
1632/// Example matches enabled
1633/// \code
1634/// @interface Foo
1635/// @property BOOL enabled;
1636/// @end
1637/// \endcode
1638extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1640
1641/// Matches Objective-C \@throw statements.
1642///
1643/// Example matches \@throw
1644/// \code
1645/// @throw obj;
1646/// \endcode
1647extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1649
1650/// Matches Objective-C @try statements.
1651///
1652/// Example matches @try
1653/// \code
1654/// @try {}
1655/// @catch (...) {}
1656/// \endcode
1657extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1659
1660/// Matches Objective-C @catch statements.
1661///
1662/// Example matches @catch
1663/// \code
1664/// @try {}
1665/// @catch (...) {}
1666/// \endcode
1667extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1669
1670/// Matches Objective-C @finally statements.
1671///
1672/// Example matches @finally
1673/// \code
1674/// @try {}
1675/// @finally {}
1676/// \endcode
1677extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1679
1680/// Matches expressions that introduce cleanups to be run at the end
1681/// of the sub-expression's evaluation.
1682///
1683/// Example matches std::string()
1684/// \code
1685/// const std::string str = std::string();
1686/// \endcode
1687extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1689
1690/// Matches init list expressions.
1691///
1692/// Given
1693/// \code
1694/// int a[] = { 1, 2 };
1695/// struct B { int x, y; };
1696/// B b = { 5, 6 };
1697/// \endcode
1698/// initListExpr()
1699/// matches "{ 1, 2 }" and "{ 5, 6 }"
1700extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1702
1703/// Matches the syntactic form of init list expressions
1704/// (if expression have it).
1705AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1706 internal::Matcher<Expr>, InnerMatcher) {
1707 const Expr *SyntForm = Node.getSyntacticForm();
1708 return (SyntForm != nullptr &&
1709 InnerMatcher.matches(*SyntForm, Finder, Builder));
1710}
1711
1712/// Matches C++ initializer list expressions.
1713///
1714/// Given
1715/// \code
1716/// std::vector<int> a({ 1, 2, 3 });
1717/// std::vector<int> b = { 4, 5 };
1718/// int c[] = { 6, 7 };
1719/// std::pair<int, int> d = { 8, 9 };
1720/// \endcode
1721/// cxxStdInitializerListExpr()
1722/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1723extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1726
1727/// Matches implicit initializers of init list expressions.
1728///
1729/// Given
1730/// \code
1731/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1732/// \endcode
1733/// implicitValueInitExpr()
1734/// matches "[0].y" (implicitly)
1735extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1737
1738/// Matches paren list expressions.
1739/// ParenListExprs don't have a predefined type and are used for late parsing.
1740/// In the final AST, they can be met in template declarations.
1741///
1742/// Given
1743/// \code
1744/// template<typename T> class X {
1745/// void f() {
1746/// X x(*this);
1747/// int a = 0, b = 1; int i = (a, b);
1748/// }
1749/// };
1750/// \endcode
1751/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1752/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1753extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1755
1756/// Matches substitutions of non-type template parameters.
1757///
1758/// Given
1759/// \code
1760/// template <int N>
1761/// struct A { static const int n = N; };
1762/// struct B : public A<42> {};
1763/// \endcode
1764/// substNonTypeTemplateParmExpr()
1765/// matches "N" in the right-hand side of "static const int n = N;"
1766extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1769
1770/// Matches using declarations.
1771///
1772/// Given
1773/// \code
1774/// namespace X { int x; }
1775/// using X::x;
1776/// \endcode
1777/// usingDecl()
1778/// matches \code using X::x \endcode
1779extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1780
1781/// Matches using-enum declarations.
1782///
1783/// Given
1784/// \code
1785/// namespace X { enum x {...}; }
1786/// using enum X::x;
1787/// \endcode
1788/// usingEnumDecl()
1789/// matches \code using enum X::x \endcode
1790extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1792
1793/// Matches using namespace declarations.
1794///
1795/// Given
1796/// \code
1797/// namespace X { int x; }
1798/// using namespace X;
1799/// \endcode
1800/// usingDirectiveDecl()
1801/// matches \code using namespace X \endcode
1802extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1804
1805/// Matches reference to a name that can be looked up during parsing
1806/// but could not be resolved to a specific declaration.
1807///
1808/// Given
1809/// \code
1810/// template<typename T>
1811/// T foo() { T a; return a; }
1812/// template<typename T>
1813/// void bar() {
1814/// foo<T>();
1815/// }
1816/// \endcode
1817/// unresolvedLookupExpr()
1818/// matches \code foo<T>() \endcode
1819extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1821
1822/// Matches unresolved using value declarations.
1823///
1824/// Given
1825/// \code
1826/// template<typename X>
1827/// class C : private X {
1828/// using X::x;
1829/// };
1830/// \endcode
1831/// unresolvedUsingValueDecl()
1832/// matches \code using X::x \endcode
1833extern const internal::VariadicDynCastAllOfMatcher<Decl,
1836
1837/// Matches unresolved using value declarations that involve the
1838/// typename.
1839///
1840/// Given
1841/// \code
1842/// template <typename T>
1843/// struct Base { typedef T Foo; };
1844///
1845/// template<typename T>
1846/// struct S : private Base<T> {
1847/// using typename Base<T>::Foo;
1848/// };
1849/// \endcode
1850/// unresolvedUsingTypenameDecl()
1851/// matches \code using Base<T>::Foo \endcode
1852extern const internal::VariadicDynCastAllOfMatcher<Decl,
1855
1856/// Matches a constant expression wrapper.
1857///
1858/// Example matches the constant in the case statement:
1859/// (matcher = constantExpr())
1860/// \code
1861/// switch (a) {
1862/// case 37: break;
1863/// }
1864/// \endcode
1865extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1867
1868/// Matches parentheses used in expressions.
1869///
1870/// Example matches (foo() + 1)
1871/// \code
1872/// int foo() { return 1; }
1873/// int a = (foo() + 1);
1874/// \endcode
1875extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1876
1877/// Matches constructor call expressions (including implicit ones).
1878///
1879/// Example matches string(ptr, n) and ptr within arguments of f
1880/// (matcher = cxxConstructExpr())
1881/// \code
1882/// void f(const string &a, const string &b);
1883/// char *ptr;
1884/// int n;
1885/// f(string(ptr, n), ptr);
1886/// \endcode
1887extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1889
1890/// Matches unresolved constructor call expressions.
1891///
1892/// Example matches T(t) in return statement of f
1893/// (matcher = cxxUnresolvedConstructExpr())
1894/// \code
1895/// template <typename T>
1896/// void f(const T& t) { return T(t); }
1897/// \endcode
1898extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1901
1902/// Matches implicit and explicit this expressions.
1903///
1904/// Example matches the implicit this expression in "return i".
1905/// (matcher = cxxThisExpr())
1906/// \code
1907/// struct foo {
1908/// int i;
1909/// int f() { return i; }
1910/// };
1911/// \endcode
1912extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1914
1915/// Matches nodes where temporaries are created.
1916///
1917/// Example matches FunctionTakesString(GetStringByValue())
1918/// (matcher = cxxBindTemporaryExpr())
1919/// \code
1920/// FunctionTakesString(GetStringByValue());
1921/// FunctionTakesStringByPointer(GetStringPointer());
1922/// \endcode
1923extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1925
1926/// Matches nodes where temporaries are materialized.
1927///
1928/// Example: Given
1929/// \code
1930/// struct T {void func();};
1931/// T f();
1932/// void g(T);
1933/// \endcode
1934/// materializeTemporaryExpr() matches 'f()' in these statements
1935/// \code
1936/// T u(f());
1937/// g(f());
1938/// f().func();
1939/// \endcode
1940/// but does not match
1941/// \code
1942/// f();
1943/// \endcode
1944extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1947
1948/// Matches new expressions.
1949///
1950/// Given
1951/// \code
1952/// new X;
1953/// \endcode
1954/// cxxNewExpr()
1955/// matches 'new X'.
1956extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1957
1958/// Matches delete expressions.
1959///
1960/// Given
1961/// \code
1962/// delete X;
1963/// \endcode
1964/// cxxDeleteExpr()
1965/// matches 'delete X'.
1966extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1968
1969/// Matches noexcept expressions.
1970///
1971/// Given
1972/// \code
1973/// bool a() noexcept;
1974/// bool b() noexcept(true);
1975/// bool c() noexcept(false);
1976/// bool d() noexcept(noexcept(a()));
1977/// bool e = noexcept(b()) || noexcept(c());
1978/// \endcode
1979/// cxxNoexceptExpr()
1980/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1981/// doesn't match the noexcept specifier in the declarations a, b, c or d.
1982extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1984
1985/// Matches a loop initializing the elements of an array in a number of contexts:
1986/// * in the implicit copy/move constructor for a class with an array member
1987/// * when a lambda-expression captures an array by value
1988/// * when a decomposition declaration decomposes an array
1989///
1990/// Given
1991/// \code
1992/// void testLambdaCapture() {
1993/// int a[10];
1994/// auto Lam1 = [a]() {
1995/// return;
1996/// };
1997/// }
1998/// \endcode
1999/// arrayInitLoopExpr() matches the implicit loop that initializes each element of
2000/// the implicit array field inside the lambda object, that represents the array `a`
2001/// captured by value.
2002extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitLoopExpr>
2004
2005/// The arrayInitIndexExpr consists of two subexpressions: a common expression
2006/// (the source array) that is evaluated once up-front, and a per-element initializer
2007/// that runs once for each array element. Within the per-element initializer,
2008/// the current index may be obtained via an ArrayInitIndexExpr.
2009///
2010/// Given
2011/// \code
2012/// void testStructBinding() {
2013/// int a[2] = {1, 2};
2014/// auto [x, y] = a;
2015/// }
2016/// \endcode
2017/// arrayInitIndexExpr() matches the array index that implicitly iterates
2018/// over the array `a` to copy each element to the anonymous array
2019/// that backs the structured binding `[x, y]` elements of which are
2020/// referred to by their aliases `x` and `y`.
2021extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitIndexExpr>
2023
2024/// Matches array subscript expressions.
2025///
2026/// Given
2027/// \code
2028/// int i = a[1];
2029/// \endcode
2030/// arraySubscriptExpr()
2031/// matches "a[1]"
2032extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
2034
2035/// Matches the value of a default argument at the call site.
2036///
2037/// Example matches the CXXDefaultArgExpr placeholder inserted for the
2038/// default value of the second parameter in the call expression f(42)
2039/// (matcher = cxxDefaultArgExpr())
2040/// \code
2041/// void f(int x, int y = 0);
2042/// f(42);
2043/// \endcode
2044extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
2046
2047/// Matches overloaded operator calls.
2048///
2049/// Note that if an operator isn't overloaded, it won't match. Instead, use
2050/// binaryOperator matcher.
2051/// Currently it does not match operators such as new delete.
2052/// FIXME: figure out why these do not match?
2053///
2054/// Example matches both operator<<((o << b), c) and operator<<(o, b)
2055/// (matcher = cxxOperatorCallExpr())
2056/// \code
2057/// ostream &operator<< (ostream &out, int i) { };
2058/// ostream &o; int b = 1, c = 1;
2059/// o << b << c;
2060/// \endcode
2061/// See also the binaryOperation() matcher for more-general matching of binary
2062/// uses of this AST node.
2063extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2065
2066/// Matches C++17 fold expressions.
2067///
2068/// Example matches `(0 + ... + args)`:
2069/// \code
2070/// template <typename... Args>
2071/// auto sum(Args... args) {
2072/// return (0 + ... + args);
2073/// }
2074/// \endcode
2075extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFoldExpr>
2077
2078/// Matches rewritten binary operators
2079///
2080/// Example matches use of "<":
2081/// \code
2082/// #include <compare>
2083/// struct HasSpaceshipMem {
2084/// int a;
2085/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2086/// };
2087/// void compare() {
2088/// HasSpaceshipMem hs1, hs2;
2089/// if (hs1 < hs2)
2090/// return;
2091/// }
2092/// \endcode
2093/// See also the binaryOperation() matcher for more-general matching
2094/// of this AST node.
2095extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2098
2099/// Matches expressions.
2100///
2101/// Example matches x()
2102/// \code
2103/// void f() { x(); }
2104/// \endcode
2105extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2106
2107/// Matches expressions that refer to declarations.
2108///
2109/// Example matches x in if (x)
2110/// \code
2111/// bool x;
2112/// if (x) {}
2113/// \endcode
2114extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2116
2117/// Matches a reference to an ObjCIvar.
2118///
2119/// Example: matches "a" in "init" method:
2120/// \code
2121/// @implementation A {
2122/// NSString *a;
2123/// }
2124/// - (void) init {
2125/// a = @"hello";
2126/// }
2127/// \endcode
2128extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2130
2131/// Matches a reference to a block.
2132///
2133/// Example: matches "^{}":
2134/// \code
2135/// void f() { ^{}(); }
2136/// \endcode
2137extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2138
2139/// Matches if statements.
2140///
2141/// Example matches 'if (x) {}'
2142/// \code
2143/// if (x) {}
2144/// \endcode
2145extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2146
2147/// Matches for statements.
2148///
2149/// Example matches 'for (;;) {}'
2150/// \code
2151/// for (;;) {}
2152/// int i[] = {1, 2, 3}; for (auto a : i);
2153/// \endcode
2154extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2155
2156/// Matches the increment statement of a for loop.
2157///
2158/// Example:
2159/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2160/// matches '++x' in
2161/// \code
2162/// for (x; x < N; ++x) { }
2163/// \endcode
2164AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2165 InnerMatcher) {
2166 const Stmt *const Increment = Node.getInc();
2167 return (Increment != nullptr &&
2168 InnerMatcher.matches(*Increment, Finder, Builder));
2169}
2170
2171/// Matches the initialization statement of a for loop.
2172///
2173/// Example:
2174/// forStmt(hasLoopInit(declStmt()))
2175/// matches 'int x = 0' in
2176/// \code
2177/// for (int x = 0; x < N; ++x) { }
2178/// \endcode
2179AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2180 InnerMatcher) {
2181 const Stmt *const Init = Node.getInit();
2182 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2183}
2184
2185/// Matches range-based for statements.
2186///
2187/// cxxForRangeStmt() matches 'for (auto a : i)'
2188/// \code
2189/// int i[] = {1, 2, 3}; for (auto a : i);
2190/// for(int j = 0; j < 5; ++j);
2191/// \endcode
2192extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2194
2195/// Matches the initialization statement of a for loop.
2196///
2197/// Example:
2198/// forStmt(hasLoopVariable(anything()))
2199/// matches 'int x' in
2200/// \code
2201/// for (int x : a) { }
2202/// \endcode
2203AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2204 InnerMatcher) {
2205 const VarDecl *const Var = Node.getLoopVariable();
2206 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2207}
2208
2209/// Matches the range initialization statement of a for loop.
2210///
2211/// Example:
2212/// forStmt(hasRangeInit(anything()))
2213/// matches 'a' in
2214/// \code
2215/// for (int x : a) { }
2216/// \endcode
2217AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2218 InnerMatcher) {
2219 const Expr *const Init = Node.getRangeInit();
2220 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2221}
2222
2223/// Matches while statements.
2224///
2225/// Given
2226/// \code
2227/// while (true) {}
2228/// \endcode
2229/// whileStmt()
2230/// matches 'while (true) {}'.
2231extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2232
2233/// Matches do statements.
2234///
2235/// Given
2236/// \code
2237/// do {} while (true);
2238/// \endcode
2239/// doStmt()
2240/// matches 'do {} while(true)'
2241extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2242
2243/// Matches break statements.
2244///
2245/// Given
2246/// \code
2247/// while (true) { break; }
2248/// \endcode
2249/// breakStmt()
2250/// matches 'break'
2251extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2252
2253/// Matches continue statements.
2254///
2255/// Given
2256/// \code
2257/// while (true) { continue; }
2258/// \endcode
2259/// continueStmt()
2260/// matches 'continue'
2261extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2263
2264/// Matches co_return statements.
2265///
2266/// Given
2267/// \code
2268/// while (true) { co_return; }
2269/// \endcode
2270/// coreturnStmt()
2271/// matches 'co_return'
2272extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2274
2275/// Matches return statements.
2276///
2277/// Given
2278/// \code
2279/// return 1;
2280/// \endcode
2281/// returnStmt()
2282/// matches 'return 1'
2283extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2284
2285/// Matches goto statements.
2286///
2287/// Given
2288/// \code
2289/// goto FOO;
2290/// FOO: bar();
2291/// \endcode
2292/// gotoStmt()
2293/// matches 'goto FOO'
2294extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2295
2296/// Matches label statements.
2297///
2298/// Given
2299/// \code
2300/// goto FOO;
2301/// FOO: bar();
2302/// \endcode
2303/// labelStmt()
2304/// matches 'FOO:'
2305extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2306
2307/// Matches address of label statements (GNU extension).
2308///
2309/// Given
2310/// \code
2311/// FOO: bar();
2312/// void *ptr = &&FOO;
2313/// goto *bar;
2314/// \endcode
2315/// addrLabelExpr()
2316/// matches '&&FOO'
2317extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2319
2320/// Matches switch statements.
2321///
2322/// Given
2323/// \code
2324/// switch(a) { case 42: break; default: break; }
2325/// \endcode
2326/// switchStmt()
2327/// matches 'switch(a)'.
2328extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2329
2330/// Matches case and default statements inside switch statements.
2331///
2332/// Given
2333/// \code
2334/// switch(a) { case 42: break; default: break; }
2335/// \endcode
2336/// switchCase()
2337/// matches 'case 42:' and 'default:'.
2338extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2339
2340/// Matches case statements inside switch statements.
2341///
2342/// Given
2343/// \code
2344/// switch(a) { case 42: break; default: break; }
2345/// \endcode
2346/// caseStmt()
2347/// matches 'case 42:'.
2348extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2349
2350/// Matches default statements inside switch statements.
2351///
2352/// Given
2353/// \code
2354/// switch(a) { case 42: break; default: break; }
2355/// \endcode
2356/// defaultStmt()
2357/// matches 'default:'.
2358extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2360
2361/// Matches compound statements.
2362///
2363/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2364/// \code
2365/// for (;;) {{}}
2366/// \endcode
2367extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2369
2370/// Matches catch statements.
2371///
2372/// \code
2373/// try {} catch(int i) {}
2374/// \endcode
2375/// cxxCatchStmt()
2376/// matches 'catch(int i)'
2377extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2379
2380/// Matches try statements.
2381///
2382/// \code
2383/// try {} catch(int i) {}
2384/// \endcode
2385/// cxxTryStmt()
2386/// matches 'try {}'
2387extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2388
2389/// Matches throw expressions.
2390///
2391/// \code
2392/// try { throw 5; } catch(int i) {}
2393/// \endcode
2394/// cxxThrowExpr()
2395/// matches 'throw 5'
2396extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2398
2399/// Matches null statements.
2400///
2401/// \code
2402/// foo();;
2403/// \endcode
2404/// nullStmt()
2405/// matches the second ';'
2406extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2407
2408/// Matches asm statements.
2409///
2410/// \code
2411/// int i = 100;
2412/// __asm("mov al, 2");
2413/// \endcode
2414/// asmStmt()
2415/// matches '__asm("mov al, 2")'
2416extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2417
2418/// Matches bool literals.
2419///
2420/// Example matches true
2421/// \code
2422/// true
2423/// \endcode
2424extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2426
2427/// Matches string literals (also matches wide string literals).
2428///
2429/// Example matches "abcd", L"abcd"
2430/// \code
2431/// char *s = "abcd";
2432/// wchar_t *ws = L"abcd";
2433/// \endcode
2434extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2436
2437/// Matches character literals (also matches wchar_t).
2438///
2439/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2440/// though.
2441///
2442/// Example matches 'a', L'a'
2443/// \code
2444/// char ch = 'a';
2445/// wchar_t chw = L'a';
2446/// \endcode
2447extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2449
2450/// Matches integer literals of all sizes / encodings, e.g.
2451/// 1, 1L, 0x1 and 1U.
2452///
2453/// Does not match character-encoded integers such as L'a'.
2454extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2456
2457/// Matches float literals of all sizes / encodings, e.g.
2458/// 1.0, 1.0f, 1.0L and 1e10.
2459///
2460/// Does not match implicit conversions such as
2461/// \code
2462/// float a = 10;
2463/// \endcode
2464extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2466
2467/// Matches imaginary literals, which are based on integer and floating
2468/// point literals e.g.: 1i, 1.0i
2469extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2471
2472/// Matches fixed point literals
2473extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2475
2476/// Matches user defined literal operator call.
2477///
2478/// Example match: "foo"_suffix
2479extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2481
2482/// Matches compound (i.e. non-scalar) literals
2483///
2484/// Example match: {1}, (1, 2)
2485/// \code
2486/// int array[4] = {1};
2487/// vector int myvec = (vector int)(1, 2);
2488/// \endcode
2489extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2491
2492/// Matches co_await expressions.
2493///
2494/// Given
2495/// \code
2496/// co_await 1;
2497/// \endcode
2498/// coawaitExpr()
2499/// matches 'co_await 1'
2500extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2502/// Matches co_await expressions where the type of the promise is dependent
2503extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2505/// Matches co_yield expressions.
2506///
2507/// Given
2508/// \code
2509/// co_yield 1;
2510/// \endcode
2511/// coyieldExpr()
2512/// matches 'co_yield 1'
2513extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2515
2516/// Matches coroutine body statements.
2517///
2518/// coroutineBodyStmt() matches the coroutine below
2519/// \code
2520/// generator<int> gen() {
2521/// co_return;
2522/// }
2523/// \endcode
2524extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoroutineBodyStmt>
2526
2527/// Matches nullptr literal.
2528extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2530
2531/// Matches GNU __builtin_choose_expr.
2532extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2533 chooseExpr;
2534
2535/// Matches builtin function __builtin_convertvector.
2536extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConvertVectorExpr>
2538
2539/// Matches GNU __null expression.
2540extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2542
2543/// Matches C11 _Generic expression.
2544extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2546
2547/// Matches atomic builtins.
2548/// Example matches __atomic_load_n(ptr, 1)
2549/// \code
2550/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2551/// \endcode
2552extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2553
2554/// Matches statement expression (GNU extension).
2555///
2556/// Example match: ({ int X = 4; X; })
2557/// \code
2558/// int C = ({ int X = 4; X; });
2559/// \endcode
2560extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2561
2562/// Matches binary operator expressions.
2563///
2564/// Example matches a || b
2565/// \code
2566/// !(a || b)
2567/// \endcode
2568/// See also the binaryOperation() matcher for more-general matching.
2569extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2571
2572/// Matches unary operator expressions.
2573///
2574/// Example matches !a
2575/// \code
2576/// !a || b
2577/// \endcode
2578extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2580
2581/// Matches conditional operator expressions.
2582///
2583/// Example matches a ? b : c
2584/// \code
2585/// (a ? b : c) + 42
2586/// \endcode
2587extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2589
2590/// Matches binary conditional operator expressions (GNU extension).
2591///
2592/// Example matches a ?: b
2593/// \code
2594/// (a ?: b) + 42;
2595/// \endcode
2596extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2599
2600/// Matches opaque value expressions. They are used as helpers
2601/// to reference another expressions and can be met
2602/// in BinaryConditionalOperators, for example.
2603///
2604/// Example matches 'a'
2605/// \code
2606/// (a ?: c) + 42;
2607/// \endcode
2608extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2610
2611/// Matches a C++ static_assert declaration.
2612///
2613/// Example:
2614/// staticAssertDecl()
2615/// matches
2616/// static_assert(sizeof(S) == sizeof(int))
2617/// in
2618/// \code
2619/// struct S {
2620/// int x;
2621/// };
2622/// static_assert(sizeof(S) == sizeof(int));
2623/// \endcode
2624extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2626
2627/// Matches a reinterpret_cast expression.
2628///
2629/// Either the source expression or the destination type can be matched
2630/// using has(), but hasDestinationType() is more specific and can be
2631/// more readable.
2632///
2633/// Example matches reinterpret_cast<char*>(&p) in
2634/// \code
2635/// void* p = reinterpret_cast<char*>(&p);
2636/// \endcode
2637extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2639
2640/// Matches a C++ static_cast expression.
2641///
2642/// \see hasDestinationType
2643/// \see reinterpretCast
2644///
2645/// Example:
2646/// cxxStaticCastExpr()
2647/// matches
2648/// static_cast<long>(8)
2649/// in
2650/// \code
2651/// long eight(static_cast<long>(8));
2652/// \endcode
2653extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2655
2656/// Matches a dynamic_cast expression.
2657///
2658/// Example:
2659/// cxxDynamicCastExpr()
2660/// matches
2661/// dynamic_cast<D*>(&b);
2662/// in
2663/// \code
2664/// struct B { virtual ~B() {} }; struct D : B {};
2665/// B b;
2666/// D* p = dynamic_cast<D*>(&b);
2667/// \endcode
2668extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2670
2671/// Matches a const_cast expression.
2672///
2673/// Example: Matches const_cast<int*>(&r) in
2674/// \code
2675/// int n = 42;
2676/// const int &r(n);
2677/// int* p = const_cast<int*>(&r);
2678/// \endcode
2679extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2681
2682/// Matches a C-style cast expression.
2683///
2684/// Example: Matches (int) 2.2f in
2685/// \code
2686/// int i = (int) 2.2f;
2687/// \endcode
2688extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2690
2691/// Matches explicit cast expressions.
2692///
2693/// Matches any cast expression written in user code, whether it be a
2694/// C-style cast, a functional-style cast, or a keyword cast.
2695///
2696/// Does not match implicit conversions.
2697///
2698/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2699/// Clang uses the term "cast" to apply to implicit conversions as well as to
2700/// actual cast expressions.
2701///
2702/// \see hasDestinationType.
2703///
2704/// Example: matches all five of the casts in
2705/// \code
2706/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2707/// \endcode
2708/// but does not match the implicit conversion in
2709/// \code
2710/// long ell = 42;
2711/// \endcode
2712extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2714
2715/// Matches the implicit cast nodes of Clang's AST.
2716///
2717/// This matches many different places, including function call return value
2718/// eliding, as well as any type conversions.
2719extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2721
2722/// Matches any cast nodes of Clang's AST.
2723///
2724/// Example: castExpr() matches each of the following:
2725/// \code
2726/// (int) 3;
2727/// const_cast<Expr *>(SubExpr);
2728/// char c = 0;
2729/// \endcode
2730/// but does not match
2731/// \code
2732/// int i = (0);
2733/// int k = 0;
2734/// \endcode
2735extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2736
2737/// Matches functional cast expressions
2738///
2739/// Example: Matches Foo(bar);
2740/// \code
2741/// Foo f = bar;
2742/// Foo g = (Foo) bar;
2743/// Foo h = Foo(bar);
2744/// \endcode
2745extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2747
2748/// Matches functional cast expressions having N != 1 arguments
2749///
2750/// Example: Matches Foo(bar, bar)
2751/// \code
2752/// Foo h = Foo(bar, bar);
2753/// \endcode
2754extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2756
2757/// Matches predefined identifier expressions [C99 6.4.2.2].
2758///
2759/// Example: Matches __func__
2760/// \code
2761/// printf("%s", __func__);
2762/// \endcode
2763extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2765
2766/// Matches C99 designated initializer expressions [C99 6.7.8].
2767///
2768/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2769/// \code
2770/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2771/// \endcode
2772extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2774
2775/// Matches designated initializer expressions that contain
2776/// a specific number of designators.
2777///
2778/// Example: Given
2779/// \code
2780/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2781/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2782/// \endcode
2783/// designatorCountIs(2)
2784/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2785/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2786AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2787 return Node.size() == N;
2788}
2789
2790/// Matches \c QualTypes in the clang AST.
2791extern const internal::VariadicAllOfMatcher<QualType> qualType;
2792
2793/// Matches \c Types in the clang AST.
2794extern const internal::VariadicAllOfMatcher<Type> type;
2795
2796/// Matches \c TypeLocs in the clang AST.
2797extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2798
2799/// Matches if any of the given matchers matches.
2800///
2801/// Unlike \c anyOf, \c eachOf will generate a match result for each
2802/// matching submatcher.
2803///
2804/// For example, in:
2805/// \code
2806/// class A { int a; int b; };
2807/// \endcode
2808/// The matcher:
2809/// \code
2810/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2811/// has(fieldDecl(hasName("b")).bind("v"))))
2812/// \endcode
2813/// will generate two results binding "v", the first of which binds
2814/// the field declaration of \c a, the second the field declaration of
2815/// \c b.
2816///
2817/// Usable as: Any Matcher
2818extern const internal::VariadicOperatorMatcherFunc<
2819 2, std::numeric_limits<unsigned>::max()>
2820 eachOf;
2821
2822/// Matches if any of the given matchers matches.
2823///
2824/// Usable as: Any Matcher
2825extern const internal::VariadicOperatorMatcherFunc<
2826 2, std::numeric_limits<unsigned>::max()>
2827 anyOf;
2828
2829/// Matches if all given matchers match.
2830///
2831/// Usable as: Any Matcher
2832extern const internal::VariadicOperatorMatcherFunc<
2833 2, std::numeric_limits<unsigned>::max()>
2834 allOf;
2835
2836/// Matches any node regardless of the submatcher.
2837///
2838/// However, \c optionally will retain any bindings generated by the submatcher.
2839/// Useful when additional information which may or may not present about a main
2840/// matching node is desired.
2841///
2842/// For example, in:
2843/// \code
2844/// class Foo {
2845/// int bar;
2846/// }
2847/// \endcode
2848/// The matcher:
2849/// \code
2850/// cxxRecordDecl(
2851/// optionally(has(
2852/// fieldDecl(hasName("bar")).bind("var")
2853/// ))).bind("record")
2854/// \endcode
2855/// will produce a result binding for both "record" and "var".
2856/// The matcher will produce a "record" binding for even if there is no data
2857/// member named "bar" in that class.
2858///
2859/// Usable as: Any Matcher
2860extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2861
2862/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2863///
2864/// Given
2865/// \code
2866/// Foo x = bar;
2867/// int y = sizeof(x) + alignof(x);
2868/// \endcode
2869/// unaryExprOrTypeTraitExpr()
2870/// matches \c sizeof(x) and \c alignof(x)
2871extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2874
2875/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2876///
2877/// Given
2878/// \code
2879/// if (true);
2880/// for (; true; );
2881/// \endcode
2882/// with the matcher
2883/// \code
2884/// mapAnyOf(ifStmt, forStmt).with(
2885/// hasCondition(cxxBoolLiteralExpr(equals(true)))
2886/// ).bind("trueCond")
2887/// \endcode
2888/// matches the \c if and the \c for. It is equivalent to:
2889/// \code
2890/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2891/// anyOf(
2892/// ifStmt(trueCond).bind("trueCond"),
2893/// forStmt(trueCond).bind("trueCond")
2894/// );
2895/// \endcode
2896///
2897/// The with() chain-call accepts zero or more matchers which are combined
2898/// as-if with allOf() in each of the node matchers.
2899/// Usable as: Any Matcher
2900template <typename T, typename... U>
2901auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2902 return internal::MapAnyOfHelper<U...>();
2903}
2904
2905/// Matches nodes which can be used with binary operators.
2906///
2907/// The code
2908/// \code
2909/// var1 != var2;
2910/// \endcode
2911/// might be represented in the clang AST as a binaryOperator, a
2912/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2913///
2914/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2915/// least one is a class type (cxxOperatorCallExpr)
2916/// * whether the code appears in a template declaration, if at least one of the
2917/// vars is a dependent-type (binaryOperator)
2918/// * whether the code relies on a rewritten binary operator, such as a
2919/// spaceship operator or an inverted equality operator
2920/// (cxxRewrittenBinaryOperator)
2921///
2922/// This matcher elides details in places where the matchers for the nodes are
2923/// compatible.
2924///
2925/// Given
2926/// \code
2927/// binaryOperation(
2928/// hasOperatorName("!="),
2929/// hasLHS(expr().bind("lhs")),
2930/// hasRHS(expr().bind("rhs"))
2931/// )
2932/// \endcode
2933/// matches each use of "!=" in:
2934/// \code
2935/// struct S{
2936/// bool operator!=(const S&) const;
2937/// };
2938///
2939/// void foo()
2940/// {
2941/// 1 != 2;
2942/// S() != S();
2943/// }
2944///
2945/// template<typename T>
2946/// void templ()
2947/// {
2948/// 1 != 2;
2949/// T() != S();
2950/// }
2951/// struct HasOpEq
2952/// {
2953/// bool operator==(const HasOpEq &) const;
2954/// };
2955///
2956/// void inverse()
2957/// {
2958/// HasOpEq s1;
2959/// HasOpEq s2;
2960/// if (s1 != s2)
2961/// return;
2962/// }
2963///
2964/// struct HasSpaceship
2965/// {
2966/// bool operator<=>(const HasOpEq &) const;
2967/// };
2968///
2969/// void use_spaceship()
2970/// {
2971/// HasSpaceship s1;
2972/// HasSpaceship s2;
2973/// if (s1 != s2)
2974/// return;
2975/// }
2976/// \endcode
2977extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2980
2981/// Matches function calls and constructor calls
2982///
2983/// Because CallExpr and CXXConstructExpr do not share a common
2984/// base class with API accessing arguments etc, AST Matchers for code
2985/// which should match both are typically duplicated. This matcher
2986/// removes the need for duplication.
2987///
2988/// Given code
2989/// \code
2990/// struct ConstructorTakesInt
2991/// {
2992/// ConstructorTakesInt(int i) {}
2993/// };
2994///
2995/// void callTakesInt(int i)
2996/// {
2997/// }
2998///
2999/// void doCall()
3000/// {
3001/// callTakesInt(42);
3002/// }
3003///
3004/// void doConstruct()
3005/// {
3006/// ConstructorTakesInt cti(42);
3007/// }
3008/// \endcode
3009///
3010/// The matcher
3011/// \code
3012/// invocation(hasArgument(0, integerLiteral(equals(42))))
3013/// \endcode
3014/// matches the expression in both doCall and doConstruct
3015extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
3016
3017/// Matches unary expressions that have a specific type of argument.
3018///
3019/// Given
3020/// \code
3021/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
3022/// \endcode
3023/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
3024/// matches \c sizeof(a) and \c alignof(c)
3026 internal::Matcher<QualType>, InnerMatcher) {
3027 const QualType ArgumentType = Node.getTypeOfArgument();
3028 return InnerMatcher.matches(ArgumentType, Finder, Builder);
3029}
3030
3031/// Matches unary expressions of a certain kind.
3032///
3033/// Given
3034/// \code
3035/// int x;
3036/// int s = sizeof(x) + alignof(x)
3037/// \endcode
3038/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
3039/// matches \c sizeof(x)
3040///
3041/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
3042/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
3044 return Node.getKind() == Kind;
3045}
3046
3047/// Same as unaryExprOrTypeTraitExpr, but only matching
3048/// alignof.
3049inline internal::BindableMatcher<Stmt> alignOfExpr(
3050 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3052 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
3053 InnerMatcher)));
3054}
3055
3056/// Same as unaryExprOrTypeTraitExpr, but only matching
3057/// sizeof.
3058inline internal::BindableMatcher<Stmt> sizeOfExpr(
3059 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3061 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
3062}
3063
3064/// Matches NamedDecl nodes that have the specified name.
3065///
3066/// Supports specifying enclosing namespaces or classes by prefixing the name
3067/// with '<enclosing>::'.
3068/// Does not match typedefs of an underlying type with the given name.
3069///
3070/// Example matches X (Name == "X")
3071/// \code
3072/// class X;
3073/// \endcode
3074///
3075/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
3076/// \code
3077/// namespace a { namespace b { class X; } }
3078/// \endcode
3079inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3080 return internal::Matcher<NamedDecl>(
3081 new internal::HasNameMatcher({std::string(Name)}));
3082}
3083
3084/// Matches NamedDecl nodes that have any of the specified names.
3085///
3086/// This matcher is only provided as a performance optimization of hasName.
3087/// \code
3088/// hasAnyName(a, b, c)
3089/// \endcode
3090/// is equivalent to, but faster than
3091/// \code
3092/// anyOf(hasName(a), hasName(b), hasName(c))
3093/// \endcode
3094extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3096 hasAnyName;
3097
3098/// Matches NamedDecl nodes whose fully qualified names contain
3099/// a substring matched by the given RegExp.
3100///
3101/// Supports specifying enclosing namespaces or classes by
3102/// prefixing the name with '<enclosing>::'. Does not match typedefs
3103/// of an underlying type with the given name.
3104///
3105/// Example matches X (regexp == "::X")
3106/// \code
3107/// class X;
3108/// \endcode
3109///
3110/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3111/// \code
3112/// namespace foo { namespace bar { class X; } }
3113/// \endcode
3114AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3115 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3116 return RegExp->match(FullNameString);
3117}
3118
3119/// Matches overloaded operator names.
3120///
3121/// Matches overloaded operator names specified in strings without the
3122/// "operator" prefix: e.g. "<<".
3123///
3124/// Given:
3125/// \code
3126/// class A { int operator*(); };
3127/// const A &operator<<(const A &a, const A &b);
3128/// A a;
3129/// a << a; // <-- This matches
3130/// \endcode
3131///
3132/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3133/// specified line and
3134/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3135/// matches the declaration of \c A.
3136///
3137/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3138inline internal::PolymorphicMatcher<
3139 internal::HasOverloadedOperatorNameMatcher,
3141 std::vector<std::string>>
3143 return internal::PolymorphicMatcher<
3144 internal::HasOverloadedOperatorNameMatcher,
3146 std::vector<std::string>>({std::string(Name)});
3147}
3148
3149/// Matches overloaded operator names.
3150///
3151/// Matches overloaded operator names specified in strings without the
3152/// "operator" prefix: e.g. "<<".
3153///
3154/// hasAnyOverloadedOperatorName("+", "-")
3155/// Is equivalent to
3156/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3157extern const internal::VariadicFunction<
3158 internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3161 std::vector<std::string>>,
3164
3165/// Matches template-dependent, but known, member names.
3166///
3167/// In template declarations, dependent members are not resolved and so can
3168/// not be matched to particular named declarations.
3169///
3170/// This matcher allows to match on the known name of members.
3171///
3172/// Given
3173/// \code
3174/// template <typename T>
3175/// struct S {
3176/// void mem();
3177/// };
3178/// template <typename T>
3179/// void x() {
3180/// S<T> s;
3181/// s.mem();
3182/// }
3183/// \endcode
3184/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3185AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3186 return Node.getMember().getAsString() == N;
3187}
3188
3189/// Matches template-dependent, but known, member names against an already-bound
3190/// node
3191///
3192/// In template declarations, dependent members are not resolved and so can
3193/// not be matched to particular named declarations.
3194///
3195/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3196/// and CXXMethodDecl nodes.
3197///
3198/// Given
3199/// \code
3200/// template <typename T>
3201/// struct S {
3202/// void mem();
3203/// };
3204/// template <typename T>
3205/// void x() {
3206/// S<T> s;
3207/// s.mem();
3208/// }
3209/// \endcode
3210/// The matcher
3211/// @code
3212/// \c cxxDependentScopeMemberExpr(
3213/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3214/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3215/// cxxMethodDecl(hasName("mem")).bind("templMem")
3216/// )))))
3217/// )))),
3218/// memberHasSameNameAsBoundNode("templMem")
3219/// )
3220/// @endcode
3221/// first matches and binds the @c mem member of the @c S template, then
3222/// compares its name to the usage in @c s.mem() in the @c x function template
3223AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3224 std::string, BindingID) {
3225 auto MemberName = Node.getMember().getAsString();
3226
3227 return Builder->removeBindings(
3228 [this, MemberName](const BoundNodesMap &Nodes) {
3229 const auto &BN = Nodes.getNode(this->BindingID);
3230 if (const auto *ND = BN.get<NamedDecl>()) {
3231 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3232 return true;
3233 return ND->getName() != MemberName;
3234 }
3235 return true;
3236 });
3237}
3238
3239/// Matches C++ classes that are directly or indirectly derived from a class
3240/// matching \c Base, or Objective-C classes that directly or indirectly
3241/// subclass a class matching \c Base.
3242///
3243/// Note that a class is not considered to be derived from itself.
3244///
3245/// Example matches Y, Z, C (Base == hasName("X"))
3246/// \code
3247/// class X;
3248/// class Y : public X {}; // directly derived
3249/// class Z : public Y {}; // indirectly derived
3250/// typedef X A;
3251/// typedef A B;
3252/// class C : public B {}; // derived from a typedef of X
3253/// \endcode
3254///
3255/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3256/// \code
3257/// class Foo;
3258/// typedef Foo X;
3259/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3260/// \endcode
3261///
3262/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3263/// \code
3264/// @interface NSObject @end
3265/// @interface Bar : NSObject @end
3266/// \endcode
3267///
3268/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3270 isDerivedFrom,
3272 internal::Matcher<NamedDecl>, Base) {
3273 // Check if the node is a C++ struct/union/class.
3274 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3275 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3276
3277 // The node must be an Objective-C class.
3278 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3279 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3280 /*Directly=*/false);
3281}
3282
3283/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3285 isDerivedFrom,
3287 std::string, BaseName, 1) {
3288 if (BaseName.empty())
3289 return false;
3290
3291 const auto M = isDerivedFrom(hasName(BaseName));
3292
3293 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3294 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3295
3296 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3297 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3298}
3299
3300/// Matches C++ classes that have a direct or indirect base matching \p
3301/// BaseSpecMatcher.
3302///
3303/// Example:
3304/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3305/// \code
3306/// class Foo;
3307/// class Bar : Foo {};
3308/// class Baz : Bar {};
3309/// class SpecialBase;
3310/// class Proxy : SpecialBase {}; // matches Proxy
3311/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3312/// \endcode
3313///
3314// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3315AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3316 BaseSpecMatcher) {
3317 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3318}
3319
3320/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3321///
3322/// Example:
3323/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3324/// \code
3325/// class Foo;
3326/// class Bar : Foo {};
3327/// class Baz : Bar {};
3328/// class SpecialBase;
3329/// class Proxy : SpecialBase {}; // matches Proxy
3330/// class IndirectlyDerived : Proxy {}; // doesn't match
3331/// \endcode
3332AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3333 BaseSpecMatcher) {
3334 return Node.hasDefinition() &&
3335 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3336 return BaseSpecMatcher.matches(Base, Finder, Builder);
3337 });
3338}
3339
3340/// Similar to \c isDerivedFrom(), but also matches classes that directly
3341/// match \c Base.
3343 isSameOrDerivedFrom,
3345 internal::Matcher<NamedDecl>, Base, 0) {
3346 const auto M = anyOf(Base, isDerivedFrom(Base));
3347
3348 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3349 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3350
3351 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3352 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3353}
3354
3355/// Overloaded method as shortcut for
3356/// \c isSameOrDerivedFrom(hasName(...)).
3358 isSameOrDerivedFrom,
3360 std::string, BaseName, 1) {
3361 if (BaseName.empty())
3362 return false;
3363
3364 const auto M = isSameOrDerivedFrom(hasName(BaseName));
3365
3366 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3367 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3368
3369 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3370 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3371}
3372
3373/// Matches C++ or Objective-C classes that are directly derived from a class
3374/// matching \c Base.
3375///
3376/// Note that a class is not considered to be derived from itself.
3377///
3378/// Example matches Y, C (Base == hasName("X"))
3379/// \code
3380/// class X;
3381/// class Y : public X {}; // directly derived
3382/// class Z : public Y {}; // indirectly derived
3383/// typedef X A;
3384/// typedef A B;
3385/// class C : public B {}; // derived from a typedef of X
3386/// \endcode
3387///
3388/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3389/// \code
3390/// class Foo;
3391/// typedef Foo X;
3392/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3393/// \endcode
3395 isDirectlyDerivedFrom,
3397 internal::Matcher<NamedDecl>, Base, 0) {
3398 // Check if the node is a C++ struct/union/class.
3399 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3400 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3401
3402 // The node must be an Objective-C class.
3403 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3404 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3405 /*Directly=*/true);
3406}
3407
3408/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3410 isDirectlyDerivedFrom,
3412 std::string, BaseName, 1) {
3413 if (BaseName.empty())
3414 return false;
3415 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3416
3417 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3418 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3419
3420 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3421 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3422}
3423/// Matches the first method of a class or struct that satisfies \c
3424/// InnerMatcher.
3425///
3426/// Given:
3427/// \code
3428/// class A { void func(); };
3429/// class B { void member(); };
3430/// \endcode
3431///
3432/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3433/// \c A but not \c B.
3434AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3435 InnerMatcher) {
3436 BoundNodesTreeBuilder Result(*Builder);
3437 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3438 Node.method_end(), Finder, &Result);
3439 if (MatchIt == Node.method_end())
3440 return false;
3441
3442 if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3443 return false;
3444 *Builder = std::move(Result);
3445 return true;
3446}
3447
3448/// Matches the generated class of lambda expressions.
3449///
3450/// Given:
3451/// \code
3452/// auto x = []{};
3453/// \endcode
3454///
3455/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3456/// \c decltype(x)
3458 return Node.isLambda();
3459}
3460
3461/// Matches AST nodes that have child AST nodes that match the
3462/// provided matcher.
3463///
3464/// Example matches X, Y
3465/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3466/// \code
3467/// class X {}; // Matches X, because X::X is a class of name X inside X.
3468/// class Y { class X {}; };
3469/// class Z { class Y { class X {}; }; }; // Does not match Z.
3470/// \endcode
3471///
3472/// ChildT must be an AST base type.
3473///
3474/// Usable as: Any Matcher
3475/// Note that has is direct matcher, so it also matches things like implicit
3476/// casts and paren casts. If you are matching with expr then you should
3477/// probably consider using ignoringParenImpCasts like:
3478/// has(ignoringParenImpCasts(expr())).
3479extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3480
3481/// Matches AST nodes that have descendant AST nodes that match the
3482/// provided matcher.
3483///
3484/// Example matches X, Y, Z
3485/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3486/// \code
3487/// class X {}; // Matches X, because X::X is a class of name X inside X.
3488/// class Y { class X {}; };
3489/// class Z { class Y { class X {}; }; };
3490/// \endcode
3491///
3492/// DescendantT must be an AST base type.
3493///
3494/// Usable as: Any Matcher
3495extern const internal::ArgumentAdaptingMatcherFunc<
3496 internal::HasDescendantMatcher>
3498
3499/// Matches AST nodes that have child AST nodes that match the
3500/// provided matcher.
3501///
3502/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3503/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3504/// \code
3505/// class X {};
3506/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3507/// // inside Y.
3508/// class Z { class Y { class X {}; }; }; // Does not match Z.
3509/// \endcode
3510///
3511/// ChildT must be an AST base type.
3512///
3513/// As opposed to 'has', 'forEach' will cause a match for each result that
3514/// matches instead of only on the first one.
3515///
3516/// Usable as: Any Matcher
3517extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3518 forEach;
3519
3520/// Matches AST nodes that have descendant AST nodes that match the
3521/// provided matcher.
3522///
3523/// Example matches X, A, A::X, B, B::C, B::C::X
3524/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3525/// \code
3526/// class X {};
3527/// class A { class X {}; }; // Matches A, because A::X is a class of name
3528/// // X inside A.
3529/// class B { class C { class X {}; }; };
3530/// \endcode
3531///
3532/// DescendantT must be an AST base type.
3533///
3534/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3535/// each result that matches instead of only on the first one.
3536///
3537/// Note: Recursively combined ForEachDescendant can cause many matches:
3538/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3539/// forEachDescendant(cxxRecordDecl())
3540/// )))
3541/// will match 10 times (plus injected class name matches) on:
3542/// \code
3543/// class A { class B { class C { class D { class E {}; }; }; }; };
3544/// \endcode
3545///
3546/// Usable as: Any Matcher
3547extern const internal::ArgumentAdaptingMatcherFunc<
3548 internal::ForEachDescendantMatcher>
3550
3551/// Matches if the node or any descendant matches.
3552///
3553/// Generates results for each match.
3554///
3555/// For example, in:
3556/// \code
3557/// class A { class B {}; class C {}; };
3558/// \endcode
3559/// The matcher:
3560/// \code
3561/// cxxRecordDecl(hasName("::A"),
3562/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3563/// \endcode
3564/// will generate results for \c A, \c B and \c C.
3565///
3566/// Usable as: Any Matcher
3567template <typename T>
3568internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3569 return eachOf(Matcher, forEachDescendant(Matcher));
3570}
3571
3572/// Matches AST nodes that have a parent that matches the provided
3573/// matcher.
3574///
3575/// Given
3576/// \code
3577/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3578/// \endcode
3579/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3580///
3581/// Usable as: Any Matcher
3582extern const internal::ArgumentAdaptingMatcherFunc<
3583 internal::HasParentMatcher,
3584 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3585 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3586 hasParent;
3587
3588/// Matches AST nodes that have an ancestor that matches the provided
3589/// matcher.
3590///
3591/// Given
3592/// \code
3593/// void f() { if (true) { int x = 42; } }
3594/// void g() { for (;;) { int x = 43; } }
3595/// \endcode
3596/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3597///
3598/// Usable as: Any Matcher
3599extern const internal::ArgumentAdaptingMatcherFunc<
3600 internal::HasAncestorMatcher,
3601 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3602 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3604
3605/// Matches if the provided matcher does not match.
3606///
3607/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3608/// \code
3609/// class X {};
3610/// class Y {};
3611/// \endcode
3612///
3613/// Usable as: Any Matcher
3614extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3615
3616/// Matches a node if the declaration associated with that node
3617/// matches the given matcher.
3618///
3619/// The associated declaration is:
3620/// - for type nodes, the declaration of the underlying type
3621/// - for CallExpr, the declaration of the callee
3622/// - for MemberExpr, the declaration of the referenced member
3623/// - for CXXConstructExpr, the declaration of the constructor
3624/// - for CXXNewExpr, the declaration of the operator new
3625/// - for ObjCIvarExpr, the declaration of the ivar
3626///
3627/// For type nodes, hasDeclaration will generally match the declaration of the
3628/// sugared type. Given
3629/// \code
3630/// class X {};
3631/// typedef X Y;
3632/// Y y;
3633/// \endcode
3634/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3635/// typedefDecl. A common use case is to match the underlying, desugared type.
3636/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3637/// \code
3638/// varDecl(hasType(hasUnqualifiedDesugaredType(
3639/// recordType(hasDeclaration(decl())))))
3640/// \endcode
3641/// In this matcher, the decl will match the CXXRecordDecl of class X.
3642///
3643/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3644/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3645/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3646/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3647/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3648/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3649/// Matcher<UnresolvedUsingType>
3650inline internal::PolymorphicMatcher<
3651 internal::HasDeclarationMatcher,
3652 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3653hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3654 return internal::PolymorphicMatcher<
3655 internal::HasDeclarationMatcher,
3656 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3657 InnerMatcher);
3658}
3659
3660/// Matches a \c NamedDecl whose underlying declaration matches the given
3661/// matcher.
3662///
3663/// Given
3664/// \code
3665/// namespace N { template<class T> void f(T t); }
3666/// template <class T> void g() { using N::f; f(T()); }
3667/// \endcode
3668/// \c unresolvedLookupExpr(hasAnyDeclaration(
3669/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3670/// matches the use of \c f in \c g() .
3671AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3672 InnerMatcher) {
3673 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3674
3675 return UnderlyingDecl != nullptr &&
3676 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3677}
3678
3679/// Matches on the implicit object argument of a member call expression, after
3680/// stripping off any parentheses or implicit casts.
3681///
3682/// Given
3683/// \code
3684/// class Y { public: void m(); };
3685/// Y g();
3686/// class X : public Y {};
3687/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3688/// \endcode
3689/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3690/// matches `y.m()` and `(g()).m()`.
3691/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3692/// matches `x.m()`.
3693/// cxxMemberCallExpr(on(callExpr()))
3694/// matches `(g()).m()`.
3695///
3696/// FIXME: Overload to allow directly matching types?
3697AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3698 InnerMatcher) {
3699 const Expr *ExprNode = Node.getImplicitObjectArgument()
3700 ->IgnoreParenImpCasts();
3701 return (ExprNode != nullptr &&
3702 InnerMatcher.matches(*ExprNode, Finder, Builder));
3703}
3704
3705
3706/// Matches on the receiver of an ObjectiveC Message expression.
3707///
3708/// Example
3709/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3710/// matches the [webView ...] message invocation.
3711/// \code
3712/// NSString *webViewJavaScript = ...
3713/// UIWebView *webView = ...
3714/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3715/// \endcode
3716AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3717 InnerMatcher) {
3718 const QualType TypeDecl = Node.getReceiverType();
3719 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3720}
3721
3722/// Returns true when the Objective-C method declaration is a class method.
3723///
3724/// Example
3725/// matcher = objcMethodDecl(isClassMethod())
3726/// matches
3727/// \code
3728/// @interface I + (void)foo; @end
3729/// \endcode
3730/// but not
3731/// \code
3732/// @interface I - (void)bar; @end
3733/// \endcode
3735 return Node.isClassMethod();
3736}
3737
3738/// Returns true when the Objective-C method declaration is an instance method.
3739///
3740/// Example
3741/// matcher = objcMethodDecl(isInstanceMethod())
3742/// matches
3743/// \code
3744/// @interface I - (void)bar; @end
3745/// \endcode
3746/// but not
3747/// \code
3748/// @interface I + (void)foo; @end
3749/// \endcode
3751 return Node.isInstanceMethod();
3752}
3753
3754/// Returns true when the Objective-C message is sent to a class.
3755///
3756/// Example
3757/// matcher = objcMessageExpr(isClassMessage())
3758/// matches
3759/// \code
3760/// [NSString stringWithFormat:@"format"];
3761/// \endcode
3762/// but not
3763/// \code
3764/// NSString *x = @"hello";
3765/// [x containsString:@"h"];
3766/// \endcode
3768 return Node.isClassMessage();
3769}
3770
3771/// Returns true when the Objective-C message is sent to an instance.
3772///
3773/// Example
3774/// matcher = objcMessageExpr(isInstanceMessage())
3775/// matches
3776/// \code
3777/// NSString *x = @"hello";
3778/// [x containsString:@"h"];
3779/// \endcode
3780/// but not
3781/// \code
3782/// [NSString stringWithFormat:@"format"];
3783/// \endcode
3784AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3785 return Node.isInstanceMessage();
3786}
3787
3788/// Matches if the Objective-C message is sent to an instance,
3789/// and the inner matcher matches on that instance.
3790///
3791/// For example the method call in
3792/// \code
3793/// NSString *x = @"hello";
3794/// [x containsString:@"h"];
3795/// \endcode
3796/// is matched by
3797/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3798AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3799 InnerMatcher) {
3800 const Expr *ReceiverNode = Node.getInstanceReceiver();
3801 return (ReceiverNode != nullptr &&
3802 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3803 Builder));
3804}
3805
3806/// Matches when BaseName == Selector.getAsString()
3807///
3808/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3809/// matches the outer message expr in the code below, but NOT the message
3810/// invocation for self.bodyView.
3811/// \code
3812/// [self.bodyView loadHTMLString:html baseURL:NULL];
3813/// \endcode
3814AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3815 Selector Sel = Node.getSelector();
3816 return BaseName == Sel.getAsString();
3817}
3818
3819/// Matches when at least one of the supplied string equals to the
3820/// Selector.getAsString()
3821///
3822/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3823/// matches both of the expressions below:
3824/// \code
3825/// [myObj methodA:argA];
3826/// [myObj methodB:argB];
3827/// \endcode
3828extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3829 StringRef,
3832
3833/// Matches ObjC selectors whose name contains
3834/// a substring matched by the given RegExp.
3835/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3836/// matches the outer message expr in the code below, but NOT the message
3837/// invocation for self.bodyView.
3838/// \code
3839/// [self.bodyView loadHTMLString:html baseURL:NULL];
3840/// \endcode
3841AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3842 std::string SelectorString = Node.getSelector().getAsString();
3843 return RegExp->match(SelectorString);
3844}
3845
3846/// Matches when the selector is the empty selector
3847///
3848/// Matches only when the selector of the objCMessageExpr is NULL. This may
3849/// represent an error condition in the tree!
3850AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3851 return Node.getSelector().isNull();
3852}
3853
3854/// Matches when the selector is a Unary Selector
3855///
3856/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3857/// matches self.bodyView in the code below, but NOT the outer message
3858/// invocation of "loadHTMLString:baseURL:".
3859/// \code
3860/// [self.bodyView loadHTMLString:html baseURL:NULL];
3861/// \endcode
3862AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3863 return Node.getSelector().isUnarySelector();
3864}
3865
3866/// Matches when the selector is a keyword selector
3867///
3868/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3869/// message expression in
3870///
3871/// \code
3872/// UIWebView *webView = ...;
3873/// CGRect bodyFrame = webView.frame;
3874/// bodyFrame.size.height = self.bodyContentHeight;
3875/// webView.frame = bodyFrame;
3876/// // ^---- matches here
3877/// \endcode
3878AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3879 return Node.getSelector().isKeywordSelector();
3880}
3881
3882/// Matches when the selector has the specified number of arguments
3883///
3884/// matcher = objCMessageExpr(numSelectorArgs(0));
3885/// matches self.bodyView in the code below
3886///
3887/// matcher = objCMessageExpr(numSelectorArgs(2));
3888/// matches the invocation of "loadHTMLString:baseURL:" but not that
3889/// of self.bodyView
3890/// \code
3891/// [self.bodyView loadHTMLString:html baseURL:NULL];
3892/// \endcode
3893AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3894 return Node.getSelector().getNumArgs() == N;
3895}
3896
3897/// Matches if the call or fold expression's callee expression matches.
3898///
3899/// Given
3900/// \code
3901/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3902/// void f() { f(); }
3903/// \endcode
3904/// callExpr(callee(expr()))
3905/// matches this->x(), x(), y.x(), f()
3906/// with callee(...)
3907/// matching this->x, x, y.x, f respectively
3908///
3909/// Given
3910/// \code
3911/// template <typename... Args>
3912/// auto sum(Args... args) {
3913/// return (0 + ... + args);
3914/// }
3915///
3916/// template <typename... Args>
3917/// auto multiply(Args... args) {
3918/// return (args * ... * 1);
3919/// }
3920/// \endcode
3921/// cxxFoldExpr(callee(expr()))
3922/// matches (args * ... * 1)
3923/// with callee(...)
3924/// matching *
3925///
3926/// Note: Callee cannot take the more general internal::Matcher<Expr>
3927/// because this introduces ambiguous overloads with calls to Callee taking a
3928/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3929/// implemented in terms of implicit casts.
3932 CXXFoldExpr),
3933 internal::Matcher<Stmt>, InnerMatcher, 0) {
3934 const auto *ExprNode = Node.getCallee();
3935 return (ExprNode != nullptr &&
3936 InnerMatcher.matches(*ExprNode, Finder, Builder));
3937}
3938
3939/// Matches 1) if the call expression's callee's declaration matches the
3940/// given matcher; or 2) if the Obj-C message expression's callee's method
3941/// declaration matches the given matcher.
3942///
3943/// Example matches y.x() (matcher = callExpr(callee(
3944/// cxxMethodDecl(hasName("x")))))
3945/// \code
3946/// class Y { public: void x(); };
3947/// void z() { Y y; y.x(); }
3948/// \endcode
3949///
3950/// Example 2. Matches [I foo] with
3951/// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3952///
3953/// \code
3954/// @interface I: NSObject
3955/// +(void)foo;
3956/// @end
3957/// ...
3958/// [I foo]
3959/// \endcode
3962 internal::Matcher<Decl>, InnerMatcher, 1) {
3963 if (isa<CallExpr>(&Node))
3964 return callExpr(hasDeclaration(InnerMatcher))
3965 .matches(Node, Finder, Builder);
3966 else {
3967 // The dynamic cast below is guaranteed to succeed as there are only 2
3968 // supported return types.
3969 const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
3970 const Decl *DeclNode = MsgNode->getMethodDecl();
3971 return (DeclNode != nullptr &&
3972 InnerMatcher.matches(*DeclNode, Finder, Builder));
3973 }
3974}
3975
3976/// Matches if the expression's or declaration's type matches a type
3977/// matcher.
3978///
3979/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3980/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3981/// and U (matcher = typedefDecl(hasType(asString("int")))
3982/// and friend class X (matcher = friendDecl(hasType("X"))
3983/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3984/// asString("class X")))
3985/// \code
3986/// class X {};
3987/// void y(X &x) { x; X z; }
3988/// typedef int U;
3989/// class Y { friend class X; };
3990/// class Z : public virtual X {};
3991/// \endcode
3993 hasType,
3996 internal::Matcher<QualType>, InnerMatcher, 0) {
3997 QualType QT = internal::getUnderlyingType(Node);
3998 if (!QT.isNull())
3999 return InnerMatcher.matches(QT, Finder, Builder);
4000 return false;
4001}
4002
4003/// Overloaded to match the declaration of the expression's or value
4004/// declaration's type.
4005///
4006/// In case of a value declaration (for example a variable declaration),
4007/// this resolves one layer of indirection. For example, in the value
4008/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
4009/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
4010/// declaration of x.
4011///
4012/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4013/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4014/// and friend class X (matcher = friendDecl(hasType("X"))
4015/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4016/// cxxRecordDecl(hasName("X"))))
4017/// \code
4018/// class X {};
4019/// void y(X &x) { x; X z; }
4020/// class Y { friend class X; };
4021/// class Z : public virtual X {};
4022/// \endcode
4023///
4024/// Example matches class Derived
4025/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
4026/// \code
4027/// class Base {};
4028/// class Derived : Base {};
4029/// \endcode
4030///
4031/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
4032/// Matcher<CXXBaseSpecifier>
4034 hasType,
4037 internal::Matcher<Decl>, InnerMatcher, 1) {
4038 QualType QT = internal::getUnderlyingType(Node);
4039 if (!QT.isNull())
4040 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
4041 return false;
4042}
4043
4044/// Matches if the type location of a node matches the inner matcher.
4045///
4046/// Examples:
4047/// \code
4048/// int x;
4049/// \endcode
4050/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
4051/// matches int x
4052///
4053/// \code
4054/// auto x = int(3);
4055/// \endcode
4056/// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
4057/// matches int(3)
4058///
4059/// \code
4060/// struct Foo { Foo(int, int); };
4061/// auto x = Foo(1, 2);
4062/// \endcode
4063/// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
4064/// matches Foo(1, 2)
4065///
4066/// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
4067/// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
4068/// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
4069/// Matcher<CXXUnresolvedConstructExpr>,
4070/// Matcher<CompoundLiteralExpr>,
4071/// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
4072/// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
4073/// Matcher<TypedefNameDecl>
4075 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 templateSpecializationType, class template specialization,
5308/// variable template specialization, and function template specialization
5309/// nodes where the template argument matches the inner matcher. This matcher
5310/// may produce multiple matches.
5311///
5312/// Given
5313/// \code
5314/// template <typename T, unsigned N, unsigned M>
5315/// struct Matrix {};
5316///
5317/// constexpr unsigned R = 2;
5318/// Matrix<int, R * 2, R * 4> M;
5319///
5320/// template <typename T, typename U>
5321/// void f(T&& t, U&& u) {}
5322///
5323/// bool B = false;
5324/// f(R, B);
5325/// \endcode
5326/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5327/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5328/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5329/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5330/// and 'bool'
5332 forEachTemplateArgument,
5336 internal::Matcher<TemplateArgument>, InnerMatcher) {
5337 ArrayRef<TemplateArgument> TemplateArgs =
5338 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5339 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5340 bool Matched = false;
5341 for (const auto &Arg : TemplateArgs) {
5342 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5343 if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5344 Matched = true;
5345 Result.addMatch(ArgBuilder);
5346 }
5347 }
5348 *Builder = std::move(Result);
5349 return Matched;
5350}
5351
5352/// Matches \c FunctionDecls that have a noreturn attribute.
5353///
5354/// Given
5355/// \code
5356/// void nope();
5357/// [[noreturn]] void a();
5358/// __attribute__((noreturn)) void b();
5359/// struct c { [[noreturn]] c(); };
5360/// \endcode
5361/// functionDecl(isNoReturn())
5362/// matches all of those except
5363/// \code
5364/// void nope();
5365/// \endcode
5366AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5367
5368/// Matches the return type of a function declaration.
5369///
5370/// Given:
5371/// \code
5372/// class X { int f() { return 1; } };
5373/// \endcode
5374/// cxxMethodDecl(returns(asString("int")))
5375/// matches int f() { return 1; }
5377 internal::Matcher<QualType>, InnerMatcher) {
5378 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5379}
5380
5381/// Matches extern "C" function or variable declarations.
5382///
5383/// Given:
5384/// \code
5385/// extern "C" void f() {}
5386/// extern "C" { void g() {} }
5387/// void h() {}
5388/// extern "C" int x = 1;
5389/// extern "C" int y = 2;
5390/// int z = 3;
5391/// \endcode
5392/// functionDecl(isExternC())
5393/// matches the declaration of f and g, but not the declaration of h.
5394/// varDecl(isExternC())
5395/// matches the declaration of x and y, but not the declaration of z.
5397 VarDecl)) {
5398 return Node.isExternC();
5399}
5400
5401/// Matches variable/function declarations that have "static" storage
5402/// class specifier ("static" keyword) written in the source.
5403///
5404/// Given:
5405/// \code
5406/// static void f() {}
5407/// static int i = 0;
5408/// extern int j;
5409/// int k;
5410/// \endcode
5411/// functionDecl(isStaticStorageClass())
5412/// matches the function declaration f.
5413/// varDecl(isStaticStorageClass())
5414/// matches the variable declaration i.
5415AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5417 VarDecl)) {
5418 return Node.getStorageClass() == SC_Static;
5419}
5420
5421/// Matches deleted function declarations.
5422///
5423/// Given:
5424/// \code
5425/// void Func();
5426/// void DeletedFunc() = delete;
5427/// \endcode
5428/// functionDecl(isDeleted())
5429/// matches the declaration of DeletedFunc, but not Func.
5431 return Node.isDeleted();
5432}
5433
5434/// Matches defaulted function declarations.
5435///
5436/// Given:
5437/// \code
5438/// class A { ~A(); };
5439/// class B { ~B() = default; };
5440/// \endcode
5441/// functionDecl(isDefaulted())
5442/// matches the declaration of ~B, but not ~A.
5444 return Node.isDefaulted();
5445}
5446
5447/// Matches weak function declarations.
5448///
5449/// Given:
5450/// \code
5451/// void foo() __attribute__((__weakref__("__foo")));
5452/// void bar();
5453/// \endcode
5454/// functionDecl(isWeak())
5455/// matches the weak declaration "foo", but not "bar".
5456AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5457
5458/// Matches functions that have a dynamic exception specification.
5459///
5460/// Given:
5461/// \code
5462/// void f();
5463/// void g() noexcept;
5464/// void h() noexcept(true);
5465/// void i() noexcept(false);
5466/// void j() throw();
5467/// void k() throw(int);
5468/// void l() throw(...);
5469/// \endcode
5470/// functionDecl(hasDynamicExceptionSpec()) and
5471/// functionProtoType(hasDynamicExceptionSpec())
5472/// match the declarations of j, k, and l, but not f, g, h, or i.
5473AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5476 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5477 return FnTy->hasDynamicExceptionSpec();
5478 return false;
5479}
5480
5481/// Matches functions that have a non-throwing exception specification.
5482///
5483/// Given:
5484/// \code
5485/// void f();
5486/// void g() noexcept;
5487/// void h() throw();
5488/// void i() throw(int);
5489/// void j() noexcept(false);
5490/// \endcode
5491/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5492/// match the declarations of g, and h, but not f, i or j.
5496 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5497
5498 // If the function does not have a prototype, then it is assumed to be a
5499 // throwing function (as it would if the function did not have any exception
5500 // specification).
5501 if (!FnTy)
5502 return false;
5503
5504 // Assume the best for any unresolved exception specification.
5506 return true;
5507
5508 return FnTy->isNothrow();
5509}
5510
5511/// Matches consteval function declarations and if consteval/if ! consteval
5512/// statements.
5513///
5514/// Given:
5515/// \code
5516/// consteval int a();
5517/// void b() { if consteval {} }
5518/// void c() { if ! consteval {} }
5519/// void d() { if ! consteval {} else {} }
5520/// \endcode
5521/// functionDecl(isConsteval())
5522/// matches the declaration of "int a()".
5523/// ifStmt(isConsteval())
5524/// matches the if statement in "void b()", "void c()", "void d()".
5527 return Node.isConsteval();
5528}
5529
5530/// Matches constexpr variable and function declarations,
5531/// and if constexpr.
5532///
5533/// Given:
5534/// \code
5535/// constexpr int foo = 42;
5536/// constexpr int bar();
5537/// void baz() { if constexpr(1 > 0) {} }
5538/// \endcode
5539/// varDecl(isConstexpr())
5540/// matches the declaration of foo.
5541/// functionDecl(isConstexpr())
5542/// matches the declaration of bar.
5543/// ifStmt(isConstexpr())
5544/// matches the if statement in baz.
5548 IfStmt)) {
5549 return Node.isConstexpr();
5550}
5551
5552/// Matches constinit variable declarations.
5553///
5554/// Given:
5555/// \code
5556/// constinit int foo = 42;
5557/// constinit const char* bar = "bar";
5558/// int baz = 42;
5559/// [[clang::require_constant_initialization]] int xyz = 42;
5560/// \endcode
5561/// varDecl(isConstinit())
5562/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5563AST_MATCHER(VarDecl, isConstinit) {
5564 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5565 return CIA->isConstinit();
5566 return false;
5567}
5568
5569/// Matches selection statements with initializer.
5570///
5571/// Given:
5572/// \code
5573/// void foo() {
5574/// if (int i = foobar(); i > 0) {}
5575/// switch (int i = foobar(); i) {}
5576/// for (auto& a = get_range(); auto& x : a) {}
5577/// }
5578/// void bar() {
5579/// if (foobar() > 0) {}
5580/// switch (foobar()) {}
5581/// for (auto& x : get_range()) {}
5582/// }
5583/// \endcode
5584/// ifStmt(hasInitStatement(anything()))
5585/// matches the if statement in foo but not in bar.
5586/// switchStmt(hasInitStatement(anything()))
5587/// matches the switch statement in foo but not in bar.
5588/// cxxForRangeStmt(hasInitStatement(anything()))
5589/// matches the range for statement in foo but not in bar.
5593 internal::Matcher<Stmt>, InnerMatcher) {
5594 const Stmt *Init = Node.getInit();
5595 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5596}
5597
5598/// Matches the condition expression of an if statement, for loop,
5599/// switch statement or conditional operator.
5600///
5601/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5602/// \code
5603/// if (true) {}
5604/// \endcode
5606 hasCondition,
5609 internal::Matcher<Expr>, InnerMatcher) {
5610 const Expr *const Condition = Node.getCond();
5611 return (Condition != nullptr &&
5612 InnerMatcher.matches(*Condition, Finder, Builder));
5613}
5614
5615/// Matches the then-statement of an if statement.
5616///
5617/// Examples matches the if statement
5618/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5619/// \code
5620/// if (false) true; else false;
5621/// \endcode
5622AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5623 const Stmt *const Then = Node.getThen();
5624 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5625}
5626
5627/// Matches the else-statement of an if statement.
5628///
5629/// Examples matches the if statement
5630/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5631/// \code
5632/// if (false) false; else true;
5633/// \endcode
5634AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5635 const Stmt *const Else = Node.getElse();
5636 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5637}
5638
5639/// Matches if a node equals a previously bound node.
5640///
5641/// Matches a node if it equals the node previously bound to \p ID.
5642///
5643/// Given
5644/// \code
5645/// class X { int a; int b; };
5646/// \endcode
5647/// cxxRecordDecl(
5648/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5649/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5650/// matches the class \c X, as \c a and \c b have the same type.
5651///
5652/// Note that when multiple matches are involved via \c forEach* matchers,
5653/// \c equalsBoundNodes acts as a filter.
5654/// For example:
5655/// compoundStmt(
5656/// forEachDescendant(varDecl().bind("d")),
5657/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5658/// will trigger a match for each combination of variable declaration
5659/// and reference to that variable declaration within a compound statement.
5662 QualType),
5663 std::string, ID) {
5664 // FIXME: Figure out whether it makes sense to allow this
5665 // on any other node types.
5666 // For *Loc it probably does not make sense, as those seem
5667 // unique. For NestedNameSepcifier it might make sense, as
5668 // those also have pointer identity, but I'm not sure whether
5669 // they're ever reused.
5670 internal::NotEqualsBoundNodePredicate Predicate;
5671 Predicate.ID = ID;
5672 Predicate.Node = DynTypedNode::create(Node);
5673 return Builder->removeBindings(Predicate);
5674}
5675
5676/// Matches the condition variable statement in an if statement.
5677///
5678/// Given
5679/// \code
5680/// if (A* a = GetAPointer()) {}
5681/// \endcode
5682/// hasConditionVariableStatement(...)
5683/// matches 'A* a = GetAPointer()'.
5684AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5685 internal::Matcher<DeclStmt>, InnerMatcher) {
5686 const DeclStmt* const DeclarationStatement =
5687 Node.getConditionVariableDeclStmt();
5688 return DeclarationStatement != nullptr &&
5689 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5690}
5691
5692/// Matches the index expression of an array subscript expression.
5693///
5694/// Given
5695/// \code
5696/// int i[5];
5697/// void f() { i[1] = 42; }
5698/// \endcode
5699/// arraySubscriptExpression(hasIndex(integerLiteral()))
5700/// matches \c i[1] with the \c integerLiteral() matching \c 1
5702 internal::Matcher<Expr>, InnerMatcher) {
5703 if (const Expr* Expression = Node.getIdx())
5704 return InnerMatcher.matches(*Expression, Finder, Builder);
5705 return false;
5706}
5707
5708/// Matches the base expression of an array subscript expression.
5709///
5710/// Given
5711/// \code
5712/// int i[5];
5713/// void f() { i[1] = 42; }
5714/// \endcode
5715/// arraySubscriptExpression(hasBase(implicitCastExpr(
5716/// hasSourceExpression(declRefExpr()))))
5717/// matches \c i[1] with the \c declRefExpr() matching \c i
5719 internal::Matcher<Expr>, InnerMatcher) {
5720 if (const Expr* Expression = Node.getBase())
5721 return InnerMatcher.matches(*Expression, Finder, Builder);
5722 return false;
5723}
5724
5725/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5726/// definition that has a given body. Note that in case of functions or
5727/// coroutines this matcher only matches the definition itself and not the
5728/// other declarations of the same function or coroutine.
5729///
5730/// Given
5731/// \code
5732/// for (;;) {}
5733/// \endcode
5734/// forStmt(hasBody(compoundStmt()))
5735/// matches 'for (;;) {}'
5736/// with compoundStmt()
5737/// matching '{}'
5738///
5739/// Given
5740/// \code
5741/// void f();
5742/// void f() {}
5743/// \endcode
5744/// functionDecl(hasBody(compoundStmt()))
5745/// matches 'void f() {}'
5746/// with compoundStmt()
5747/// matching '{}'
5748/// but does not match 'void f();'
5750 hasBody,
5753 internal::Matcher<Stmt>, InnerMatcher) {
5754 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5755 return false;
5756 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5757 return (Statement != nullptr &&
5758 InnerMatcher.matches(*Statement, Finder, Builder));
5759}
5760
5761/// Matches a function declaration that has a given body present in the AST.
5762/// Note that this matcher matches all the declarations of a function whose
5763/// body is present in the AST.
5764///
5765/// Given
5766/// \code
5767/// void f();
5768/// void f() {}
5769/// void g();
5770/// \endcode
5771/// functionDecl(hasAnyBody(compoundStmt()))
5772/// matches both 'void f();'
5773/// and 'void f() {}'
5774/// with compoundStmt()
5775/// matching '{}'
5776/// but does not match 'void g();'
5778 internal::Matcher<Stmt>, InnerMatcher) {
5779 const Stmt *const Statement = Node.getBody();
5780 return (Statement != nullptr &&
5781 InnerMatcher.matches(*Statement, Finder, Builder));
5782}
5783
5784
5785/// Matches compound statements where at least one substatement matches
5786/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5787///
5788/// Given
5789/// \code
5790/// { {}; 1+2; }
5791/// \endcode
5792/// hasAnySubstatement(compoundStmt())
5793/// matches '{ {}; 1+2; }'
5794/// with compoundStmt()
5795/// matching '{}'
5796AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5798 StmtExpr),
5799 internal::Matcher<Stmt>, InnerMatcher) {
5800 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5801 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5802 CS->body_end(), Finder,
5803 Builder) != CS->body_end();
5804}
5805
5806/// Checks that a compound statement contains a specific number of
5807/// child statements.
5808///
5809/// Example: Given
5810/// \code
5811/// { for (;;) {} }
5812/// \endcode
5813/// compoundStmt(statementCountIs(0)))
5814/// matches '{}'
5815/// but does not match the outer compound statement.
5816AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5817 return Node.size() == N;
5818}
5819
5820/// Matches literals that are equal to the given value of type ValueT.
5821///
5822/// Given
5823/// \code
5824/// f('\0', false, 3.14, 42);
5825/// \endcode
5826/// characterLiteral(equals(0))
5827/// matches '\0'
5828/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5829/// match false
5830/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5831/// match 3.14
5832/// integerLiteral(equals(42))
5833/// matches 42
5834///
5835/// Note that you cannot directly match a negative numeric literal because the
5836/// minus sign is not part of the literal: It is a unary operator whose operand
5837/// is the positive numeric literal. Instead, you must use a unaryOperator()
5838/// matcher to match the minus sign:
5839///
5840/// unaryOperator(hasOperatorName("-"),
5841/// hasUnaryOperand(integerLiteral(equals(13))))
5842///
5843/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5844/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5845template <typename ValueT>
5846internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5847 void(internal::AllNodeBaseTypes), ValueT>
5848equals(const ValueT &Value) {
5849 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5850 void(internal::AllNodeBaseTypes), ValueT>(
5851 Value);
5852}
5853
5858 bool, Value, 0) {
5859 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5860 .matchesNode(Node);
5861}
5862
5867 unsigned, Value, 1) {
5868 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5869 .matchesNode(Node);
5870}
5871
5877 double, Value, 2) {
5878 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5879 .matchesNode(Node);
5880}
5881
5882/// Matches the operator Name of operator expressions and fold expressions
5883/// (binary or unary).
5884///
5885/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5886/// \code
5887/// !(a || b)
5888/// \endcode
5889///
5890/// Example matches `(0 + ... + args)`
5891/// (matcher = cxxFoldExpr(hasOperatorName("+")))
5892/// \code
5893/// template <typename... Args>
5894/// auto sum(Args... args) {
5895/// return (0 + ... + args);
5896/// }
5897/// \endcode
5899 hasOperatorName,
5903 std::string, Name) {
5904 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5905 return *OpName == Name;
5906 return false;
5907}
5908
5909/// Matches operator expressions (binary or unary) that have any of the
5910/// specified names.
5911///
5912/// hasAnyOperatorName("+", "-")
5913/// Is equivalent to
5914/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5915extern const internal::VariadicFunction<
5916 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5920 std::vector<std::string>>,
5923
5924/// Matches all kinds of assignment operators.
5925///
5926/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5927/// \code
5928/// if (a == b)
5929/// a += b;
5930/// \endcode
5931///
5932/// Example 2: matches s1 = s2
5933/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5934/// \code
5935/// struct S { S& operator=(const S&); };
5936/// void x() { S s1, s2; s1 = s2; }
5937/// \endcode
5939 isAssignmentOperator,
5942 return Node.isAssignmentOp();
5943}
5944
5945/// Matches comparison operators.
5946///
5947/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5948/// \code
5949/// if (a == b)
5950/// a += b;
5951/// \endcode
5952///
5953/// Example 2: matches s1 < s2
5954/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5955/// \code
5956/// struct S { bool operator<(const S& other); };
5957/// void x(S s1, S s2) { bool b1 = s1 < s2; }
5958/// \endcode
5960 isComparisonOperator,
5963 return Node.isComparisonOp();
5964}
5965
5966/// Matches the left hand side of binary operator expressions.
5967///
5968/// Example matches a (matcher = binaryOperator(hasLHS()))
5969/// \code
5970/// a || b
5971/// \endcode
5973 hasLHS,
5977 internal::Matcher<Expr>, InnerMatcher) {
5978 const Expr *LeftHandSide = internal::getLHS(Node);
5979 return (LeftHandSide != nullptr &&
5980 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
5981}
5982
5983/// Matches the right hand side of binary operator expressions.
5984///
5985/// Example matches b (matcher = binaryOperator(hasRHS()))
5986/// \code
5987/// a || b
5988/// \endcode
5990 hasRHS,
5994 internal::Matcher<Expr>, InnerMatcher) {
5995 const Expr *RightHandSide = internal::getRHS(Node);
5996 return (RightHandSide != nullptr &&
5997 InnerMatcher.matches(*RightHandSide, Finder, Builder));
5998}
5999
6000/// Matches if either the left hand side or the right hand side of a
6001/// binary operator or fold expression matches.
6003 hasEitherOperand,
6006 internal::Matcher<Expr>, InnerMatcher) {
6007 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6008 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
6009 .matches(Node, Finder, Builder);
6010}
6011
6012/// Matches if both matchers match with opposite sides of the binary operator
6013/// or fold expression.
6014///
6015/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
6016/// integerLiteral(equals(2)))
6017/// \code
6018/// 1 + 2 // Match
6019/// 2 + 1 // Match
6020/// 1 + 1 // No match
6021/// 2 + 2 // No match
6022/// \endcode
6024 hasOperands,
6027 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
6028 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6029 anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
6030