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 export declaration.
1240///
1241/// Example matches following declarations.
1242/// \code
1243/// export void foo();
1244/// export { void foo(); }
1245/// export namespace { void foo(); }
1246/// export int v;
1247/// \endcode
1248extern const internal::VariadicDynCastAllOfMatcher<Decl, ExportDecl> exportDecl;
1249
1250/// Matches any value declaration.
1251///
1252/// Example matches A, B, C and F
1253/// \code
1254/// enum X { A, B, C };
1255/// void F();
1256/// \endcode
1257extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1258
1259/// Matches C++ constructor declarations.
1260///
1261/// Example matches Foo::Foo() and Foo::Foo(int)
1262/// \code
1263/// class Foo {
1264/// public:
1265/// Foo();
1266/// Foo(int);
1267/// int DoSomething();
1268/// };
1269/// \endcode
1270extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1272
1273/// Matches explicit C++ destructor declarations.
1274///
1275/// Example matches Foo::~Foo()
1276/// \code
1277/// class Foo {
1278/// public:
1279/// virtual ~Foo();
1280/// };
1281/// \endcode
1282extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1284
1285/// Matches enum declarations.
1286///
1287/// Example matches X
1288/// \code
1289/// enum X {
1290/// A, B, C
1291/// };
1292/// \endcode
1293extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1294
1295/// Matches enum constants.
1296///
1297/// Example matches A, B, C
1298/// \code
1299/// enum X {
1300/// A, B, C
1301/// };
1302/// \endcode
1303extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1305
1306/// Matches tag declarations.
1307///
1308/// Example matches X, Z, U, S, E
1309/// \code
1310/// class X;
1311/// template<class T> class Z {};
1312/// struct S {};
1313/// union U {};
1314/// enum E {
1315/// A, B, C
1316/// };
1317/// \endcode
1318extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1319
1320/// Matches method declarations.
1321///
1322/// Example matches y
1323/// \code
1324/// class X { void y(); };
1325/// \endcode
1326extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1328
1329/// Matches conversion operator declarations.
1330///
1331/// Example matches the operator.
1332/// \code
1333/// class X { operator int() const; };
1334/// \endcode
1335extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1337
1338/// Matches user-defined and implicitly generated deduction guide.
1339///
1340/// Example matches the deduction guide.
1341/// \code
1342/// template<typename T>
1343/// class X { X(int) };
1344/// X(int) -> X<int>;
1345/// \endcode
1346extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1348
1349/// Matches concept declarations.
1350///
1351/// Example matches integral
1352/// \code
1353/// template<typename T>
1354/// concept integral = std::is_integral_v<T>;
1355/// \endcode
1356extern const internal::VariadicDynCastAllOfMatcher<Decl, ConceptDecl>
1358
1359/// Matches variable declarations.
1360///
1361/// Note: this does not match declarations of member variables, which are
1362/// "field" declarations in Clang parlance.
1363///
1364/// Example matches a
1365/// \code
1366/// int a;
1367/// \endcode
1368extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1369
1370/// Matches field declarations.
1371///
1372/// Given
1373/// \code
1374/// class X { int m; };
1375/// \endcode
1376/// fieldDecl()
1377/// matches 'm'.
1378extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1379
1380/// Matches indirect field declarations.
1381///
1382/// Given
1383/// \code
1384/// struct X { struct { int a; }; };
1385/// \endcode
1386/// indirectFieldDecl()
1387/// matches 'a'.
1388extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1390
1391/// Matches function declarations.
1392///
1393/// Example matches f
1394/// \code
1395/// void f();
1396/// \endcode
1397extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1399
1400/// Matches C++ function template declarations.
1401///
1402/// Example matches f
1403/// \code
1404/// template<class T> void f(T t) {}
1405/// \endcode
1406extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1408
1409/// Matches friend declarations.
1410///
1411/// Given
1412/// \code
1413/// class X { friend void foo(); };
1414/// \endcode
1415/// friendDecl()
1416/// matches 'friend void foo()'.
1417extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1418
1419/// Matches statements.
1420///
1421/// Given
1422/// \code
1423/// { ++a; }
1424/// \endcode
1425/// stmt()
1426/// matches both the compound statement '{ ++a; }' and '++a'.
1427extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1428
1429/// Matches declaration statements.
1430///
1431/// Given
1432/// \code
1433/// int a;
1434/// \endcode
1435/// declStmt()
1436/// matches 'int a'.
1437extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1438
1439/// Matches member expressions.
1440///
1441/// Given
1442/// \code
1443/// class Y {
1444/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1445/// int a; static int b;
1446/// };
1447/// \endcode
1448/// memberExpr()
1449/// matches this->x, x, y.x, a, this->b
1450extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1451
1452/// Matches unresolved member expressions.
1453///
1454/// Given
1455/// \code
1456/// struct X {
1457/// template <class T> void f();
1458/// void g();
1459/// };
1460/// template <class T> void h() { X x; x.f<T>(); x.g(); }
1461/// \endcode
1462/// unresolvedMemberExpr()
1463/// matches x.f<T>
1464extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1466
1467/// Matches member expressions where the actual member referenced could not be
1468/// resolved because the base expression or the member name was dependent.
1469///
1470/// Given
1471/// \code
1472/// template <class T> void f() { T t; t.g(); }
1473/// \endcode
1474/// cxxDependentScopeMemberExpr()
1475/// matches t.g
1476extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1479
1480/// Matches call expressions.
1481///
1482/// Example matches x.y() and y()
1483/// \code
1484/// X x;
1485/// x.y();
1486/// y();
1487/// \endcode
1488extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1489
1490/// Matches call expressions which were resolved using ADL.
1491///
1492/// Example matches y(x) but not y(42) or NS::y(x).
1493/// \code
1494/// namespace NS {
1495/// struct X {};
1496/// void y(X);
1497/// }
1498///
1499/// void y(...);
1500///
1501/// void test() {
1502/// NS::X x;
1503/// y(x); // Matches
1504/// NS::y(x); // Doesn't match
1505/// y(42); // Doesn't match
1506/// using NS::y;
1507/// y(x); // Found by both unqualified lookup and ADL, doesn't match
1508// }
1509/// \endcode
1510AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1511
1512/// Matches lambda expressions.
1513///
1514/// Example matches [&](){return 5;}
1515/// \code
1516/// [&](){return 5;}
1517/// \endcode
1518extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1519
1520/// Matches member call expressions.
1521///
1522/// Example matches x.y()
1523/// \code
1524/// X x;
1525/// x.y();
1526/// \endcode
1527extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1529
1530/// Matches ObjectiveC Message invocation expressions.
1531///
1532/// The innermost message send invokes the "alloc" class method on the
1533/// NSString class, while the outermost message send invokes the
1534/// "initWithString" instance method on the object returned from
1535/// NSString's "alloc". This matcher should match both message sends.
1536/// \code
1537/// [[NSString alloc] initWithString:@"Hello"]
1538/// \endcode
1539extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1541
1542/// Matches ObjectiveC String literal expressions.
1543///
1544/// Example matches @"abcd"
1545/// \code
1546/// NSString *s = @"abcd";
1547/// \endcode
1548extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
1550
1551/// Matches Objective-C interface declarations.
1552///
1553/// Example matches Foo
1554/// \code
1555/// @interface Foo
1556/// @end
1557/// \endcode
1558extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1560
1561/// Matches Objective-C implementation declarations.
1562///
1563/// Example matches Foo
1564/// \code
1565/// @implementation Foo
1566/// @end
1567/// \endcode
1568extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1570
1571/// Matches Objective-C protocol declarations.
1572///
1573/// Example matches FooDelegate
1574/// \code
1575/// @protocol FooDelegate
1576/// @end
1577/// \endcode
1578extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1580
1581/// Matches Objective-C category declarations.
1582///
1583/// Example matches Foo (Additions)
1584/// \code
1585/// @interface Foo (Additions)
1586/// @end
1587/// \endcode
1588extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1590
1591/// Matches Objective-C category definitions.
1592///
1593/// Example matches Foo (Additions)
1594/// \code
1595/// @implementation Foo (Additions)
1596/// @end
1597/// \endcode
1598extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1600
1601/// Matches Objective-C method declarations.
1602///
1603/// Example matches both declaration and definition of -[Foo method]
1604/// \code
1605/// @interface Foo
1606/// - (void)method;
1607/// @end
1608///
1609/// @implementation Foo
1610/// - (void)method {}
1611/// @end
1612/// \endcode
1613extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1615
1616/// Matches block declarations.
1617///
1618/// Example matches the declaration of the nameless block printing an input
1619/// integer.
1620///
1621/// \code
1622/// myFunc(^(int p) {
1623/// printf("%d", p);
1624/// })
1625/// \endcode
1626extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1627 blockDecl;
1628
1629/// Matches Objective-C instance variable declarations.
1630///
1631/// Example matches _enabled
1632/// \code
1633/// @implementation Foo {
1634/// BOOL _enabled;
1635/// }
1636/// @end
1637/// \endcode
1638extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1640
1641/// Matches Objective-C property declarations.
1642///
1643/// Example matches enabled
1644/// \code
1645/// @interface Foo
1646/// @property BOOL enabled;
1647/// @end
1648/// \endcode
1649extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1651
1652/// Matches Objective-C \@throw statements.
1653///
1654/// Example matches \@throw
1655/// \code
1656/// @throw obj;
1657/// \endcode
1658extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1660
1661/// Matches Objective-C @try statements.
1662///
1663/// Example matches @try
1664/// \code
1665/// @try {}
1666/// @catch (...) {}
1667/// \endcode
1668extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1670
1671/// Matches Objective-C @catch statements.
1672///
1673/// Example matches @catch
1674/// \code
1675/// @try {}
1676/// @catch (...) {}
1677/// \endcode
1678extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1680
1681/// Matches Objective-C @finally statements.
1682///
1683/// Example matches @finally
1684/// \code
1685/// @try {}
1686/// @finally {}
1687/// \endcode
1688extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1690
1691/// Matches expressions that introduce cleanups to be run at the end
1692/// of the sub-expression's evaluation.
1693///
1694/// Example matches std::string()
1695/// \code
1696/// const std::string str = std::string();
1697/// \endcode
1698extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1700
1701/// Matches init list expressions.
1702///
1703/// Given
1704/// \code
1705/// int a[] = { 1, 2 };
1706/// struct B { int x, y; };
1707/// B b = { 5, 6 };
1708/// \endcode
1709/// initListExpr()
1710/// matches "{ 1, 2 }" and "{ 5, 6 }"
1711extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1713
1714/// Matches the syntactic form of init list expressions
1715/// (if expression have it).
1716AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1717 internal::Matcher<Expr>, InnerMatcher) {
1718 const Expr *SyntForm = Node.getSyntacticForm();
1719 return (SyntForm != nullptr &&
1720 InnerMatcher.matches(*SyntForm, Finder, Builder));
1721}
1722
1723/// Matches C++ initializer list expressions.
1724///
1725/// Given
1726/// \code
1727/// std::vector<int> a({ 1, 2, 3 });
1728/// std::vector<int> b = { 4, 5 };
1729/// int c[] = { 6, 7 };
1730/// std::pair<int, int> d = { 8, 9 };
1731/// \endcode
1732/// cxxStdInitializerListExpr()
1733/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1734extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1737
1738/// Matches implicit initializers of init list expressions.
1739///
1740/// Given
1741/// \code
1742/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1743/// \endcode
1744/// implicitValueInitExpr()
1745/// matches "[0].y" (implicitly)
1746extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1748
1749/// Matches paren list expressions.
1750/// ParenListExprs don't have a predefined type and are used for late parsing.
1751/// In the final AST, they can be met in template declarations.
1752///
1753/// Given
1754/// \code
1755/// template<typename T> class X {
1756/// void f() {
1757/// X x(*this);
1758/// int a = 0, b = 1; int i = (a, b);
1759/// }
1760/// };
1761/// \endcode
1762/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1763/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1764extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1766
1767/// Matches substitutions of non-type template parameters.
1768///
1769/// Given
1770/// \code
1771/// template <int N>
1772/// struct A { static const int n = N; };
1773/// struct B : public A<42> {};
1774/// \endcode
1775/// substNonTypeTemplateParmExpr()
1776/// matches "N" in the right-hand side of "static const int n = N;"
1777extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1780
1781/// Matches using declarations.
1782///
1783/// Given
1784/// \code
1785/// namespace X { int x; }
1786/// using X::x;
1787/// \endcode
1788/// usingDecl()
1789/// matches \code using X::x \endcode
1790extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1791
1792/// Matches using-enum declarations.
1793///
1794/// Given
1795/// \code
1796/// namespace X { enum x {...}; }
1797/// using enum X::x;
1798/// \endcode
1799/// usingEnumDecl()
1800/// matches \code using enum X::x \endcode
1801extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1803
1804/// Matches using namespace declarations.
1805///
1806/// Given
1807/// \code
1808/// namespace X { int x; }
1809/// using namespace X;
1810/// \endcode
1811/// usingDirectiveDecl()
1812/// matches \code using namespace X \endcode
1813extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1815
1816/// Matches reference to a name that can be looked up during parsing
1817/// but could not be resolved to a specific declaration.
1818///
1819/// Given
1820/// \code
1821/// template<typename T>
1822/// T foo() { T a; return a; }
1823/// template<typename T>
1824/// void bar() {
1825/// foo<T>();
1826/// }
1827/// \endcode
1828/// unresolvedLookupExpr()
1829/// matches \code foo<T>() \endcode
1830extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1832
1833/// Matches unresolved using value declarations.
1834///
1835/// Given
1836/// \code
1837/// template<typename X>
1838/// class C : private X {
1839/// using X::x;
1840/// };
1841/// \endcode
1842/// unresolvedUsingValueDecl()
1843/// matches \code using X::x \endcode
1844extern const internal::VariadicDynCastAllOfMatcher<Decl,
1847
1848/// Matches unresolved using value declarations that involve the
1849/// typename.
1850///
1851/// Given
1852/// \code
1853/// template <typename T>
1854/// struct Base { typedef T Foo; };
1855///
1856/// template<typename T>
1857/// struct S : private Base<T> {
1858/// using typename Base<T>::Foo;
1859/// };
1860/// \endcode
1861/// unresolvedUsingTypenameDecl()
1862/// matches \code using Base<T>::Foo \endcode
1863extern const internal::VariadicDynCastAllOfMatcher<Decl,
1866
1867/// Matches a constant expression wrapper.
1868///
1869/// Example matches the constant in the case statement:
1870/// (matcher = constantExpr())
1871/// \code
1872/// switch (a) {
1873/// case 37: break;
1874/// }
1875/// \endcode
1876extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1878
1879/// Matches parentheses used in expressions.
1880///
1881/// Example matches (foo() + 1)
1882/// \code
1883/// int foo() { return 1; }
1884/// int a = (foo() + 1);
1885/// \endcode
1886extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1887
1888/// Matches constructor call expressions (including implicit ones).
1889///
1890/// Example matches string(ptr, n) and ptr within arguments of f
1891/// (matcher = cxxConstructExpr())
1892/// \code
1893/// void f(const string &a, const string &b);
1894/// char *ptr;
1895/// int n;
1896/// f(string(ptr, n), ptr);
1897/// \endcode
1898extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1900
1901/// Matches unresolved constructor call expressions.
1902///
1903/// Example matches T(t) in return statement of f
1904/// (matcher = cxxUnresolvedConstructExpr())
1905/// \code
1906/// template <typename T>
1907/// void f(const T& t) { return T(t); }
1908/// \endcode
1909extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1912
1913/// Matches implicit and explicit this expressions.
1914///
1915/// Example matches the implicit this expression in "return i".
1916/// (matcher = cxxThisExpr())
1917/// \code
1918/// struct foo {
1919/// int i;
1920/// int f() { return i; }
1921/// };
1922/// \endcode
1923extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1925
1926/// Matches nodes where temporaries are created.
1927///
1928/// Example matches FunctionTakesString(GetStringByValue())
1929/// (matcher = cxxBindTemporaryExpr())
1930/// \code
1931/// FunctionTakesString(GetStringByValue());
1932/// FunctionTakesStringByPointer(GetStringPointer());
1933/// \endcode
1934extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1936
1937/// Matches nodes where temporaries are materialized.
1938///
1939/// Example: Given
1940/// \code
1941/// struct T {void func();};
1942/// T f();
1943/// void g(T);
1944/// \endcode
1945/// materializeTemporaryExpr() matches 'f()' in these statements
1946/// \code
1947/// T u(f());
1948/// g(f());
1949/// f().func();
1950/// \endcode
1951/// but does not match
1952/// \code
1953/// f();
1954/// \endcode
1955extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1958
1959/// Matches new expressions.
1960///
1961/// Given
1962/// \code
1963/// new X;
1964/// \endcode
1965/// cxxNewExpr()
1966/// matches 'new X'.
1967extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1968
1969/// Matches delete expressions.
1970///
1971/// Given
1972/// \code
1973/// delete X;
1974/// \endcode
1975/// cxxDeleteExpr()
1976/// matches 'delete X'.
1977extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1979
1980/// Matches noexcept expressions.
1981///
1982/// Given
1983/// \code
1984/// bool a() noexcept;
1985/// bool b() noexcept(true);
1986/// bool c() noexcept(false);
1987/// bool d() noexcept(noexcept(a()));
1988/// bool e = noexcept(b()) || noexcept(c());
1989/// \endcode
1990/// cxxNoexceptExpr()
1991/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1992/// doesn't match the noexcept specifier in the declarations a, b, c or d.
1993extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1995
1996/// Matches a loop initializing the elements of an array in a number of contexts:
1997/// * in the implicit copy/move constructor for a class with an array member
1998/// * when a lambda-expression captures an array by value
1999/// * when a decomposition declaration decomposes an array
2000///
2001/// Given
2002/// \code
2003/// void testLambdaCapture() {
2004/// int a[10];
2005/// auto Lam1 = [a]() {
2006/// return;
2007/// };
2008/// }
2009/// \endcode
2010/// arrayInitLoopExpr() matches the implicit loop that initializes each element of
2011/// the implicit array field inside the lambda object, that represents the array `a`
2012/// captured by value.
2013extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitLoopExpr>
2015
2016/// The arrayInitIndexExpr consists of two subexpressions: a common expression
2017/// (the source array) that is evaluated once up-front, and a per-element initializer
2018/// that runs once for each array element. Within the per-element initializer,
2019/// the current index may be obtained via an ArrayInitIndexExpr.
2020///
2021/// Given
2022/// \code
2023/// void testStructBinding() {
2024/// int a[2] = {1, 2};
2025/// auto [x, y] = a;
2026/// }
2027/// \endcode
2028/// arrayInitIndexExpr() matches the array index that implicitly iterates
2029/// over the array `a` to copy each element to the anonymous array
2030/// that backs the structured binding `[x, y]` elements of which are
2031/// referred to by their aliases `x` and `y`.
2032extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitIndexExpr>
2034
2035/// Matches array subscript expressions.
2036///
2037/// Given
2038/// \code
2039/// int i = a[1];
2040/// \endcode
2041/// arraySubscriptExpr()
2042/// matches "a[1]"
2043extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
2045
2046/// Matches the value of a default argument at the call site.
2047///
2048/// Example matches the CXXDefaultArgExpr placeholder inserted for the
2049/// default value of the second parameter in the call expression f(42)
2050/// (matcher = cxxDefaultArgExpr())
2051/// \code
2052/// void f(int x, int y = 0);
2053/// f(42);
2054/// \endcode
2055extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
2057
2058/// Matches overloaded operator calls.
2059///
2060/// Note that if an operator isn't overloaded, it won't match. Instead, use
2061/// binaryOperator matcher.
2062/// Currently it does not match operators such as new delete.
2063/// FIXME: figure out why these do not match?
2064///
2065/// Example matches both operator<<((o << b), c) and operator<<(o, b)
2066/// (matcher = cxxOperatorCallExpr())
2067/// \code
2068/// ostream &operator<< (ostream &out, int i) { };
2069/// ostream &o; int b = 1, c = 1;
2070/// o << b << c;
2071/// \endcode
2072/// See also the binaryOperation() matcher for more-general matching of binary
2073/// uses of this AST node.
2074extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2076
2077/// Matches C++17 fold expressions.
2078///
2079/// Example matches `(0 + ... + args)`:
2080/// \code
2081/// template <typename... Args>
2082/// auto sum(Args... args) {
2083/// return (0 + ... + args);
2084/// }
2085/// \endcode
2086extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFoldExpr>
2088
2089/// Matches rewritten binary operators
2090///
2091/// Example matches use of "<":
2092/// \code
2093/// #include <compare>
2094/// struct HasSpaceshipMem {
2095/// int a;
2096/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2097/// };
2098/// void compare() {
2099/// HasSpaceshipMem hs1, hs2;
2100/// if (hs1 < hs2)
2101/// return;
2102/// }
2103/// \endcode
2104/// See also the binaryOperation() matcher for more-general matching
2105/// of this AST node.
2106extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2109
2110/// Matches expressions.
2111///
2112/// Example matches x()
2113/// \code
2114/// void f() { x(); }
2115/// \endcode
2116extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2117
2118/// Matches expressions that refer to declarations.
2119///
2120/// Example matches x in if (x)
2121/// \code
2122/// bool x;
2123/// if (x) {}
2124/// \endcode
2125extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2127
2128/// Matches expressions that refer to dependent scope declarations.
2129///
2130/// example matches T::v;
2131/// \code
2132/// template <class T> class X : T { void f() { T::v; } };
2133/// \endcode
2134extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2137
2138/// Matches a reference to an ObjCIvar.
2139///
2140/// Example: matches "a" in "init" method:
2141/// \code
2142/// @implementation A {
2143/// NSString *a;
2144/// }
2145/// - (void) init {
2146/// a = @"hello";
2147/// }
2148/// \endcode
2149extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2151
2152/// Matches a reference to a block.
2153///
2154/// Example: matches "^{}":
2155/// \code
2156/// void f() { ^{}(); }
2157/// \endcode
2158extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2159
2160/// Matches if statements.
2161///
2162/// Example matches 'if (x) {}'
2163/// \code
2164/// if (x) {}
2165/// \endcode
2166extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2167
2168/// Matches for statements.
2169///
2170/// Example matches 'for (;;) {}'
2171/// \code
2172/// for (;;) {}
2173/// int i[] = {1, 2, 3}; for (auto a : i);
2174/// \endcode
2175extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2176
2177/// Matches the increment statement of a for loop.
2178///
2179/// Example:
2180/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2181/// matches '++x' in
2182/// \code
2183/// for (x; x < N; ++x) { }
2184/// \endcode
2185AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2186 InnerMatcher) {
2187 const Stmt *const Increment = Node.getInc();
2188 return (Increment != nullptr &&
2189 InnerMatcher.matches(*Increment, Finder, Builder));
2190}
2191
2192/// Matches the initialization statement of a for loop.
2193///
2194/// Example:
2195/// forStmt(hasLoopInit(declStmt()))
2196/// matches 'int x = 0' in
2197/// \code
2198/// for (int x = 0; x < N; ++x) { }
2199/// \endcode
2200AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2201 InnerMatcher) {
2202 const Stmt *const Init = Node.getInit();
2203 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2204}
2205
2206/// Matches range-based for statements.
2207///
2208/// cxxForRangeStmt() matches 'for (auto a : i)'
2209/// \code
2210/// int i[] = {1, 2, 3}; for (auto a : i);
2211/// for(int j = 0; j < 5; ++j);
2212/// \endcode
2213extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2215
2216/// Matches the initialization statement of a for loop.
2217///
2218/// Example:
2219/// forStmt(hasLoopVariable(anything()))
2220/// matches 'int x' in
2221/// \code
2222/// for (int x : a) { }
2223/// \endcode
2224AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2225 InnerMatcher) {
2226 const VarDecl *const Var = Node.getLoopVariable();
2227 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2228}
2229
2230/// Matches the range initialization statement of a for loop.
2231///
2232/// Example:
2233/// forStmt(hasRangeInit(anything()))
2234/// matches 'a' in
2235/// \code
2236/// for (int x : a) { }
2237/// \endcode
2238AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2239 InnerMatcher) {
2240 const Expr *const Init = Node.getRangeInit();
2241 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2242}
2243
2244/// Matches while statements.
2245///
2246/// Given
2247/// \code
2248/// while (true) {}
2249/// \endcode
2250/// whileStmt()
2251/// matches 'while (true) {}'.
2252extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2253
2254/// Matches do statements.
2255///
2256/// Given
2257/// \code
2258/// do {} while (true);
2259/// \endcode
2260/// doStmt()
2261/// matches 'do {} while(true)'
2262extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2263
2264/// Matches break statements.
2265///
2266/// Given
2267/// \code
2268/// while (true) { break; }
2269/// \endcode
2270/// breakStmt()
2271/// matches 'break'
2272extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2273
2274/// Matches continue statements.
2275///
2276/// Given
2277/// \code
2278/// while (true) { continue; }
2279/// \endcode
2280/// continueStmt()
2281/// matches 'continue'
2282extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2284
2285/// Matches co_return statements.
2286///
2287/// Given
2288/// \code
2289/// while (true) { co_return; }
2290/// \endcode
2291/// coreturnStmt()
2292/// matches 'co_return'
2293extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2295
2296/// Matches return statements.
2297///
2298/// Given
2299/// \code
2300/// return 1;
2301/// \endcode
2302/// returnStmt()
2303/// matches 'return 1'
2304extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2305
2306/// Matches goto statements.
2307///
2308/// Given
2309/// \code
2310/// goto FOO;
2311/// FOO: bar();
2312/// \endcode
2313/// gotoStmt()
2314/// matches 'goto FOO'
2315extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2316
2317/// Matches label statements.
2318///
2319/// Given
2320/// \code
2321/// goto FOO;
2322/// FOO: bar();
2323/// \endcode
2324/// labelStmt()
2325/// matches 'FOO:'
2326extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2327
2328/// Matches address of label statements (GNU extension).
2329///
2330/// Given
2331/// \code
2332/// FOO: bar();
2333/// void *ptr = &&FOO;
2334/// goto *bar;
2335/// \endcode
2336/// addrLabelExpr()
2337/// matches '&&FOO'
2338extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2340
2341/// Matches switch statements.
2342///
2343/// Given
2344/// \code
2345/// switch(a) { case 42: break; default: break; }
2346/// \endcode
2347/// switchStmt()
2348/// matches 'switch(a)'.
2349extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2350
2351/// Matches case and default statements inside switch statements.
2352///
2353/// Given
2354/// \code
2355/// switch(a) { case 42: break; default: break; }
2356/// \endcode
2357/// switchCase()
2358/// matches 'case 42:' and 'default:'.
2359extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2360
2361/// Matches case statements inside switch statements.
2362///
2363/// Given
2364/// \code
2365/// switch(a) { case 42: break; default: break; }
2366/// \endcode
2367/// caseStmt()
2368/// matches 'case 42:'.
2369extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2370
2371/// Matches default statements inside switch statements.
2372///
2373/// Given
2374/// \code
2375/// switch(a) { case 42: break; default: break; }
2376/// \endcode
2377/// defaultStmt()
2378/// matches 'default:'.
2379extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2381
2382/// Matches compound statements.
2383///
2384/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2385/// \code
2386/// for (;;) {{}}
2387/// \endcode
2388extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2390
2391/// Matches catch statements.
2392///
2393/// \code
2394/// try {} catch(int i) {}
2395/// \endcode
2396/// cxxCatchStmt()
2397/// matches 'catch(int i)'
2398extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2400
2401/// Matches try statements.
2402///
2403/// \code
2404/// try {} catch(int i) {}
2405/// \endcode
2406/// cxxTryStmt()
2407/// matches 'try {}'
2408extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2409
2410/// Matches throw expressions.
2411///
2412/// \code
2413/// try { throw 5; } catch(int i) {}
2414/// \endcode
2415/// cxxThrowExpr()
2416/// matches 'throw 5'
2417extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2419
2420/// Matches null statements.
2421///
2422/// \code
2423/// foo();;
2424/// \endcode
2425/// nullStmt()
2426/// matches the second ';'
2427extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2428
2429/// Matches asm statements.
2430///
2431/// \code
2432/// int i = 100;
2433/// __asm("mov al, 2");
2434/// \endcode
2435/// asmStmt()
2436/// matches '__asm("mov al, 2")'
2437extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2438
2439/// Matches bool literals.
2440///
2441/// Example matches true
2442/// \code
2443/// true
2444/// \endcode
2445extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2447
2448/// Matches string literals (also matches wide string literals).
2449///
2450/// Example matches "abcd", L"abcd"
2451/// \code
2452/// char *s = "abcd";
2453/// wchar_t *ws = L"abcd";
2454/// \endcode
2455extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2457
2458/// Matches character literals (also matches wchar_t).
2459///
2460/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2461/// though.
2462///
2463/// Example matches 'a', L'a'
2464/// \code
2465/// char ch = 'a';
2466/// wchar_t chw = L'a';
2467/// \endcode
2468extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2470
2471/// Matches integer literals of all sizes / encodings, e.g.
2472/// 1, 1L, 0x1 and 1U.
2473///
2474/// Does not match character-encoded integers such as L'a'.
2475extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2477
2478/// Matches float literals of all sizes / encodings, e.g.
2479/// 1.0, 1.0f, 1.0L and 1e10.
2480///
2481/// Does not match implicit conversions such as
2482/// \code
2483/// float a = 10;
2484/// \endcode
2485extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2487
2488/// Matches imaginary literals, which are based on integer and floating
2489/// point literals e.g.: 1i, 1.0i
2490extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2492
2493/// Matches fixed point literals
2494extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2496
2497/// Matches user defined literal operator call.
2498///
2499/// Example match: "foo"_suffix
2500extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2502
2503/// Matches compound (i.e. non-scalar) literals
2504///
2505/// Example match: {1}, (1, 2)
2506/// \code
2507/// int array[4] = {1};
2508/// vector int myvec = (vector int)(1, 2);
2509/// \endcode
2510extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2512
2513/// Matches co_await expressions.
2514///
2515/// Given
2516/// \code
2517/// co_await 1;
2518/// \endcode
2519/// coawaitExpr()
2520/// matches 'co_await 1'
2521extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2523/// Matches co_await expressions where the type of the promise is dependent
2524extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2526/// Matches co_yield expressions.
2527///
2528/// Given
2529/// \code
2530/// co_yield 1;
2531/// \endcode
2532/// coyieldExpr()
2533/// matches 'co_yield 1'
2534extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2536
2537/// Matches coroutine body statements.
2538///
2539/// coroutineBodyStmt() matches the coroutine below
2540/// \code
2541/// generator<int> gen() {
2542/// co_return;
2543/// }
2544/// \endcode
2545extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoroutineBodyStmt>
2547
2548/// Matches nullptr literal.
2549extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2551
2552/// Matches GNU __builtin_choose_expr.
2553extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2554 chooseExpr;
2555
2556/// Matches builtin function __builtin_convertvector.
2557extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConvertVectorExpr>
2559
2560/// Matches GNU __null expression.
2561extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2563
2564/// Matches C11 _Generic expression.
2565extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2567
2568/// Matches atomic builtins.
2569/// Example matches __atomic_load_n(ptr, 1)
2570/// \code
2571/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2572/// \endcode
2573extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2574
2575/// Matches statement expression (GNU extension).
2576///
2577/// Example match: ({ int X = 4; X; })
2578/// \code
2579/// int C = ({ int X = 4; X; });
2580/// \endcode
2581extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2582
2583/// Matches binary operator expressions.
2584///
2585/// Example matches a || b
2586/// \code
2587/// !(a || b)
2588/// \endcode
2589/// See also the binaryOperation() matcher for more-general matching.
2590extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2592
2593/// Matches unary operator expressions.
2594///
2595/// Example matches !a
2596/// \code
2597/// !a || b
2598/// \endcode
2599extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2601
2602/// Matches conditional operator expressions.
2603///
2604/// Example matches a ? b : c
2605/// \code
2606/// (a ? b : c) + 42
2607/// \endcode
2608extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2610
2611/// Matches binary conditional operator expressions (GNU extension).
2612///
2613/// Example matches a ?: b
2614/// \code
2615/// (a ?: b) + 42;
2616/// \endcode
2617extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2620
2621/// Matches opaque value expressions. They are used as helpers
2622/// to reference another expressions and can be met
2623/// in BinaryConditionalOperators, for example.
2624///
2625/// Example matches 'a'
2626/// \code
2627/// (a ?: c) + 42;
2628/// \endcode
2629extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2631
2632/// Matches a C++ static_assert declaration.
2633///
2634/// Example:
2635/// staticAssertDecl()
2636/// matches
2637/// static_assert(sizeof(S) == sizeof(int))
2638/// in
2639/// \code
2640/// struct S {
2641/// int x;
2642/// };
2643/// static_assert(sizeof(S) == sizeof(int));
2644/// \endcode
2645extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2647
2648/// Matches a reinterpret_cast expression.
2649///
2650/// Either the source expression or the destination type can be matched
2651/// using has(), but hasDestinationType() is more specific and can be
2652/// more readable.
2653///
2654/// Example matches reinterpret_cast<char*>(&p) in
2655/// \code
2656/// void* p = reinterpret_cast<char*>(&p);
2657/// \endcode
2658extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2660
2661/// Matches a C++ static_cast expression.
2662///
2663/// \see hasDestinationType
2664/// \see reinterpretCast
2665///
2666/// Example:
2667/// cxxStaticCastExpr()
2668/// matches
2669/// static_cast<long>(8)
2670/// in
2671/// \code
2672/// long eight(static_cast<long>(8));
2673/// \endcode
2674extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2676
2677/// Matches a dynamic_cast expression.
2678///
2679/// Example:
2680/// cxxDynamicCastExpr()
2681/// matches
2682/// dynamic_cast<D*>(&b);
2683/// in
2684/// \code
2685/// struct B { virtual ~B() {} }; struct D : B {};
2686/// B b;
2687/// D* p = dynamic_cast<D*>(&b);
2688/// \endcode
2689extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2691
2692/// Matches a const_cast expression.
2693///
2694/// Example: Matches const_cast<int*>(&r) in
2695/// \code
2696/// int n = 42;
2697/// const int &r(n);
2698/// int* p = const_cast<int*>(&r);
2699/// \endcode
2700extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2702
2703/// Matches a C-style cast expression.
2704///
2705/// Example: Matches (int) 2.2f in
2706/// \code
2707/// int i = (int) 2.2f;
2708/// \endcode
2709extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2711
2712/// Matches explicit cast expressions.
2713///
2714/// Matches any cast expression written in user code, whether it be a
2715/// C-style cast, a functional-style cast, or a keyword cast.
2716///
2717/// Does not match implicit conversions.
2718///
2719/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2720/// Clang uses the term "cast" to apply to implicit conversions as well as to
2721/// actual cast expressions.
2722///
2723/// \see hasDestinationType.
2724///
2725/// Example: matches all five of the casts in
2726/// \code
2727/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2728/// \endcode
2729/// but does not match the implicit conversion in
2730/// \code
2731/// long ell = 42;
2732/// \endcode
2733extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2735
2736/// Matches the implicit cast nodes of Clang's AST.
2737///
2738/// This matches many different places, including function call return value
2739/// eliding, as well as any type conversions.
2740extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2742
2743/// Matches any cast nodes of Clang's AST.
2744///
2745/// Example: castExpr() matches each of the following:
2746/// \code
2747/// (int) 3;
2748/// const_cast<Expr *>(SubExpr);
2749/// char c = 0;
2750/// \endcode
2751/// but does not match
2752/// \code
2753/// int i = (0);
2754/// int k = 0;
2755/// \endcode
2756extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2757
2758/// Matches functional cast expressions
2759///
2760/// Example: Matches Foo(bar);
2761/// \code
2762/// Foo f = bar;
2763/// Foo g = (Foo) bar;
2764/// Foo h = Foo(bar);
2765/// \endcode
2766extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2768
2769/// Matches functional cast expressions having N != 1 arguments
2770///
2771/// Example: Matches Foo(bar, bar)
2772/// \code
2773/// Foo h = Foo(bar, bar);
2774/// \endcode
2775extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2777
2778/// Matches predefined identifier expressions [C99 6.4.2.2].
2779///
2780/// Example: Matches __func__
2781/// \code
2782/// printf("%s", __func__);
2783/// \endcode
2784extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2786
2787/// Matches C99 designated initializer expressions [C99 6.7.8].
2788///
2789/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2790/// \code
2791/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2792/// \endcode
2793extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2795
2796/// Matches designated initializer expressions that contain
2797/// a specific number of designators.
2798///
2799/// Example: Given
2800/// \code
2801/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2802/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2803/// \endcode
2804/// designatorCountIs(2)
2805/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2806/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2807AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2808 return Node.size() == N;
2809}
2810
2811/// Matches \c QualTypes in the clang AST.
2812extern const internal::VariadicAllOfMatcher<QualType> qualType;
2813
2814/// Matches \c Types in the clang AST.
2815extern const internal::VariadicAllOfMatcher<Type> type;
2816
2817/// Matches \c TypeLocs in the clang AST.
2818extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2819
2820/// Matches if any of the given matchers matches.
2821///
2822/// Unlike \c anyOf, \c eachOf will generate a match result for each
2823/// matching submatcher.
2824///
2825/// For example, in:
2826/// \code
2827/// class A { int a; int b; };
2828/// \endcode
2829/// The matcher:
2830/// \code
2831/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2832/// has(fieldDecl(hasName("b")).bind("v"))))
2833/// \endcode
2834/// will generate two results binding "v", the first of which binds
2835/// the field declaration of \c a, the second the field declaration of
2836/// \c b.
2837///
2838/// Usable as: Any Matcher
2839extern const internal::VariadicOperatorMatcherFunc<
2840 2, std::numeric_limits<unsigned>::max()>
2841 eachOf;
2842
2843/// Matches if any of the given matchers matches.
2844///
2845/// Usable as: Any Matcher
2846extern const internal::VariadicOperatorMatcherFunc<
2847 2, std::numeric_limits<unsigned>::max()>
2848 anyOf;
2849
2850/// Matches if all given matchers match.
2851///
2852/// Usable as: Any Matcher
2853extern const internal::VariadicOperatorMatcherFunc<
2854 2, std::numeric_limits<unsigned>::max()>
2855 allOf;
2856
2857/// Matches any node regardless of the submatcher.
2858///
2859/// However, \c optionally will retain any bindings generated by the submatcher.
2860/// Useful when additional information which may or may not present about a main
2861/// matching node is desired.
2862///
2863/// For example, in:
2864/// \code
2865/// class Foo {
2866/// int bar;
2867/// }
2868/// \endcode
2869/// The matcher:
2870/// \code
2871/// cxxRecordDecl(
2872/// optionally(has(
2873/// fieldDecl(hasName("bar")).bind("var")
2874/// ))).bind("record")
2875/// \endcode
2876/// will produce a result binding for both "record" and "var".
2877/// The matcher will produce a "record" binding for even if there is no data
2878/// member named "bar" in that class.
2879///
2880/// Usable as: Any Matcher
2881extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2882
2883/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2884///
2885/// Given
2886/// \code
2887/// Foo x = bar;
2888/// int y = sizeof(x) + alignof(x);
2889/// \endcode
2890/// unaryExprOrTypeTraitExpr()
2891/// matches \c sizeof(x) and \c alignof(x)
2892extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2895
2896/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2897///
2898/// Given
2899/// \code
2900/// if (true);
2901/// for (; true; );
2902/// \endcode
2903/// with the matcher
2904/// \code
2905/// mapAnyOf(ifStmt, forStmt).with(
2906/// hasCondition(cxxBoolLiteralExpr(equals(true)))
2907/// ).bind("trueCond")
2908/// \endcode
2909/// matches the \c if and the \c for. It is equivalent to:
2910/// \code
2911/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2912/// anyOf(
2913/// ifStmt(trueCond).bind("trueCond"),
2914/// forStmt(trueCond).bind("trueCond")
2915/// );
2916/// \endcode
2917///
2918/// The with() chain-call accepts zero or more matchers which are combined
2919/// as-if with allOf() in each of the node matchers.
2920/// Usable as: Any Matcher
2921template <typename T, typename... U>
2922auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2923 return internal::MapAnyOfHelper<U...>();
2924}
2925
2926/// Matches nodes which can be used with binary operators.
2927///
2928/// The code
2929/// \code
2930/// var1 != var2;
2931/// \endcode
2932/// might be represented in the clang AST as a binaryOperator, a
2933/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2934///
2935/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2936/// least one is a class type (cxxOperatorCallExpr)
2937/// * whether the code appears in a template declaration, if at least one of the
2938/// vars is a dependent-type (binaryOperator)
2939/// * whether the code relies on a rewritten binary operator, such as a
2940/// spaceship operator or an inverted equality operator
2941/// (cxxRewrittenBinaryOperator)
2942///
2943/// This matcher elides details in places where the matchers for the nodes are
2944/// compatible.
2945///
2946/// Given
2947/// \code
2948/// binaryOperation(
2949/// hasOperatorName("!="),
2950/// hasLHS(expr().bind("lhs")),
2951/// hasRHS(expr().bind("rhs"))
2952/// )
2953/// \endcode
2954/// matches each use of "!=" in:
2955/// \code
2956/// struct S{
2957/// bool operator!=(const S&) const;
2958/// };
2959///
2960/// void foo()
2961/// {
2962/// 1 != 2;
2963/// S() != S();
2964/// }
2965///
2966/// template<typename T>
2967/// void templ()
2968/// {
2969/// 1 != 2;
2970/// T() != S();
2971/// }
2972/// struct HasOpEq
2973/// {
2974/// bool operator==(const HasOpEq &) const;
2975/// };
2976///
2977/// void inverse()
2978/// {
2979/// HasOpEq s1;
2980/// HasOpEq s2;
2981/// if (s1 != s2)
2982/// return;
2983/// }
2984///
2985/// struct HasSpaceship
2986/// {
2987/// bool operator<=>(const HasOpEq &) const;
2988/// };
2989///
2990/// void use_spaceship()
2991/// {
2992/// HasSpaceship s1;
2993/// HasSpaceship s2;
2994/// if (s1 != s2)
2995/// return;
2996/// }
2997/// \endcode
2998extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
3001
3002/// Matches function calls and constructor calls
3003///
3004/// Because CallExpr and CXXConstructExpr do not share a common
3005/// base class with API accessing arguments etc, AST Matchers for code
3006/// which should match both are typically duplicated. This matcher
3007/// removes the need for duplication.
3008///
3009/// Given code
3010/// \code
3011/// struct ConstructorTakesInt
3012/// {
3013/// ConstructorTakesInt(int i) {}
3014/// };
3015///
3016/// void callTakesInt(int i)
3017/// {
3018/// }
3019///
3020/// void doCall()
3021/// {
3022/// callTakesInt(42);
3023/// }
3024///
3025/// void doConstruct()
3026/// {
3027/// ConstructorTakesInt cti(42);
3028/// }
3029/// \endcode
3030///
3031/// The matcher
3032/// \code
3033/// invocation(hasArgument(0, integerLiteral(equals(42))))
3034/// \endcode
3035/// matches the expression in both doCall and doConstruct
3036extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
3037
3038/// Matches unary expressions that have a specific type of argument.
3039///
3040/// Given
3041/// \code
3042/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
3043/// \endcode
3044/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
3045/// matches \c sizeof(a) and \c alignof(c)
3047 internal::Matcher<QualType>, InnerMatcher) {
3048 const QualType ArgumentType = Node.getTypeOfArgument();
3049 return InnerMatcher.matches(ArgumentType, Finder, Builder);
3050}
3051
3052/// Matches unary expressions of a certain kind.
3053///
3054/// Given
3055/// \code
3056/// int x;
3057/// int s = sizeof(x) + alignof(x)
3058/// \endcode
3059/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
3060/// matches \c sizeof(x)
3061///
3062/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
3063/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
3065 return Node.getKind() == Kind;
3066}
3067
3068/// Same as unaryExprOrTypeTraitExpr, but only matching
3069/// alignof.
3070inline internal::BindableMatcher<Stmt> alignOfExpr(
3071 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3073 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
3074 InnerMatcher)));
3075}
3076
3077/// Same as unaryExprOrTypeTraitExpr, but only matching
3078/// sizeof.
3079inline internal::BindableMatcher<Stmt> sizeOfExpr(
3080 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3082 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
3083}
3084
3085/// Matches NamedDecl nodes that have the specified name.
3086///
3087/// Supports specifying enclosing namespaces or classes by prefixing the name
3088/// with '<enclosing>::'.
3089/// Does not match typedefs of an underlying type with the given name.
3090///
3091/// Example matches X (Name == "X")
3092/// \code
3093/// class X;
3094/// \endcode
3095///
3096/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
3097/// \code
3098/// namespace a { namespace b { class X; } }
3099/// \endcode
3100inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3101 return internal::Matcher<NamedDecl>(
3102 new internal::HasNameMatcher({std::string(Name)}));
3103}
3104
3105/// Matches NamedDecl nodes that have any of the specified names.
3106///
3107/// This matcher is only provided as a performance optimization of hasName.
3108/// \code
3109/// hasAnyName(a, b, c)
3110/// \endcode
3111/// is equivalent to, but faster than
3112/// \code
3113/// anyOf(hasName(a), hasName(b), hasName(c))
3114/// \endcode
3115extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3117 hasAnyName;
3118
3119/// Matches NamedDecl nodes whose fully qualified names contain
3120/// a substring matched by the given RegExp.
3121///
3122/// Supports specifying enclosing namespaces or classes by
3123/// prefixing the name with '<enclosing>::'. Does not match typedefs
3124/// of an underlying type with the given name.
3125///
3126/// Example matches X (regexp == "::X")
3127/// \code
3128/// class X;
3129/// \endcode
3130///
3131/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3132/// \code
3133/// namespace foo { namespace bar { class X; } }
3134/// \endcode
3135AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3136 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3137 return RegExp->match(FullNameString);
3138}
3139
3140/// Matches overloaded operator names.
3141///
3142/// Matches overloaded operator names specified in strings without the
3143/// "operator" prefix: e.g. "<<".
3144///
3145/// Given:
3146/// \code
3147/// class A { int operator*(); };
3148/// const A &operator<<(const A &a, const A &b);
3149/// A a;
3150/// a << a; // <-- This matches
3151/// \endcode
3152///
3153/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3154/// specified line and
3155/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3156/// matches the declaration of \c A.
3157///
3158/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3159inline internal::PolymorphicMatcher<
3160 internal::HasOverloadedOperatorNameMatcher,
3162 std::vector<std::string>>
3164 return internal::PolymorphicMatcher<
3165 internal::HasOverloadedOperatorNameMatcher,
3167 std::vector<std::string>>({std::string(Name)});
3168}
3169
3170/// Matches overloaded operator names.
3171///
3172/// Matches overloaded operator names specified in strings without the
3173/// "operator" prefix: e.g. "<<".
3174///
3175/// hasAnyOverloadedOperatorName("+", "-")
3176/// Is equivalent to
3177/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3178extern const internal::VariadicFunction<
3179 internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3182 std::vector<std::string>>,
3185
3186/// Matches template-dependent, but known, member names.
3187///
3188/// In template declarations, dependent members are not resolved and so can
3189/// not be matched to particular named declarations.
3190///
3191/// This matcher allows to match on the known name of members.
3192///
3193/// Given
3194/// \code
3195/// template <typename T>
3196/// struct S {
3197/// void mem();
3198/// };
3199/// template <typename T>
3200/// void x() {
3201/// S<T> s;
3202/// s.mem();
3203/// }
3204/// \endcode
3205/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3206AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3207 return Node.getMember().getAsString() == N;
3208}
3209
3210/// Matches template-dependent, but known, member names against an already-bound
3211/// node
3212///
3213/// In template declarations, dependent members are not resolved and so can
3214/// not be matched to particular named declarations.
3215///
3216/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3217/// and CXXMethodDecl nodes.
3218///
3219/// Given
3220/// \code
3221/// template <typename T>
3222/// struct S {
3223/// void mem();
3224/// };
3225/// template <typename T>
3226/// void x() {
3227/// S<T> s;
3228/// s.mem();
3229/// }
3230/// \endcode
3231/// The matcher
3232/// @code
3233/// \c cxxDependentScopeMemberExpr(
3234/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3235/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3236/// cxxMethodDecl(hasName("mem")).bind("templMem")
3237/// )))))
3238/// )))),
3239/// memberHasSameNameAsBoundNode("templMem")
3240/// )
3241/// @endcode
3242/// first matches and binds the @c mem member of the @c S template, then
3243/// compares its name to the usage in @c s.mem() in the @c x function template
3244AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3245 std::string, BindingID) {
3246 auto MemberName = Node.getMember().getAsString();
3247
3248 return Builder->removeBindings(
3249 [this, MemberName](const BoundNodesMap &Nodes) {
3250 const DynTypedNode &BN = Nodes.getNode(this->BindingID);
3251 if (const auto *ND = BN.get<NamedDecl>()) {
3252 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3253 return true;
3254 return ND->getName() != MemberName;
3255 }
3256 return true;
3257 });
3258}
3259
3260/// Matches C++ classes that are directly or indirectly derived from a class
3261/// matching \c Base, or Objective-C classes that directly or indirectly
3262/// subclass a class matching \c Base.
3263///
3264/// Note that a class is not considered to be derived from itself.
3265///
3266/// Example matches Y, Z, C (Base == hasName("X"))
3267/// \code
3268/// class X;
3269/// class Y : public X {}; // directly derived
3270/// class Z : public Y {}; // indirectly derived
3271/// typedef X A;
3272/// typedef A B;
3273/// class C : public B {}; // derived from a typedef of X
3274/// \endcode
3275///
3276/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3277/// \code
3278/// class Foo;
3279/// typedef Foo X;
3280/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3281/// \endcode
3282///
3283/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3284/// \code
3285/// @interface NSObject @end
3286/// @interface Bar : NSObject @end
3287/// \endcode
3288///
3289/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3291 isDerivedFrom,
3293 internal::Matcher<NamedDecl>, Base) {
3294 // Check if the node is a C++ struct/union/class.
3295 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3296 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3297
3298 // The node must be an Objective-C class.
3299 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3300 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3301 /*Directly=*/false);
3302}
3303
3304/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3306 isDerivedFrom,
3308 std::string, BaseName, 1) {
3309 if (BaseName.empty())
3310 return false;
3311
3312 const auto M = isDerivedFrom(hasName(BaseName));
3313
3314 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3315 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3316
3317 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3318 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3319}
3320
3321/// Matches C++ classes that have a direct or indirect base matching \p
3322/// BaseSpecMatcher.
3323///
3324/// Example:
3325/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3326/// \code
3327/// class Foo;
3328/// class Bar : Foo {};
3329/// class Baz : Bar {};
3330/// class SpecialBase;
3331/// class Proxy : SpecialBase {}; // matches Proxy
3332/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3333/// \endcode
3334///
3335// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3336AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3337 BaseSpecMatcher) {
3338 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3339}
3340
3341/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3342///
3343/// Example:
3344/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3345/// \code
3346/// class Foo;
3347/// class Bar : Foo {};
3348/// class Baz : Bar {};
3349/// class SpecialBase;
3350/// class Proxy : SpecialBase {}; // matches Proxy
3351/// class IndirectlyDerived : Proxy {}; // doesn't match
3352/// \endcode
3353AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3354 BaseSpecMatcher) {
3355 return Node.hasDefinition() &&
3356 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3357 return BaseSpecMatcher.matches(Base, Finder, Builder);
3358 });
3359}
3360
3361/// Similar to \c isDerivedFrom(), but also matches classes that directly
3362/// match \c Base.
3364 isSameOrDerivedFrom,
3366 internal::Matcher<NamedDecl>, Base, 0) {
3367 const auto M = anyOf(Base, isDerivedFrom(Base));
3368
3369 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3370 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3371
3372 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3373 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3374}
3375
3376/// Overloaded method as shortcut for
3377/// \c isSameOrDerivedFrom(hasName(...)).
3379 isSameOrDerivedFrom,
3381 std::string, BaseName, 1) {
3382 if (BaseName.empty())
3383 return false;
3384
3385 const auto M = isSameOrDerivedFrom(hasName(BaseName));
3386
3387 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3388 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3389
3390 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3391 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3392}
3393
3394/// Matches C++ or Objective-C classes that are directly derived from a class
3395/// matching \c Base.
3396///
3397/// Note that a class is not considered to be derived from itself.
3398///
3399/// Example matches Y, C (Base == hasName("X"))
3400/// \code
3401/// class X;
3402/// class Y : public X {}; // directly derived
3403/// class Z : public Y {}; // indirectly derived
3404/// typedef X A;
3405/// typedef A B;
3406/// class C : public B {}; // derived from a typedef of X
3407/// \endcode
3408///
3409/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3410/// \code
3411/// class Foo;
3412/// typedef Foo X;
3413/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3414/// \endcode
3416 isDirectlyDerivedFrom,
3418 internal::Matcher<NamedDecl>, Base, 0) {
3419 // Check if the node is a C++ struct/union/class.
3420 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3421 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3422
3423 // The node must be an Objective-C class.
3424 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3425 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3426 /*Directly=*/true);
3427}
3428
3429/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3431 isDirectlyDerivedFrom,
3433 std::string, BaseName, 1) {
3434 if (BaseName.empty())
3435 return false;
3436 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3437
3438 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3439 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3440
3441 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3442 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3443}
3444/// Matches the first method of a class or struct that satisfies \c
3445/// InnerMatcher.
3446///
3447/// Given:
3448/// \code
3449/// class A { void func(); };
3450/// class B { void member(); };
3451/// \endcode
3452///
3453/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3454/// \c A but not \c B.
3455AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3456 InnerMatcher) {
3457 BoundNodesTreeBuilder Result(*Builder);
3458 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3459 Node.method_end(), Finder, &Result);
3460 if (MatchIt == Node.method_end())
3461 return false;
3462
3463 if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3464 return false;
3465 *Builder = std::move(Result);
3466 return true;
3467}
3468
3469/// Matches the generated class of lambda expressions.
3470///
3471/// Given:
3472/// \code
3473/// auto x = []{};
3474/// \endcode
3475///
3476/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3477/// \c decltype(x)
3479 return Node.isLambda();
3480}
3481
3482/// Matches AST nodes that have child AST nodes that match the
3483/// provided matcher.
3484///
3485/// Example matches X, Y
3486/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3487/// \code
3488/// class X {}; // Matches X, because X::X is a class of name X inside X.
3489/// class Y { class X {}; };
3490/// class Z { class Y { class X {}; }; }; // Does not match Z.
3491/// \endcode
3492///
3493/// ChildT must be an AST base type.
3494///
3495/// Usable as: Any Matcher
3496/// Note that has is direct matcher, so it also matches things like implicit
3497/// casts and paren casts. If you are matching with expr then you should
3498/// probably consider using ignoringParenImpCasts like:
3499/// has(ignoringParenImpCasts(expr())).
3500extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3501
3502/// Matches AST nodes that have descendant AST nodes that match the
3503/// provided matcher.
3504///
3505/// Example matches X, Y, Z
3506/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3507/// \code
3508/// class X {}; // Matches X, because X::X is a class of name X inside X.
3509/// class Y { class X {}; };
3510/// class Z { class Y { class X {}; }; };
3511/// \endcode
3512///
3513/// DescendantT must be an AST base type.
3514///
3515/// Usable as: Any Matcher
3516extern const internal::ArgumentAdaptingMatcherFunc<
3517 internal::HasDescendantMatcher>
3519
3520/// Matches AST nodes that have child AST nodes that match the
3521/// provided matcher.
3522///
3523/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3524/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3525/// \code
3526/// class X {};
3527/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3528/// // inside Y.
3529/// class Z { class Y { class X {}; }; }; // Does not match Z.
3530/// \endcode
3531///
3532/// ChildT must be an AST base type.
3533///
3534/// As opposed to 'has', 'forEach' will cause a match for each result that
3535/// matches instead of only on the first one.
3536///
3537/// Usable as: Any Matcher
3538extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3539 forEach;
3540
3541/// Matches AST nodes that have descendant AST nodes that match the
3542/// provided matcher.
3543///
3544/// Example matches X, A, A::X, B, B::C, B::C::X
3545/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3546/// \code
3547/// class X {};
3548/// class A { class X {}; }; // Matches A, because A::X is a class of name
3549/// // X inside A.
3550/// class B { class C { class X {}; }; };
3551/// \endcode
3552///
3553/// DescendantT must be an AST base type.
3554///
3555/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3556/// each result that matches instead of only on the first one.
3557///
3558/// Note: Recursively combined ForEachDescendant can cause many matches:
3559/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3560/// forEachDescendant(cxxRecordDecl())
3561/// )))
3562/// will match 10 times (plus injected class name matches) on:
3563/// \code
3564/// class A { class B { class C { class D { class E {}; }; }; }; };
3565/// \endcode
3566///
3567/// Usable as: Any Matcher
3568extern const internal::ArgumentAdaptingMatcherFunc<
3569 internal::ForEachDescendantMatcher>
3571
3572/// Matches if the node or any descendant matches.
3573///
3574/// Generates results for each match.
3575///
3576/// For example, in:
3577/// \code
3578/// class A { class B {}; class C {}; };
3579/// \endcode
3580/// The matcher:
3581/// \code
3582/// cxxRecordDecl(hasName("::A"),
3583/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3584/// \endcode
3585/// will generate results for \c A, \c B and \c C.
3586///
3587/// Usable as: Any Matcher
3588template <typename T>
3589internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3590 return eachOf(Matcher, forEachDescendant(Matcher));
3591}
3592
3593/// Matches AST nodes that have a parent that matches the provided
3594/// matcher.
3595///
3596/// Given
3597/// \code
3598/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3599/// \endcode
3600/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3601///
3602/// Usable as: Any Matcher
3603extern const internal::ArgumentAdaptingMatcherFunc<
3604 internal::HasParentMatcher,
3605 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3606 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3607 hasParent;
3608
3609/// Matches AST nodes that have an ancestor that matches the provided
3610/// matcher.
3611///
3612/// Given
3613/// \code
3614/// void f() { if (true) { int x = 42; } }
3615/// void g() { for (;;) { int x = 43; } }
3616/// \endcode
3617/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3618///
3619/// Usable as: Any Matcher
3620extern const internal::ArgumentAdaptingMatcherFunc<
3621 internal::HasAncestorMatcher,
3622 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3623 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3625
3626/// Matches if the provided matcher does not match.
3627///
3628/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3629/// \code
3630/// class X {};
3631/// class Y {};
3632/// \endcode
3633///
3634/// Usable as: Any Matcher
3635extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3636
3637/// Matches a node if the declaration associated with that node
3638/// matches the given matcher.
3639///
3640/// The associated declaration is:
3641/// - for type nodes, the declaration of the underlying type
3642/// - for CallExpr, the declaration of the callee
3643/// - for MemberExpr, the declaration of the referenced member
3644/// - for CXXConstructExpr, the declaration of the constructor
3645/// - for CXXNewExpr, the declaration of the operator new
3646/// - for ObjCIvarExpr, the declaration of the ivar
3647///
3648/// For type nodes, hasDeclaration will generally match the declaration of the
3649/// sugared type. Given
3650/// \code
3651/// class X {};
3652/// typedef X Y;
3653/// Y y;
3654/// \endcode
3655/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3656/// typedefDecl. A common use case is to match the underlying, desugared type.
3657/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3658/// \code
3659/// varDecl(hasType(hasUnqualifiedDesugaredType(
3660/// recordType(hasDeclaration(decl())))))
3661/// \endcode
3662/// In this matcher, the decl will match the CXXRecordDecl of class X.
3663///
3664/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3665/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3666/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3667/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3668/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3669/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3670/// Matcher<UnresolvedUsingType>
3671inline internal::PolymorphicMatcher<
3672 internal::HasDeclarationMatcher,
3673 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3674hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3675 return internal::PolymorphicMatcher<
3676 internal::HasDeclarationMatcher,
3677 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3678 InnerMatcher);
3679}
3680
3681/// Matches a \c NamedDecl whose underlying declaration matches the given
3682/// matcher.
3683///
3684/// Given
3685/// \code
3686/// namespace N { template<class T> void f(T t); }
3687/// template <class T> void g() { using N::f; f(T()); }
3688/// \endcode
3689/// \c unresolvedLookupExpr(hasAnyDeclaration(
3690/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3691/// matches the use of \c f in \c g() .
3692AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3693 InnerMatcher) {
3694 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3695
3696 return UnderlyingDecl != nullptr &&
3697 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3698}
3699
3700/// Matches on the implicit object argument of a member call expression, after
3701/// stripping off any parentheses or implicit casts.
3702///
3703/// Given
3704/// \code
3705/// class Y { public: void m(); };
3706/// Y g();
3707/// class X : public Y {};
3708/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3709/// \endcode
3710/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3711/// matches `y.m()` and `(g()).m()`.
3712/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3713/// matches `x.m()`.
3714/// cxxMemberCallExpr(on(callExpr()))
3715/// matches `(g()).m()`.
3716///
3717/// FIXME: Overload to allow directly matching types?
3718AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3719 InnerMatcher) {
3720 const Expr *ExprNode = Node.getImplicitObjectArgument()
3721 ->IgnoreParenImpCasts();
3722 return (ExprNode != nullptr &&
3723 InnerMatcher.matches(*ExprNode, Finder, Builder));
3724}
3725
3726
3727/// Matches on the receiver of an ObjectiveC Message expression.
3728///
3729/// Example
3730/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3731/// matches the [webView ...] message invocation.
3732/// \code
3733/// NSString *webViewJavaScript = ...
3734/// UIWebView *webView = ...
3735/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3736/// \endcode
3737AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3738 InnerMatcher) {
3739 const QualType TypeDecl = Node.getReceiverType();
3740 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3741}
3742
3743/// Returns true when the Objective-C method declaration is a class method.
3744///
3745/// Example
3746/// matcher = objcMethodDecl(isClassMethod())
3747/// matches
3748/// \code
3749/// @interface I + (void)foo; @end
3750/// \endcode
3751/// but not
3752/// \code
3753/// @interface I - (void)bar; @end
3754/// \endcode
3756 return Node.isClassMethod();
3757}
3758
3759/// Returns true when the Objective-C method declaration is an instance method.
3760///
3761/// Example
3762/// matcher = objcMethodDecl(isInstanceMethod())
3763/// matches
3764/// \code
3765/// @interface I - (void)bar; @end
3766/// \endcode
3767/// but not
3768/// \code
3769/// @interface I + (void)foo; @end
3770/// \endcode
3772 return Node.isInstanceMethod();
3773}
3774
3775/// Returns true when the Objective-C message is sent to a class.
3776///
3777/// Example
3778/// matcher = objcMessageExpr(isClassMessage())
3779/// matches
3780/// \code
3781/// [NSString stringWithFormat:@"format"];
3782/// \endcode
3783/// but not
3784/// \code
3785/// NSString *x = @"hello";
3786/// [x containsString:@"h"];
3787/// \endcode
3789 return Node.isClassMessage();
3790}
3791
3792/// Returns true when the Objective-C message is sent to an instance.
3793///
3794/// Example
3795/// matcher = objcMessageExpr(isInstanceMessage())
3796/// matches
3797/// \code
3798/// NSString *x = @"hello";
3799/// [x containsString:@"h"];
3800/// \endcode
3801/// but not
3802/// \code
3803/// [NSString stringWithFormat:@"format"];
3804/// \endcode
3805AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3806 return Node.isInstanceMessage();
3807}
3808
3809/// Matches if the Objective-C message is sent to an instance,
3810/// and the inner matcher matches on that instance.
3811///
3812/// For example the method call in
3813/// \code
3814/// NSString *x = @"hello";
3815/// [x containsString:@"h"];
3816/// \endcode
3817/// is matched by
3818/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3819AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3820 InnerMatcher) {
3821 const Expr *ReceiverNode = Node.getInstanceReceiver();
3822 return (ReceiverNode != nullptr &&
3823 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3824 Builder));
3825}
3826
3827/// Matches when BaseName == Selector.getAsString()
3828///
3829/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3830/// matches the outer message expr in the code below, but NOT the message
3831/// invocation for self.bodyView.
3832/// \code
3833/// [self.bodyView loadHTMLString:html baseURL:NULL];
3834/// \endcode
3835AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3836 Selector Sel = Node.getSelector();
3837 return BaseName == Sel.getAsString();
3838}
3839
3840/// Matches when at least one of the supplied string equals to the
3841/// Selector.getAsString()
3842///
3843/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3844/// matches both of the expressions below:
3845/// \code
3846/// [myObj methodA:argA];
3847/// [myObj methodB:argB];
3848/// \endcode
3849extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3850 StringRef,
3853
3854/// Matches ObjC selectors whose name contains
3855/// a substring matched by the given RegExp.
3856/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3857/// matches the outer message expr in the code below, but NOT the message
3858/// invocation for self.bodyView.
3859/// \code
3860/// [self.bodyView loadHTMLString:html baseURL:NULL];
3861/// \endcode
3862AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3863 std::string SelectorString = Node.getSelector().getAsString();
3864 return RegExp->match(SelectorString);
3865}
3866
3867/// Matches when the selector is the empty selector
3868///
3869/// Matches only when the selector of the objCMessageExpr is NULL. This may
3870/// represent an error condition in the tree!
3871AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3872 return Node.getSelector().isNull();
3873}
3874
3875/// Matches when the selector is a Unary Selector
3876///
3877/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3878/// matches self.bodyView in the code below, but NOT the outer message
3879/// invocation of "loadHTMLString:baseURL:".
3880/// \code
3881/// [self.bodyView loadHTMLString:html baseURL:NULL];
3882/// \endcode
3883AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3884 return Node.getSelector().isUnarySelector();
3885}
3886
3887/// Matches when the selector is a keyword selector
3888///
3889/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3890/// message expression in
3891///
3892/// \code
3893/// UIWebView *webView = ...;
3894/// CGRect bodyFrame = webView.frame;
3895/// bodyFrame.size.height = self.bodyContentHeight;
3896/// webView.frame = bodyFrame;
3897/// // ^---- matches here
3898/// \endcode
3899AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3900 return Node.getSelector().isKeywordSelector();
3901}
3902
3903/// Matches when the selector has the specified number of arguments
3904///
3905/// matcher = objCMessageExpr(numSelectorArgs(0));
3906/// matches self.bodyView in the code below
3907///
3908/// matcher = objCMessageExpr(numSelectorArgs(2));
3909/// matches the invocation of "loadHTMLString:baseURL:" but not that
3910/// of self.bodyView
3911/// \code
3912/// [self.bodyView loadHTMLString:html baseURL:NULL];
3913/// \endcode
3914AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3915 return Node.getSelector().getNumArgs() == N;
3916}
3917
3918/// Matches if the call or fold expression's callee expression matches.
3919///
3920/// Given
3921/// \code
3922/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3923/// void f() { f(); }
3924/// \endcode
3925/// callExpr(callee(expr()))
3926/// matches this->x(), x(), y.x(), f()
3927/// with callee(...)
3928/// matching this->x, x, y.x, f respectively
3929///
3930/// Given
3931/// \code
3932/// template <typename... Args>
3933/// auto sum(Args... args) {
3934/// return (0 + ... + args);
3935/// }
3936///
3937/// template <typename... Args>
3938/// auto multiply(Args... args) {
3939/// return (args * ... * 1);
3940/// }
3941/// \endcode
3942/// cxxFoldExpr(callee(expr()))
3943/// matches (args * ... * 1)
3944/// with callee(...)
3945/// matching *
3946///
3947/// Note: Callee cannot take the more general internal::Matcher<Expr>
3948/// because this introduces ambiguous overloads with calls to Callee taking a
3949/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3950/// implemented in terms of implicit casts.
3953 CXXFoldExpr),
3954 internal::Matcher<Stmt>, InnerMatcher, 0) {
3955 const auto *ExprNode = Node.getCallee();
3956 return (ExprNode != nullptr &&
3957 InnerMatcher.matches(*ExprNode, Finder, Builder));
3958}
3959
3960/// Matches 1) if the call expression's callee's declaration matches the
3961/// given matcher; or 2) if the Obj-C message expression's callee's method
3962/// declaration matches the given matcher.
3963///
3964/// Example matches y.x() (matcher = callExpr(callee(
3965/// cxxMethodDecl(hasName("x")))))
3966/// \code
3967/// class Y { public: void x(); };
3968/// void z() { Y y; y.x(); }
3969/// \endcode
3970///
3971/// Example 2. Matches [I foo] with
3972/// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3973///
3974/// \code
3975/// @interface I: NSObject
3976/// +(void)foo;
3977/// @end
3978/// ...
3979/// [I foo]
3980/// \endcode
3983 internal::Matcher<Decl>, InnerMatcher, 1) {
3984 if (isa<CallExpr>(&Node))
3985 return callExpr(hasDeclaration(InnerMatcher))
3986 .matches(Node, Finder, Builder);
3987 else {
3988 // The dynamic cast below is guaranteed to succeed as there are only 2
3989 // supported return types.
3990 const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
3991 const Decl *DeclNode = MsgNode->getMethodDecl();
3992 return (DeclNode != nullptr &&
3993 InnerMatcher.matches(*DeclNode, Finder, Builder));
3994 }
3995}
3996
3997/// Matches if the expression's or declaration's type matches a type
3998/// matcher.
3999///
4000/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4001/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4002/// and U (matcher = typedefDecl(hasType(asString("int")))
4003/// and friend class X (matcher = friendDecl(hasType("X"))
4004/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4005/// asString("class X")))
4006/// \code
4007/// class X {};
4008/// void y(X &x) { x; X z; }
4009/// typedef int U;
4010/// class Y { friend class X; };
4011/// class Z : public virtual X {};
4012/// \endcode
4014 hasType,
4017 internal::Matcher<QualType>, InnerMatcher, 0) {
4018 QualType QT = internal::getUnderlyingType(Node);
4019 if (!QT.isNull())
4020 return InnerMatcher.matches(QT, Finder, Builder);
4021 return false;
4022}
4023
4024/// Overloaded to match the declaration of the expression's or value
4025/// declaration's type.
4026///
4027/// In case of a value declaration (for example a variable declaration),
4028/// this resolves one layer of indirection. For example, in the value
4029/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
4030/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
4031/// declaration of x.
4032///
4033/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4034/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4035/// and friend class X (matcher = friendDecl(hasType("X"))
4036/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4037/// cxxRecordDecl(hasName("X"))))
4038/// \code
4039/// class X {};
4040/// void y(X &x) { x; X z; }
4041/// class Y { friend class X; };
4042/// class Z : public virtual X {};
4043/// \endcode
4044///
4045/// Example matches class Derived
4046/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
4047/// \code
4048/// class Base {};
4049/// class Derived : Base {};
4050/// \endcode
4051///
4052/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
4053/// Matcher<CXXBaseSpecifier>
4055 hasType,
4058 internal::Matcher<Decl>, InnerMatcher, 1) {
4059 QualType QT = internal::getUnderlyingType(Node);
4060 if (!QT.isNull())
4061 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
4062 return false;
4063}
4064
4065/// Matches if the type location of a node matches the inner matcher.
4066///
4067/// Examples:
4068/// \code
4069/// int x;
4070/// \endcode
4071/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
4072/// matches int x
4073///
4074/// \code
4075/// auto x = int(3);
4076/// \endcode
4077/// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
4078/// matches int(3)
4079///
4080/// \code
4081/// struct Foo { Foo(int, int); };
4082/// auto x = Foo(1, 2);
4083/// \endcode
4084/// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
4085/// matches Foo(1, 2)
4086///
4087/// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
4088/// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
4089/// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
4090/// Matcher<CXXUnresolvedConstructExpr>,
4091/// Matcher<CompoundLiteralExpr>,
4092/// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
4093/// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
4094/// Matcher<TypedefNameDecl>
4096 hasTypeLoc,
4102 internal::Matcher<TypeLoc>, Inner) {
4103 TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
4104 if (source == nullptr) {
4105 // This happens for example for implicit destructors.
4106 return false;
4107 }
4108 return Inner.matches(source->getTypeLoc(), Finder, Builder);
4109}
4110
4111/// Matches if the matched type is represented by the given string.
4112///
4113/// Given
4114/// \code
4115/// class Y { public: void x(); };
4116/// void z() { Y* y; y->x(); }
4117/// \endcode
4118/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
4119/// matches y->x()
4120AST_MATCHER_P(QualType, asString, std::string, Name) {
4121 return Name == Node.getAsString();
4122}
4123
4124/// Matches if the matched type is a pointer type and the pointee type
4125/// matches the specified matcher.
4126///
4127/// Example matches y->x()
4128/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
4129/// cxxRecordDecl(hasName("Y")))))))
4130/// \code
4131/// class Y { public: void x(); };
4132/// void z() { Y *y; y->x(); }
4133/// \endcode
4135 QualType, pointsTo, internal::Matcher<QualType>,
4136 InnerMatcher) {
4137 return (!Node.isNull() && Node->isAnyPointerType() &&
4138 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4139}
4140
4141/// Overloaded to match the pointee type's declaration.
4142AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
4143 InnerMatcher, 1) {
4144 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
4145 .matches(Node, Finder, Builder);
4146}
4147
4148/// Matches if the matched type matches the unqualified desugared
4149/// type of the matched node.
4150///
4151/// For example, in:
4152/// \code
4153/// class A {};
4154/// using B = A;
4155/// \endcode
4156/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4157/// both B and A.
4158AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4159 InnerMatcher) {
4160 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4161 Builder);
4162}
4163
4164/// Matches if the matched type is a reference type and the referenced
4165/// type matches the specified matcher.
4166///
4167/// Example matches X &x and const X &y
4168/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4169/// \code
4170/// class X {
4171/// void a(X b) {
4172/// X &x = b;
4173/// const X &y = b;
4174/// }
4175/// };
4176/// \endcode
4177AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4178 InnerMatcher) {
4179 return (!Node.isNull() && Node->isReferenceType() &&
4180 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4181}
4182
4183/// Matches QualTypes whose canonical type matches InnerMatcher.
4184///
4185/// Given:
4186/// \code
4187/// typedef int &int_ref;
4188/// int a;
4189/// int_ref b = a;
4190/// \endcode
4191///
4192/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4193/// declaration of b but \c
4194/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4195AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4196 InnerMatcher) {
4197 if (Node.isNull())
4198 return false;
4199 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4200}
4201
4202/// Overloaded to match the referenced type's declaration.
4203AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4204 InnerMatcher, 1) {
4205 return references(qualType(hasDeclaration(InnerMatcher)))
4206 .matches(Node, Finder, Builder);
4207}
4208
4209/// Matches on the implicit object argument of a member call expression. Unlike
4210/// `on`, matches the argument directly without stripping away anything.
4211///
4212/// Given
4213/// \code
4214/// class Y { public: void m(); };
4215/// Y g();
4216/// class X : public Y { void g(); };
4217/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4218/// \endcode
4219/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4220/// cxxRecordDecl(hasName("Y")))))
4221/// matches `y.m()`, `x.m()` and (`g()).m()`, but not `x.g()`).
4222/// cxxMemberCallExpr(on(callExpr()))
4223/// only matches `(g()).m()` (the parens are ignored).
4224///
4225/// FIXME: Overload to allow directly matching types?
4226AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4227 internal::Matcher<Expr>, InnerMatcher) {
4228 const Expr *ExprNode = Node.getImplicitObjectArgument();
4229 return (ExprNode != nullptr &&
4230 InnerMatcher.matches(*ExprNode, Finder, Builder));
4231}
4232
4233/// Matches if the type of the expression's implicit object argument either
4234/// matches the InnerMatcher, or is a pointer to a type that matches the
4235/// InnerMatcher.
4236///
4237/// Given
4238/// \code
4239/// class Y { public: void m(); };
4240/// class X : public Y { void g(); };
4241/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4242/// \endcode
4243/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4244/// cxxRecordDecl(hasName("Y")))))
4245/// matches `y.m()`, `p->m()` and `x.m()`.
4246/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4247/// cxxRecordDecl(hasName("X")))))
4248/// matches `x.g()`.
4250 internal::Matcher<QualType>, InnerMatcher, 0) {
4251 return onImplicitObjectArgument(
4252 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4253 .matches(Node, Finder, Builder);
4254}
4255
4256/// Overloaded to match the type's declaration.
4258 internal::Matcher<Decl>, InnerMatcher, 1) {
4259 return onImplicitObjectArgument(
4260 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4261 .matches(Node, Finder, Builder);
4262}
4263
4264/// Matches a DeclRefExpr that refers to a declaration that matches the
4265/// specified matcher.
4266///
4267/// Example matches x in if(x)
4268/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4269/// \code
4270/// bool x;
4271/// if (x) {}
4272/// \endcode
4273AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4274 InnerMatcher) {
4275 const Decl *DeclNode = Node.getDecl();
4276 return (DeclNode != nullptr &&
4277 InnerMatcher.matches(*DeclNode, Finder, Builder));
4278}
4279
4280/// Matches if a node refers to a declaration through a specific
4281/// using shadow declaration.
4282///
4283/// Examples:
4284/// \code
4285/// namespace a { int f(); }
4286/// using a::f;
4287/// int x = f();
4288/// \endcode
4289/// declRefExpr(throughUsingDecl(anything()))
4290/// matches \c f
4291///
4292/// \code
4293/// namespace a { class X{}; }
4294/// using a::X;
4295/// X x;
4296/// \endcode
4297/// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4298/// matches \c X
4299///
4300/// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4303 UsingType),
4304 internal::Matcher<UsingShadowDecl>, Inner) {
4305 const NamedDecl *FoundDecl = Node.getFoundDecl();
4306 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4307 return Inner.matches(*UsingDecl, Finder, Builder);
4308 return false;
4309}
4310
4311/// Matches an \c OverloadExpr if any of the declarations in the set of
4312/// overloads matches the given matcher.
4313///
4314/// Given
4315/// \code
4316/// template <typename T> void foo(T);
4317/// template <typename T> void bar(T);
4318/// template <typename T> void baz(T t) {
4319/// foo(t);
4320/// bar(t);
4321/// }
4322/// \endcode
4323/// unresolvedLookupExpr(hasAnyDeclaration(
4324/// functionTemplateDecl(hasName("foo"))))
4325/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4326AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4327 InnerMatcher) {
4328 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4329 Node.decls_end(), Finder,
4330 Builder) != Node.decls_end();
4331}
4332
4333/// Matches the Decl of a DeclStmt which has a single declaration.
4334///
4335/// Given
4336/// \code
4337/// int a, b;
4338/// int c;
4339/// \endcode
4340/// declStmt(hasSingleDecl(anything()))
4341/// matches 'int c;' but not 'int a, b;'.
4342AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4343 if (Node.isSingleDecl()) {
4344 const Decl *FoundDecl = Node.getSingleDecl();
4345 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4346 }
4347 return false;
4348}
4349
4350/// Matches a variable declaration that has an initializer expression
4351/// that matches the given matcher.
4352///
4353/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4354/// \code
4355/// bool y() { return true; }
4356/// bool x = y();
4357/// \endcode
4359 VarDecl, hasInitializer, internal::Matcher<Expr>,
4360 InnerMatcher) {
4361 const Expr *Initializer = Node.getAnyInitializer();
4362 return (Initializer != nullptr &&
4363 InnerMatcher.matches(*Initializer, Finder, Builder));
4364}
4365
4366/// Matches a variable serving as the implicit variable for a lambda init-
4367/// capture.
4368///
4369/// Example matches x (matcher = varDecl(isInitCapture()))
4370/// \code
4371/// auto f = [x=3]() { return x; };
4372/// \endcode
4373AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4374
4375/// Matches each lambda capture in a lambda expression.
4376///
4377/// Given
4378/// \code
4379/// int main() {
4380/// int x, y;
4381/// float z;
4382/// auto f = [=]() { return x + y + z; };
4383/// }
4384/// \endcode
4385/// lambdaExpr(forEachLambdaCapture(
4386/// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4387/// will trigger two matches, binding for 'x' and 'y' respectively.
4388AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4389 internal::Matcher<LambdaCapture>, InnerMatcher) {
4390 BoundNodesTreeBuilder Result;
4391 bool Matched = false;
4392 for (const auto &Capture : Node.captures()) {
4393 if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4394 continue;
4395 BoundNodesTreeBuilder CaptureBuilder(*Builder);
4396 if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4397 Matched = true;
4398 Result.addMatch(CaptureBuilder);
4399 }
4400 }
4401 *Builder = std::move(Result);
4402 return Matched;
4403}
4404
4405/// \brief Matches a static variable with local scope.
4406///
4407/// Example matches y (matcher = varDecl(isStaticLocal()))
4408/// \code
4409/// void f() {
4410/// int x;
4411/// static int y;
4412/// }
4413/// static int z;
4414/// \endcode
4415AST_MATCHER(VarDecl, isStaticLocal) {
4416 return Node.isStaticLocal();
4417}
4418
4419/// Matches a variable declaration that has function scope and is a
4420/// non-static local variable.
4421///
4422/// Example matches x (matcher = varDecl(hasLocalStorage())
4423/// \code
4424/// void f() {
4425/// int x;
4426/// static int y;
4427/// }
4428/// int z;
4429/// \endcode
4430AST_MATCHER(VarDecl, hasLocalStorage) {
4431 return Node.hasLocalStorage();
4432}
4433
4434/// Matches a variable declaration that does not have local storage.
4435///
4436/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4437/// \code
4438/// void f() {
4439/// int x;
4440/// static int y;
4441/// }
4442/// int z;
4443/// \endcode
4444AST_MATCHER(VarDecl, hasGlobalStorage) {
4445 return Node.hasGlobalStorage();
4446}
4447
4448/// Matches a variable declaration that has automatic storage duration.
4449///
4450/// Example matches x, but not y, z, or a.
4451/// (matcher = varDecl(hasAutomaticStorageDuration())
4452/// \code
4453/// void f() {
4454/// int x;
4455/// static int y;
4456/// thread_local int z;
4457/// }
4458/// int a;
4459/// \endcode
4460AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4461 return Node.getStorageDuration() == SD_Automatic;
4462}
4463
4464/// Matches a variable declaration that has static storage duration.
4465/// It includes the variable declared at namespace scope and those declared
4466/// with "static" and "extern" storage class specifiers.
4467///
4468/// \code
4469/// void f() {
4470/// int x;
4471/// static int y;
4472/// thread_local int z;
4473/// }
4474/// int a;
4475/// static int b;
4476/// extern int c;
4477/// varDecl(hasStaticStorageDuration())
4478/// matches the function declaration y, a, b and c.
4479/// \endcode
4480AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4481 return Node.getStorageDuration() == SD_Static;
4482}
4483
4484/// Matches a variable declaration that has thread storage duration.
4485///
4486/// Example matches z, but not x, z, or a.
4487/// (matcher = varDecl(hasThreadStorageDuration())
4488/// \code
4489/// void f() {
4490/// int x;
4491/// static int y;
4492/// thread_local int z;
4493/// }
4494/// int a;
4495/// \endcode
4496AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4497 return Node.getStorageDuration() == SD_Thread;
4498}
4499
4500/// Matches a variable declaration that is an exception variable from
4501/// a C++ catch block, or an Objective-C \@catch statement.
4502///
4503/// Example matches x (matcher = varDecl(isExceptionVariable())
4504/// \code
4505/// void f(int y) {
4506/// try {
4507/// } catch (int x) {
4508/// }
4509/// }
4510/// \endcode
4511AST_MATCHER(VarDecl, isExceptionVariable) {
4512 return Node.isExceptionVariable();
4513}
4514
4515/// Checks that a call expression or a constructor call expression has
4516/// a specific number of arguments (including absent default arguments).
4517///
4518/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4519/// \code
4520/// void f(int x, int y);
4521/// f(0, 0);
4522/// \endcode
4527 unsigned, N) {
4528 unsigned NumArgs = Node.getNumArgs();
4529 if (!Finder->isTraversalIgnoringImplicitNodes())
4530 return NumArgs == N;
4531 while (NumArgs) {
4532 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4533 break;
4534 --NumArgs;
4535 }
4536 return NumArgs == N;
4537}
4538
4539/// Checks that a call expression or a constructor call expression has at least
4540/// the specified number of arguments (including absent default arguments).
4541///
4542/// Example matches f(0, 0) and g(0, 0, 0)
4543/// (matcher = callExpr(argumentCountAtLeast(2)))
4544/// \code
4545/// void f(int x, int y);
4546/// void g(int x, int y, int z);
4547/// f(0, 0);
4548/// g(0, 0, 0);
4549/// \endcode
4550AST_POLYMORPHIC_MATCHER_P(argumentCountAtLeast,
4554 unsigned, N) {
4555 unsigned NumArgs = Node.getNumArgs();
4556 if (!Finder->isTraversalIgnoringImplicitNodes())
4557 return NumArgs >= N;
4558 while (NumArgs) {
4559 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4560 break;
4561 --NumArgs;
4562 }
4563 return NumArgs >= N;
4564}
4565
4566/// Matches the n'th argument of a call expression or a constructor
4567/// call expression.
4568///
4569/// Example matches y in x(y)
4570/// (matcher = callExpr(hasArgument(0, declRefExpr())))
4571/// \code
4572/// void x(int) { int y; x(y); }
4573/// \endcode
4578 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4579 if (N >= Node.getNumArgs())
4580 return false;
4581 const Expr *Arg = Node.getArg(N);
4582 if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4583 return false;
4584 return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4585}
4586
4587/// Matches the operand that does not contain the parameter pack.
4588///
4589/// Example matches `(0 + ... + args)` and `(args * ... * 1)`
4590/// (matcher = cxxFoldExpr(hasFoldInit(expr())))
4591/// with hasFoldInit(...)
4592/// matching `0` and `1` respectively
4593/// \code
4594/// template <typename... Args>
4595/// auto sum(Args... args) {
4596/// return (0 + ... + args);
4597/// }
4598///
4599/// template <typename... Args>
4600/// auto multiply(Args... args) {
4601/// return (args * ... * 1);
4602/// }
4603/// \endcode
4604AST_MATCHER_P(CXXFoldExpr, hasFoldInit, internal::Matcher<Expr>, InnerMacher) {
4605 const auto *const Init = Node.getInit();
4606 return Init && InnerMacher.matches(*Init, Finder, Builder);
4607}
4608
4609/// Matches the operand that contains the parameter pack.
4610///
4611/// Example matches `(0 + ... + args)`
4612/// (matcher = cxxFoldExpr(hasPattern(expr())))
4613/// with hasPattern(...)
4614/// matching `args`
4615/// \code
4616/// template <typename... Args>
4617/// auto sum(Args... args) {
4618/// return (0 + ... + args);
4619/// }
4620///
4621/// template <typename... Args>
4622/// auto multiply(Args... args) {
4623/// return (args * ... * 1);
4624/// }
4625/// \endcode
4626AST_MATCHER_P(CXXFoldExpr, hasPattern, internal::Matcher<Expr>, InnerMacher) {
4627 const Expr *const Pattern = Node.getPattern();
4628 return Pattern && InnerMacher.matches(*Pattern, Finder, Builder);
4629}
4630
4631/// Matches right-folding fold expressions.
4632///
4633/// Example matches `(args * ... * 1)`
4634/// (matcher = cxxFoldExpr(isRightFold()))
4635/// \code
4636/// template <typename... Args>
4637/// auto sum(Args... args) {
4638/// return (0 + ... + args);
4639/// }
4640///
4641/// template <typename... Args>
4642/// auto multiply(Args... args) {
4643/// return (args * ... * 1);
4644/// }
4645/// \endcode
4646AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
4647
4648/// Matches left-folding fold expressions.
4649///
4650/// Example matches `(0 + ... + args)`
4651/// (matcher = cxxFoldExpr(isLeftFold()))
4652/// \code
4653/// template <typename... Args>
4654/// auto sum(Args... args) {
4655/// return (0 + ... + args);
4656/// }
4657///
4658/// template <typename... Args>
4659/// auto multiply(Args... args) {
4660/// return (args * ... * 1);
4661/// }
4662/// \endcode
4663AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
4664
4665/// Matches unary fold expressions, i.e. fold expressions without an
4666/// initializer.
4667///
4668/// Example matches `(args * ...)`
4669/// (matcher = cxxFoldExpr(isUnaryFold()))
4670/// \code
4671/// template <typename... Args>
4672/// auto sum(Args... args) {
4673/// return (0 + ... + args);
4674/// }
4675///
4676/// template <typename... Args>
4677/// auto multiply(Args... args) {
4678/// return (args * ...);
4679/// }
4680/// \endcode
4681AST_MATCHER(CXXFoldExpr, isUnaryFold) { return Node.getInit() == nullptr; }
4682
4683/// Matches binary fold expressions, i.e. fold expressions with an initializer.
4684///
4685/// Example matches `(0 + ... + args)`
4686/// (matcher = cxxFoldExpr(isBinaryFold()))
4687/// \code
4688/// template <typename... Args>
4689/// auto sum(Args... args) {
4690/// return (0 + ... + args);
4691/// }
4692///
4693/// template <typename... Args>
4694/// auto multiply(Args... args) {
4695/// return (args * ...);
4696/// }
4697/// \endcode
4698AST_MATCHER(CXXFoldExpr, isBinaryFold) { return Node.getInit() != nullptr; }
4699
4700/// Matches the n'th item of an initializer list expression.
4701///
4702/// Example matches y.
4703/// (matcher = initListExpr(hasInit(0, expr())))
4704/// \code
4705/// int x{y}.
4706/// \endcode
4707AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N, internal::Matcher<Expr>,
4708 InnerMatcher) {
4709 return N < Node.getNumInits() &&
4710 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4711}
4712
4713/// Matches declaration statements that contain a specific number of
4714/// declarations.
4715///
4716/// Example: Given
4717/// \code
4718/// int a, b;
4719/// int c;
4720/// int d = 2, e;
4721/// \endcode
4722/// declCountIs(2)
4723/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4724AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4725 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4726}
4727
4728/// Matches the n'th declaration of a declaration statement.
4729///
4730/// Note that this does not work for global declarations because the AST
4731/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4732/// DeclStmt's.
4733/// Example: Given non-global declarations
4734/// \code
4735/// int a, b = 0;
4736/// int c;
4737/// int d = 2, e;
4738/// \endcode
4739/// declStmt(containsDeclaration(
4740/// 0, varDecl(hasInitializer(anything()))))
4741/// matches only 'int d = 2, e;', and
4742/// declStmt(containsDeclaration(1, varDecl()))
4743/// \code
4744/// matches 'int a, b = 0' as well as 'int d = 2, e;'
4745/// but 'int c;' is not matched.
4746/// \endcode
4747AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4748 internal::Matcher<Decl>, InnerMatcher) {
4749 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4750 if (N >= NumDecls)
4751 return false;
4752 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4753 std::advance(Iterator, N);
4754 return InnerMatcher.matches(**Iterator, Finder, Builder);
4755}
4756
4757/// Matches a C++ catch statement that has a catch-all handler.
4758///
4759/// Given
4760/// \code
4761/// try {
4762/// // ...
4763/// } catch (int) {
4764/// // ...
4765/// } catch (...) {
4766/// // ...
4767/// }
4768/// \endcode
4769/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4771 return Node.getExceptionDecl() == nullptr;
4772}
4773
4774/// Matches a constructor initializer.
4775///
4776/// Given
4777/// \code
4778/// struct Foo {
4779/// Foo() : foo_(1) { }
4780/// int foo_;
4781/// };
4782/// \endcode
4783/// cxxRecordDecl(has(cxxConstructorDecl(
4784/// hasAnyConstructorInitializer(anything())
4785/// )))
4786/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4787AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4788 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4789 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4790 Node.init_end(), Finder, Builder);
4791 if (MatchIt == Node.init_end())
4792 return false;
4793 return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4794}
4795
4796/// Matches the field declaration of a constructor initializer.
4797///
4798/// Given
4799/// \code
4800/// struct Foo {
4801/// Foo() : foo_(1) { }
4802/// int foo_;
4803/// };
4804/// \endcode
4805/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4806/// forField(hasName("foo_"))))))
4807/// matches Foo
4808/// with forField matching foo_
4810 internal::Matcher<FieldDecl>, InnerMatcher) {
4811 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4812 return (NodeAsDecl != nullptr &&
4813 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4814}
4815
4816/// Matches the initializer expression of a constructor initializer.
4817///
4818/// Given
4819/// \code
4820/// struct Foo {
4821/// Foo() : foo_(1) { }
4822/// int foo_;
4823/// };
4824/// \endcode
4825/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4826/// withInitializer(integerLiteral(equals(1)))))))
4827/// matches Foo
4828/// with withInitializer matching (1)
4830 internal::Matcher<Expr>, InnerMatcher) {
4831 const Expr* NodeAsExpr = Node.getInit();
4832 return (NodeAsExpr != nullptr &&
4833 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4834}
4835
4836/// Matches a constructor initializer if it is explicitly written in
4837/// code (as opposed to implicitly added by the compiler).
4838///
4839/// Given
4840/// \code
4841/// struct Foo {
4842/// Foo() { }
4843/// Foo(int) : foo_("A") { }
4844/// string foo_;
4845/// };
4846/// \endcode
4847/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4848/// will match Foo(int), but not Foo()
4850 return Node.isWritten();
4851}
4852
4853/// Matches a constructor initializer if it is initializing a base, as
4854/// opposed to a member.
4855///
4856/// Given
4857/// \code
4858/// struct B {};
4859/// struct D : B {
4860/// int I;
4861/// D(int i) : I(i) {}
4862/// };
4863/// struct E : B {
4864/// E() : B() {}
4865/// };
4866/// \endcode
4867/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4868/// will match E(), but not match D(int).
4869AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4870 return Node.isBaseInitializer();
4871}
4872
4873/// Matches a constructor initializer if it is initializing a member, as
4874/// opposed to a base.
4875///
4876/// Given
4877/// \code
4878/// struct B {};
4879/// struct D : B {
4880/// int I;
4881/// D(int i) : I(i) {}
4882/// };
4883/// struct E : B {
4884/// E() : B() {}
4885/// };
4886/// \endcode
4887/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4888/// will match D(int), but not match E().
4889AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4890 return Node.isMemberInitializer();
4891}
4892
4893/// Matches any argument of a call expression or a constructor call
4894/// expression, or an ObjC-message-send expression.
4895///
4896/// Given
4897/// \code
4898/// void x(int, int, int) { int y; x(1, y, 42); }
4899/// \endcode
4900/// callExpr(hasAnyArgument(declRefExpr()))
4901/// matches x(1, y, 42)
4902/// with hasAnyArgument(...)
4903/// matching y
4904///
4905/// For ObjectiveC, given
4906/// \code
4907/// @interface I - (void) f:(int) y; @end
4908/// void foo(I *i) { [i f:12]; }
4909/// \endcode
4910/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4911/// matches [i f:12]
4916 internal::Matcher<Expr>, InnerMatcher) {
4917 for (const Expr *Arg : Node.arguments()) {
4918 if (Finder->isTraversalIgnoringImplicitNodes() &&
4919 isa<CXXDefaultArgExpr>(Arg))
4920 break;
4921 BoundNodesTreeBuilder Result(*Builder);
4922 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4923 *Builder = std::move(Result);
4924 return true;
4925 }
4926 }
4927 return false;
4928}
4929
4930/// Matches lambda captures.
4931///
4932/// Given
4933/// \code
4934/// int main() {
4935/// int x;
4936/// auto f = [x](){};
4937/// auto g = [x = 1](){};
4938/// }
4939/// \endcode
4940/// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4941/// `lambdaCapture()` matches `x` and `x=1`.
4942extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4943
4944/// Matches any capture in a lambda expression.
4945///
4946/// Given
4947/// \code
4948/// void foo() {
4949/// int t = 5;
4950/// auto f = [=](){ return t; };
4951/// }
4952/// \endcode
4953/// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4954/// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4955/// both match `[=](){ return t; }`.
4956AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4957 InnerMatcher) {
4958 for (const LambdaCapture &Capture : Node.captures()) {
4959 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4960 if (InnerMatcher.matches(Capture, Finder, &Result)) {
4961 *Builder = std::move(Result);
4962 return true;
4963 }
4964 }
4965 return false;
4966}
4967
4968/// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4969/// `VarDecl` can be a separate variable that is captured by value or
4970/// reference, or a synthesized variable if the capture has an initializer.
4971///
4972/// Given
4973/// \code
4974/// void foo() {
4975/// int x;
4976/// auto f = [x](){};
4977/// auto g = [x = 1](){};
4978/// }
4979/// \endcode
4980/// In the matcher
4981/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4982/// capturesVar(hasName("x")) matches `x` and `x = 1`.
4983AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
4984 InnerMatcher) {
4985 if (!Node.capturesVariable())
4986 return false;
4987 auto *capturedVar = Node.getCapturedVar();
4988 return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
4989}
4990
4991/// Matches a `LambdaCapture` that refers to 'this'.
4992///
4993/// Given
4994/// \code
4995/// class C {
4996/// int cc;
4997/// int f() {
4998/// auto l = [this]() { return cc; };
4999/// return l();
5000/// }
5001/// };
5002/// \endcode
5003/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
5004/// matches `[this]() { return cc; }`.
5005AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
5006
5007/// Matches a constructor call expression which uses list initialization.
5008AST_MATCHER(CXXConstructExpr, isListInitialization) {
5009 return Node.isListInitialization();
5010}
5011
5012/// Matches a constructor call expression which requires
5013/// zero initialization.
5014///
5015/// Given
5016/// \code
5017/// void foo() {
5018/// struct point { double x; double y; };
5019/// point pt[2] = { { 1.0, 2.0 } };
5020/// }
5021/// \endcode
5022/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
5023/// will match the implicit array filler for pt[1].
5024AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
5025 return Node.requiresZeroInitialization();
5026}
5027
5028/// Matches the n'th parameter of a function or an ObjC method
5029/// declaration or a block.
5030///
5031/// Given
5032/// \code
5033/// class X { void f(int x) {} };
5034/// \endcode
5035/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
5036/// matches f(int x) {}
5037/// with hasParameter(...)
5038/// matching int x
5039///
5040/// For ObjectiveC, given
5041/// \code
5042/// @interface I - (void) f:(int) y; @end
5043/// \endcode
5044//
5045/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
5046/// matches the declaration of method f with hasParameter
5047/// matching y.
5051 BlockDecl),
5052 unsigned, N, internal::Matcher<ParmVarDecl>,
5053 InnerMatcher) {
5054 return (N < Node.parameters().size()
5055 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
5056}
5057
5058/// Matches if the given method declaration declares a member function with an
5059/// explicit object parameter.
5060///
5061/// Given
5062/// \code
5063/// struct A {
5064/// int operator-(this A, int);
5065/// void fun(this A &&self);
5066/// static int operator()(int);
5067/// int operator+(int);
5068/// };
5069/// \endcode
5070///
5071/// cxxMethodDecl(isExplicitObjectMemberFunction()) matches the first two
5072/// methods but not the last two.
5073AST_MATCHER(CXXMethodDecl, isExplicitObjectMemberFunction) {
5074 return Node.isExplicitObjectMemberFunction();
5075}
5076
5077/// Matches all arguments and their respective ParmVarDecl.
5078///
5079/// Given
5080/// \code
5081/// void f(int i);
5082/// int y;
5083/// f(y);
5084/// \endcode
5085/// callExpr(
5086/// forEachArgumentWithParam(
5087/// declRefExpr(to(varDecl(hasName("y")))),
5088/// parmVarDecl(hasType(isInteger()))
5089/// ))
5090/// matches f(y);
5091/// with declRefExpr(...)
5092/// matching int y
5093/// and parmVarDecl(...)
5094/// matching int i
5095AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
5098 internal::Matcher<Expr>, ArgMatcher,
5099 internal::Matcher<ParmVarDecl>, ParamMatcher) {
5100 BoundNodesTreeBuilder Result;
5101 // The first argument of an overloaded member operator is the implicit object
5102 // argument of the method which should not be matched against a parameter, so
5103 // we skip over it here.
5104 BoundNodesTreeBuilder Matches;
5105 unsigned ArgIndex =
5107 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5108 .matches(Node, Finder, &Matches)
5109 ? 1
5110 : 0;
5111 int ParamIndex = 0;
5112 bool Matched = false;
5113 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
5114 BoundNodesTreeBuilder ArgMatches(*Builder);
5115 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
5116 Finder, &ArgMatches)) {
5117 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5119 hasParameter(ParamIndex, ParamMatcher)))),
5120 callExpr(callee(functionDecl(
5121 hasParameter(ParamIndex, ParamMatcher))))))
5122 .matches(Node, Finder, &ParamMatches)) {
5123 Result.addMatch(ParamMatches);
5124 Matched = true;
5125 }
5126 }
5127 ++ParamIndex;
5128 }
5129 *Builder = std::move(Result);
5130 return Matched;
5131}
5132
5133/// Matches all arguments and their respective types for a \c CallExpr or
5134/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
5135/// it works on calls through function pointers as well.
5136///
5137/// The difference is, that function pointers do not provide access to a
5138/// \c ParmVarDecl, but only the \c QualType for each argument.
5139///
5140/// Given
5141/// \code
5142/// void f(int i);
5143/// int y;
5144/// f(y);
5145/// void (*f_ptr)(int) = f;
5146/// f_ptr(y);
5147/// \endcode
5148/// callExpr(
5149/// forEachArgumentWithParamType(
5150/// declRefExpr(to(varDecl(hasName("y")))),
5151/// qualType(isInteger()).bind("type)
5152/// ))
5153/// matches f(y) and f_ptr(y)
5154/// with declRefExpr(...)
5155/// matching int y
5156/// and qualType(...)
5157/// matching int
5158AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
5161 internal::Matcher<Expr>, ArgMatcher,
5162 internal::Matcher<QualType>, ParamMatcher) {
5163 BoundNodesTreeBuilder Result;
5164 // The first argument of an overloaded member operator is the implicit object
5165 // argument of the method which should not be matched against a parameter, so
5166 // we skip over it here.
5167 BoundNodesTreeBuilder Matches;
5168 unsigned ArgIndex =
5170 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5171 .matches(Node, Finder, &Matches)
5172 ? 1
5173 : 0;
5174 const FunctionProtoType *FProto = nullptr;
5175
5176 if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
5177 if (const auto *Value =
5178 dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
5180
5181 // This does not necessarily lead to a `FunctionProtoType`,
5182 // e.g. K&R functions do not have a function prototype.
5183 if (QT->isFunctionPointerType())
5184 FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
5185
5186 if (QT->isMemberFunctionPointerType()) {
5187 const auto *MP = QT->getAs<MemberPointerType>();
5188 assert(MP && "Must be member-pointer if its a memberfunctionpointer");
5189 FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
5190 assert(FProto &&
5191 "The call must have happened through a member function "
5192 "pointer");
5193 }
5194 }
5195 }
5196
5197 unsigned ParamIndex = 0;
5198 bool Matched = false;
5199 unsigned NumArgs = Node.getNumArgs();
5200 if (FProto && FProto->isVariadic())
5201 NumArgs = std::min(NumArgs, FProto->getNumParams());
5202
5203 for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
5204 BoundNodesTreeBuilder ArgMatches(*Builder);
5205 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
5206 &ArgMatches)) {
5207 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5208
5209 // This test is cheaper compared to the big matcher in the next if.
5210 // Therefore, please keep this order.
5211 if (FProto && FProto->getNumParams() > ParamIndex) {
5212 QualType ParamType = FProto->getParamType(ParamIndex);
5213 if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
5214 Result.addMatch(ParamMatches);
5215 Matched = true;
5216 continue;
5217 }
5218 }
5220 hasParameter(ParamIndex, hasType(ParamMatcher))))),
5221 callExpr(callee(functionDecl(
5222 hasParameter(ParamIndex, hasType(ParamMatcher)))))))
5223 .matches(Node, Finder, &ParamMatches)) {
5224 Result.addMatch(ParamMatches);
5225 Matched = true;
5226 continue;
5227 }
5228 }
5229 }
5230 *Builder = std::move(Result);
5231 return Matched;
5232}
5233
5234/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
5235/// list. The parameter list could be that of either a block, function, or
5236/// objc-method.
5237///
5238///
5239/// Given
5240///
5241/// \code
5242/// void f(int a, int b, int c) {
5243/// }
5244/// \endcode
5245///
5246/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
5247///
5248/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
5249AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
5250 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
5251
5252 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
5253 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5254 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
5255 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5256 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
5257 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5258
5259 return false;
5260}
5261
5262/// Matches any parameter of a function or an ObjC method declaration or a
5263/// block.
5264///
5265/// Does not match the 'this' parameter of a method.
5266///
5267/// Given
5268/// \code
5269/// class X { void f(int x, int y, int z) {} };
5270/// \endcode
5271/// cxxMethodDecl(hasAnyParameter(hasName("y")))
5272/// matches f(int x, int y, int z) {}
5273/// with hasAnyParameter(...)
5274/// matching int y
5275///
5276/// For ObjectiveC, given
5277/// \code
5278/// @interface I - (void) f:(int) y; @end
5279/// \endcode
5280//
5281/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5282/// matches the declaration of method f with hasParameter
5283/// matching y.
5284///
5285/// For blocks, given
5286/// \code
5287/// b = ^(int y) { printf("%d", y) };
5288/// \endcode
5289///
5290/// the matcher blockDecl(hasAnyParameter(hasName("y")))
5291/// matches the declaration of the block b with hasParameter
5292/// matching y.
5296 BlockDecl),
5297 internal::Matcher<ParmVarDecl>,
5298 InnerMatcher) {
5299 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5300 Node.param_end(), Finder,
5301 Builder) != Node.param_end();
5302}
5303
5304/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5305/// specific parameter count.
5306///
5307/// Given
5308/// \code
5309/// void f(int i) {}
5310/// void g(int i, int j) {}
5311/// void h(int i, int j);
5312/// void j(int i);
5313/// void k(int x, int y, int z, ...);
5314/// \endcode
5315/// functionDecl(parameterCountIs(2))
5316/// matches \c g and \c h
5317/// functionProtoType(parameterCountIs(2))
5318/// matches \c g and \c h
5319/// functionProtoType(parameterCountIs(3))
5320/// matches \c k
5324 unsigned, N) {
5325 return Node.getNumParams() == N;
5326}
5327
5328/// Matches templateSpecializationType, class template specialization,
5329/// variable template specialization, and function template specialization
5330/// nodes where the template argument matches the inner matcher. This matcher
5331/// may produce multiple matches.
5332///
5333/// Given
5334/// \code
5335/// template <typename T, unsigned N, unsigned M>
5336/// struct Matrix {};
5337///
5338/// constexpr unsigned R = 2;
5339/// Matrix<int, R * 2, R * 4> M;
5340///
5341/// template <typename T, typename U>
5342/// void f(T&& t, U&& u) {}
5343///
5344/// bool B = false;
5345/// f(R, B);
5346/// \endcode
5347/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5348/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5349/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5350/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5351/// and 'bool'
5353 forEachTemplateArgument,
5357 internal::Matcher<TemplateArgument>, InnerMatcher) {
5358 ArrayRef<TemplateArgument> TemplateArgs =
5359 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5360 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5361 bool Matched = false;
5362 for (const auto &Arg : TemplateArgs) {
5363 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5364 if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5365 Matched = true;
5366 Result.addMatch(ArgBuilder);
5367 }
5368 }
5369 *Builder = std::move(Result);
5370 return Matched;
5371}
5372
5373/// Matches \c FunctionDecls that have a noreturn attribute.
5374///
5375/// Given
5376/// \code
5377/// void nope();
5378/// [[noreturn]] void a();
5379/// __attribute__((noreturn)) void b();
5380/// struct c { [[noreturn]] c(); };
5381/// \endcode
5382/// functionDecl(isNoReturn())
5383/// matches all of those except
5384/// \code
5385/// void nope();
5386/// \endcode
5387AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5388
5389/// Matches the return type of a function declaration.
5390///
5391/// Given:
5392/// \code
5393/// class X { int f() { return 1; } };
5394/// \endcode
5395/// cxxMethodDecl(returns(asString("int")))
5396/// matches int f() { return 1; }
5398 internal::Matcher<QualType>, InnerMatcher) {
5399 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5400}
5401
5402/// Matches extern "C" function or variable declarations.
5403///
5404/// Given:
5405/// \code
5406/// extern "C" void f() {}
5407/// extern "C" { void g() {} }
5408/// void h() {}
5409/// extern "C" int x = 1;
5410/// extern "C" int y = 2;
5411/// int z = 3;
5412/// \endcode
5413/// functionDecl(isExternC())
5414/// matches the declaration of f and g, but not the declaration of h.
5415/// varDecl(isExternC())
5416/// matches the declaration of x and y, but not the declaration of z.
5418 VarDecl)) {
5419 return Node.isExternC();
5420}
5421
5422/// Matches variable/function declarations that have "static" storage
5423/// class specifier ("static" keyword) written in the source.
5424///
5425/// Given:
5426/// \code
5427/// static void f() {}
5428/// static int i = 0;
5429/// extern int j;
5430/// int k;
5431/// \endcode
5432/// functionDecl(isStaticStorageClass())
5433/// matches the function declaration f.
5434/// varDecl(isStaticStorageClass())
5435/// matches the variable declaration i.
5436AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5438 VarDecl)) {
5439 return Node.getStorageClass() == SC_Static;
5440}
5441
5442/// Matches deleted function declarations.
5443///
5444/// Given:
5445/// \code
5446/// void Func();
5447/// void DeletedFunc() = delete;
5448/// \endcode
5449/// functionDecl(isDeleted())
5450/// matches the declaration of DeletedFunc, but not Func.
5452 return Node.isDeleted();
5453}
5454
5455/// Matches defaulted function declarations.
5456///
5457/// Given:
5458/// \code
5459/// class A { ~A(); };
5460/// class B { ~B() = default; };
5461/// \endcode
5462/// functionDecl(isDefaulted())
5463/// matches the declaration of ~B, but not ~A.
5465 return Node.isDefaulted();
5466}
5467
5468/// Matches weak function declarations.
5469///
5470/// Given:
5471/// \code
5472/// void foo() __attribute__((__weakref__("__foo")));
5473/// void bar();
5474/// \endcode
5475/// functionDecl(isWeak())
5476/// matches the weak declaration "foo", but not "bar".
5477AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5478
5479/// Matches functions that have a dynamic exception specification.
5480///
5481/// Given:
5482/// \code
5483/// void f();
5484/// void g() noexcept;
5485/// void h() noexcept(true);
5486/// void i() noexcept(false);
5487/// void j() throw();
5488/// void k() throw(int);
5489/// void l() throw(...);
5490/// \endcode
5491/// functionDecl(hasDynamicExceptionSpec()) and
5492/// functionProtoType(hasDynamicExceptionSpec())
5493/// match the declarations of j, k, and l, but not f, g, h, or i.
5494AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5497 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5498 return FnTy->hasDynamicExceptionSpec();
5499 return false;
5500}
5501
5502/// Matches functions that have a non-throwing exception specification.
5503///
5504/// Given:
5505/// \code
5506/// void f();
5507/// void g() noexcept;
5508/// void h() throw();
5509/// void i() throw(int);
5510/// void j() noexcept(false);
5511/// \endcode
5512/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5513/// match the declarations of g, and h, but not f, i or j.
5517 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5518
5519 // If the function does not have a prototype, then it is assumed to be a
5520 // throwing function (as it would if the function did not have any exception
5521 // specification).
5522 if (!FnTy)
5523 return false;
5524
5525 // Assume the best for any unresolved exception specification.
5527 return true;
5528
5529 return FnTy->isNothrow();
5530}
5531
5532/// Matches consteval function declarations and if consteval/if ! consteval
5533/// statements.
5534///
5535/// Given:
5536/// \code
5537/// consteval int a();
5538/// void b() { if consteval {} }
5539/// void c() { if ! consteval {} }
5540/// void d() { if ! consteval {} else {} }
5541/// \endcode
5542/// functionDecl(isConsteval())
5543/// matches the declaration of "int a()".
5544/// ifStmt(isConsteval())
5545/// matches the if statement in "void b()", "void c()", "void d()".
5548 return Node.isConsteval();
5549}
5550
5551/// Matches constexpr variable and function declarations,
5552/// and if constexpr.
5553///
5554/// Given:
5555/// \code
5556/// constexpr int foo = 42;
5557/// constexpr int bar();
5558/// void baz() { if constexpr(1 > 0) {} }
5559/// \endcode
5560/// varDecl(isConstexpr())
5561/// matches the declaration of foo.
5562/// functionDecl(isConstexpr())
5563/// matches the declaration of bar.
5564/// ifStmt(isConstexpr())
5565/// matches the if statement in baz.
5569 IfStmt)) {
5570 return Node.isConstexpr();
5571}
5572
5573/// Matches constinit variable declarations.
5574///
5575/// Given:
5576/// \code
5577/// constinit int foo = 42;
5578/// constinit const char* bar = "bar";
5579/// int baz = 42;
5580/// [[clang::require_constant_initialization]] int xyz = 42;
5581/// \endcode
5582/// varDecl(isConstinit())
5583/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5584AST_MATCHER(VarDecl, isConstinit) {
5585 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5586 return CIA->isConstinit();
5587 return false;
5588}
5589
5590/// Matches selection statements with initializer.
5591///
5592/// Given:
5593/// \code
5594/// void foo() {
5595/// if (int i = foobar(); i > 0) {}
5596/// switch (int i = foobar(); i) {}
5597/// for (auto& a = get_range(); auto& x : a) {}
5598/// }
5599/// void bar() {
5600/// if (foobar() > 0) {}
5601/// switch (foobar()) {}
5602/// for (auto& x : get_range()) {}
5603/// }
5604/// \endcode
5605/// ifStmt(hasInitStatement(anything()))
5606/// matches the if statement in foo but not in bar.
5607/// switchStmt(hasInitStatement(anything()))
5608/// matches the switch statement in foo but not in bar.
5609/// cxxForRangeStmt(hasInitStatement(anything()))
5610/// matches the range for statement in foo but not in bar.
5614 internal::Matcher<Stmt>, InnerMatcher) {
5615 const Stmt *Init = Node.getInit();
5616 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5617}
5618
5619/// Matches the condition expression of an if statement, for loop,
5620/// switch statement or conditional operator.
5621///
5622/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5623/// \code
5624/// if (true) {}
5625/// \endcode
5627 hasCondition,
5630 internal::Matcher<Expr>, InnerMatcher) {
5631 const Expr *const Condition = Node.getCond();
5632 return (Condition != nullptr &&
5633 InnerMatcher.matches(*Condition, Finder, Builder));
5634}
5635
5636/// Matches the then-statement of an if statement.
5637///
5638/// Examples matches the if statement
5639/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5640/// \code
5641/// if (false) true; else false;
5642/// \endcode
5643AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5644 const Stmt *const Then = Node.getThen();
5645 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5646}
5647
5648/// Matches the else-statement of an if statement.
5649///
5650/// Examples matches the if statement
5651/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5652/// \code
5653/// if (false) false; else true;
5654/// \endcode
5655AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5656 const Stmt *const Else = Node.getElse();
5657 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5658}
5659
5660/// Matches if a node equals a previously bound node.
5661///
5662/// Matches a node if it equals the node previously bound to \p ID.
5663///
5664/// Given
5665/// \code
5666/// class X { int a; int b; };
5667/// \endcode
5668/// cxxRecordDecl(
5669/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5670/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5671/// matches the class \c X, as \c a and \c b have the same type.
5672///
5673/// Note that when multiple matches are involved via \c forEach* matchers,
5674/// \c equalsBoundNodes acts as a filter.
5675/// For example:
5676/// compoundStmt(
5677/// forEachDescendant(varDecl().bind("d")),
5678/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5679/// will trigger a match for each combination of variable declaration
5680/// and reference to that variable declaration within a compound statement.
5683 QualType),
5684 std::string, ID) {
5685 // FIXME: Figure out whether it makes sense to allow this
5686 // on any other node types.
5687 // For *Loc it probably does not make sense, as those seem
5688 // unique. For NestedNameSepcifier it might make sense, as
5689 // those also have pointer identity, but I'm not sure whether
5690 // they're ever reused.
5691 internal::NotEqualsBoundNodePredicate Predicate;
5692 Predicate.ID = ID;
5693 Predicate.Node = DynTypedNode::create(Node);
5694 return Builder->removeBindings(Predicate);
5695}
5696
5697/// Matches the condition variable statement in an if statement.
5698///
5699/// Given
5700/// \code
5701/// if (A* a = GetAPointer()) {}
5702/// \endcode
5703/// hasConditionVariableStatement(...)
5704/// matches 'A* a = GetAPointer()'.
5705AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5706 internal::Matcher<DeclStmt>, InnerMatcher) {
5707 const DeclStmt* const DeclarationStatement =
5708 Node.getConditionVariableDeclStmt();
5709 return DeclarationStatement != nullptr &&
5710 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5711}
5712
5713/// Matches the index expression of an array subscript expression.
5714///
5715/// Given
5716/// \code
5717/// int i[5];
5718/// void f() { i[1] = 42; }
5719/// \endcode
5720/// arraySubscriptExpression(hasIndex(integerLiteral()))
5721/// matches \c i[1] with the \c integerLiteral() matching \c 1
5723 internal::Matcher<Expr>, InnerMatcher) {
5724 if (const Expr* Expression = Node.getIdx())
5725 return InnerMatcher.matches(*Expression, Finder, Builder);
5726 return false;
5727}
5728
5729/// Matches the base expression of an array subscript expression.
5730///
5731/// Given
5732/// \code
5733/// int i[5];
5734/// void f() { i[1] = 42; }
5735/// \endcode
5736/// arraySubscriptExpression(hasBase(implicitCastExpr(
5737/// hasSourceExpression(declRefExpr()))))
5738/// matches \c i[1] with the \c declRefExpr() matching \c i
5740 internal::Matcher<Expr>, InnerMatcher) {
5741 if (const Expr* Expression = Node.getBase())
5742 return InnerMatcher.matches(*Expression, Finder, Builder);
5743 return false;
5744}
5745
5746/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5747/// definition that has a given body. Note that in case of functions or
5748/// coroutines this matcher only matches the definition itself and not the
5749/// other declarations of the same function or coroutine.
5750///
5751/// Given
5752/// \code
5753/// for (;;) {}
5754/// \endcode
5755/// forStmt(hasBody(compoundStmt()))
5756/// matches 'for (;;) {}'
5757/// with compoundStmt()
5758/// matching '{}'
5759///
5760/// Given
5761/// \code
5762/// void f();
5763/// void f() {}
5764/// \endcode
5765/// functionDecl(hasBody(compoundStmt()))
5766/// matches 'void f() {}'
5767/// with compoundStmt()
5768/// matching '{}'
5769/// but does not match 'void f();'
5771 hasBody,
5774 internal::Matcher<Stmt>, InnerMatcher) {
5775 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5776 return false;
5777 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5778 return (Statement != nullptr &&
5779 InnerMatcher.matches(*Statement, Finder, Builder));
5780}
5781
5782/// Matches a function declaration that has a given body present in the AST.
5783/// Note that this matcher matches all the declarations of a function whose
5784/// body is present in the AST.
5785///
5786/// Given
5787/// \code
5788/// void f();
5789/// void f() {}
5790/// void g();
5791/// \endcode
5792/// functionDecl(hasAnyBody(compoundStmt()))
5793/// matches both 'void f();'
5794/// and 'void f() {}'
5795/// with compoundStmt()
5796/// matching '{}'
5797/// but does not match 'void g();'
5799 internal::Matcher<Stmt>, InnerMatcher) {
5800 const Stmt *const Statement = Node.getBody();
5801 return (Statement != nullptr &&
5802 InnerMatcher.matches(*Statement, Finder, Builder));
5803}
5804
5805
5806/// Matches compound statements where at least one substatement matches
5807/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5808///
5809/// Given
5810/// \code
5811/// { {}; 1+2; }
5812/// \endcode
5813/// hasAnySubstatement(compoundStmt())
5814/// matches '{ {}; 1+2; }'
5815/// with compoundStmt()
5816/// matching '{}'
5817AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5819 StmtExpr),
5820 internal::Matcher<Stmt>, InnerMatcher) {
5821 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5822 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5823 CS->body_end(), Finder,
5824 Builder) != CS->body_end();
5825}
5826
5827/// Checks that a compound statement contains a specific number of
5828/// child statements.
5829///
5830/// Example: Given
5831/// \code
5832/// { for (;;) {} }
5833/// \endcode
5834/// compoundStmt(statementCountIs(0)))
5835/// matches '{}'
5836/// but does not match the outer compound statement.
5837AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5838 return Node.size() == N;
5839}
5840
5841/// Matches literals that are equal to the given value of type ValueT.
5842///
5843/// Given
5844/// \code
5845/// f('\0', false, 3.14, 42);
5846/// \endcode
5847/// characterLiteral(equals(0))
5848/// matches '\0'
5849/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5850/// match false
5851/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5852/// match 3.14
5853/// integerLiteral(equals(42))
5854/// matches 42
5855///
5856/// Note that you cannot directly match a negative numeric literal because the
5857/// minus sign is not part of the literal: It is a unary operator whose operand
5858/// is the positive numeric literal. Instead, you must use a unaryOperator()
5859/// matcher to match the minus sign:
5860///
5861/// unaryOperator(hasOperatorName("-"),
5862/// hasUnaryOperand(integerLiteral(equals(13))))
5863///
5864/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5865/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5866template <typename ValueT>
5867internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5868 void(internal::AllNodeBaseTypes), ValueT>
5869equals(const ValueT &Value) {
5870 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5871 void(internal::AllNodeBaseTypes), ValueT>(
5872 Value);
5873}
5874
5879 bool, Value, 0) {
5880 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5881 .matchesNode(Node);
5882}
5883
5888 unsigned, Value, 1) {
5889 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5890 .matchesNode(Node);
5891}
5892
5898 double, Value, 2) {
5899 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5900 .matchesNode(Node);
5901}
5902
5903/// Matches the operator Name of operator expressions and fold expressions
5904/// (binary or unary).
5905///
5906/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5907/// \code
5908/// !(a || b)
5909/// \endcode
5910///
5911/// Example matches `(0 + ... + args)`
5912/// (matcher = cxxFoldExpr(hasOperatorName("+")))
5913/// \code
5914/// template <typename... Args>
5915/// auto sum(Args... args) {
5916/// return (0 + ... + args);
5917/// }
5918/// \endcode
5920 hasOperatorName,
5924 std::string, Name) {
5925 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5926 return *OpName == Name;
5927 return false;
5928}
5929
5930/// Matches operator expressions (binary or unary) that have any of the
5931/// specified names.
5932///
5933/// hasAnyOperatorName("+", "-")
5934/// Is equivalent to
5935/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5936extern const internal::VariadicFunction<
5937 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5941 std::vector<std::string>>,
5944
5945/// Matches all kinds of assignment operators.
5946///
5947/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5948/// \code
5949/// if (a == b)
5950/// a += b;
5951/// \endcode
5952///
5953/// Example 2: matches s1 = s2
5954/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5955/// \code
5956/// struct S { S& operator=(const S&); };
5957/// void x() { S s1, s2; s1 = s2; }
5958/// \endcode
5960 isAssignmentOperator,
5963 return Node.isAssignmentOp();
5964}
5965
5966/// Matches comparison operators.
5967///
5968/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5969/// \code
5970/// if (a == b)
5971/// a += b;
5972/// \endcode
5973///
5974/// Example 2: matches s1 < s2
5975/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5976/// \code
5977/// struct S { bool operator<(const S& other); };
5978/// void x(S s1, S s2) { bool b1 = s1 < s2; }
5979/// \endcode
5981 isComparisonOperator,
5984 return Node.isComparisonOp();
5985}
5986
5987/// Matches the left hand side of binary operator expressions.
5988///
5989/// Example matches a (matcher = binaryOperator(hasLHS()))
5990/// \code
5991/// a || b
5992/// \endcode
5994 hasLHS,
5998 internal::Matcher<Expr>, InnerMatcher) {
5999 const Expr *LeftHandSide = internal::getLHS(Node);
6000 return (LeftHandSide != nullptr &&
6001 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
6002}
6003
6004/// Matches the right hand side of binary operator expressions.
6005///
6006/// Example matches b (matcher = binaryOperator(hasRHS()))
6007/// \code
6008/// a || b
6009/// \endcode
6011 hasRHS,
6015 internal::Matcher<Expr>, InnerMatcher) {
6016 const Expr *RightHandSide = internal::getRHS(Node);
6017 return (RightHandSide != nullptr &&
6018 InnerMatcher.matches(*RightHandSide, Finder, Builder));
6019}
6020
6021/// Matches if either the left hand side or the right hand side of a
6022/// binary operator or fold expression matches.
6024 hasEitherOperand,
6027 internal::Matcher<Expr>, InnerMatcher) {
6028 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6029 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
6030 .matches(Node, Finder, Builder);
6031}