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() && Node.getBitWidthValue() == Width;
712}
713
714/// Matches non-static data members that have an in-class initializer.
715///
716/// Given
717/// \code
718/// class C {
719/// int a = 2;
720/// int b = 3;
721/// int c;
722/// };
723/// \endcode
724/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
725/// matches 'int a;' but not 'int b;'.
726/// fieldDecl(hasInClassInitializer(anything()))
727/// matches 'int a;' and 'int b;' but not 'int c;'.
728AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
729 InnerMatcher) {
730 const Expr *Initializer = Node.getInClassInitializer();
731 return (Initializer != nullptr &&
732 InnerMatcher.matches(*Initializer, Finder, Builder));
733}
734
735/// Determines whether the function is "main", which is the entry point
736/// into an executable program.
738 return Node.isMain();
739}
740
741/// Matches the specialized template of a specialization declaration.
742///
743/// Given
744/// \code
745/// template<typename T> class A {}; #1
746/// template<> class A<int> {}; #2
747/// \endcode
748/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
749/// matches '#2' with classTemplateDecl() matching the class template
750/// declaration of 'A' at #1.
752 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
753 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
754 return (Decl != nullptr &&
755 InnerMatcher.matches(*Decl, Finder, Builder));
756}
757
758/// Matches an entity that has been implicitly added by the compiler (e.g.
759/// implicit default/copy constructors).
762 LambdaCapture)) {
763 return Node.isImplicit();
764}
765
766/// Matches templateSpecializationTypes, class template specializations,
767/// variable template specializations, and function template specializations
768/// that have at least one TemplateArgument matching the given InnerMatcher.
769///
770/// Given
771/// \code
772/// template<typename T> class A {};
773/// template<> class A<double> {};
774/// A<int> a;
775///
776/// template<typename T> f() {};
777/// void func() { f<int>(); };
778/// \endcode
779///
780/// \endcode
781/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
782/// refersToType(asString("int"))))
783/// matches the specialization \c A<int>
784///
785/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
786/// matches the specialization \c f<int>
788 hasAnyTemplateArgument,
792 internal::Matcher<TemplateArgument>, InnerMatcher) {
794 internal::getTemplateSpecializationArgs(Node);
795 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
796 Builder) != List.end();
797}
798
799/// Causes all nested matchers to be matched with the specified traversal kind.
800///
801/// Given
802/// \code
803/// void foo()
804/// {
805/// int i = 3.0;
806/// }
807/// \endcode
808/// The matcher
809/// \code
810/// traverse(TK_IgnoreUnlessSpelledInSource,
811/// varDecl(hasInitializer(floatLiteral().bind("init")))
812/// )
813/// \endcode
814/// matches the variable declaration with "init" bound to the "3.0".
815template <typename T>
816internal::Matcher<T> traverse(TraversalKind TK,
817 const internal::Matcher<T> &InnerMatcher) {
818 return internal::DynTypedMatcher::constructRestrictedWrapper(
819 new internal::TraversalMatcher<T>(TK, InnerMatcher),
820 InnerMatcher.getID().first)
821 .template unconditionalConvertTo<T>();
822}
823
824template <typename T>
825internal::BindableMatcher<T>
826traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
827 return internal::BindableMatcher<T>(
828 internal::DynTypedMatcher::constructRestrictedWrapper(
829 new internal::TraversalMatcher<T>(TK, InnerMatcher),
830 InnerMatcher.getID().first)
831 .template unconditionalConvertTo<T>());
832}
833
834template <typename... T>
835internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
837 const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
838 return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
839 TK, InnerMatcher);
840}
841
842template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
843 typename T, typename ToTypes>
844internal::TraversalWrapper<
845 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
846traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
847 ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
848 return internal::TraversalWrapper<
849 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
850 ToTypes>>(TK, InnerMatcher);
851}
852
853template <template <typename T, typename... P> class MatcherT, typename... P,
854 typename ReturnTypesF>
855internal::TraversalWrapper<
856 internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>
857traverse(TraversalKind TK,
858 const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>
859 &InnerMatcher) {
860 return internal::TraversalWrapper<
861 internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK,
862 InnerMatcher);
863}
864
865template <typename... T>
866internal::Matcher<typename internal::GetClade<T...>::Type>
867traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
868 return traverse(TK, InnerMatcher.with());
869}
870
871/// Matches expressions that match InnerMatcher after any implicit AST
872/// nodes are stripped off.
873///
874/// Parentheses and explicit casts are not discarded.
875/// Given
876/// \code
877/// class C {};
878/// C a = C();
879/// C b;
880/// C c = b;
881/// \endcode
882/// The matchers
883/// \code
884/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
885/// \endcode
886/// would match the declarations for a, b, and c.
887/// While
888/// \code
889/// varDecl(hasInitializer(cxxConstructExpr()))
890/// \endcode
891/// only match the declarations for b and c.
892AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
893 InnerMatcher) {
894 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
895}
896
897/// Matches expressions that match InnerMatcher after any implicit casts
898/// are stripped off.
899///
900/// Parentheses and explicit casts are not discarded.
901/// Given
902/// \code
903/// int arr[5];
904/// int a = 0;
905/// char b = 0;
906/// const int c = a;
907/// int *d = arr;
908/// long e = (long) 0l;
909/// \endcode
910/// The matchers
911/// \code
912/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
913/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
914/// \endcode
915/// would match the declarations for a, b, c, and d, but not e.
916/// While
917/// \code
918/// varDecl(hasInitializer(integerLiteral()))
919/// varDecl(hasInitializer(declRefExpr()))
920/// \endcode
921/// only match the declarations for a.
922AST_MATCHER_P(Expr, ignoringImpCasts,
923 internal::Matcher<Expr>, InnerMatcher) {
924 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
925}
926
927/// Matches expressions that match InnerMatcher after parentheses and
928/// casts are stripped off.
929///
930/// Implicit and non-C Style casts are also discarded.
931/// Given
932/// \code
933/// int a = 0;
934/// char b = (0);
935/// void* c = reinterpret_cast<char*>(0);
936/// char d = char(0);
937/// \endcode
938/// The matcher
939/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
940/// would match the declarations for a, b, c, and d.
941/// while
942/// varDecl(hasInitializer(integerLiteral()))
943/// only match the declaration for a.
944AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
945 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
946}
947
948/// Matches expressions that match InnerMatcher after implicit casts and
949/// parentheses are stripped off.
950///
951/// Explicit casts are not discarded.
952/// Given
953/// \code
954/// int arr[5];
955/// int a = 0;
956/// char b = (0);
957/// const int c = a;
958/// int *d = (arr);
959/// long e = ((long) 0l);
960/// \endcode
961/// The matchers
962/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
963/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
964/// would match the declarations for a, b, c, and d, but not e.
965/// while
966/// varDecl(hasInitializer(integerLiteral()))
967/// varDecl(hasInitializer(declRefExpr()))
968/// would only match the declaration for a.
969AST_MATCHER_P(Expr, ignoringParenImpCasts,
970 internal::Matcher<Expr>, InnerMatcher) {
971 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
972}
973
974/// Matches types that match InnerMatcher after any parens are stripped.
975///
976/// Given
977/// \code
978/// void (*fp)(void);
979/// \endcode
980/// The matcher
981/// \code
982/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
983/// \endcode
984/// would match the declaration for fp.
985AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
986 InnerMatcher, 0) {
987 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
988}
989
990/// Overload \c ignoringParens for \c Expr.
991///
992/// Given
993/// \code
994/// const char* str = ("my-string");
995/// \endcode
996/// The matcher
997/// \code
998/// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
999/// \endcode
1000/// would match the implicit cast resulting from the assignment.
1001AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
1002 InnerMatcher, 1) {
1003 const Expr *E = Node.IgnoreParens();
1004 return InnerMatcher.matches(*E, Finder, Builder);
1005}
1006
1007/// Matches expressions that are instantiation-dependent even if it is
1008/// neither type- nor value-dependent.
1009///
1010/// In the following example, the expression sizeof(sizeof(T() + T()))
1011/// is instantiation-dependent (since it involves a template parameter T),
1012/// but is neither type- nor value-dependent, since the type of the inner
1013/// sizeof is known (std::size_t) and therefore the size of the outer
1014/// sizeof is known.
1015/// \code
1016/// template<typename T>
1017/// void f(T x, T y) { sizeof(sizeof(T() + T()); }
1018/// \endcode
1019/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
1020AST_MATCHER(Expr, isInstantiationDependent) {
1021 return Node.isInstantiationDependent();
1022}
1023
1024/// Matches expressions that are type-dependent because the template type
1025/// is not yet instantiated.
1026///
1027/// For example, the expressions "x" and "x + y" are type-dependent in
1028/// the following code, but "y" is not type-dependent:
1029/// \code
1030/// template<typename T>
1031/// void add(T x, int y) {
1032/// x + y;
1033/// }
1034/// \endcode
1035/// expr(isTypeDependent()) matches x + y
1036AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
1037
1038/// Matches expression that are value-dependent because they contain a
1039/// non-type template parameter.
1040///
1041/// For example, the array bound of "Chars" in the following example is
1042/// value-dependent.
1043/// \code
1044/// template<int Size> int f() { return Size; }
1045/// \endcode
1046/// expr(isValueDependent()) matches return Size
1047AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
1048
1049/// Matches templateSpecializationType, class template specializations,
1050/// variable template specializations, and function template specializations
1051/// where the n'th TemplateArgument matches the given InnerMatcher.
1052///
1053/// Given
1054/// \code
1055/// template<typename T, typename U> class A {};
1056/// A<bool, int> b;
1057/// A<int, bool> c;
1058///
1059/// template<typename T> void f() {}
1060/// void func() { f<int>(); };
1061/// \endcode
1062/// classTemplateSpecializationDecl(hasTemplateArgument(
1063/// 1, refersToType(asString("int"))))
1064/// matches the specialization \c A<bool, int>
1065///
1066/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1067/// matches the specialization \c f<int>
1069 hasTemplateArgument,
1073 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1075 internal::getTemplateSpecializationArgs(Node);
1076 if (List.size() <= N)
1077 return false;
1078 return InnerMatcher.matches(List[N], Finder, Builder);
1079}
1080
1081/// Matches if the number of template arguments equals \p N.
1082///
1083/// Given
1084/// \code
1085/// template<typename T> struct C {};
1086/// C<int> c;
1087/// \endcode
1088/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1089/// matches C<int>.
1091 templateArgumentCountIs,
1094 unsigned, N) {
1095 return internal::getTemplateSpecializationArgs(Node).size() == N;
1096}
1097
1098/// Matches a TemplateArgument that refers to a certain type.
1099///
1100/// Given
1101/// \code
1102/// struct X {};
1103/// template<typename T> struct A {};
1104/// A<X> a;
1105/// \endcode
1106/// classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
1107/// recordType(hasDeclaration(recordDecl(hasName("X")))))))
1108/// matches the specialization of \c struct A generated by \c A<X>.
1110 internal::Matcher<QualType>, InnerMatcher) {
1111 if (Node.getKind() != TemplateArgument::Type)
1112 return false;
1113 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1114}
1115
1116/// Matches a TemplateArgument that refers to a certain template.
1117///
1118/// Given
1119/// \code
1120/// template<template <typename> class S> class X {};
1121/// template<typename T> class Y {};
1122/// X<Y> xi;
1123/// \endcode
1124/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1125/// refersToTemplate(templateName())))
1126/// matches the specialization \c X<Y>
1128 internal::Matcher<TemplateName>, InnerMatcher) {
1129 if (Node.getKind() != TemplateArgument::Template)
1130 return false;
1131 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1132}
1133
1134/// Matches a canonical TemplateArgument that refers to a certain
1135/// declaration.
1136///
1137/// Given
1138/// \code
1139/// struct B { int next; };
1140/// template<int(B::*next_ptr)> struct A {};
1141/// A<&B::next> a;
1142/// \endcode
1143/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1144/// refersToDeclaration(fieldDecl(hasName("next")))))
1145/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1146/// \c B::next
1147AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1148 internal::Matcher<Decl>, InnerMatcher) {
1149 if (Node.getKind() == TemplateArgument::Declaration)
1150 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1151 return false;
1152}
1153
1154/// Matches a sugar TemplateArgument that refers to a certain expression.
1155///
1156/// Given
1157/// \code
1158/// struct B { int next; };
1159/// template<int(B::*next_ptr)> struct A {};
1160/// A<&B::next> a;
1161/// \endcode
1162/// templateSpecializationType(hasAnyTemplateArgument(
1163/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1164/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1165/// \c B::next
1166AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1167 if (Node.getKind() == TemplateArgument::Expression)
1168 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1169 return false;
1170}
1171
1172/// Matches a TemplateArgument that is an integral value.
1173///
1174/// Given
1175/// \code
1176/// template<int T> struct C {};
1177/// C<42> c;
1178/// \endcode
1179/// classTemplateSpecializationDecl(
1180/// hasAnyTemplateArgument(isIntegral()))
1181/// matches the implicit instantiation of C in C<42>
1182/// with isIntegral() matching 42.
1184 return Node.getKind() == TemplateArgument::Integral;
1185}
1186
1187/// Matches a TemplateArgument that refers to an integral type.
1188///
1189/// Given
1190/// \code
1191/// template<int T> struct C {};
1192/// C<42> c;
1193/// \endcode
1194/// classTemplateSpecializationDecl(
1195/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1196/// matches the implicit instantiation of C in C<42>.
1197AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1198 internal::Matcher<QualType>, InnerMatcher) {
1199 if (Node.getKind() != TemplateArgument::Integral)
1200 return false;
1201 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1202}
1203
1204/// Matches a TemplateArgument of integral type with a given value.
1205///
1206/// Note that 'Value' is a string as the template argument's value is
1207/// an arbitrary precision integer. 'Value' must be euqal to the canonical
1208/// representation of that integral value in base 10.
1209///
1210/// Given
1211/// \code
1212/// template<int T> struct C {};
1213/// C<42> c;
1214/// \endcode
1215/// classTemplateSpecializationDecl(
1216/// hasAnyTemplateArgument(equalsIntegralValue("42")))
1217/// matches the implicit instantiation of C in C<42>.
1218AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1219 std::string, Value) {
1220 if (Node.getKind() != TemplateArgument::Integral)
1221 return false;
1222 return toString(Node.getAsIntegral(), 10) == Value;
1223}
1224
1225/// Matches an Objective-C autorelease pool statement.
1226///
1227/// Given
1228/// \code
1229/// @autoreleasepool {
1230/// int x = 0;
1231/// }
1232/// \endcode
1233/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1234/// inside the autorelease pool.
1235extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1237
1238/// Matches any export declaration.
1239///
1240/// Example matches following declarations.
1241/// \code
1242/// export void foo();
1243/// export { void foo(); }
1244/// export namespace { void foo(); }
1245/// export int v;
1246/// \endcode
1247extern const internal::VariadicDynCastAllOfMatcher<Decl, ExportDecl> exportDecl;
1248
1249/// Matches any value declaration.
1250///
1251/// Example matches A, B, C and F
1252/// \code
1253/// enum X { A, B, C };
1254/// void F();
1255/// \endcode
1256extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1257
1258/// Matches C++ constructor declarations.
1259///
1260/// Example matches Foo::Foo() and Foo::Foo(int)
1261/// \code
1262/// class Foo {
1263/// public:
1264/// Foo();
1265/// Foo(int);
1266/// int DoSomething();
1267/// };
1268/// \endcode
1269extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1271
1272/// Matches explicit C++ destructor declarations.
1273///
1274/// Example matches Foo::~Foo()
1275/// \code
1276/// class Foo {
1277/// public:
1278/// virtual ~Foo();
1279/// };
1280/// \endcode
1281extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1283
1284/// Matches enum declarations.
1285///
1286/// Example matches X
1287/// \code
1288/// enum X {
1289/// A, B, C
1290/// };
1291/// \endcode
1292extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1293
1294/// Matches enum constants.
1295///
1296/// Example matches A, B, C
1297/// \code
1298/// enum X {
1299/// A, B, C
1300/// };
1301/// \endcode
1302extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1304
1305/// Matches tag declarations.
1306///
1307/// Example matches X, Z, U, S, E
1308/// \code
1309/// class X;
1310/// template<class T> class Z {};
1311/// struct S {};
1312/// union U {};
1313/// enum E {
1314/// A, B, C
1315/// };
1316/// \endcode
1317extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1318
1319/// Matches method declarations.
1320///
1321/// Example matches y
1322/// \code
1323/// class X { void y(); };
1324/// \endcode
1325extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1327
1328/// Matches conversion operator declarations.
1329///
1330/// Example matches the operator.
1331/// \code
1332/// class X { operator int() const; };
1333/// \endcode
1334extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1336
1337/// Matches user-defined and implicitly generated deduction guide.
1338///
1339/// Example matches the deduction guide.
1340/// \code
1341/// template<typename T>
1342/// class X { X(int) };
1343/// X(int) -> X<int>;
1344/// \endcode
1345extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1347
1348/// Matches concept declarations.
1349///
1350/// Example matches integral
1351/// \code
1352/// template<typename T>
1353/// concept integral = std::is_integral_v<T>;
1354/// \endcode
1355extern const internal::VariadicDynCastAllOfMatcher<Decl, ConceptDecl>
1357
1358/// Matches variable declarations.
1359///
1360/// Note: this does not match declarations of member variables, which are
1361/// "field" declarations in Clang parlance.
1362///
1363/// Example matches a
1364/// \code
1365/// int a;
1366/// \endcode
1367extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1368
1369/// Matches field declarations.
1370///
1371/// Given
1372/// \code
1373/// class X { int m; };
1374/// \endcode
1375/// fieldDecl()
1376/// matches 'm'.
1377extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1378
1379/// Matches indirect field declarations.
1380///
1381/// Given
1382/// \code
1383/// struct X { struct { int a; }; };
1384/// \endcode
1385/// indirectFieldDecl()
1386/// matches 'a'.
1387extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1389
1390/// Matches function declarations.
1391///
1392/// Example matches f
1393/// \code
1394/// void f();
1395/// \endcode
1396extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1398
1399/// Matches C++ function template declarations.
1400///
1401/// Example matches f
1402/// \code
1403/// template<class T> void f(T t) {}
1404/// \endcode
1405extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1407
1408/// Matches friend declarations.
1409///
1410/// Given
1411/// \code
1412/// class X { friend void foo(); };
1413/// \endcode
1414/// friendDecl()
1415/// matches 'friend void foo()'.
1416extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1417
1418/// Matches statements.
1419///
1420/// Given
1421/// \code
1422/// { ++a; }
1423/// \endcode
1424/// stmt()
1425/// matches both the compound statement '{ ++a; }' and '++a'.
1426extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1427
1428/// Matches declaration statements.
1429///
1430/// Given
1431/// \code
1432/// int a;
1433/// \endcode
1434/// declStmt()
1435/// matches 'int a'.
1436extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1437
1438/// Matches member expressions.
1439///
1440/// Given
1441/// \code
1442/// class Y {
1443/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1444/// int a; static int b;
1445/// };
1446/// \endcode
1447/// memberExpr()
1448/// matches this->x, x, y.x, a, this->b
1449extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1450
1451/// Matches unresolved member expressions.
1452///
1453/// Given
1454/// \code
1455/// struct X {
1456/// template <class T> void f();
1457/// void g();
1458/// };
1459/// template <class T> void h() { X x; x.f<T>(); x.g(); }
1460/// \endcode
1461/// unresolvedMemberExpr()
1462/// matches x.f<T>
1463extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1465
1466/// Matches member expressions where the actual member referenced could not be
1467/// resolved because the base expression or the member name was dependent.
1468///
1469/// Given
1470/// \code
1471/// template <class T> void f() { T t; t.g(); }
1472/// \endcode
1473/// cxxDependentScopeMemberExpr()
1474/// matches t.g
1475extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1478
1479/// Matches call expressions.
1480///
1481/// Example matches x.y() and y()
1482/// \code
1483/// X x;
1484/// x.y();
1485/// y();
1486/// \endcode
1487extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1488
1489/// Matches call expressions which were resolved using ADL.
1490///
1491/// Example matches y(x) but not y(42) or NS::y(x).
1492/// \code
1493/// namespace NS {
1494/// struct X {};
1495/// void y(X);
1496/// }
1497///
1498/// void y(...);
1499///
1500/// void test() {
1501/// NS::X x;
1502/// y(x); // Matches
1503/// NS::y(x); // Doesn't match
1504/// y(42); // Doesn't match
1505/// using NS::y;
1506/// y(x); // Found by both unqualified lookup and ADL, doesn't match
1507// }
1508/// \endcode
1509AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1510
1511/// Matches lambda expressions.
1512///
1513/// Example matches [&](){return 5;}
1514/// \code
1515/// [&](){return 5;}
1516/// \endcode
1517extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1518
1519/// Matches member call expressions.
1520///
1521/// Example matches x.y()
1522/// \code
1523/// X x;
1524/// x.y();
1525/// \endcode
1526extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1528
1529/// Matches ObjectiveC Message invocation expressions.
1530///
1531/// The innermost message send invokes the "alloc" class method on the
1532/// NSString class, while the outermost message send invokes the
1533/// "initWithString" instance method on the object returned from
1534/// NSString's "alloc". This matcher should match both message sends.
1535/// \code
1536/// [[NSString alloc] initWithString:@"Hello"]
1537/// \endcode
1538extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1540
1541/// Matches ObjectiveC String literal expressions.
1542///
1543/// Example matches @"abcd"
1544/// \code
1545/// NSString *s = @"abcd";
1546/// \endcode
1547extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
1549
1550/// Matches Objective-C interface declarations.
1551///
1552/// Example matches Foo
1553/// \code
1554/// @interface Foo
1555/// @end
1556/// \endcode
1557extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1559
1560/// Matches Objective-C implementation declarations.
1561///
1562/// Example matches Foo
1563/// \code
1564/// @implementation Foo
1565/// @end
1566/// \endcode
1567extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1569
1570/// Matches Objective-C protocol declarations.
1571///
1572/// Example matches FooDelegate
1573/// \code
1574/// @protocol FooDelegate
1575/// @end
1576/// \endcode
1577extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1579
1580/// Matches Objective-C category declarations.
1581///
1582/// Example matches Foo (Additions)
1583/// \code
1584/// @interface Foo (Additions)
1585/// @end
1586/// \endcode
1587extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1589
1590/// Matches Objective-C category definitions.
1591///
1592/// Example matches Foo (Additions)
1593/// \code
1594/// @implementation Foo (Additions)
1595/// @end
1596/// \endcode
1597extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1599
1600/// Matches Objective-C method declarations.
1601///
1602/// Example matches both declaration and definition of -[Foo method]
1603/// \code
1604/// @interface Foo
1605/// - (void)method;
1606/// @end
1607///
1608/// @implementation Foo
1609/// - (void)method {}
1610/// @end
1611/// \endcode
1612extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1614
1615/// Matches block declarations.
1616///
1617/// Example matches the declaration of the nameless block printing an input
1618/// integer.
1619///
1620/// \code
1621/// myFunc(^(int p) {
1622/// printf("%d", p);
1623/// })
1624/// \endcode
1625extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1626 blockDecl;
1627
1628/// Matches Objective-C instance variable declarations.
1629///
1630/// Example matches _enabled
1631/// \code
1632/// @implementation Foo {
1633/// BOOL _enabled;
1634/// }
1635/// @end
1636/// \endcode
1637extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1639
1640/// Matches Objective-C property declarations.
1641///
1642/// Example matches enabled
1643/// \code
1644/// @interface Foo
1645/// @property BOOL enabled;
1646/// @end
1647/// \endcode
1648extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1650
1651/// Matches Objective-C \@throw statements.
1652///
1653/// Example matches \@throw
1654/// \code
1655/// @throw obj;
1656/// \endcode
1657extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1659
1660/// Matches Objective-C @try statements.
1661///
1662/// Example matches @try
1663/// \code
1664/// @try {}
1665/// @catch (...) {}
1666/// \endcode
1667extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1669
1670/// Matches Objective-C @catch statements.
1671///
1672/// Example matches @catch
1673/// \code
1674/// @try {}
1675/// @catch (...) {}
1676/// \endcode
1677extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1679
1680/// Matches Objective-C @finally statements.
1681///
1682/// Example matches @finally
1683/// \code
1684/// @try {}
1685/// @finally {}
1686/// \endcode
1687extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1689
1690/// Matches expressions that introduce cleanups to be run at the end
1691/// of the sub-expression's evaluation.
1692///
1693/// Example matches std::string()
1694/// \code
1695/// const std::string str = std::string();
1696/// \endcode
1697extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1699
1700/// Matches init list expressions.
1701///
1702/// Given
1703/// \code
1704/// int a[] = { 1, 2 };
1705/// struct B { int x, y; };
1706/// B b = { 5, 6 };
1707/// \endcode
1708/// initListExpr()
1709/// matches "{ 1, 2 }" and "{ 5, 6 }"
1710extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1712
1713/// Matches the syntactic form of init list expressions
1714/// (if expression have it).
1715AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1716 internal::Matcher<Expr>, InnerMatcher) {
1717 const Expr *SyntForm = Node.getSyntacticForm();
1718 return (SyntForm != nullptr &&
1719 InnerMatcher.matches(*SyntForm, Finder, Builder));
1720}
1721
1722/// Matches C++ initializer list expressions.
1723///
1724/// Given
1725/// \code
1726/// std::vector<int> a({ 1, 2, 3 });
1727/// std::vector<int> b = { 4, 5 };
1728/// int c[] = { 6, 7 };
1729/// std::pair<int, int> d = { 8, 9 };
1730/// \endcode
1731/// cxxStdInitializerListExpr()
1732/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1733extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1736
1737/// Matches implicit initializers of init list expressions.
1738///
1739/// Given
1740/// \code
1741/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1742/// \endcode
1743/// implicitValueInitExpr()
1744/// matches "[0].y" (implicitly)
1745extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1747
1748/// Matches paren list expressions.
1749/// ParenListExprs don't have a predefined type and are used for late parsing.
1750/// In the final AST, they can be met in template declarations.
1751///
1752/// Given
1753/// \code
1754/// template<typename T> class X {
1755/// void f() {
1756/// X x(*this);
1757/// int a = 0, b = 1; int i = (a, b);
1758/// }
1759/// };
1760/// \endcode
1761/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1762/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1763extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1765
1766/// Matches substitutions of non-type template parameters.
1767///
1768/// Given
1769/// \code
1770/// template <int N>
1771/// struct A { static const int n = N; };
1772/// struct B : public A<42> {};
1773/// \endcode
1774/// substNonTypeTemplateParmExpr()
1775/// matches "N" in the right-hand side of "static const int n = N;"
1776extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1779
1780/// Matches using declarations.
1781///
1782/// Given
1783/// \code
1784/// namespace X { int x; }
1785/// using X::x;
1786/// \endcode
1787/// usingDecl()
1788/// matches \code using X::x \endcode
1789extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1790
1791/// Matches using-enum declarations.
1792///
1793/// Given
1794/// \code
1795/// namespace X { enum x {...}; }
1796/// using enum X::x;
1797/// \endcode
1798/// usingEnumDecl()
1799/// matches \code using enum X::x \endcode
1800extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1802
1803/// Matches using namespace declarations.
1804///
1805/// Given
1806/// \code
1807/// namespace X { int x; }
1808/// using namespace X;
1809/// \endcode
1810/// usingDirectiveDecl()
1811/// matches \code using namespace X \endcode
1812extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1814
1815/// Matches reference to a name that can be looked up during parsing
1816/// but could not be resolved to a specific declaration.
1817///
1818/// Given
1819/// \code
1820/// template<typename T>
1821/// T foo() { T a; return a; }
1822/// template<typename T>
1823/// void bar() {
1824/// foo<T>();
1825/// }
1826/// \endcode
1827/// unresolvedLookupExpr()
1828/// matches \code foo<T>() \endcode
1829extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1831
1832/// Matches unresolved using value declarations.
1833///
1834/// Given
1835/// \code
1836/// template<typename X>
1837/// class C : private X {
1838/// using X::x;
1839/// };
1840/// \endcode
1841/// unresolvedUsingValueDecl()
1842/// matches \code using X::x \endcode
1843extern const internal::VariadicDynCastAllOfMatcher<Decl,
1846
1847/// Matches unresolved using value declarations that involve the
1848/// typename.
1849///
1850/// Given
1851/// \code
1852/// template <typename T>
1853/// struct Base { typedef T Foo; };
1854///
1855/// template<typename T>
1856/// struct S : private Base<T> {
1857/// using typename Base<T>::Foo;
1858/// };
1859/// \endcode
1860/// unresolvedUsingTypenameDecl()
1861/// matches \code using Base<T>::Foo \endcode
1862extern const internal::VariadicDynCastAllOfMatcher<Decl,
1865
1866/// Matches a constant expression wrapper.
1867///
1868/// Example matches the constant in the case statement:
1869/// (matcher = constantExpr())
1870/// \code
1871/// switch (a) {
1872/// case 37: break;
1873/// }
1874/// \endcode
1875extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1877
1878/// Matches parentheses used in expressions.
1879///
1880/// Example matches (foo() + 1)
1881/// \code
1882/// int foo() { return 1; }
1883/// int a = (foo() + 1);
1884/// \endcode
1885extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1886
1887/// Matches constructor call expressions (including implicit ones).
1888///
1889/// Example matches string(ptr, n) and ptr within arguments of f
1890/// (matcher = cxxConstructExpr())
1891/// \code
1892/// void f(const string &a, const string &b);
1893/// char *ptr;
1894/// int n;
1895/// f(string(ptr, n), ptr);
1896/// \endcode
1897extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1899
1900/// Matches unresolved constructor call expressions.
1901///
1902/// Example matches T(t) in return statement of f
1903/// (matcher = cxxUnresolvedConstructExpr())
1904/// \code
1905/// template <typename T>
1906/// void f(const T& t) { return T(t); }
1907/// \endcode
1908extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1911
1912/// Matches implicit and explicit this expressions.
1913///
1914/// Example matches the implicit this expression in "return i".
1915/// (matcher = cxxThisExpr())
1916/// \code
1917/// struct foo {
1918/// int i;
1919/// int f() { return i; }
1920/// };
1921/// \endcode
1922extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1924
1925/// Matches nodes where temporaries are created.
1926///
1927/// Example matches FunctionTakesString(GetStringByValue())
1928/// (matcher = cxxBindTemporaryExpr())
1929/// \code
1930/// FunctionTakesString(GetStringByValue());
1931/// FunctionTakesStringByPointer(GetStringPointer());
1932/// \endcode
1933extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1935
1936/// Matches nodes where temporaries are materialized.
1937///
1938/// Example: Given
1939/// \code
1940/// struct T {void func();};
1941/// T f();
1942/// void g(T);
1943/// \endcode
1944/// materializeTemporaryExpr() matches 'f()' in these statements
1945/// \code
1946/// T u(f());
1947/// g(f());
1948/// f().func();
1949/// \endcode
1950/// but does not match
1951/// \code
1952/// f();
1953/// \endcode
1954extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1957
1958/// Matches new expressions.
1959///
1960/// Given
1961/// \code
1962/// new X;
1963/// \endcode
1964/// cxxNewExpr()
1965/// matches 'new X'.
1966extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1967
1968/// Matches delete expressions.
1969///
1970/// Given
1971/// \code
1972/// delete X;
1973/// \endcode
1974/// cxxDeleteExpr()
1975/// matches 'delete X'.
1976extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1978
1979/// Matches noexcept expressions.
1980///
1981/// Given
1982/// \code
1983/// bool a() noexcept;
1984/// bool b() noexcept(true);
1985/// bool c() noexcept(false);
1986/// bool d() noexcept(noexcept(a()));
1987/// bool e = noexcept(b()) || noexcept(c());
1988/// \endcode
1989/// cxxNoexceptExpr()
1990/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1991/// doesn't match the noexcept specifier in the declarations a, b, c or d.
1992extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1994
1995/// Matches a loop initializing the elements of an array in a number of contexts:
1996/// * in the implicit copy/move constructor for a class with an array member
1997/// * when a lambda-expression captures an array by value
1998/// * when a decomposition declaration decomposes an array
1999///
2000/// Given
2001/// \code
2002/// void testLambdaCapture() {
2003/// int a[10];
2004/// auto Lam1 = [a]() {
2005/// return;
2006/// };
2007/// }
2008/// \endcode
2009/// arrayInitLoopExpr() matches the implicit loop that initializes each element of
2010/// the implicit array field inside the lambda object, that represents the array `a`
2011/// captured by value.
2012extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitLoopExpr>
2014
2015/// The arrayInitIndexExpr consists of two subexpressions: a common expression
2016/// (the source array) that is evaluated once up-front, and a per-element initializer
2017/// that runs once for each array element. Within the per-element initializer,
2018/// the current index may be obtained via an ArrayInitIndexExpr.
2019///
2020/// Given
2021/// \code
2022/// void testStructBinding() {
2023/// int a[2] = {1, 2};
2024/// auto [x, y] = a;
2025/// }
2026/// \endcode
2027/// arrayInitIndexExpr() matches the array index that implicitly iterates
2028/// over the array `a` to copy each element to the anonymous array
2029/// that backs the structured binding `[x, y]` elements of which are
2030/// referred to by their aliases `x` and `y`.
2031extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitIndexExpr>
2033
2034/// Matches array subscript expressions.
2035///
2036/// Given
2037/// \code
2038/// int i = a[1];
2039/// \endcode
2040/// arraySubscriptExpr()
2041/// matches "a[1]"
2042extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
2044
2045/// Matches the value of a default argument at the call site.
2046///
2047/// Example matches the CXXDefaultArgExpr placeholder inserted for the
2048/// default value of the second parameter in the call expression f(42)
2049/// (matcher = cxxDefaultArgExpr())
2050/// \code
2051/// void f(int x, int y = 0);
2052/// f(42);
2053/// \endcode
2054extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
2056
2057/// Matches overloaded operator calls.
2058///
2059/// Note that if an operator isn't overloaded, it won't match. Instead, use
2060/// binaryOperator matcher.
2061/// Currently it does not match operators such as new delete.
2062/// FIXME: figure out why these do not match?
2063///
2064/// Example matches both operator<<((o << b), c) and operator<<(o, b)
2065/// (matcher = cxxOperatorCallExpr())
2066/// \code
2067/// ostream &operator<< (ostream &out, int i) { };
2068/// ostream &o; int b = 1, c = 1;
2069/// o << b << c;
2070/// \endcode
2071/// See also the binaryOperation() matcher for more-general matching of binary
2072/// uses of this AST node.
2073extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2075
2076/// Matches C++17 fold expressions.
2077///
2078/// Example matches `(0 + ... + args)`:
2079/// \code
2080/// template <typename... Args>
2081/// auto sum(Args... args) {
2082/// return (0 + ... + args);
2083/// }
2084/// \endcode
2085extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFoldExpr>
2087
2088/// Matches rewritten binary operators
2089///
2090/// Example matches use of "<":
2091/// \code
2092/// #include <compare>
2093/// struct HasSpaceshipMem {
2094/// int a;
2095/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2096/// };
2097/// void compare() {
2098/// HasSpaceshipMem hs1, hs2;
2099/// if (hs1 < hs2)
2100/// return;
2101/// }
2102/// \endcode
2103/// See also the binaryOperation() matcher for more-general matching
2104/// of this AST node.
2105extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2108
2109/// Matches expressions.
2110///
2111/// Example matches x()
2112/// \code
2113/// void f() { x(); }
2114/// \endcode
2115extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2116
2117/// Matches expressions that refer to declarations.
2118///
2119/// Example matches x in if (x)
2120/// \code
2121/// bool x;
2122/// if (x) {}
2123/// \endcode
2124extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2126
2127/// Matches expressions that refer to dependent scope declarations.
2128///
2129/// example matches T::v;
2130/// \code
2131/// template <class T> class X : T { void f() { T::v; } };
2132/// \endcode
2133extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2136
2137/// Matches a reference to an ObjCIvar.
2138///
2139/// Example: matches "a" in "init" method:
2140/// \code
2141/// @implementation A {
2142/// NSString *a;
2143/// }
2144/// - (void) init {
2145/// a = @"hello";
2146/// }
2147/// \endcode
2148extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2150
2151/// Matches a reference to a block.
2152///
2153/// Example: matches "^{}":
2154/// \code
2155/// void f() { ^{}(); }
2156/// \endcode
2157extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2158
2159/// Matches if statements.
2160///
2161/// Example matches 'if (x) {}'
2162/// \code
2163/// if (x) {}
2164/// \endcode
2165extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2166
2167/// Matches for statements.
2168///
2169/// Example matches 'for (;;) {}'
2170/// \code
2171/// for (;;) {}
2172/// int i[] = {1, 2, 3}; for (auto a : i);
2173/// \endcode
2174extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2175
2176/// Matches the increment statement of a for loop.
2177///
2178/// Example:
2179/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2180/// matches '++x' in
2181/// \code
2182/// for (x; x < N; ++x) { }
2183/// \endcode
2184AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2185 InnerMatcher) {
2186 const Stmt *const Increment = Node.getInc();
2187 return (Increment != nullptr &&
2188 InnerMatcher.matches(*Increment, Finder, Builder));
2189}
2190
2191/// Matches the initialization statement of a for loop.
2192///
2193/// Example:
2194/// forStmt(hasLoopInit(declStmt()))
2195/// matches 'int x = 0' in
2196/// \code
2197/// for (int x = 0; x < N; ++x) { }
2198/// \endcode
2199AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2200 InnerMatcher) {
2201 const Stmt *const Init = Node.getInit();
2202 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2203}
2204
2205/// Matches range-based for statements.
2206///
2207/// cxxForRangeStmt() matches 'for (auto a : i)'
2208/// \code
2209/// int i[] = {1, 2, 3}; for (auto a : i);
2210/// for(int j = 0; j < 5; ++j);
2211/// \endcode
2212extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2214
2215/// Matches the initialization statement of a for loop.
2216///
2217/// Example:
2218/// forStmt(hasLoopVariable(anything()))
2219/// matches 'int x' in
2220/// \code
2221/// for (int x : a) { }
2222/// \endcode
2223AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2224 InnerMatcher) {
2225 const VarDecl *const Var = Node.getLoopVariable();
2226 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2227}
2228
2229/// Matches the range initialization statement of a for loop.
2230///
2231/// Example:
2232/// forStmt(hasRangeInit(anything()))
2233/// matches 'a' in
2234/// \code
2235/// for (int x : a) { }
2236/// \endcode
2237AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2238 InnerMatcher) {
2239 const Expr *const Init = Node.getRangeInit();
2240 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2241}
2242
2243/// Matches while statements.
2244///
2245/// Given
2246/// \code
2247/// while (true) {}
2248/// \endcode
2249/// whileStmt()
2250/// matches 'while (true) {}'.
2251extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2252
2253/// Matches do statements.
2254///
2255/// Given
2256/// \code
2257/// do {} while (true);
2258/// \endcode
2259/// doStmt()
2260/// matches 'do {} while(true)'
2261extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2262
2263/// Matches break statements.
2264///
2265/// Given
2266/// \code
2267/// while (true) { break; }
2268/// \endcode
2269/// breakStmt()
2270/// matches 'break'
2271extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2272
2273/// Matches continue statements.
2274///
2275/// Given
2276/// \code
2277/// while (true) { continue; }
2278/// \endcode
2279/// continueStmt()
2280/// matches 'continue'
2281extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2283
2284/// Matches co_return statements.
2285///
2286/// Given
2287/// \code
2288/// while (true) { co_return; }
2289/// \endcode
2290/// coreturnStmt()
2291/// matches 'co_return'
2292extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2294
2295/// Matches return statements.
2296///
2297/// Given
2298/// \code
2299/// return 1;
2300/// \endcode
2301/// returnStmt()
2302/// matches 'return 1'
2303extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2304
2305/// Matches goto statements.
2306///
2307/// Given
2308/// \code
2309/// goto FOO;
2310/// FOO: bar();
2311/// \endcode
2312/// gotoStmt()
2313/// matches 'goto FOO'
2314extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2315
2316/// Matches label statements.
2317///
2318/// Given
2319/// \code
2320/// goto FOO;
2321/// FOO: bar();
2322/// \endcode
2323/// labelStmt()
2324/// matches 'FOO:'
2325extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2326
2327/// Matches address of label statements (GNU extension).
2328///
2329/// Given
2330/// \code
2331/// FOO: bar();
2332/// void *ptr = &&FOO;
2333/// goto *bar;
2334/// \endcode
2335/// addrLabelExpr()
2336/// matches '&&FOO'
2337extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2339
2340/// Matches switch statements.
2341///
2342/// Given
2343/// \code
2344/// switch(a) { case 42: break; default: break; }
2345/// \endcode
2346/// switchStmt()
2347/// matches 'switch(a)'.
2348extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2349
2350/// Matches case and default statements inside switch statements.
2351///
2352/// Given
2353/// \code
2354/// switch(a) { case 42: break; default: break; }
2355/// \endcode
2356/// switchCase()
2357/// matches 'case 42:' and 'default:'.
2358extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2359
2360/// Matches case statements inside switch statements.
2361///
2362/// Given
2363/// \code
2364/// switch(a) { case 42: break; default: break; }
2365/// \endcode
2366/// caseStmt()
2367/// matches 'case 42:'.
2368extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2369
2370/// Matches default statements inside switch statements.
2371///
2372/// Given
2373/// \code
2374/// switch(a) { case 42: break; default: break; }
2375/// \endcode
2376/// defaultStmt()
2377/// matches 'default:'.
2378extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2380
2381/// Matches compound statements.
2382///
2383/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2384/// \code
2385/// for (;;) {{}}
2386/// \endcode
2387extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2389
2390/// Matches catch statements.
2391///
2392/// \code
2393/// try {} catch(int i) {}
2394/// \endcode
2395/// cxxCatchStmt()
2396/// matches 'catch(int i)'
2397extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2399
2400/// Matches try statements.
2401///
2402/// \code
2403/// try {} catch(int i) {}
2404/// \endcode
2405/// cxxTryStmt()
2406/// matches 'try {}'
2407extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2408
2409/// Matches throw expressions.
2410///
2411/// \code
2412/// try { throw 5; } catch(int i) {}
2413/// \endcode
2414/// cxxThrowExpr()
2415/// matches 'throw 5'
2416extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2418
2419/// Matches null statements.
2420///
2421/// \code
2422/// foo();;
2423/// \endcode
2424/// nullStmt()
2425/// matches the second ';'
2426extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2427
2428/// Matches asm statements.
2429///
2430/// \code
2431/// int i = 100;
2432/// __asm("mov al, 2");
2433/// \endcode
2434/// asmStmt()
2435/// matches '__asm("mov al, 2")'
2436extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2437
2438/// Matches bool literals.
2439///
2440/// Example matches true
2441/// \code
2442/// true
2443/// \endcode
2444extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2446
2447/// Matches string literals (also matches wide string literals).
2448///
2449/// Example matches "abcd", L"abcd"
2450/// \code
2451/// char *s = "abcd";
2452/// wchar_t *ws = L"abcd";
2453/// \endcode
2454extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2456
2457/// Matches character literals (also matches wchar_t).
2458///
2459/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2460/// though.
2461///
2462/// Example matches 'a', L'a'
2463/// \code
2464/// char ch = 'a';
2465/// wchar_t chw = L'a';
2466/// \endcode
2467extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2469
2470/// Matches integer literals of all sizes / encodings, e.g.
2471/// 1, 1L, 0x1 and 1U.
2472///
2473/// Does not match character-encoded integers such as L'a'.
2474extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2476
2477/// Matches float literals of all sizes / encodings, e.g.
2478/// 1.0, 1.0f, 1.0L and 1e10.
2479///
2480/// Does not match implicit conversions such as
2481/// \code
2482/// float a = 10;
2483/// \endcode
2484extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2486
2487/// Matches imaginary literals, which are based on integer and floating
2488/// point literals e.g.: 1i, 1.0i
2489extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2491
2492/// Matches fixed point literals
2493extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2495
2496/// Matches user defined literal operator call.
2497///
2498/// Example match: "foo"_suffix
2499extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2501
2502/// Matches compound (i.e. non-scalar) literals
2503///
2504/// Example match: {1}, (1, 2)
2505/// \code
2506/// int array[4] = {1};
2507/// vector int myvec = (vector int)(1, 2);
2508/// \endcode
2509extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2511
2512/// Matches co_await expressions.
2513///
2514/// Given
2515/// \code
2516/// co_await 1;
2517/// \endcode
2518/// coawaitExpr()
2519/// matches 'co_await 1'
2520extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2522/// Matches co_await expressions where the type of the promise is dependent
2523extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2525/// Matches co_yield expressions.
2526///
2527/// Given
2528/// \code
2529/// co_yield 1;
2530/// \endcode
2531/// coyieldExpr()
2532/// matches 'co_yield 1'
2533extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2535
2536/// Matches coroutine body statements.
2537///
2538/// coroutineBodyStmt() matches the coroutine below
2539/// \code
2540/// generator<int> gen() {
2541/// co_return;
2542/// }
2543/// \endcode
2544extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoroutineBodyStmt>
2546
2547/// Matches nullptr literal.
2548extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2550
2551/// Matches GNU __builtin_choose_expr.
2552extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2553 chooseExpr;
2554
2555/// Matches builtin function __builtin_convertvector.
2556extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConvertVectorExpr>
2558
2559/// Matches GNU __null expression.
2560extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2562
2563/// Matches C11 _Generic expression.
2564extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2566
2567/// Matches atomic builtins.
2568/// Example matches __atomic_load_n(ptr, 1)
2569/// \code
2570/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2571/// \endcode
2572extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2573
2574/// Matches statement expression (GNU extension).
2575///
2576/// Example match: ({ int X = 4; X; })
2577/// \code
2578/// int C = ({ int X = 4; X; });
2579/// \endcode
2580extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2581
2582/// Matches binary operator expressions.
2583///
2584/// Example matches a || b
2585/// \code
2586/// !(a || b)
2587/// \endcode
2588/// See also the binaryOperation() matcher for more-general matching.
2589extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2591
2592/// Matches unary operator expressions.
2593///
2594/// Example matches !a
2595/// \code
2596/// !a || b
2597/// \endcode
2598extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2600
2601/// Matches conditional operator expressions.
2602///
2603/// Example matches a ? b : c
2604/// \code
2605/// (a ? b : c) + 42
2606/// \endcode
2607extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2609
2610/// Matches binary conditional operator expressions (GNU extension).
2611///
2612/// Example matches a ?: b
2613/// \code
2614/// (a ?: b) + 42;
2615/// \endcode
2616extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2619
2620/// Matches opaque value expressions. They are used as helpers
2621/// to reference another expressions and can be met
2622/// in BinaryConditionalOperators, for example.
2623///
2624/// Example matches 'a'
2625/// \code
2626/// (a ?: c) + 42;
2627/// \endcode
2628extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2630
2631/// Matches a C++ static_assert declaration.
2632///
2633/// Example:
2634/// staticAssertDecl()
2635/// matches
2636/// static_assert(sizeof(S) == sizeof(int))
2637/// in
2638/// \code
2639/// struct S {
2640/// int x;
2641/// };
2642/// static_assert(sizeof(S) == sizeof(int));
2643/// \endcode
2644extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2646
2647/// Matches a reinterpret_cast expression.
2648///
2649/// Either the source expression or the destination type can be matched
2650/// using has(), but hasDestinationType() is more specific and can be
2651/// more readable.
2652///
2653/// Example matches reinterpret_cast<char*>(&p) in
2654/// \code
2655/// void* p = reinterpret_cast<char*>(&p);
2656/// \endcode
2657extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2659
2660/// Matches a C++ static_cast expression.
2661///
2662/// \see hasDestinationType
2663/// \see reinterpretCast
2664///
2665/// Example:
2666/// cxxStaticCastExpr()
2667/// matches
2668/// static_cast<long>(8)
2669/// in
2670/// \code
2671/// long eight(static_cast<long>(8));
2672/// \endcode
2673extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2675
2676/// Matches a dynamic_cast expression.
2677///
2678/// Example:
2679/// cxxDynamicCastExpr()
2680/// matches
2681/// dynamic_cast<D*>(&b);
2682/// in
2683/// \code
2684/// struct B { virtual ~B() {} }; struct D : B {};
2685/// B b;
2686/// D* p = dynamic_cast<D*>(&b);
2687/// \endcode
2688extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2690
2691/// Matches a const_cast expression.
2692///
2693/// Example: Matches const_cast<int*>(&r) in
2694/// \code
2695/// int n = 42;
2696/// const int &r(n);
2697/// int* p = const_cast<int*>(&r);
2698/// \endcode
2699extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2701
2702/// Matches a C-style cast expression.
2703///
2704/// Example: Matches (int) 2.2f in
2705/// \code
2706/// int i = (int) 2.2f;
2707/// \endcode
2708extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2710
2711/// Matches explicit cast expressions.
2712///
2713/// Matches any cast expression written in user code, whether it be a
2714/// C-style cast, a functional-style cast, or a keyword cast.
2715///
2716/// Does not match implicit conversions.
2717///
2718/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2719/// Clang uses the term "cast" to apply to implicit conversions as well as to
2720/// actual cast expressions.
2721///
2722/// \see hasDestinationType.
2723///
2724/// Example: matches all five of the casts in
2725/// \code
2726/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2727/// \endcode
2728/// but does not match the implicit conversion in
2729/// \code
2730/// long ell = 42;
2731/// \endcode
2732extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2734
2735/// Matches the implicit cast nodes of Clang's AST.
2736///
2737/// This matches many different places, including function call return value
2738/// eliding, as well as any type conversions.
2739extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2741
2742/// Matches any cast nodes of Clang's AST.
2743///
2744/// Example: castExpr() matches each of the following:
2745/// \code
2746/// (int) 3;
2747/// const_cast<Expr *>(SubExpr);
2748/// char c = 0;
2749/// \endcode
2750/// but does not match
2751/// \code
2752/// int i = (0);
2753/// int k = 0;
2754/// \endcode
2755extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2756
2757/// Matches functional cast expressions
2758///
2759/// Example: Matches Foo(bar);
2760/// \code
2761/// Foo f = bar;
2762/// Foo g = (Foo) bar;
2763/// Foo h = Foo(bar);
2764/// \endcode
2765extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2767
2768/// Matches functional cast expressions having N != 1 arguments
2769///
2770/// Example: Matches Foo(bar, bar)
2771/// \code
2772/// Foo h = Foo(bar, bar);
2773/// \endcode
2774extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2776
2777/// Matches predefined identifier expressions [C99 6.4.2.2].
2778///
2779/// Example: Matches __func__
2780/// \code
2781/// printf("%s", __func__);
2782/// \endcode
2783extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2785
2786/// Matches C99 designated initializer expressions [C99 6.7.8].
2787///
2788/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2789/// \code
2790/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2791/// \endcode
2792extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2794
2795/// Matches designated initializer expressions that contain
2796/// a specific number of designators.
2797///
2798/// Example: Given
2799/// \code
2800/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2801/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2802/// \endcode
2803/// designatorCountIs(2)
2804/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2805/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2806AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2807 return Node.size() == N;
2808}
2809
2810/// Matches \c QualTypes in the clang AST.
2811extern const internal::VariadicAllOfMatcher<QualType> qualType;
2812
2813/// Matches \c Types in the clang AST.
2814extern const internal::VariadicAllOfMatcher<Type> type;
2815
2816/// Matches \c TypeLocs in the clang AST.
2817extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2818
2819/// Matches if any of the given matchers matches.
2820///
2821/// Unlike \c anyOf, \c eachOf will generate a match result for each
2822/// matching submatcher.
2823///
2824/// For example, in:
2825/// \code
2826/// class A { int a; int b; };
2827/// \endcode
2828/// The matcher:
2829/// \code
2830/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2831/// has(fieldDecl(hasName("b")).bind("v"))))
2832/// \endcode
2833/// will generate two results binding "v", the first of which binds
2834/// the field declaration of \c a, the second the field declaration of
2835/// \c b.
2836///
2837/// Usable as: Any Matcher
2838extern const internal::VariadicOperatorMatcherFunc<
2839 2, std::numeric_limits<unsigned>::max()>
2840 eachOf;
2841
2842/// Matches if any of the given matchers matches.
2843///
2844/// Usable as: Any Matcher
2845extern const internal::VariadicOperatorMatcherFunc<
2846 2, std::numeric_limits<unsigned>::max()>
2847 anyOf;
2848
2849/// Matches if all given matchers match.
2850///
2851/// Usable as: Any Matcher
2852extern const internal::VariadicOperatorMatcherFunc<
2853 2, std::numeric_limits<unsigned>::max()>
2854 allOf;
2855
2856/// Matches any node regardless of the submatcher.
2857///
2858/// However, \c optionally will retain any bindings generated by the submatcher.
2859/// Useful when additional information which may or may not present about a main
2860/// matching node is desired.
2861///
2862/// For example, in:
2863/// \code
2864/// class Foo {
2865/// int bar;
2866/// }
2867/// \endcode
2868/// The matcher:
2869/// \code
2870/// cxxRecordDecl(
2871/// optionally(has(
2872/// fieldDecl(hasName("bar")).bind("var")
2873/// ))).bind("record")
2874/// \endcode
2875/// will produce a result binding for both "record" and "var".
2876/// The matcher will produce a "record" binding for even if there is no data
2877/// member named "bar" in that class.
2878///
2879/// Usable as: Any Matcher
2880extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2881
2882/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2883///
2884/// Given
2885/// \code
2886/// Foo x = bar;
2887/// int y = sizeof(x) + alignof(x);
2888/// \endcode
2889/// unaryExprOrTypeTraitExpr()
2890/// matches \c sizeof(x) and \c alignof(x)
2891extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2894
2895/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2896///
2897/// Given
2898/// \code
2899/// if (true);
2900/// for (; true; );
2901/// \endcode
2902/// with the matcher
2903/// \code
2904/// mapAnyOf(ifStmt, forStmt).with(
2905/// hasCondition(cxxBoolLiteralExpr(equals(true)))
2906/// ).bind("trueCond")
2907/// \endcode
2908/// matches the \c if and the \c for. It is equivalent to:
2909/// \code
2910/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2911/// anyOf(
2912/// ifStmt(trueCond).bind("trueCond"),
2913/// forStmt(trueCond).bind("trueCond")
2914/// );
2915/// \endcode
2916///
2917/// The with() chain-call accepts zero or more matchers which are combined
2918/// as-if with allOf() in each of the node matchers.
2919/// Usable as: Any Matcher
2920template <typename T, typename... U>
2921auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2922 return internal::MapAnyOfHelper<U...>();
2923}
2924
2925/// Matches nodes which can be used with binary operators.
2926///
2927/// The code
2928/// \code
2929/// var1 != var2;
2930/// \endcode
2931/// might be represented in the clang AST as a binaryOperator, a
2932/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2933///
2934/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2935/// least one is a class type (cxxOperatorCallExpr)
2936/// * whether the code appears in a template declaration, if at least one of the
2937/// vars is a dependent-type (binaryOperator)
2938/// * whether the code relies on a rewritten binary operator, such as a
2939/// spaceship operator or an inverted equality operator
2940/// (cxxRewrittenBinaryOperator)
2941///
2942/// This matcher elides details in places where the matchers for the nodes are
2943/// compatible.
2944///
2945/// Given
2946/// \code
2947/// binaryOperation(
2948/// hasOperatorName("!="),
2949/// hasLHS(expr().bind("lhs")),
2950/// hasRHS(expr().bind("rhs"))
2951/// )
2952/// \endcode
2953/// matches each use of "!=" in:
2954/// \code
2955/// struct S{
2956/// bool operator!=(const S&) const;
2957/// };
2958///
2959/// void foo()
2960/// {
2961/// 1 != 2;
2962/// S() != S();
2963/// }
2964///
2965/// template<typename T>
2966/// void templ()
2967/// {
2968/// 1 != 2;
2969/// T() != S();
2970/// }
2971/// struct HasOpEq
2972/// {
2973/// bool operator==(const HasOpEq &) const;
2974/// };
2975///
2976/// void inverse()
2977/// {
2978/// HasOpEq s1;
2979/// HasOpEq s2;
2980/// if (s1 != s2)
2981/// return;
2982/// }
2983///
2984/// struct HasSpaceship
2985/// {
2986/// bool operator<=>(const HasOpEq &) const;
2987/// };
2988///
2989/// void use_spaceship()
2990/// {
2991/// HasSpaceship s1;
2992/// HasSpaceship s2;
2993/// if (s1 != s2)
2994/// return;
2995/// }
2996/// \endcode
2997extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
3000
3001/// Matches function calls and constructor calls
3002///
3003/// Because CallExpr and CXXConstructExpr do not share a common
3004/// base class with API accessing arguments etc, AST Matchers for code
3005/// which should match both are typically duplicated. This matcher
3006/// removes the need for duplication.
3007///
3008/// Given code
3009/// \code
3010/// struct ConstructorTakesInt
3011/// {
3012/// ConstructorTakesInt(int i) {}
3013/// };
3014///
3015/// void callTakesInt(int i)
3016/// {
3017/// }
3018///
3019/// void doCall()
3020/// {
3021/// callTakesInt(42);
3022/// }
3023///
3024/// void doConstruct()
3025/// {
3026/// ConstructorTakesInt cti(42);
3027/// }
3028/// \endcode
3029///
3030/// The matcher
3031/// \code
3032/// invocation(hasArgument(0, integerLiteral(equals(42))))
3033/// \endcode
3034/// matches the expression in both doCall and doConstruct
3035extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
3036
3037/// Matches unary expressions that have a specific type of argument.
3038///
3039/// Given
3040/// \code
3041/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
3042/// \endcode
3043/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
3044/// matches \c sizeof(a) and \c alignof(c)
3046 internal::Matcher<QualType>, InnerMatcher) {
3047 const QualType ArgumentType = Node.getTypeOfArgument();
3048 return InnerMatcher.matches(ArgumentType, Finder, Builder);
3049}
3050
3051/// Matches unary expressions of a certain kind.
3052///
3053/// Given
3054/// \code
3055/// int x;
3056/// int s = sizeof(x) + alignof(x)
3057/// \endcode
3058/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
3059/// matches \c sizeof(x)
3060///
3061/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
3062/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
3064 return Node.getKind() == Kind;
3065}
3066
3067/// Same as unaryExprOrTypeTraitExpr, but only matching
3068/// alignof.
3069inline internal::BindableMatcher<Stmt> alignOfExpr(
3070 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3072 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
3073 InnerMatcher)));
3074}
3075
3076/// Same as unaryExprOrTypeTraitExpr, but only matching
3077/// sizeof.
3078inline internal::BindableMatcher<Stmt> sizeOfExpr(
3079 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3081 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
3082}
3083
3084/// Matches NamedDecl nodes that have the specified name.
3085///
3086/// Supports specifying enclosing namespaces or classes by prefixing the name
3087/// with '<enclosing>::'.
3088/// Does not match typedefs of an underlying type with the given name.
3089///
3090/// Example matches X (Name == "X")
3091/// \code
3092/// class X;
3093/// \endcode
3094///
3095/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
3096/// \code
3097/// namespace a { namespace b { class X; } }
3098/// \endcode
3099inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3100 return internal::Matcher<NamedDecl>(
3101 new internal::HasNameMatcher({std::string(Name)}));
3102}
3103
3104/// Matches NamedDecl nodes that have any of the specified names.
3105///
3106/// This matcher is only provided as a performance optimization of hasName.
3107/// \code
3108/// hasAnyName(a, b, c)
3109/// \endcode
3110/// is equivalent to, but faster than
3111/// \code
3112/// anyOf(hasName(a), hasName(b), hasName(c))
3113/// \endcode
3114extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3116 hasAnyName;
3117
3118/// Matches NamedDecl nodes whose fully qualified names contain
3119/// a substring matched by the given RegExp.
3120///
3121/// Supports specifying enclosing namespaces or classes by
3122/// prefixing the name with '<enclosing>::'. Does not match typedefs
3123/// of an underlying type with the given name.
3124///
3125/// Example matches X (regexp == "::X")
3126/// \code
3127/// class X;
3128/// \endcode
3129///
3130/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3131/// \code
3132/// namespace foo { namespace bar { class X; } }
3133/// \endcode
3134AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3135 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3136 return RegExp->match(FullNameString);
3137}
3138
3139/// Matches overloaded operator names.
3140///
3141/// Matches overloaded operator names specified in strings without the
3142/// "operator" prefix: e.g. "<<".
3143///
3144/// Given:
3145/// \code
3146/// class A { int operator*(); };
3147/// const A &operator<<(const A &a, const A &b);
3148/// A a;
3149/// a << a; // <-- This matches
3150/// \endcode
3151///
3152/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3153/// specified line and
3154/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3155/// matches the declaration of \c A.
3156///
3157/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3158inline internal::PolymorphicMatcher<
3159 internal::HasOverloadedOperatorNameMatcher,
3161 std::vector<std::string>>
3163 return internal::PolymorphicMatcher<
3164 internal::HasOverloadedOperatorNameMatcher,
3166 std::vector<std::string>>({std::string(Name)});
3167}
3168
3169/// Matches overloaded operator names.
3170///
3171/// Matches overloaded operator names specified in strings without the
3172/// "operator" prefix: e.g. "<<".
3173///
3174/// hasAnyOverloadedOperatorName("+", "-")
3175/// Is equivalent to
3176/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3177extern const internal::VariadicFunction<
3178 internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3181 std::vector<std::string>>,
3184
3185/// Matches template-dependent, but known, member names.
3186///
3187/// In template declarations, dependent members are not resolved and so can
3188/// not be matched to particular named declarations.
3189///
3190/// This matcher allows to match on the known name of members.
3191///
3192/// Given
3193/// \code
3194/// template <typename T>
3195/// struct S {
3196/// void mem();
3197/// };
3198/// template <typename T>
3199/// void x() {
3200/// S<T> s;
3201/// s.mem();
3202/// }
3203/// \endcode
3204/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3205AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3206 return Node.getMember().getAsString() == N;
3207}
3208
3209/// Matches template-dependent, but known, member names against an already-bound
3210/// node
3211///
3212/// In template declarations, dependent members are not resolved and so can
3213/// not be matched to particular named declarations.
3214///
3215/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3216/// and CXXMethodDecl nodes.
3217///
3218/// Given
3219/// \code
3220/// template <typename T>
3221/// struct S {
3222/// void mem();
3223/// };
3224/// template <typename T>
3225/// void x() {
3226/// S<T> s;
3227/// s.mem();
3228/// }
3229/// \endcode
3230/// The matcher
3231/// @code
3232/// \c cxxDependentScopeMemberExpr(
3233/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3234/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3235/// cxxMethodDecl(hasName("mem")).bind("templMem")
3236/// )))))
3237/// )))),
3238/// memberHasSameNameAsBoundNode("templMem")
3239/// )
3240/// @endcode
3241/// first matches and binds the @c mem member of the @c S template, then
3242/// compares its name to the usage in @c s.mem() in the @c x function template
3243AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3244 std::string, BindingID) {
3245 auto MemberName = Node.getMember().getAsString();
3246
3247 return Builder->removeBindings(
3248 [this, MemberName](const BoundNodesMap &Nodes) {
3249 const DynTypedNode &BN = Nodes.getNode(this->BindingID);
3250 if (const auto *ND = BN.get<NamedDecl>()) {
3251 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3252 return true;
3253 return ND->getName() != MemberName;
3254 }
3255 return true;
3256 });
3257}
3258
3259/// Matches the dependent name of a DependentScopeDeclRefExpr or
3260/// DependentNameType
3261///
3262/// Given:
3263/// \code
3264/// template <class T> class X : T { void f() { T::v; } };
3265/// \endcode
3266/// \c dependentScopeDeclRefExpr(hasDependentName("v")) matches `T::v`
3267///
3268/// Given:
3269/// \code
3270/// template <typename T> struct declToImport {
3271/// typedef typename T::type dependent_name;
3272/// };
3273/// \endcode
3274/// \c dependentNameType(hasDependentName("type")) matches `T::type`
3278 std::string, N) {
3279 return internal::getDependentName(Node) == N;
3280}
3281
3282/// Matches C++ classes that are directly or indirectly derived from a class
3283/// matching \c Base, or Objective-C classes that directly or indirectly
3284/// subclass a class matching \c Base.
3285///
3286/// Note that a class is not considered to be derived from itself.
3287///
3288/// Example matches Y, Z, C (Base == hasName("X"))
3289/// \code
3290/// class X;
3291/// class Y : public X {}; // directly derived
3292/// class Z : public Y {}; // indirectly derived
3293/// typedef X A;
3294/// typedef A B;
3295/// class C : public B {}; // derived from a typedef of X
3296/// \endcode
3297///
3298/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3299/// \code
3300/// class Foo;
3301/// typedef Foo X;
3302/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3303/// \endcode
3304///
3305/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3306/// \code
3307/// @interface NSObject @end
3308/// @interface Bar : NSObject @end
3309/// \endcode
3310///
3311/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3313 isDerivedFrom,
3315 internal::Matcher<NamedDecl>, Base) {
3316 // Check if the node is a C++ struct/union/class.
3317 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3318 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3319
3320 // The node must be an Objective-C class.
3321 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3322 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3323 /*Directly=*/false);
3324}
3325
3326/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3328 isDerivedFrom,
3330 std::string, BaseName, 1) {
3331 if (BaseName.empty())
3332 return false;
3333
3334 const auto M = isDerivedFrom(hasName(BaseName));
3335
3336 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3337 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3338
3339 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3340 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3341}
3342
3343/// Matches C++ classes that have a direct or indirect base matching \p
3344/// BaseSpecMatcher.
3345///
3346/// Example:
3347/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3348/// \code
3349/// class Foo;
3350/// class Bar : Foo {};
3351/// class Baz : Bar {};
3352/// class SpecialBase;
3353/// class Proxy : SpecialBase {}; // matches Proxy
3354/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3355/// \endcode
3356///
3357// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3358AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3359 BaseSpecMatcher) {
3360 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3361}
3362
3363/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3364///
3365/// Example:
3366/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3367/// \code
3368/// class Foo;
3369/// class Bar : Foo {};
3370/// class Baz : Bar {};
3371/// class SpecialBase;
3372/// class Proxy : SpecialBase {}; // matches Proxy
3373/// class IndirectlyDerived : Proxy {}; // doesn't match
3374/// \endcode
3375AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3376 BaseSpecMatcher) {
3377 return Node.hasDefinition() &&
3378 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3379 return BaseSpecMatcher.matches(Base, Finder, Builder);
3380 });
3381}
3382
3383/// Similar to \c isDerivedFrom(), but also matches classes that directly
3384/// match \c Base.
3386 isSameOrDerivedFrom,
3388 internal::Matcher<NamedDecl>, Base, 0) {
3389 const auto M = anyOf(Base, isDerivedFrom(Base));
3390
3391 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3392 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3393
3394 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3395 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3396}
3397
3398/// Overloaded method as shortcut for
3399/// \c isSameOrDerivedFrom(hasName(...)).
3401 isSameOrDerivedFrom,
3403 std::string, BaseName, 1) {
3404 if (BaseName.empty())
3405 return false;
3406
3407 const auto M = isSameOrDerivedFrom(hasName(BaseName));
3408
3409 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3410 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3411
3412 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3413 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3414}
3415
3416/// Matches C++ or Objective-C classes that are directly derived from a class
3417/// matching \c Base.
3418///
3419/// Note that a class is not considered to be derived from itself.
3420///
3421/// Example matches Y, C (Base == hasName("X"))
3422/// \code
3423/// class X;
3424/// class Y : public X {}; // directly derived
3425/// class Z : public Y {}; // indirectly derived
3426/// typedef X A;
3427/// typedef A B;
3428/// class C : public B {}; // derived from a typedef of X
3429/// \endcode
3430///
3431/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3432/// \code
3433/// class Foo;
3434/// typedef Foo X;
3435/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3436/// \endcode
3438 isDirectlyDerivedFrom,
3440 internal::Matcher<NamedDecl>, Base, 0) {
3441 // Check if the node is a C++ struct/union/class.
3442 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3443 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3444
3445 // The node must be an Objective-C class.
3446 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3447 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3448 /*Directly=*/true);
3449}
3450
3451/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3453 isDirectlyDerivedFrom,
3455 std::string, BaseName, 1) {
3456 if (BaseName.empty())
3457 return false;
3458 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3459
3460 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3461 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3462
3463 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3464 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3465}
3466/// Matches the first method of a class or struct that satisfies \c
3467/// InnerMatcher.
3468///
3469/// Given:
3470/// \code
3471/// class A { void func(); };
3472/// class B { void member(); };
3473/// \endcode
3474///
3475/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3476/// \c A but not \c B.
3477AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3478 InnerMatcher) {
3479 BoundNodesTreeBuilder Result(*Builder);
3480 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3481 Node.method_end(), Finder, &Result);
3482 if (MatchIt == Node.method_end())
3483 return false;
3484
3485 if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3486 return false;
3487 *Builder = std::move(Result);
3488 return true;
3489}
3490
3491/// Matches the generated class of lambda expressions.
3492///
3493/// Given:
3494/// \code
3495/// auto x = []{};
3496/// \endcode
3497///
3498/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3499/// \c decltype(x)
3501 return Node.isLambda();
3502}
3503
3504/// Matches AST nodes that have child AST nodes that match the
3505/// provided matcher.
3506///
3507/// Example matches X, Y
3508/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3509/// \code
3510/// class X {}; // Matches X, because X::X is a class of name X inside X.
3511/// class Y { class X {}; };
3512/// class Z { class Y { class X {}; }; }; // Does not match Z.
3513/// \endcode
3514///
3515/// ChildT must be an AST base type.
3516///
3517/// Usable as: Any Matcher
3518/// Note that has is direct matcher, so it also matches things like implicit
3519/// casts and paren casts. If you are matching with expr then you should
3520/// probably consider using ignoringParenImpCasts like:
3521/// has(ignoringParenImpCasts(expr())).
3522extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3523
3524/// Matches AST nodes that have descendant AST nodes that match the
3525/// provided matcher.
3526///
3527/// Example matches X, Y, Z
3528/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3529/// \code
3530/// class X {}; // Matches X, because X::X is a class of name X inside X.
3531/// class Y { class X {}; };
3532/// class Z { class Y { class X {}; }; };
3533/// \endcode
3534///
3535/// DescendantT must be an AST base type.
3536///
3537/// Usable as: Any Matcher
3538extern const internal::ArgumentAdaptingMatcherFunc<
3539 internal::HasDescendantMatcher>
3541
3542/// Matches AST nodes that have child AST nodes that match the
3543/// provided matcher.
3544///
3545/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3546/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3547/// \code
3548/// class X {};
3549/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3550/// // inside Y.
3551/// class Z { class Y { class X {}; }; }; // Does not match Z.
3552/// \endcode
3553///
3554/// ChildT must be an AST base type.
3555///
3556/// As opposed to 'has', 'forEach' will cause a match for each result that
3557/// matches instead of only on the first one.
3558///
3559/// Usable as: Any Matcher
3560extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3561 forEach;
3562
3563/// Matches AST nodes that have descendant AST nodes that match the
3564/// provided matcher.
3565///
3566/// Example matches X, A, A::X, B, B::C, B::C::X
3567/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3568/// \code
3569/// class X {};
3570/// class A { class X {}; }; // Matches A, because A::X is a class of name
3571/// // X inside A.
3572/// class B { class C { class X {}; }; };
3573/// \endcode
3574///
3575/// DescendantT must be an AST base type.
3576///
3577/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3578/// each result that matches instead of only on the first one.
3579///
3580/// Note: Recursively combined ForEachDescendant can cause many matches:
3581/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3582/// forEachDescendant(cxxRecordDecl())
3583/// )))
3584/// will match 10 times (plus injected class name matches) on:
3585/// \code
3586/// class A { class B { class C { class D { class E {}; }; }; }; };
3587/// \endcode
3588///
3589/// Usable as: Any Matcher
3590extern const internal::ArgumentAdaptingMatcherFunc<
3591 internal::ForEachDescendantMatcher>
3593
3594/// Matches if the node or any descendant matches.
3595///
3596/// Generates results for each match.
3597///
3598/// For example, in:
3599/// \code
3600/// class A { class B {}; class C {}; };
3601/// \endcode
3602/// The matcher:
3603/// \code
3604/// cxxRecordDecl(hasName("::A"),
3605/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3606/// \endcode
3607/// will generate results for \c A, \c B and \c C.
3608///
3609/// Usable as: Any Matcher
3610template <typename T>
3611internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3612 return eachOf(Matcher, forEachDescendant(Matcher));
3613}
3614
3615/// Matches AST nodes that have a parent that matches the provided
3616/// matcher.
3617///
3618/// Given
3619/// \code
3620/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3621/// \endcode
3622/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3623///
3624/// Usable as: Any Matcher
3625extern const internal::ArgumentAdaptingMatcherFunc<
3626 internal::HasParentMatcher,
3627 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3628 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3629 hasParent;
3630
3631/// Matches AST nodes that have an ancestor that matches the provided
3632/// matcher.
3633///
3634/// Given
3635/// \code
3636/// void f() { if (true) { int x = 42; } }
3637/// void g() { for (;;) { int x = 43; } }
3638/// \endcode
3639/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3640///
3641/// Usable as: Any Matcher
3642extern const internal::ArgumentAdaptingMatcherFunc<
3643 internal::HasAncestorMatcher,
3644 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3645 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3647
3648/// Matches if the provided matcher does not match.
3649///
3650/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3651/// \code
3652/// class X {};
3653/// class Y {};
3654/// \endcode
3655///
3656/// Usable as: Any Matcher
3657extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3658
3659/// Matches a node if the declaration associated with that node
3660/// matches the given matcher.
3661///
3662/// The associated declaration is:
3663/// - for type nodes, the declaration of the underlying type
3664/// - for CallExpr, the declaration of the callee
3665/// - for MemberExpr, the declaration of the referenced member
3666/// - for CXXConstructExpr, the declaration of the constructor
3667/// - for CXXNewExpr, the declaration of the operator new
3668/// - for ObjCIvarExpr, the declaration of the ivar
3669///
3670/// For type nodes, hasDeclaration will generally match the declaration of the
3671/// sugared type. Given
3672/// \code
3673/// class X {};
3674/// typedef X Y;
3675/// Y y;
3676/// \endcode
3677/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3678/// typedefDecl. A common use case is to match the underlying, desugared type.
3679/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3680/// \code
3681/// varDecl(hasType(hasUnqualifiedDesugaredType(
3682/// recordType(hasDeclaration(decl())))))
3683/// \endcode
3684/// In this matcher, the decl will match the CXXRecordDecl of class X.
3685///
3686/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3687/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3688/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3689/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3690/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3691/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3692/// Matcher<UnresolvedUsingType>
3693inline internal::PolymorphicMatcher<
3694 internal::HasDeclarationMatcher,
3695 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3696hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3697 return internal::PolymorphicMatcher<
3698 internal::HasDeclarationMatcher,
3699 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3700 InnerMatcher);
3701}
3702
3703/// Matches a \c NamedDecl whose underlying declaration matches the given
3704/// matcher.
3705///
3706/// Given
3707/// \code
3708/// namespace N { template<class T> void f(T t); }
3709/// template <class T> void g() { using N::f; f(T()); }
3710/// \endcode
3711/// \c unresolvedLookupExpr(hasAnyDeclaration(
3712/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3713/// matches the use of \c f in \c g() .
3714AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3715 InnerMatcher) {
3716 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3717
3718 return UnderlyingDecl != nullptr &&
3719 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3720}
3721
3722/// Matches on the implicit object argument of a member call expression, after
3723/// stripping off any parentheses or implicit casts.
3724///
3725/// Given
3726/// \code
3727/// class Y { public: void m(); };
3728/// Y g();
3729/// class X : public Y {};
3730/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3731/// \endcode
3732/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3733/// matches `y.m()` and `(g()).m()`.
3734/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3735/// matches `x.m()`.
3736/// cxxMemberCallExpr(on(callExpr()))
3737/// matches `(g()).m()`.
3738///
3739/// FIXME: Overload to allow directly matching types?
3740AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3741 InnerMatcher) {
3742 const Expr *ExprNode = Node.getImplicitObjectArgument()
3743 ->IgnoreParenImpCasts();
3744 return (ExprNode != nullptr &&
3745 InnerMatcher.matches(*ExprNode, Finder, Builder));
3746}
3747
3748
3749/// Matches on the receiver of an ObjectiveC Message expression.
3750///
3751/// Example
3752/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3753/// matches the [webView ...] message invocation.
3754/// \code
3755/// NSString *webViewJavaScript = ...
3756/// UIWebView *webView = ...
3757/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3758/// \endcode
3759AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3760 InnerMatcher) {
3761 const QualType TypeDecl = Node.getReceiverType();
3762 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3763}
3764
3765/// Returns true when the Objective-C method declaration is a class method.
3766///
3767/// Example
3768/// matcher = objcMethodDecl(isClassMethod())
3769/// matches
3770/// \code
3771/// @interface I + (void)foo; @end
3772/// \endcode
3773/// but not
3774/// \code
3775/// @interface I - (void)bar; @end
3776/// \endcode
3778 return Node.isClassMethod();
3779}
3780
3781/// Returns true when the Objective-C method declaration is an instance method.
3782///
3783/// Example
3784/// matcher = objcMethodDecl(isInstanceMethod())
3785/// matches
3786/// \code
3787/// @interface I - (void)bar; @end
3788/// \endcode
3789/// but not
3790/// \code
3791/// @interface I + (void)foo; @end
3792/// \endcode
3794 return Node.isInstanceMethod();
3795}
3796
3797/// Returns true when the Objective-C message is sent to a class.
3798///
3799/// Example
3800/// matcher = objcMessageExpr(isClassMessage())
3801/// matches
3802/// \code
3803/// [NSString stringWithFormat:@"format"];
3804/// \endcode
3805/// but not
3806/// \code
3807/// NSString *x = @"hello";
3808/// [x containsString:@"h"];
3809/// \endcode
3811 return Node.isClassMessage();
3812}
3813
3814/// Returns true when the Objective-C message is sent to an instance.
3815///
3816/// Example
3817/// matcher = objcMessageExpr(isInstanceMessage())
3818/// matches
3819/// \code
3820/// NSString *x = @"hello";
3821/// [x containsString:@"h"];
3822/// \endcode
3823/// but not
3824/// \code
3825/// [NSString stringWithFormat:@"format"];
3826/// \endcode
3827AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3828 return Node.isInstanceMessage();
3829}
3830
3831/// Matches if the Objective-C message is sent to an instance,
3832/// and the inner matcher matches on that instance.
3833///
3834/// For example the method call in
3835/// \code
3836/// NSString *x = @"hello";
3837/// [x containsString:@"h"];
3838/// \endcode
3839/// is matched by
3840/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3841AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3842 InnerMatcher) {
3843 const Expr *ReceiverNode = Node.getInstanceReceiver();
3844 return (ReceiverNode != nullptr &&
3845 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3846 Builder));
3847}
3848
3849/// Matches when BaseName == Selector.getAsString()
3850///
3851/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3852/// matches the outer message expr in the code below, but NOT the message
3853/// invocation for self.bodyView.
3854/// \code
3855/// [self.bodyView loadHTMLString:html baseURL:NULL];
3856/// \endcode
3857AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3858 Selector Sel = Node.getSelector();
3859 return BaseName == Sel.getAsString();
3860}
3861
3862/// Matches when at least one of the supplied string equals to the
3863/// Selector.getAsString()
3864///
3865/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3866/// matches both of the expressions below:
3867/// \code
3868/// [myObj methodA:argA];
3869/// [myObj methodB:argB];
3870/// \endcode
3871extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3872 StringRef,
3875
3876/// Matches ObjC selectors whose name contains
3877/// a substring matched by the given RegExp.
3878/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3879/// matches the outer message expr in the code below, but NOT the message
3880/// invocation for self.bodyView.
3881/// \code
3882/// [self.bodyView loadHTMLString:html baseURL:NULL];
3883/// \endcode
3884AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3885 std::string SelectorString = Node.getSelector().getAsString();
3886 return RegExp->match(SelectorString);
3887}
3888
3889/// Matches when the selector is the empty selector
3890///
3891/// Matches only when the selector of the objCMessageExpr is NULL. This may
3892/// represent an error condition in the tree!
3893AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3894 return Node.getSelector().isNull();
3895}
3896
3897/// Matches when the selector is a Unary Selector
3898///
3899/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3900/// matches self.bodyView in the code below, but NOT the outer message
3901/// invocation of "loadHTMLString:baseURL:".
3902/// \code
3903/// [self.bodyView loadHTMLString:html baseURL:NULL];
3904/// \endcode
3905AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3906 return Node.getSelector().isUnarySelector();
3907}
3908
3909/// Matches when the selector is a keyword selector
3910///
3911/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3912/// message expression in
3913///
3914/// \code
3915/// UIWebView *webView = ...;
3916/// CGRect bodyFrame = webView.frame;
3917/// bodyFrame.size.height = self.bodyContentHeight;
3918/// webView.frame = bodyFrame;
3919/// // ^---- matches here
3920/// \endcode
3921AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3922 return Node.getSelector().isKeywordSelector();
3923}
3924
3925/// Matches when the selector has the specified number of arguments
3926///
3927/// matcher = objCMessageExpr(numSelectorArgs(0));
3928/// matches self.bodyView in the code below
3929///
3930/// matcher = objCMessageExpr(numSelectorArgs(2));
3931/// matches the invocation of "loadHTMLString:baseURL:" but not that
3932/// of self.bodyView
3933/// \code
3934/// [self.bodyView loadHTMLString:html baseURL:NULL];
3935/// \endcode
3936AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3937 return Node.getSelector().getNumArgs() == N;
3938}
3939
3940/// Matches if the call or fold expression's callee expression matches.
3941///
3942/// Given
3943/// \code
3944/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3945/// void f() { f(); }
3946/// \endcode
3947/// callExpr(callee(expr()))
3948/// matches this->x(), x(), y.x(), f()
3949/// with callee(...)
3950/// matching this->x, x, y.x, f respectively
3951///
3952/// Given
3953/// \code
3954/// template <typename... Args>
3955/// auto sum(Args... args) {
3956/// return (0 + ... + args);
3957/// }
3958///
3959/// template <typename... Args>
3960/// auto multiply(Args... args) {
3961/// return (args * ... * 1);
3962/// }
3963/// \endcode
3964/// cxxFoldExpr(callee(expr()))
3965/// matches (args * ... * 1)
3966/// with callee(...)
3967/// matching *
3968///
3969/// Note: Callee cannot take the more general internal::Matcher<Expr>
3970/// because this introduces ambiguous overloads with calls to Callee taking a
3971/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3972/// implemented in terms of implicit casts.
3975 CXXFoldExpr),
3976 internal::Matcher<Stmt>, InnerMatcher, 0) {
3977 const auto *ExprNode = Node.getCallee();
3978 return (ExprNode != nullptr &&
3979 InnerMatcher.matches(*ExprNode, Finder, Builder));
3980}
3981
3982/// Matches 1) if the call expression's callee's declaration matches the
3983/// given matcher; or 2) if the Obj-C message expression's callee's method
3984/// declaration matches the given matcher.
3985///
3986/// Example matches y.x() (matcher = callExpr(callee(
3987/// cxxMethodDecl(hasName("x")))))
3988/// \code
3989/// class Y { public: void x(); };
3990/// void z() { Y y; y.x(); }
3991/// \endcode
3992///
3993/// Example 2. Matches [I foo] with
3994/// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3995///
3996/// \code
3997/// @interface I: NSObject
3998/// +(void)foo;
3999/// @end
4000/// ...
4001/// [I foo]
4002/// \endcode
4005 internal::Matcher<Decl>, InnerMatcher, 1) {
4006 if (isa<CallExpr>(&Node))
4007 return callExpr(hasDeclaration(InnerMatcher))
4008 .matches(Node, Finder, Builder);
4009 else {
4010 // The dynamic cast below is guaranteed to succeed as there are only 2
4011 // supported return types.
4012 const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
4013 const Decl *DeclNode = MsgNode->getMethodDecl();
4014 return (DeclNode != nullptr &&
4015 InnerMatcher.matches(*DeclNode, Finder, Builder));
4016 }
4017}
4018
4019/// Matches if the expression's or declaration's type matches a type
4020/// matcher.
4021///
4022/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4023/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4024/// and U (matcher = typedefDecl(hasType(asString("int")))
4025/// and friend class X (matcher = friendDecl(hasType("X"))
4026/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4027/// asString("class X")))
4028/// \code
4029/// class X {};
4030/// void y(X &x) { x; X z; }
4031/// typedef int U;
4032/// class Y { friend class X; };
4033/// class Z : public virtual X {};
4034/// \endcode
4036 hasType,
4039 internal::Matcher<QualType>, InnerMatcher, 0) {
4040 QualType QT = internal::getUnderlyingType(Node);
4041 if (!QT.isNull())
4042 return InnerMatcher.matches(QT, Finder, Builder);
4043 return false;
4044}
4045
4046/// Overloaded to match the declaration of the expression's or value
4047/// declaration's type.
4048///
4049/// In case of a value declaration (for example a variable declaration),
4050/// this resolves one layer of indirection. For example, in the value
4051/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
4052/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
4053/// declaration of x.
4054///
4055/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4056/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4057/// and friend class X (matcher = friendDecl(hasType("X"))
4058/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4059/// cxxRecordDecl(hasName("X"))))
4060/// \code
4061/// class X {};
4062/// void y(X &x) { x; X z; }
4063/// class Y { friend class X; };
4064/// class Z : public virtual X {};
4065/// \endcode
4066///
4067/// Example matches class Derived
4068/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
4069/// \code
4070/// class Base {};
4071/// class Derived : Base {};
4072/// \endcode
4073///
4074/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
4075/// Matcher<CXXBaseSpecifier>
4077 hasType,
4080 internal::Matcher<Decl>, InnerMatcher, 1) {
4081 QualType QT = internal::getUnderlyingType(Node);
4082 if (!QT.isNull())
4083 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
4084 return false;
4085}
4086
4087/// Matches if the type location of a node matches the inner matcher.
4088///
4089/// Examples:
4090/// \code
4091/// int x;
4092/// \endcode
4093/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
4094/// matches int x
4095///
4096/// \code
4097/// auto x = int(3);
4098/// \endcode
4099/// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
4100/// matches int(3)
4101///
4102/// \code
4103/// struct Foo { Foo(int, int); };
4104/// auto x = Foo(1, 2);
4105/// \endcode
4106/// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
4107/// matches Foo(1, 2)
4108///
4109/// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
4110/// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
4111/// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
4112/// Matcher<CXXUnresolvedConstructExpr>,
4113/// Matcher<CompoundLiteralExpr>,
4114/// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
4115/// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
4116/// Matcher<TypedefNameDecl>
4118 hasTypeLoc,
4124 internal::Matcher<TypeLoc>, Inner) {
4125 TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
4126 if (source == nullptr) {
4127 // This happens for example for implicit destructors.
4128 return false;
4129 }
4130 return Inner.matches(source->getTypeLoc(), Finder, Builder);
4131}
4132
4133/// Matches if the matched type is represented by the given string.
4134///
4135/// Given
4136/// \code
4137/// class Y { public: void x(); };
4138/// void z() { Y* y; y->x(); }
4139/// \endcode
4140/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
4141/// matches y->x()
4142AST_MATCHER_P(QualType, asString, std::string, Name) {
4143 return Name == Node.getAsString();
4144}
4145
4146/// Matches if the matched type is a pointer type and the pointee type
4147/// matches the specified matcher.
4148///
4149/// Example matches y->x()
4150/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
4151/// cxxRecordDecl(hasName("Y")))))))
4152/// \code
4153/// class Y { public: void x(); };
4154/// void z() { Y *y; y->x(); }
4155/// \endcode
4157 QualType, pointsTo, internal::Matcher<QualType>,
4158 InnerMatcher) {
4159 return (!Node.isNull() && Node->isAnyPointerType() &&
4160 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4161}
4162
4163/// Overloaded to match the pointee type's declaration.
4164AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
4165 InnerMatcher, 1) {
4166 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
4167 .matches(Node, Finder, Builder);
4168}
4169
4170/// Matches if the matched type matches the unqualified desugared
4171/// type of the matched node.
4172///
4173/// For example, in:
4174/// \code
4175/// class A {};
4176/// using B = A;
4177/// \endcode
4178/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4179/// both B and A.
4180AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4181 InnerMatcher) {
4182 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4183 Builder);
4184}
4185
4186/// Matches if the matched type is a reference type and the referenced
4187/// type matches the specified matcher.
4188///
4189/// Example matches X &x and const X &y
4190/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4191/// \code
4192/// class X {
4193/// void a(X b) {
4194/// X &x = b;
4195/// const X &y = b;
4196/// }
4197/// };
4198/// \endcode
4199AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4200 InnerMatcher) {
4201 return (!Node.isNull() && Node->isReferenceType() &&
4202 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4203}
4204
4205/// Matches QualTypes whose canonical type matches InnerMatcher.
4206///
4207/// Given:
4208/// \code
4209/// typedef int &int_ref;
4210/// int a;
4211/// int_ref b = a;
4212/// \endcode
4213///
4214/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4215/// declaration of b but \c
4216/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4217AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4218 InnerMatcher) {
4219 if (Node.isNull())
4220 return false;
4221 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4222}
4223
4224/// Overloaded to match the referenced type's declaration.
4225AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4226 InnerMatcher, 1) {
4227 return references(qualType(hasDeclaration(InnerMatcher)))
4228 .matches(Node, Finder, Builder);
4229}
4230
4231/// Matches on the implicit object argument of a member call expression. Unlike
4232/// `on`, matches the argument directly without stripping away anything.
4233///
4234/// Given
4235/// \code
4236/// class Y { public: void m(); };
4237/// Y g();
4238/// class X : public Y { void g(); };
4239/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4240/// \endcode
4241/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4242/// cxxRecordDecl(hasName("Y")))))
4243/// matches `y.m()`, `x.m()` and (`g()).m()`, but not `x.g()`).
4244/// cxxMemberCallExpr(on(callExpr()))
4245/// only matches `(g()).m()` (the parens are ignored).
4246///
4247/// FIXME: Overload to allow directly matching types?
4248AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4249 internal::Matcher<Expr>, InnerMatcher) {
4250 const Expr *ExprNode = Node.getImplicitObjectArgument();
4251 return (ExprNode != nullptr &&
4252 InnerMatcher.matches(*ExprNode, Finder, Builder));
4253}
4254
4255/// Matches if the type of the expression's implicit object argument either
4256/// matches the InnerMatcher, or is a pointer to a type that matches the
4257/// InnerMatcher.
4258///
4259/// Given
4260/// \code
4261/// class Y { public: void m(); };
4262/// class X : public Y { void g(); };
4263/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4264/// \endcode
4265/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4266/// cxxRecordDecl(hasName("Y")))))
4267/// matches `y.m()`, `p->m()` and `x.m()`.
4268/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4269/// cxxRecordDecl(hasName("X")))))
4270/// matches `x.g()`.
4272 internal::Matcher<QualType>, InnerMatcher, 0) {
4273 return onImplicitObjectArgument(
4274 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4275 .matches(Node, Finder, Builder);
4276}
4277
4278/// Overloaded to match the type's declaration.
4280 internal::Matcher<Decl>, InnerMatcher, 1) {
4281 return onImplicitObjectArgument(
4282 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4283 .matches(Node, Finder, Builder);
4284}
4285
4286/// Matches a DeclRefExpr that refers to a declaration that matches the
4287/// specified matcher.
4288///
4289/// Example matches x in if(x)
4290/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4291/// \code
4292/// bool x;
4293/// if (x) {}
4294/// \endcode
4295AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4296 InnerMatcher) {
4297 const Decl *DeclNode = Node.getDecl();
4298 return (DeclNode != nullptr &&
4299 InnerMatcher.matches(*DeclNode, Finder, Builder));
4300}
4301
4302/// Matches if a node refers to a declaration through a specific
4303/// using shadow declaration.
4304///
4305/// Examples:
4306/// \code
4307/// namespace a { int f(); }
4308/// using a::f;
4309/// int x = f();
4310/// \endcode
4311/// declRefExpr(throughUsingDecl(anything()))
4312/// matches \c f
4313///
4314/// \code
4315/// namespace a { class X{}; }
4316/// using a::X;
4317/// X x;
4318/// \endcode
4319/// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4320/// matches \c X
4321///
4322/// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4325 UsingType),
4326 internal::Matcher<UsingShadowDecl>, Inner) {
4327 const NamedDecl *FoundDecl = Node.getFoundDecl();
4328 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4329 return Inner.matches(*UsingDecl, Finder, Builder);
4330 return false;
4331}
4332
4333/// Matches an \c OverloadExpr if any of the declarations in the set of
4334/// overloads matches the given matcher.
4335///
4336/// Given
4337/// \code
4338/// template <typename T> void foo(T);
4339/// template <typename T> void bar(T);
4340/// template <typename T> void baz(T t) {
4341/// foo(t);
4342/// bar(t);
4343/// }
4344/// \endcode
4345/// unresolvedLookupExpr(hasAnyDeclaration(
4346/// functionTemplateDecl(hasName("foo"))))
4347/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4348AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4349 InnerMatcher) {
4350 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4351 Node.decls_end(), Finder,
4352 Builder) != Node.decls_end();
4353}
4354
4355/// Matches the Decl of a DeclStmt which has a single declaration.
4356///
4357/// Given
4358/// \code
4359/// int a, b;
4360/// int c;
4361/// \endcode
4362/// declStmt(hasSingleDecl(anything()))
4363/// matches 'int c;' but not 'int a, b;'.
4364AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4365 if (Node.isSingleDecl()) {
4366 const Decl *FoundDecl = Node.getSingleDecl();
4367 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4368 }
4369 return false;
4370}
4371
4372/// Matches a variable declaration that has an initializer expression
4373/// that matches the given matcher.
4374///
4375/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4376/// \code
4377/// bool y() { return true; }
4378/// bool x = y();
4379/// \endcode
4381 VarDecl, hasInitializer, internal::Matcher<Expr>,
4382 InnerMatcher) {
4383 const Expr *Initializer = Node.getAnyInitializer();
4384 return (Initializer != nullptr &&
4385 InnerMatcher.matches(*Initializer, Finder, Builder));
4386}
4387
4388/// Matches a variable serving as the implicit variable for a lambda init-
4389/// capture.
4390///
4391/// Example matches x (matcher = varDecl(isInitCapture()))
4392/// \code
4393/// auto f = [x=3]() { return x; };
4394/// \endcode
4395AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4396
4397/// Matches each lambda capture in a lambda expression.
4398///
4399/// Given
4400/// \code
4401/// int main() {
4402/// int x, y;
4403/// float z;
4404/// auto f = [=]() { return x + y + z; };
4405/// }
4406/// \endcode
4407/// lambdaExpr(forEachLambdaCapture(
4408/// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4409/// will trigger two matches, binding for 'x' and 'y' respectively.
4410AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4411 internal::Matcher<LambdaCapture>, InnerMatcher) {
4412 BoundNodesTreeBuilder Result;
4413 bool Matched = false;
4414 for (const auto &Capture : Node.captures()) {
4415 if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4416 continue;
4417 BoundNodesTreeBuilder CaptureBuilder(*Builder);
4418 if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4419 Matched = true;
4420 Result.addMatch(CaptureBuilder);
4421 }
4422 }
4423 *Builder = std::move(Result);
4424 return Matched;
4425}
4426
4427/// \brief Matches a static variable with local scope.
4428///
4429/// Example matches y (matcher = varDecl(isStaticLocal()))
4430/// \code
4431/// void f() {
4432/// int x;
4433/// static int y;
4434/// }
4435/// static int z;
4436/// \endcode
4437AST_MATCHER(VarDecl, isStaticLocal) {
4438 return Node.isStaticLocal();
4439}
4440
4441/// Matches a variable declaration that has function scope and is a
4442/// non-static local variable.
4443///
4444/// Example matches x (matcher = varDecl(hasLocalStorage())
4445/// \code
4446/// void f() {
4447/// int x;
4448/// static int y;
4449/// }
4450/// int z;
4451/// \endcode
4452AST_MATCHER(VarDecl, hasLocalStorage) {
4453 return Node.hasLocalStorage();
4454}
4455
4456/// Matches a variable declaration that does not have local storage.
4457///
4458/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4459/// \code
4460/// void f() {
4461/// int x;
4462/// static int y;
4463/// }
4464/// int z;
4465/// \endcode
4466AST_MATCHER(VarDecl, hasGlobalStorage) {
4467 return Node.hasGlobalStorage();
4468}
4469
4470/// Matches a variable declaration that has automatic storage duration.
4471///
4472/// Example matches x, but not y, z, or a.
4473/// (matcher = varDecl(hasAutomaticStorageDuration())
4474/// \code
4475/// void f() {
4476/// int x;
4477/// static int y;
4478/// thread_local int z;
4479/// }
4480/// int a;
4481/// \endcode
4482AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4483 return Node.getStorageDuration() == SD_Automatic;
4484}
4485
4486/// Matches a variable declaration that has static storage duration.
4487/// It includes the variable declared at namespace scope and those declared
4488/// with "static" and "extern" storage class specifiers.
4489///
4490/// \code
4491/// void f() {
4492/// int x;
4493/// static int y;
4494/// thread_local int z;
4495/// }
4496/// int a;
4497/// static int b;
4498/// extern int c;
4499/// varDecl(hasStaticStorageDuration())
4500/// matches the function declaration y, a, b and c.
4501/// \endcode
4502AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4503 return Node.getStorageDuration() == SD_Static;
4504}
4505
4506/// Matches a variable declaration that has thread storage duration.
4507///
4508/// Example matches z, but not x, z, or a.
4509/// (matcher = varDecl(hasThreadStorageDuration())
4510/// \code
4511/// void f() {
4512/// int x;
4513/// static int y;
4514/// thread_local int z;
4515/// }
4516/// int a;
4517/// \endcode
4518AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4519 return Node.getStorageDuration() == SD_Thread;
4520}
4521
4522/// Matches a variable declaration that is an exception variable from
4523/// a C++ catch block, or an Objective-C \@catch statement.
4524///
4525/// Example matches x (matcher = varDecl(isExceptionVariable())
4526/// \code
4527/// void f(int y) {
4528/// try {
4529/// } catch (int x) {
4530/// }
4531/// }
4532/// \endcode
4533AST_MATCHER(VarDecl, isExceptionVariable) {
4534 return Node.isExceptionVariable();
4535}
4536
4537/// Checks that a call expression or a constructor call expression has
4538/// a specific number of arguments (including absent default arguments).
4539///
4540/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4541/// \code
4542/// void f(int x, int y);
4543/// f(0, 0);
4544/// \endcode
4549 unsigned, N) {
4550 unsigned NumArgs = Node.getNumArgs();
4551 if (!Finder->isTraversalIgnoringImplicitNodes())
4552 return NumArgs == N;
4553 while (NumArgs) {
4554 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4555 break;
4556 --NumArgs;
4557 }
4558 return NumArgs == N;
4559}
4560
4561/// Checks that a call expression or a constructor call expression has at least
4562/// the specified number of arguments (including absent default arguments).
4563///
4564/// Example matches f(0, 0) and g(0, 0, 0)
4565/// (matcher = callExpr(argumentCountAtLeast(2)))
4566/// \code
4567/// void f(int x, int y);
4568/// void g(int x, int y, int z);
4569/// f(0, 0);
4570/// g(0, 0, 0);
4571/// \endcode
4572AST_POLYMORPHIC_MATCHER_P(argumentCountAtLeast,
4576 unsigned, N) {
4577 unsigned NumArgs = Node.getNumArgs();
4578 if (!Finder->isTraversalIgnoringImplicitNodes())
4579 return NumArgs >= N;
4580 while (NumArgs) {
4581 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4582 break;
4583 --NumArgs;
4584 }
4585 return NumArgs >= N;
4586}
4587
4588/// Matches the n'th argument of a call expression or a constructor
4589/// call expression.
4590///
4591/// Example matches y in x(y)
4592/// (matcher = callExpr(hasArgument(0, declRefExpr())))
4593/// \code
4594/// void x(int) { int y; x(y); }
4595/// \endcode
4600 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4601 if (N >= Node.getNumArgs())
4602 return false;
4603 const Expr *Arg = Node.getArg(N);
4604 if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4605 return false;
4606 return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4607}
4608
4609/// Matches the operand that does not contain the parameter pack.
4610///
4611/// Example matches `(0 + ... + args)` and `(args * ... * 1)`
4612/// (matcher = cxxFoldExpr(hasFoldInit(expr())))
4613/// with hasFoldInit(...)
4614/// matching `0` and `1` respectively
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, hasFoldInit, internal::Matcher<Expr>, InnerMacher) {
4627 const auto *const Init = Node.getInit();
4628 return Init && InnerMacher.matches(*Init, Finder, Builder);
4629}
4630
4631/// Matches the operand that contains the parameter pack.
4632///
4633/// Example matches `(0 + ... + args)`
4634/// (matcher = cxxFoldExpr(hasPattern(expr())))
4635/// with hasPattern(...)
4636/// matching `args`
4637/// \code
4638/// template <typename... Args>
4639/// auto sum(Args... args) {
4640/// return (0 + ... + args);
4641/// }
4642///
4643/// template <typename... Args>
4644/// auto multiply(Args... args) {
4645/// return (args * ... * 1);
4646/// }
4647/// \endcode
4648AST_MATCHER_P(CXXFoldExpr, hasPattern, internal::Matcher<Expr>, InnerMacher) {
4649 const Expr *const Pattern = Node.getPattern();
4650 return Pattern && InnerMacher.matches(*Pattern, Finder, Builder);
4651}
4652
4653/// Matches right-folding fold expressions.
4654///
4655/// Example matches `(args * ... * 1)`
4656/// (matcher = cxxFoldExpr(isRightFold()))
4657/// \code
4658/// template <typename... Args>
4659/// auto sum(Args... args) {
4660/// return (0 + ... + args);
4661/// }
4662///
4663/// template <typename... Args>
4664/// auto multiply(Args... args) {
4665/// return (args * ... * 1);
4666/// }
4667/// \endcode
4668AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
4669
4670/// Matches left-folding fold expressions.
4671///
4672/// Example matches `(0 + ... + args)`
4673/// (matcher = cxxFoldExpr(isLeftFold()))
4674/// \code
4675/// template <typename... Args>
4676/// auto sum(Args... args) {
4677/// return (0 + ... + args);
4678/// }
4679///
4680/// template <typename... Args>
4681/// auto multiply(Args... args) {
4682/// return (args * ... * 1);
4683/// }
4684/// \endcode
4685AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
4686
4687/// Matches unary fold expressions, i.e. fold expressions without an
4688/// initializer.
4689///
4690/// Example matches `(args * ...)`
4691/// (matcher = cxxFoldExpr(isUnaryFold()))
4692/// \code
4693/// template <typename... Args>
4694/// auto sum(Args... args) {
4695/// return (0 + ... + args);
4696/// }
4697///
4698/// template <typename... Args>
4699/// auto multiply(Args... args) {
4700/// return (args * ...);
4701/// }
4702/// \endcode
4703AST_MATCHER(CXXFoldExpr, isUnaryFold) { return Node.getInit() == nullptr; }
4704
4705/// Matches binary fold expressions, i.e. fold expressions with an initializer.
4706///
4707/// Example matches `(0 + ... + args)`
4708/// (matcher = cxxFoldExpr(isBinaryFold()))
4709/// \code
4710/// template <typename... Args>
4711/// auto sum(Args... args) {
4712/// return (0 + ... + args);
4713/// }
4714///
4715/// template <typename... Args>
4716/// auto multiply(Args... args) {
4717/// return (args * ...);
4718/// }
4719/// \endcode
4720AST_MATCHER(CXXFoldExpr, isBinaryFold) { return Node.getInit() != nullptr; }
4721
4722/// Matches the n'th item of an initializer list expression.
4723///
4724/// Example matches y.
4725/// (matcher = initListExpr(hasInit(0, expr())))
4726/// \code
4727/// int x{y}.
4728/// \endcode
4729AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N, internal::Matcher<Expr>,
4730 InnerMatcher) {
4731 return N < Node.getNumInits() &&
4732 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4733}
4734
4735/// Matches declaration statements that contain a specific number of
4736/// declarations.
4737///
4738/// Example: Given
4739/// \code
4740/// int a, b;
4741/// int c;
4742/// int d = 2, e;
4743/// \endcode
4744/// declCountIs(2)
4745/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4746AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4747 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4748}
4749
4750/// Matches the n'th declaration of a declaration statement.
4751///
4752/// Note that this does not work for global declarations because the AST
4753/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4754/// DeclStmt's.
4755/// Example: Given non-global declarations
4756/// \code
4757/// int a, b = 0;
4758/// int c;
4759/// int d = 2, e;
4760/// \endcode
4761/// declStmt(containsDeclaration(
4762/// 0, varDecl(hasInitializer(anything()))))
4763/// matches only 'int d = 2, e;', and
4764/// declStmt(containsDeclaration(1, varDecl()))
4765/// \code
4766/// matches 'int a, b = 0' as well as 'int d = 2, e;'
4767/// but 'int c;' is not matched.
4768/// \endcode
4769AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4770 internal::Matcher<Decl>, InnerMatcher) {
4771 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4772 if (N >= NumDecls)
4773 return false;
4774 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4775 std::advance(Iterator, N);
4776 return InnerMatcher.matches(**Iterator, Finder, Builder);
4777}
4778
4779/// Matches a C++ catch statement that has a catch-all handler.
4780///
4781/// Given
4782/// \code
4783/// try {
4784/// // ...
4785/// } catch (int) {
4786/// // ...
4787/// } catch (...) {
4788/// // ...
4789/// }
4790/// \endcode
4791/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4793 return Node.getExceptionDecl() == nullptr;
4794}
4795
4796/// Matches 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(
4806/// hasAnyConstructorInitializer(anything())
4807/// )))
4808/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4809AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4810 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4811 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4812 Node.init_end(), Finder, Builder);
4813 if (MatchIt == Node.init_end())
4814 return false;
4815 return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4816}
4817
4818/// Matches the field declaration of a constructor initializer.
4819///
4820/// Given
4821/// \code
4822/// struct Foo {
4823/// Foo() : foo_(1) { }
4824/// int foo_;
4825/// };
4826/// \endcode
4827/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4828/// forField(hasName("foo_"))))))
4829/// matches Foo
4830/// with forField matching foo_
4832 internal::Matcher<FieldDecl>, InnerMatcher) {
4833 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4834 return (NodeAsDecl != nullptr &&
4835 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4836}
4837
4838/// Matches the initializer expression of a constructor initializer.
4839///
4840/// Given
4841/// \code
4842/// struct Foo {
4843/// Foo() : foo_(1) { }
4844/// int foo_;
4845/// };
4846/// \endcode
4847/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4848/// withInitializer(integerLiteral(equals(1)))))))
4849/// matches Foo
4850/// with withInitializer matching (1)
4852 internal::Matcher<Expr>, InnerMatcher) {
4853 const Expr* NodeAsExpr = Node.getInit();
4854 return (NodeAsExpr != nullptr &&
4855 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4856}
4857
4858/// Matches a constructor initializer if it is explicitly written in
4859/// code (as opposed to implicitly added by the compiler).
4860///
4861/// Given
4862/// \code
4863/// struct Foo {
4864/// Foo() { }
4865/// Foo(int) : foo_("A") { }
4866/// string foo_;
4867/// };
4868/// \endcode
4869/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4870/// will match Foo(int), but not Foo()
4872 return Node.isWritten();
4873}
4874
4875/// Matches a constructor initializer if it is initializing a base, as
4876/// opposed to a member.
4877///
4878/// Given
4879/// \code
4880/// struct B {};
4881/// struct D : B {
4882/// int I;
4883/// D(int i) : I(i) {}
4884/// };
4885/// struct E : B {
4886/// E() : B() {}
4887/// };
4888/// \endcode
4889/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4890/// will match E(), but not match D(int).
4891AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4892 return Node.isBaseInitializer();
4893}
4894
4895/// Matches a constructor initializer if it is initializing a member, as
4896/// opposed to a base.
4897///
4898/// Given
4899/// \code
4900/// struct B {};
4901/// struct D : B {
4902/// int I;
4903/// D(int i) : I(i) {}
4904/// };
4905/// struct E : B {
4906/// E() : B() {}
4907/// };
4908/// \endcode
4909/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4910/// will match D(int), but not match E().
4911AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4912 return Node.isMemberInitializer();
4913}
4914
4915/// Matches any argument of a call expression or a constructor call
4916/// expression, or an ObjC-message-send expression.
4917///
4918/// Given
4919/// \code
4920/// void x(int, int, int) { int y; x(1, y, 42); }
4921/// \endcode
4922/// callExpr(hasAnyArgument(declRefExpr()))
4923/// matches x(1, y, 42)
4924/// with hasAnyArgument(...)
4925/// matching y
4926///
4927/// For ObjectiveC, given
4928/// \code
4929/// @interface I - (void) f:(int) y; @end
4930/// void foo(I *i) { [i f:12]; }
4931/// \endcode
4932/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4933/// matches [i f:12]
4938 internal::Matcher<Expr>, InnerMatcher) {
4939 for (const Expr *Arg : Node.arguments()) {
4940 if (Finder->isTraversalIgnoringImplicitNodes() &&
4941 isa<CXXDefaultArgExpr>(Arg))
4942 break;
4943 BoundNodesTreeBuilder Result(*Builder);
4944 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4945 *Builder = std::move(Result);
4946 return true;
4947 }
4948 }
4949 return false;
4950}
4951
4952/// Matches lambda captures.
4953///
4954/// Given
4955/// \code
4956/// int main() {
4957/// int x;
4958/// auto f = [x](){};
4959/// auto g = [x = 1](){};
4960/// }
4961/// \endcode
4962/// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4963/// `lambdaCapture()` matches `x` and `x=1`.
4964extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4965
4966/// Matches any capture in a lambda expression.
4967///
4968/// Given
4969/// \code
4970/// void foo() {
4971/// int t = 5;
4972/// auto f = [=](){ return t; };
4973/// }
4974/// \endcode
4975/// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4976/// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4977/// both match `[=](){ return t; }`.
4978AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4979 InnerMatcher) {
4980 for (const LambdaCapture &Capture : Node.captures()) {
4981 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4982 if (InnerMatcher.matches(Capture, Finder, &Result)) {
4983 *Builder = std::move(Result);
4984 return true;
4985 }
4986 }
4987 return false;
4988}
4989
4990/// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4991/// `VarDecl` can be a separate variable that is captured by value or
4992/// reference, or a synthesized variable if the capture has an initializer.
4993///
4994/// Given
4995/// \code
4996/// void foo() {
4997/// int x;
4998/// auto f = [x](){};
4999/// auto g = [x = 1](){};
5000/// }
5001/// \endcode
5002/// In the matcher
5003/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
5004/// capturesVar(hasName("x")) matches `x` and `x = 1`.
5005AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
5006 InnerMatcher) {
5007 if (!Node.capturesVariable())
5008 return false;
5009 auto *capturedVar = Node.getCapturedVar();
5010 return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
5011}
5012
5013/// Matches a `LambdaCapture` that refers to 'this'.
5014///
5015/// Given
5016/// \code
5017/// class C {
5018/// int cc;
5019/// int f() {
5020/// auto l = [this]() { return cc; };
5021/// return l();
5022/// }
5023/// };
5024/// \endcode
5025/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
5026/// matches `[this]() { return cc; }`.
5027AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
5028
5029/// Matches a constructor call expression which uses list initialization.
5030AST_MATCHER(CXXConstructExpr, isListInitialization) {
5031 return Node.isListInitialization();
5032}
5033
5034/// Matches a constructor call expression which requires
5035/// zero initialization.
5036///
5037/// Given
5038/// \code
5039/// void foo() {
5040/// struct point { double x; double y; };
5041/// point pt[2] = { { 1.0, 2.0 } };
5042/// }
5043/// \endcode
5044/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
5045/// will match the implicit array filler for pt[1].
5046AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
5047 return Node.requiresZeroInitialization();
5048}
5049
5050/// Matches the n'th parameter of a function or an ObjC method
5051/// declaration or a block.
5052///
5053/// Given
5054/// \code
5055/// class X { void f(int x) {} };
5056/// \endcode
5057/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
5058/// matches f(int x) {}
5059/// with hasParameter(...)
5060/// matching int x
5061///
5062/// For ObjectiveC, given
5063/// \code
5064/// @interface I - (void) f:(int) y; @end
5065/// \endcode
5066//
5067/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
5068/// matches the declaration of method f with hasParameter
5069/// matching y.
5073 BlockDecl),
5074 unsigned, N, internal::Matcher<ParmVarDecl>,
5075 InnerMatcher) {
5076 return (N < Node.parameters().size()
5077 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
5078}
5079
5080/// Matches if the given method declaration declares a member function with an
5081/// explicit object parameter.
5082///
5083/// Given
5084/// \code
5085/// struct A {
5086/// int operator-(this A, int);
5087/// void fun(this A &&self);
5088/// static int operator()(int);
5089/// int operator+(int);
5090/// };
5091/// \endcode
5092///
5093/// cxxMethodDecl(isExplicitObjectMemberFunction()) matches the first two
5094/// methods but not the last two.
5095AST_MATCHER(CXXMethodDecl, isExplicitObjectMemberFunction) {
5096 return Node.isExplicitObjectMemberFunction();
5097}
5098
5099/// Matches all arguments and their respective ParmVarDecl.
5100///
5101/// Given
5102/// \code
5103/// void f(int i);
5104/// int y;
5105/// f(y);
5106/// \endcode
5107/// callExpr(
5108/// forEachArgumentWithParam(
5109/// declRefExpr(to(varDecl(hasName("y")))),
5110/// parmVarDecl(hasType(isInteger()))
5111/// ))
5112/// matches f(y);
5113/// with declRefExpr(...)
5114/// matching int y
5115/// and parmVarDecl(...)
5116/// matching int i
5117AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
5120 internal::Matcher<Expr>, ArgMatcher,
5121 internal::Matcher<ParmVarDecl>, ParamMatcher) {
5122 BoundNodesTreeBuilder Result;
5123 // The first argument of an overloaded member operator is the implicit object
5124 // argument of the method which should not be matched against a parameter, so
5125 // we skip over it here.
5126 BoundNodesTreeBuilder Matches;
5127 unsigned ArgIndex =
5129 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5130 .matches(Node, Finder, &Matches)
5131 ? 1
5132 : 0;
5133 int ParamIndex = 0;
5134 bool Matched = false;
5135 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
5136 BoundNodesTreeBuilder ArgMatches(*Builder);
5137 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
5138 Finder, &ArgMatches)) {
5139 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5141 hasParameter(ParamIndex, ParamMatcher)))),
5142 callExpr(callee(functionDecl(
5143 hasParameter(ParamIndex, ParamMatcher))))))
5144 .matches(Node, Finder, &ParamMatches)) {
5145 Result.addMatch(ParamMatches);
5146 Matched = true;
5147 }
5148 }
5149 ++ParamIndex;
5150 }
5151 *Builder = std::move(Result);
5152 return Matched;
5153}
5154
5155/// Matches all arguments and their respective types for a \c CallExpr or
5156/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
5157/// it works on calls through function pointers as well.
5158///
5159/// The difference is, that function pointers do not provide access to a
5160/// \c ParmVarDecl, but only the \c QualType for each argument.
5161///
5162/// Given
5163/// \code
5164/// void f(int i);
5165/// int y;
5166/// f(y);
5167/// void (*f_ptr)(int) = f;
5168/// f_ptr(y);
5169/// \endcode
5170/// callExpr(
5171/// forEachArgumentWithParamType(
5172/// declRefExpr(to(varDecl(hasName("y")))),
5173/// qualType(isInteger()).bind("type)
5174/// ))
5175/// matches f(y) and f_ptr(y)
5176/// with declRefExpr(...)
5177/// matching int y
5178/// and qualType(...)
5179/// matching int
5180AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
5183 internal::Matcher<Expr>, ArgMatcher,
5184 internal::Matcher<QualType>, ParamMatcher) {
5185 BoundNodesTreeBuilder Result;
5186 // The first argument of an overloaded member operator is the implicit object
5187 // argument of the method which should not be matched against a parameter, so
5188 // we skip over it here.
5189 BoundNodesTreeBuilder Matches;
5190 unsigned ArgIndex =
5192 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5193 .matches(Node, Finder, &Matches)
5194 ? 1
5195 : 0;
5196 const FunctionProtoType *FProto = nullptr;
5197
5198 if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
5199 if (const auto *Value =
5200 dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
5202
5203 // This does not necessarily lead to a `FunctionProtoType`,
5204 // e.g. K&R functions do not have a function prototype.
5205 if (QT->isFunctionPointerType())
5206 FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
5207
5208 if (QT->isMemberFunctionPointerType()) {
5209 const auto *MP = QT->getAs<MemberPointerType>();
5210 assert(MP && "Must be member-pointer if its a memberfunctionpointer");
5211 FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
5212 assert(FProto &&
5213 "The call must have happened through a member function "
5214 "pointer");
5215 }
5216 }
5217 }
5218
5219 unsigned ParamIndex = 0;
5220 bool Matched = false;
5221 unsigned NumArgs = Node.getNumArgs();
5222 if (FProto && FProto->isVariadic())
5223 NumArgs = std::min(NumArgs, FProto->getNumParams());
5224
5225 for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
5226 BoundNodesTreeBuilder ArgMatches(*Builder);
5227 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
5228 &ArgMatches)) {
5229 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5230
5231 // This test is cheaper compared to the big matcher in the next if.
5232 // Therefore, please keep this order.
5233 if (FProto && FProto->getNumParams() > ParamIndex) {
5234 QualType ParamType = FProto->getParamType(ParamIndex);
5235 if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
5236 Result.addMatch(ParamMatches);
5237 Matched = true;
5238 continue;
5239 }
5240 }
5242 hasParameter(ParamIndex, hasType(ParamMatcher))))),
5243 callExpr(callee(functionDecl(
5244 hasParameter(ParamIndex, hasType(ParamMatcher)))))))
5245 .matches(Node, Finder, &ParamMatches)) {
5246 Result.addMatch(ParamMatches);
5247 Matched = true;
5248 continue;
5249 }
5250 }
5251 }
5252 *Builder = std::move(Result);
5253 return Matched;
5254}
5255
5256/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
5257/// list. The parameter list could be that of either a block, function, or
5258/// objc-method.
5259///
5260///
5261/// Given
5262///
5263/// \code
5264/// void f(int a, int b, int c) {
5265/// }
5266/// \endcode
5267///
5268/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
5269///
5270/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
5271AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
5272 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
5273
5274 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
5275 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5276 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
5277 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5278 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
5279 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5280
5281 return false;
5282}
5283
5284/// Matches any parameter of a function or an ObjC method declaration or a
5285/// block.
5286///
5287/// Does not match the 'this' parameter of a method.
5288///
5289/// Given
5290/// \code
5291/// class X { void f(int x, int y, int z) {} };
5292/// \endcode
5293/// cxxMethodDecl(hasAnyParameter(hasName("y")))
5294/// matches f(int x, int y, int z) {}
5295/// with hasAnyParameter(...)
5296/// matching int y
5297///
5298/// For ObjectiveC, given
5299/// \code
5300/// @interface I - (void) f:(int) y; @end
5301/// \endcode
5302//
5303/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5304/// matches the declaration of method f with hasParameter
5305/// matching y.
5306///
5307/// For blocks, given
5308/// \code
5309/// b = ^(int y) { printf("%d", y) };
5310/// \endcode
5311///
5312/// the matcher blockDecl(hasAnyParameter(hasName("y")))
5313/// matches the declaration of the block b with hasParameter
5314/// matching y.
5318 BlockDecl),
5319 internal::Matcher<ParmVarDecl>,
5320 InnerMatcher) {
5321 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5322 Node.param_end(), Finder,
5323 Builder) != Node.param_end();
5324}
5325
5326/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5327/// specific parameter count.
5328///
5329/// Given
5330/// \code
5331/// void f(int i) {}
5332/// void g(int i, int j) {}
5333/// void h(int i, int j);
5334/// void j(int i);
5335/// void k(int x, int y, int z, ...);
5336/// \endcode
5337/// functionDecl(parameterCountIs(2))
5338/// matches \c g and \c h
5339/// functionProtoType(parameterCountIs(2))
5340/// matches \c g and \c h
5341/// functionProtoType(parameterCountIs(3))
5342/// matches \c k
5346 unsigned, N) {
5347 return Node.getNumParams() == N;
5348}
5349
5350/// Matches templateSpecializationType, class template specialization,
5351/// variable template specialization, and function template specialization
5352/// nodes where the template argument matches the inner matcher. This matcher
5353/// may produce multiple matches.
5354///
5355/// Given
5356/// \code
5357/// template <typename T, unsigned N, unsigned M>
5358/// struct Matrix {};
5359///
5360/// constexpr unsigned R = 2;
5361/// Matrix<int, R * 2, R * 4> M;
5362///
5363/// template <typename T, typename U>
5364/// void f(T&& t, U&& u) {}
5365///
5366/// bool B = false;
5367/// f(R, B);
5368/// \endcode
5369/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5370/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5371/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5372/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5373/// and 'bool'
5375 forEachTemplateArgument,
5379 internal::Matcher<TemplateArgument>, InnerMatcher) {
5380 ArrayRef<TemplateArgument> TemplateArgs =
5381 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5382 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5383 bool Matched = false;
5384 for (const auto &Arg : TemplateArgs) {
5385 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5386 if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5387 Matched = true;
5388 Result.addMatch(ArgBuilder);
5389 }
5390 }
5391 *Builder = std::move(Result);
5392 return Matched;
5393}
5394
5395/// Matches \c FunctionDecls that have a noreturn attribute.
5396///
5397/// Given
5398/// \code
5399/// void nope();
5400/// [[noreturn]] void a();
5401/// __attribute__((noreturn)) void b();
5402/// struct c { [[noreturn]] c(); };
5403/// \endcode
5404/// functionDecl(isNoReturn())
5405/// matches all of those except
5406/// \code
5407/// void nope();
5408/// \endcode
5409AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5410
5411/// Matches the return type of a function declaration.
5412///
5413/// Given:
5414/// \code
5415/// class X { int f() { return 1; } };
5416/// \endcode
5417/// cxxMethodDecl(returns(asString("int")))
5418/// matches int f() { return 1; }
5420 internal::Matcher<QualType>, InnerMatcher) {
5421 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5422}
5423
5424/// Matches extern "C" function or variable declarations.
5425///
5426/// Given:
5427/// \code
5428/// extern "C" void f() {}
5429/// extern "C" { void g() {} }
5430/// void h() {}
5431/// extern "C" int x = 1;
5432/// extern "C" int y = 2;
5433/// int z = 3;
5434/// \endcode
5435/// functionDecl(isExternC())
5436/// matches the declaration of f and g, but not the declaration of h.
5437/// varDecl(isExternC())
5438/// matches the declaration of x and y, but not the declaration of z.
5440 VarDecl)) {
5441 return Node.isExternC();
5442}
5443
5444/// Matches variable/function declarations that have "static" storage
5445/// class specifier ("static" keyword) written in the source.
5446///
5447/// Given:
5448/// \code
5449/// static void f() {}
5450/// static int i = 0;
5451/// extern int j;
5452/// int k;
5453/// \endcode
5454/// functionDecl(isStaticStorageClass())
5455/// matches the function declaration f.
5456/// varDecl(isStaticStorageClass())
5457/// matches the variable declaration i.
5458AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5460 VarDecl)) {
5461 return Node.getStorageClass() == SC_Static;
5462}
5463
5464/// Matches deleted function declarations.
5465///
5466/// Given:
5467/// \code
5468/// void Func();
5469/// void DeletedFunc() = delete;
5470/// \endcode
5471/// functionDecl(isDeleted())
5472/// matches the declaration of DeletedFunc, but not Func.
5474 return Node.isDeleted();
5475}
5476
5477/// Matches defaulted function declarations.
5478///
5479/// Given:
5480/// \code
5481/// class A { ~A(); };
5482/// class B { ~B() = default; };
5483/// \endcode
5484/// functionDecl(isDefaulted())
5485/// matches the declaration of ~B, but not ~A.
5487 return Node.isDefaulted();
5488}
5489
5490/// Matches weak function declarations.
5491///
5492/// Given:
5493/// \code
5494/// void foo() __attribute__((__weakref__("__foo")));
5495/// void bar();
5496/// \endcode
5497/// functionDecl(isWeak())
5498/// matches the weak declaration "foo", but not "bar".
5499AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5500
5501/// Matches functions that have a dynamic exception specification.
5502///
5503/// Given:
5504/// \code
5505/// void f();
5506/// void g() noexcept;
5507/// void h() noexcept(true);
5508/// void i() noexcept(false);
5509/// void j() throw();
5510/// void k() throw(int);
5511/// void l() throw(...);
5512/// \endcode
5513/// functionDecl(hasDynamicExceptionSpec()) and
5514/// functionProtoType(hasDynamicExceptionSpec())
5515/// match the declarations of j, k, and l, but not f, g, h, or i.
5516AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5519 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5520 return FnTy->hasDynamicExceptionSpec();
5521 return false;
5522}
5523
5524/// Matches functions that have a non-throwing exception specification.
5525///
5526/// Given:
5527/// \code
5528/// void f();
5529/// void g() noexcept;
5530/// void h() throw();
5531/// void i() throw(int);
5532/// void j() noexcept(false);
5533/// \endcode
5534/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5535/// match the declarations of g, and h, but not f, i or j.
5539 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5540
5541 // If the function does not have a prototype, then it is assumed to be a
5542 // throwing function (as it would if the function did not have any exception
5543 // specification).
5544 if (!FnTy)
5545 return false;
5546
5547 // Assume the best for any unresolved exception specification.
5549 return true;
5550
5551 return FnTy->isNothrow();
5552}
5553
5554/// Matches consteval function declarations and if consteval/if ! consteval
5555/// statements.
5556///
5557/// Given:
5558/// \code
5559/// consteval int a();
5560/// void b() { if consteval {} }
5561/// void c() { if ! consteval {} }
5562/// void d() { if ! consteval {} else {} }
5563/// \endcode
5564/// functionDecl(isConsteval())
5565/// matches the declaration of "int a()".
5566/// ifStmt(isConsteval())
5567/// matches the if statement in "void b()", "void c()", "void d()".
5570 return Node.isConsteval();
5571}
5572
5573/// Matches constexpr variable and function declarations,
5574/// and if constexpr.
5575///
5576/// Given:
5577/// \code
5578/// constexpr int foo = 42;
5579/// constexpr int bar();
5580/// void baz() { if constexpr(1 > 0) {} }
5581/// \endcode
5582/// varDecl(isConstexpr())
5583/// matches the declaration of foo.
5584/// functionDecl(isConstexpr())
5585/// matches the declaration of bar.
5586/// ifStmt(isConstexpr())
5587/// matches the if statement in baz.
5591 IfStmt)) {
5592 return Node.isConstexpr();
5593}
5594
5595/// Matches constinit variable declarations.
5596///
5597/// Given:
5598/// \code
5599/// constinit int foo = 42;
5600/// constinit const char* bar = "bar";
5601/// int baz = 42;
5602/// [[clang::require_constant_initialization]] int xyz = 42;
5603/// \endcode
5604/// varDecl(isConstinit())
5605/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5606AST_MATCHER(VarDecl, isConstinit) {
5607 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5608 return CIA->isConstinit();
5609 return false;
5610}
5611
5612/// Matches selection statements with initializer.
5613///
5614/// Given:
5615/// \code
5616/// void foo() {
5617/// if (int i = foobar(); i > 0) {}
5618/// switch (int i = foobar(); i) {}
5619/// for (auto& a = get_range(); auto& x : a) {}
5620/// }
5621/// void bar() {
5622/// if (foobar() > 0) {}
5623/// switch (foobar()) {}
5624/// for (auto& x : get_range()) {}
5625/// }
5626/// \endcode
5627/// ifStmt(hasInitStatement(anything()))
5628/// matches the if statement in foo but not in bar.
5629/// switchStmt(hasInitStatement(anything()))
5630/// matches the switch statement in foo but not in bar.
5631/// cxxForRangeStmt(hasInitStatement(anything()))
5632/// matches the range for statement in foo but not in bar.
5636 internal::Matcher<Stmt>, InnerMatcher) {
5637 const Stmt *Init = Node.getInit();
5638 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5639}
5640
5641/// Matches the condition expression of an if statement, for loop,
5642/// switch statement or conditional operator.
5643///
5644/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5645/// \code
5646/// if (true) {}
5647/// \endcode
5649 hasCondition,
5652 internal::Matcher<Expr>, InnerMatcher) {
5653 const Expr *const Condition = Node.getCond();
5654 return (Condition != nullptr &&
5655 InnerMatcher.matches(*Condition, Finder, Builder));
5656}
5657
5658/// Matches the then-statement of an if statement.
5659///
5660/// Examples matches the if statement
5661/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5662/// \code
5663/// if (false) true; else false;
5664/// \endcode
5665AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5666 const Stmt *const Then = Node.getThen();
5667 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5668}
5669
5670/// Matches the else-statement of an if statement.
5671///
5672/// Examples matches the if statement
5673/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5674/// \code
5675/// if (false) false; else true;
5676/// \endcode
5677AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5678 const Stmt *const Else = Node.getElse();
5679 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5680}
5681
5682/// Matches if a node equals a previously bound node.
5683///
5684/// Matches a node if it equals the node previously bound to \p ID.
5685///
5686/// Given
5687/// \code
5688/// class X { int a; int b; };
5689/// \endcode
5690/// cxxRecordDecl(
5691/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5692/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5693/// matches the class \c X, as \c a and \c b have the same type.
5694///
5695/// Note that when multiple matches are involved via \c forEach* matchers,
5696/// \c equalsBoundNodes acts as a filter.
5697/// For example:
5698/// compoundStmt(
5699/// forEachDescendant(varDecl().bind("d")),
5700/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5701/// will trigger a match for each combination of variable declaration
5702/// and reference to that variable declaration within a compound statement.
5705 QualType),
5706 std::string, ID) {
5707 // FIXME: Figure out whether it makes sense to allow this
5708 // on any other node types.
5709 // For *Loc it probably does not make sense, as those seem
5710 // unique. For NestedNameSepcifier it might make sense, as
5711 // those also have pointer identity, but I'm not sure whether
5712 // they're ever reused.
5713 internal::NotEqualsBoundNodePredicate Predicate;
5714 Predicate.ID = ID;
5715 Predicate.Node = DynTypedNode::create(Node);
5716 return Builder->removeBindings(Predicate);
5717}
5718
5719/// Matches the condition variable statement in an if statement.
5720///
5721/// Given
5722/// \code
5723/// if (A* a = GetAPointer()) {}
5724/// \endcode
5725/// hasConditionVariableStatement(...)
5726/// matches 'A* a = GetAPointer()'.
5727AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5728 internal::Matcher<DeclStmt>, InnerMatcher) {
5729 const DeclStmt* const DeclarationStatement =
5730 Node.getConditionVariableDeclStmt();
5731 return DeclarationStatement != nullptr &&
5732 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5733}
5734
5735/// Matches the index expression of an array subscript expression.
5736///
5737/// Given
5738/// \code
5739/// int i[5];
5740/// void f() { i[1] = 42; }
5741/// \endcode
5742/// arraySubscriptExpression(hasIndex(integerLiteral()))
5743/// matches \c i[1] with the \c integerLiteral() matching \c 1
5745 internal::Matcher<Expr>, InnerMatcher) {
5746 if (const Expr* Expression = Node.getIdx())
5747 return InnerMatcher.matches(*Expression, Finder, Builder);
5748 return false;
5749}
5750
5751/// Matches the base expression of an array subscript expression.
5752///
5753/// Given
5754/// \code
5755/// int i[5];
5756/// void f() { i[1] = 42; }
5757/// \endcode
5758/// arraySubscriptExpression(hasBase(implicitCastExpr(
5759/// hasSourceExpression(declRefExpr()))))
5760/// matches \c i[1] with the \c declRefExpr() matching \c i
5762 internal::Matcher<Expr>, InnerMatcher) {
5763 if (const Expr* Expression = Node.getBase())
5764 return InnerMatcher.matches(*Expression, Finder, Builder);
5765 return false;
5766}
5767
5768/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5769/// definition that has a given body. Note that in case of functions or
5770/// coroutines this matcher only matches the definition itself and not the
5771/// other declarations of the same function or coroutine.
5772///
5773/// Given
5774/// \code
5775/// for (;;) {}
5776/// \endcode
5777/// forStmt(hasBody(compoundStmt()))
5778/// matches 'for (;;) {}'
5779/// with compoundStmt()
5780/// matching '{}'
5781///
5782/// Given
5783/// \code
5784/// void f();
5785/// void f() {}
5786/// \endcode
5787/// functionDecl(hasBody(compoundStmt()))
5788/// matches 'void f() {}'
5789/// with compoundStmt()
5790/// matching '{}'
5791/// but does not match 'void f();'
5793 hasBody,
5796 internal::Matcher<Stmt>, InnerMatcher) {
5797 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5798 return false;
5799 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5800 return (Statement != nullptr &&
5801 InnerMatcher.matches(*Statement, Finder, Builder));
5802}
5803
5804/// Matches a function declaration that has a given body present in the AST.
5805/// Note that this matcher matches all the declarations of a function whose
5806/// body is present in the AST.
5807///
5808/// Given
5809/// \code
5810/// void f();
5811/// void f() {}
5812/// void g();
5813/// \endcode
5814/// functionDecl(hasAnyBody(compoundStmt()))
5815/// matches both 'void f();'
5816/// and 'void f() {}'
5817/// with compoundStmt()
5818/// matching '{}'
5819/// but does not match 'void g();'
5821 internal::Matcher<Stmt>, InnerMatcher) {
5822 const Stmt *const Statement = Node.getBody();
5823 return (Statement != nullptr &&
5824 InnerMatcher.matches(*Statement, Finder, Builder));
5825}
5826
5827
5828/// Matches compound statements where at least one substatement matches
5829/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5830///
5831/// Given
5832/// \code
5833/// { {}; 1+2; }
5834/// \endcode
5835/// hasAnySubstatement(compoundStmt())
5836/// matches '{ {}; 1+2; }'
5837/// with compoundStmt()
5838/// matching '{}'
5839AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5841 StmtExpr),
5842 internal::Matcher<Stmt>, InnerMatcher) {
5843 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5844 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5845 CS->body_end(), Finder,
5846 Builder) != CS->body_end();
5847}
5848
5849/// Checks that a compound statement contains a specific number of
5850/// child statements.
5851///
5852/// Example: Given
5853/// \code
5854/// { for (;;) {} }
5855/// \endcode
5856/// compoundStmt(statementCountIs(0)))
5857/// matches '{}'
5858/// but does not match the outer compound statement.
5859AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5860 return Node.size() == N;
5861}
5862
5863/// Matches literals that are equal to the given value of type ValueT.
5864///
5865/// Given
5866/// \code
5867/// f('\0', false, 3.14, 42);
5868/// \endcode
5869/// characterLiteral(equals(0))
5870/// matches '\0'
5871/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5872/// match false
5873/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5874/// match 3.14
5875/// integerLiteral(equals(42))
5876/// matches 42
5877///
5878/// Note that you cannot directly match a negative numeric literal because the
5879/// minus sign is not part of the literal: It is a unary operator whose operand
5880/// is the positive numeric literal. Instead, you must use a unaryOperator()
5881/// matcher to match the minus sign:
5882///
5883/// unaryOperator(hasOperatorName("-"),
5884/// hasUnaryOperand(integerLiteral(equals(13))))
5885///
5886/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5887/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5888template <typename ValueT>
5889internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5890 void(internal::AllNodeBaseTypes), ValueT>
5891equals(const ValueT &Value) {
5892 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5893 void(internal::AllNodeBaseTypes), ValueT>(
5894 Value);
5895}
5896
5901 bool, Value, 0) {
5902 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5903 .matchesNode(Node);
5904}
5905
5910 unsigned, Value, 1) {
5911 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5912 .matchesNode(Node);
5913}
5914
5920 double, Value, 2) {
5921 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5922 .matchesNode(Node);
5923}
5924
5925/// Matches the operator Name of operator expressions and fold expressions
5926/// (binary or unary).
5927///
5928/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5929/// \code
5930/// !(a || b)
5931/// \endcode
5932///
5933/// Example matches `(0 + ... + args)`
5934/// (matcher = cxxFoldExpr(hasOperatorName("+")))
5935/// \code
5936/// template <typename... Args>
5937/// auto sum(Args... args) {
5938/// return (0 + ... + args);
5939/// }
5940/// \endcode
5942 hasOperatorName,
5946 std::string, Name) {
5947 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5948 return *OpName == Name;
5949 return false;
5950}
5951
5952/// Matches operator expressions (binary or unary) that have any of the
5953/// specified names.
5954///
5955/// hasAnyOperatorName("+", "-")
5956/// Is equivalent to
5957/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5958extern const internal::VariadicFunction<
5959 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5963 std::vector<std::string>>,
5966
5967/// Matches all kinds of assignment operators.
5968///
5969/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5970/// \code
5971/// if (a == b)
5972/// a += b;
5973/// \endcode
5974///
5975/// Example 2: matches s1 = s2
5976/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5977/// \code
5978/// struct S { S& operator=(const S&); };
5979/// void x() { S s1, s2; s1 = s2; }
5980/// \endcode
5982 isAssignmentOperator,
5985 return Node.isAssignmentOp();
5986}
5987
5988/// Matches comparison operators.
5989///
5990/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5991/// \code
5992/// if (a == b)
5993/// a += b;
5994/// \endcode
5995///
5996/// Example 2: matches s1 < s2
5997/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5998/// \code
5999/// struct S { bool operator<(const S& other); };
6000/// void x(S s1, S s2) { bool b1 = s1 < s2; }
6001/// \endcode
6003 isComparisonOperator,
6006 return Node.isComparisonOp();
6007}
6008
6009/// Matches the left hand side of binary operator expressions.
6010///
6011/// Example matches a (matcher = binaryOperator(hasLHS()))
6012/// \code
6013/// a || b
6014/// \endcode
6016 hasLHS,
6020 internal::Matcher<Expr>, InnerMatcher) {
6021 const Expr *LeftHandSide = internal::getLHS(Node);
6022 return (LeftHandSide != nullptr &&
6023 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
6024}
6025
6026/// Matches the right hand side of binary operator expressions.
6027///
6028/// Example matches b (matcher = binaryOperator(hasRHS()))
6029/// \code
6030/// a || b
6031/// \endcode
6033 hasRHS,
6037 internal::Matcher<Expr>, InnerMatcher) {
6038 const Expr *RightHandSide = internal::getRHS(Node);
6039 return (RightHandSide != nullptr &&
6040 InnerMatcher.matches(*RightHandSide, Finder, Builder));
6041}
6042
6043/// Matches if either the left hand side or the right hand side of a
6044/// binary operator or fold expression matches.
6046 hasEitherOperand,
6049 internal::Matcher<Expr>, InnerMatcher) {
6050 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6051 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
6052 .matches(Node, Finder, Builder);
6053}
6054
6055/// Matches if both matchers match with opposite sides of the binary operator
6056/// or fold expression.
6057///
6058/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
6059/// integerLiteral(equals(2)))
6060/// \code
6061/// 1 + 2 // Match
6062/// 2 + 1 // Match
6063/// 1 + 1 // No match
6064/// 2 + 2 // No match
6065/// \endcode
6067 hasOperands,
6070 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
6071 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6072 anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
6073 allOf(hasRHS(Matcher1), hasLHS(Matcher2))))
6074 .matches(Node, Finder, Builder);
6075}
6076
6077/// Matches if the operand of a unary operator matches.
6078///
6079/// Example matches true (matcher = hasUnaryOperand(
6080/// cxxBoolLiteral(equals(true))))
6081/// \code
6082/// !true
6083/// \endcode
6087 internal::Matcher<Expr>, InnerMatcher) {
6088 const Expr *const Operand = internal::getSubExpr(Node);
6089 return (Operand != nullptr &&
6090 InnerMatcher.matches(*Operand, Finder, Builder));
6091}
6092
6093/// Matches if the cast's source expression
6094/// or opaque value's source expression matches the given matcher.
6095///
6096/// Example 1: matches "a string"
6097/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
6098/// \code
6099/// class URL { URL(string); };
6100/// URL url = "a string";
6101/// \endcode
6102///
6103/// Example 2: matches 'b' (matcher =
6104/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
6105/// \code
6106/// int a = b ?: 1;
6107/// \endcode
6108AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
6111 internal::Matcher<Expr>, InnerMatcher) {
6112 const Expr *const SubExpression =
6113 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
6114 return (SubExpression != nullptr &&
6115 InnerMatcher.matches(*SubExpression, Finder, Builder));
6116}
6117
6118/// Matches casts that has a given cast kind.
6119///
6120/// Example: matches the implicit cast around \c 0
6121/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
6122/// \code
6123/// int *p = 0;
6124/// \endcode
6125///
6126/// If the matcher is use from clang-query, CastKind parameter
6127/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
6129 return Node.getCastKind() == Kind;
6130}
6131
6132/// Matches casts whose destination type matches a given matcher.
6133///
6134/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
6135/// actual casts "explicit" casts.)
6137 internal::Matcher<QualType>, InnerMatcher) {
6138 const QualType NodeType = Node.getTypeAsWritten();
6139 return InnerMatcher.matches(NodeType, Finder, Builder);
6140}
6141
6142/// Matches implicit casts whose destination type matches a given
6143/// matcher.
6144AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
6145 internal::Matcher<QualType>, InnerMatcher) {
6146 return InnerMatcher.matches(Node.getType(), Finder, Builder);
6147}
6148
6149/// Matches TagDecl object that are spelled with "struct."
6150///
6151/// Example matches S, but not C, U or E.
6152/// \code
6153/// struct S {};
6154/// class C {};
6155/// union U {};
6156/// enum E {};
6157/// \endcode
6159 return Node.isStruct();
6160}
6161
6162/// Matches TagDecl object that are spelled with "union."
6163///
6164/// Example matches U, but not C, S or E.
6165/// \code
6166/// struct S {};
6167/// class C {};
6168/// union U {};
6169/// enum E {};
6170/// \endcode
6172 return Node.isUnion();
6173}
6174
6175/// Matches TagDecl object that are spelled with "class."
6176///
6177/// Example matches C, but not S, U or E.
6178/// \code
6179/// struct S {};
6180/// class C {};
6181/// union U {};
6182/// enum E {};
6183/// \endcode
6185 return Node.isClass();
6186}
6187
6188/// Matches TagDecl object that are spelled with "enum."
6189///
6190/// Example matches E, but not C, S or U.
6191/// \code
6192/// struct S {};
6193/// class C {};
6194/// union U {};
6195/// enum E {};
6196/// \endcode
6198 return Node.isEnum();
6199}
6200
6201/// Matches the true branch expression of a conditional operator.
6202///
6203/// Example 1 (conditional ternary operator): matches a
6204/// \code
6205/// condition ? a : b
6206/// \endcode
6207///
6208/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
6209/// \code
6210/// condition ?: b
6211/// \endcode
6213 internal::Matcher<Expr>, InnerMatcher) {
6214 const Expr *Expression = Node.getTrueExpr();
6215 return (Expression != nullptr &&
6216 InnerMatcher.matches(*Expression, Finder, Builder));
6217}
6218
6219/// Matches the false branch expression of a conditional operator
6220/// (binary or ternary).
6221///
6222/// Example matches b
6223/// \code
6224/// condition ? a : b
6225/// condition ?: b
6226/// \endcode
6228 internal::Matcher<Expr>, InnerMatcher) {
6229 const Expr *Expression = Node.getFalseExpr();
6230 return (Expression != nullptr &&
6231 InnerMatcher.matches(*Expression, Finder, Builder));
6232}
6233
6234/// Matches if a declaration has a body attached.
6235///
6236/// Example matches A, va, fa
6237/// \code
6238/// class A {};
6239/// class B; // Doesn't match, as it has no body.
6240/// int va;
6241/// extern int vb; // Doesn't match, as it doesn't define the variable.
6242/// void fa() {}
6243/// void fb(); // Doesn't match, as it has no body.
6244/// @interface X
6245/// - (void)ma; // Doesn't match, interface is declaration.
6246/// @end
6247/// @implementation X
6248/// - (void)ma {}
6249/// @end
6250/// \endcode
6251///
6252/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
6253/// Matcher<ObjCMethodDecl>
6257 FunctionDecl)) {
6258 return Node.isThisDeclarationADefinition();
6259}
6260
6261/// Matches if a function declaration is variadic.
6262///
6263/// Example matches f, but not g or h. The function i will not match, even when
6264/// compiled in C mode.
6265/// \code
6266/// void f(...);
6267/// void g(int);
6268/// template <typename... Ts> void h(Ts...);
6269/// void i();
6270/// \endcode
6272 return Node.isVariadic();
6273}
6274
6275/// Matches the class declaration that the given method declaration
6276/// belongs to.
6277///
6278/// FIXME: Generalize this for other kinds of declarations.
6279/// FIXME: What other kind of declarations would we need to generalize
6280/// this to?
6281///
6282/// Example matches A() in the last line
6283/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
6284/// ofClass(hasName("A"))))))
6285/// \code
6286/// class A {
6287/// public:
6288/// A();
6289/// };
6290/// A a = A();
6291/// \endcode
6293 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
6294
6295 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
6296
6297 const CXXRecordDecl *Parent = Node.getParent();
6298 return (Parent != nullptr &&
6299 InnerMatcher.matches(*Parent, Finder, Builder));
6300}
6301
6302/// Matches each method overridden by the given method. This matcher may
6303/// produce multiple matches.
6304///
6305/// Given
6306/// \code
6307/// class A { virtual void f(); };
6308/// class B : public A { void f(); };
6309/// class C : public B { void f(); };
6310/// \endcode
6311/// cxxMethodDecl(ofClass(hasName("C")),
6312/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6313/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
6314/// that B::f is not overridden by C::f).
6315///
6316/// The check can produce multiple matches in case of multiple inheritance, e.g.
6317/// \code
6318/// class A1 { virtual void f(); };
6319/// class A2 { virtual void f(); };
6320/// class C : public A1, public A2 { void f(); };
6321/// \endcode
6322/// cxxMethodDecl(ofClass(hasName("C")),
6323/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6324/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
6325/// once with "b" binding "A2::f" and "d" binding "C::f".
6326AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
6327 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
6328 BoundNodesTreeBuilder Result;
6329 bool Matched = false;
6330 for (const auto *Overridden : Node.overridden_methods()) {
6331 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
6332 const bool OverriddenMatched =
6333 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
6334 if (OverriddenMatched) {
6335 Matched = true;
6336 Result.addMatch(OverriddenBuilder);
6337 }
6338 }
6339 *Builder = std::move(Result);
6340 return Matched;
6341}
6342
6343/// Matches declarations of virtual methods and C++ base specifers that specify
6344/// virtual inheritance.
6345///
6346/// Example:
6347/// \code
6348/// class A {
6349/// public:
6350/// virtual void x(); // matches x
6351/// };
6352/// \endcode
6353///
6354/// Example:
6355/// \code
6356/// class Base {};
6357/// class DirectlyDerived : virtual Base {}; // matches Base
6358/// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
6359/// \endcode
6360///
6361/// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
6365 return Node.isVirtual();
6366}
6367
6368/// Matches if the given method declaration has an explicit "virtual".
6369///
6370/// Given
6371/// \code
6372/// class A {
6373/// public:
6374/// virtual void x();
6375/// };
6376/// class B : public A {
6377/// public:
6378/// void x();
6379/// };
6380/// \endcode
6381/// matches A::x but not B::x
6382AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
6383 return Node.isVirtualAsWritten();
6384}
6385
6386AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
6387 return Node.isInheritingConstructor();
6388}
6389
6390/// Matches if the given method or class declaration is final.
6391///
6392/// Given:
6393/// \code
6394/// class A final {};
6395///
6396/// struct B {
6397/// virtual void f();
6398/// };
6399///
6400/// struct C : B {
6401/// void f() final;
6402/// };
6403/// \endcode
6404/// matches A and C::f, but not B, C, or B::f
6407 CXXMethodDecl)) {
6408 return Node.template hasAttr<FinalAttr>();
6409}
6410
6411/// Matches if the given method declaration is pure.
6412///
6413/// Given
6414/// \code
6415/// class A {
6416/// public:
6417/// virtual void x() = 0;
6418/// };
6419/// \endcode
6420/// matches A::x
6421AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPureVirtual(); }
6422
6423/// Matches if the given method declaration is const.
6424///
6425/// Given
6426/// \code
6427/// struct A {
6428/// void foo() const;
6429/// void bar();
6430/// };
6431/// \endcode
6432///
6433/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
6435 return Node.isConst();
6436}
6437
6438/// Matches if the given method declaration declares a copy assignment
6439/// operator.
6440///
6441/// Given
6442/// \code
6443/// struct A {
6444/// A &operator=(const A &);
6445/// A &operator=(A &&);
6446/// };
6447/// \endcode
6448///
6449/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
6450/// the second one.
6451AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
6452 return Node.isCopyAssignmentOperator();
6453}
6454
6455/// Matches if the given method declaration declares a move assignment
6456/// operator.
6457///
6458/// Given
6459/// \code
6460/// struct A {
6461/// A &operator=(const A &);
6462/// A &operator=(A &&);
6463/// };
6464/// \endcode
6465///
6466/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
6467/// the first one.
6468AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
6469 return Node.isMoveAssignmentOperator();
6470}
6471
6472/// Matches if the given method declaration overrides another method.
6473///
6474/// Given
6475/// \code
6476/// class A {
6477/// public:
6478/// virtual void x();
6479/// };
6480/// class B : public A {
6481/// public:
6482/// virtual void x();
6483/// };
6484/// \endcode
6485/// matches B::x
6487 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
6488}
6489
6490/// Matches method declarations that are user-provided.
6491///
6492/// Given
6493/// \code
6494/// struct S {
6495/// S(); // #1
6496/// S(const S &) = default; // #2
6497/// S(S &&) = delete; // #3
6498/// };
6499/// \endcode
6500/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
6501AST_MATCHER(CXXMethodDecl, isUserProvided) {
6502 return Node.isUserProvided();
6503}
6504
6505/// Matches member expressions that are called with '->' as opposed
6506/// to '.'.
6507///
6508/// Member calls on the implicit this pointer match as called with '->'.
6509///
6510/// Given
6511/// \code
6512/// class Y {
6513/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
6514/// template <class T> void f() { this->f<T>(); f<T>(); }
6515/// int a;
6516/// static int b;
6517/// };
6518/// template <class T>
6519/// class Z {
6520/// void x() { this->m; }
6521/// };
6522/// \endcode
6523/// memberExpr(isArrow())
6524/// matches this->x, x, y.x, a, this->b
6525/// cxxDependentScopeMemberExpr(isArrow())
6526/// matches this->m
6527/// unresolvedMemberExpr(isArrow())
6528/// matches this->f<T>, f<T>
6532 return Node.isArrow();
6533}
6534
6535/// Matches QualType nodes that are of integer type.
6536///
6537/// Given
6538/// \code
6539/// void a(int);
6540/// void b(long);
6541/// void c(double);
6542/// \endcode
6543/// functionDecl(hasAnyParameter(hasType(isInteger())))
6544/// matches "a(int)", "b(long)", but not "c(double)".
6546 return Node->isIntegerType();
6547}
6548
6549/// Matches QualType nodes that are of unsigned integer type.
6550///
6551/// Given
6552/// \code
6553/// void a(int);
6554/// void b(unsigned long);
6555/// void c(double);
6556/// \endcode
6557/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6558/// matches "b(unsigned long)", but not "a(int)" and "c(double)".
6559AST_MATCHER(QualType, isUnsignedInteger) {
6560 return Node->isUnsignedIntegerType();
6561}
6562
6563/// Matches QualType nodes that are of signed integer type.
6564///
6565/// Given
6566/// \code
6567/// void a(int);
6568/// void b(unsigned long);
6569/// void c(double);
6570/// \endcode
6571/// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6572/// matches "a(int)", but not "b(unsigned long)" and "c(double)".
6573AST_MATCHER(QualType, isSignedInteger) {
6574 return Node->isSignedIntegerType();
6575}
6576
6577/// Matches QualType nodes that are of character type.
6578///
6579/// Given
6580/// \code
6581/// void a(char);
6582/// void b(wchar_t);
6583/// void c(double);
6584/// \endcode
6585/// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6586/// matches "a(char)", "b(wchar_t)", but not "c(double)".
6587AST_MATCHER(QualType, isAnyCharacter) {
6588 return Node->isAnyCharacterType();
6589}
6590
6591/// Matches QualType nodes that are of any pointer type; this includes
6592/// the Objective-C object pointer type, which is different despite being
6593/// syntactically similar.
6594///
6595/// Given
6596/// \code
6597/// int *i = nullptr;
6598///
6599/// @interface Foo
6600/// @end
6601/// Foo *f;
6602///
6603/// int j;
6604/// \endcode
6605/// varDecl(hasType(isAnyPointer()))
6606/// matches "int *i" and "Foo *f", but not "int j".
6607AST_MATCHER(QualType, isAnyPointer) {
6608 return Node->isAnyPointerType();
6609}
6610
6611/// Matches QualType nodes that are const-qualified, i.e., that
6612/// include "top-level" const.
6613///
6614/// Given
6615/// \code
6616/// void a(int);
6617/// void b(int const);
6618/// void c(const int);
6619/// void d(const int*);
6620/// void e(int const) {};
6621/// \endcode
6622/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6623/// matches "void b(int const)", "void c(const int)" and
6624/// "void e(int const) {}". It does not match d as there
6625/// is no top-level const on the parameter type "const int *".
6626AST_MATCHER(QualType, isConstQualified) {
6627 return Node.isConstQualified();
6628}
6629
6630/// Matches QualType nodes that are volatile-qualified, i.e., that
6631/// include "top-level" volatile.
6632///
6633/// Given
6634/// \code
6635/// void a(int);
6636/// void b(int volatile);
6637/// void c(volatile int);
6638/// void d(volatile int*);
6639/// void e(int volatile) {};
6640/// \endcode
6641/// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6642/// matches "void b(int volatile)", "void c(volatile int)" and
6643/// "void e(int volatile) {}". It does not match d as there
6644/// is no top-level volatile on the parameter type "volatile int *".
6645AST_MATCHER(QualType, isVolatileQualified) {
6646 return Node.isVolatileQualified();
6647}
6648
6649/// Matches QualType nodes that have local CV-qualifiers attached to
6650/// the node, not hidden within a typedef.
6651///
6652/// Given
6653/// \code
6654/// typedef const int const_int;
6655/// const_int i;
6656/// int *const j;
6657/// int *volatile k;
6658/// int m;
6659/// \endcode
6660/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
6661/// \c i is const-qualified but the qualifier is not local.
6662AST_MATCHER(QualType, hasLocalQualifiers) {
6663 return Node.hasLocalQualifiers();
6664}
6665
6666/// Matches a member expression where the member is matched by a
6667/// given matcher.
6668///
6669/// Given
6670/// \code
6671/// struct { int first, second; } first, second;
6672/// int i(second.first);
6673/// int j(first.second);
6674/// \endcode
6675/// memberExpr(member(hasName("first")))
6676/// matches second.first
6677/// but not first.second (because the member name there is "second").
6679 internal::Matcher<ValueDecl>, InnerMatcher) {
6680 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
6681}
6682
6683/// Matches a member expression where the object expression is matched by a
6684/// given matcher. Implicit object expressions are included; that is, it matches
6685/// use of implicit `this`.
6686///
6687/// Given
6688/// \code
6689/// struct X {
6690/// int m;
6691/// int f(X x) { x.m; return m; }
6692/// };
6693/// \endcode
6694/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
6695/// matches `x.m`, but not `m`; however,
6696/// memberExpr(hasObjectExpression(hasType(pointsTo(
6697// cxxRecordDecl(hasName("X"))))))
6698/// matches `m` (aka. `this->m`), but not `x.m`.
6700 hasObjectExpression,
6703 internal::Matcher<Expr>, InnerMatcher) {
6704 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
6705 if (E->isImplicitAccess())
6706 return false;
6707 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
6708 if (E->isImplicitAccess())
6709 return false;
6710 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
6711}
6712
6713/// Matches any using shadow declaration.
6714///
6715/// Given
6716/// \code
6717/// namespace X { void b(); }
6718/// using X::b;
6719/// \endcode
6720/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
6721/// matches \code using X::b \endcode
6722AST_MATCHER_P(BaseUsingDecl, hasAnyUsingShadowDecl,
6723 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
6724 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
6725 Node.shadow_end(), Finder,
6726 Builder) != Node.shadow_end();
6727}
6728
6729/// Matches a using shadow declaration where the target declaration is
6730/// matched by the given matcher.
6731///
6732/// Given
6733/// \code
6734/// namespace X { int a; void b(); }
6735/// using X::a;
6736/// using X::b;
6737/// \endcode
6738/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
6739/// matches \code using X::b \endcode
6740/// but not \code using X::a \endcode
6742 internal::Matcher<NamedDecl>, InnerMatcher) {
6743 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
6744}
6745
6746/// Matches template instantiations of function, class, or static
6747/// member variable template instantiations.
6748///
6749/// Given
6750/// \code
6751/// template <typename T> class X {}; class A {}; X<A> x;
6752/// \endcode
6753/// or
6754/// \code
6755/// template <typename T> class X {}; class A {}; template class X<A>;
6756/// \endcode
6757/// or
6758/// \code
6759/// template <typename T> class X {}; class A {}; extern template class X<A>;
6760/// \endcode
6761/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6762/// matches the template instantiation of X<A>.
6763///
6764/// But given
6765/// \code
6766/// template <typename T> class X {}; class A {};
6767/// template <> class X<A> {}; X<A> x;
6768/// \endcode
6769/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6770/// does not match, as X<A> is an explicit template specialization.
6771///
6772/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6775 CXXRecordDecl)) {
6776 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
6777 Node.getTemplateSpecializationKind() ==
6779 Node.getTemplateSpecializationKind() ==
6781}
6782
6783/// Matches declarations that are template instantiations or are inside
6784/// template instantiations.
6785///
6786/// Given
6787/// \code
6788/// template<typename T> void A(T t) { T i; }
6789/// A(0);
6790/// A(0U);
6791/// \endcode
6792/// functionDecl(isInstantiated())
6793/// matches 'A(int) {...};' and 'A(unsigned) {...}'.
6794AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
6795 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6798 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
6799}
6800
6801/// Matches statements inside of a template instantiation.
6802///
6803/// Given
6804/// \code
6805/// int j;
6806/// template<typename T> void A(T t) { T i; j += 42;}
6807/// A(0);
6808/// A(0U);
6809/// \endcode
6810/// declStmt(isInTemplateInstantiation())
6811/// matches 'int i;' and 'unsigned i'.
6812/// unless(stmt(isInTemplateInstantiation()))
6813/// will NOT match j += 42; as it's shared between the template definition and
6814/// instantiation.
6815AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
6819}
6820
6821/// Matches explicit template specializations of function, class, or
6822/// static member variable template instantiations.
6823///
6824/// Given
6825/// \code
6826/// template<typename T> void A(T t) { }
6827/// template<> void A(int N) { }
6828/// \endcode
6829/// functionDecl(isExplicitTemplateSpecialization())
6830/// matches the specialization A<int>().
6831///
6832/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6833AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
6835 CXXRecordDecl)) {
6836 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
6837}
6838
6839/// Matches \c TypeLocs for which the given inner
6840/// QualType-matcher matches.
6841AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
6842 internal::Matcher<QualType>, InnerMatcher, 0) {
6843 return internal::BindableMatcher<TypeLoc>(
6844 new internal::TypeLocTypeMatcher(InnerMatcher));
6845}
6846
6847/// Matches `QualifiedTypeLoc`s in the clang AST.
6848///
6849/// Given
6850/// \code
6851/// const int x = 0;
6852/// \endcode
6853/// qualifiedTypeLoc()
6854/// matches `const int`.
6855extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, QualifiedTypeLoc>
6857
6858/// Matches `QualifiedTypeLoc`s that have an unqualified `TypeLoc` matching
6859/// `InnerMatcher`.
6860///
6861/// Given
6862/// \code
6863/// int* const x;
6864/// const int y;
6865/// \endcode
6866/// qualifiedTypeLoc(hasUnqualifiedLoc(pointerTypeLoc()))
6867/// matches the `TypeLoc` of the variable declaration of `x`, but not `y`.
6868AST_MATCHER_P(QualifiedTypeLoc, hasUnqualifiedLoc, internal::Matcher<TypeLoc>,
6869 InnerMatcher) {
6870 return InnerMatcher.matches(Node.getUnqualifiedLoc(), Finder, Builder);
6871}
6872
6873/// Matches a function declared with the specified return `TypeLoc`.
6874///
6875/// Given
6876/// \code
6877/// int f() { return 5; }
6878/// void g() {}
6879/// \endcode
6880/// functionDecl(hasReturnTypeLoc(loc(asString("int"))))
6881/// matches the declaration of `f`, but not `g`.
6882AST_MATCHER_P(FunctionDecl, hasReturnTypeLoc, internal::Matcher<TypeLoc>,
6883 ReturnMatcher) {
6884 auto Loc = Node.getFunctionTypeLoc();
6885 return Loc && ReturnMatcher.matches(Loc.getReturnLoc(), Finder, Builder);
6886}
6887
6888/// Matches pointer `TypeLoc`s.
6889///
6890/// Given
6891/// \code
6892/// int* x;
6893/// \endcode
6894/// pointerTypeLoc()
6895/// matches `int*`.
6896extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, PointerTypeLoc>
6898
6899/// Matches pointer `TypeLoc`s that have a pointee `TypeLoc` matching
6900/// `PointeeMatcher`.
6901///
6902/// Given
6903/// \code
6904/// int* x;
6905/// \endcode
6906/// pointerTypeLoc(hasPointeeLoc(loc(asString("int"))))
6907/// matches `int*`.
6908AST_MATCHER_P(PointerTypeLoc, hasPointeeLoc, internal::Matcher<TypeLoc>,
6909 PointeeMatcher) {
6910 return PointeeMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
6911}
6912
6913/// Matches reference `TypeLoc`s.
6914///
6915/// Given
6916/// \code
6917/// int x = 3;
6918/// int& l = x;
6919/// int&& r = 3;
6920/// \endcode
6921/// referenceTypeLoc()
6922/// matches `int&` and `int&&`.
6923extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ReferenceTypeLoc>
6925
6926/// Matches reference `TypeLoc`s that have a referent `TypeLoc` matching
6927/// `ReferentMatcher`.
6928///
6929/// Given
6930/// \code
6931/// int x = 3;
6932/// int& xx = x;
6933/// \endcode
6934/// referenceTypeLoc(hasReferentLoc(loc(asString("int"))))
6935/// matches `int&`.
6936AST_MATCHER_P(ReferenceTypeLoc, hasReferentLoc, internal::Matcher<TypeLoc>,
6937 ReferentMatcher) {
6938 return ReferentMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
6939}
6940
6941/// Matches template specialization `TypeLoc`s.
6942///
6943/// Given
6944/// \code
6945/// template <typename T> class C {};
6946/// C<char> var;
6947/// \endcode
6948/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(typeLoc())))
6949/// matches `C<char> var`.
6950extern const internal::VariadicDynCastAllOfMatcher<
6953
6954/// Matches template specialization `TypeLoc`s, class template specializations,
6955/// variable template specializations, and function template specializations
6956/// that have at least one `TemplateArgumentLoc` matching the given
6957/// `InnerMatcher`.
6958///
6959/// Given
6960/// \code
6961/// template<typename T> class A {};
6962/// A<int> a;
6963/// \endcode
6964/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasAnyTemplateArgumentLoc(
6965/// hasTypeLoc(loc(asString("int")))))))
6966/// matches `A<int> a`.
6968 hasAnyTemplateArgumentLoc,
6972 internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
6973 auto Args = internal::getTemplateArgsWritten(Node);
6974 return matchesFirstInRange(InnerMatcher, Args.begin(), Args.end(), Finder,
6975 Builder) != Args.end();
6976 return false;
6977}
6978
6979/// Matches template specialization `TypeLoc`s, class template specializations,
6980/// variable template specializations, and function template specializations
6981/// where the n'th `TemplateArgumentLoc` matches the given `InnerMatcher`.
6982///
6983/// Given
6984/// \code
6985/// template<typename T, typename U> class A {};
6986/// A<double, int> b;
6987/// A<int, double> c;
6988/// \endcode
6989/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasTemplateArgumentLoc(0,
6990/// hasTypeLoc(loc(asString("double")))))))
6991/// matches `A<double, int> b`, but not `A<int, double> c`.
6993 hasTemplateArgumentLoc,
6997 unsigned, Index, internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
6998 auto Args = internal::getTemplateArgsWritten(Node);
6999 return Index < Args.size() &&
7000 InnerMatcher.matches(Args[Index], Finder, Builder);
7001}
7002
7003/// Matches C or C++ elaborated `TypeLoc`s.
7004///
7005/// Given
7006/// \code
7007/// struct s {};
7008/// struct s ss;
7009/// \endcode
7010/// elaboratedTypeLoc()
7011/// matches the `TypeLoc` of the variable declaration of `ss`.
7012extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ElaboratedTypeLoc>
7014
7015/// Matches elaborated `TypeLoc`s that have a named `TypeLoc` matching
7016/// `InnerMatcher`.
7017///
7018/// Given
7019/// \code
7020/// template <typename T>
7021/// class C {};
7022/// class C<int> c;
7023///
7024/// class D {};
7025/// class D d;
7026/// \endcode
7027/// elaboratedTypeLoc(hasNamedTypeLoc(templateSpecializationTypeLoc()));
7028/// matches the `TypeLoc` of the variable declaration of `c`, but not `d`.
7029AST_MATCHER_P(ElaboratedTypeLoc, hasNamedTypeLoc, internal::Matcher<TypeLoc>,
7030 InnerMatcher) {
7031 return InnerMatcher.matches(Node.getNamedTypeLoc(), Finder, Builder);
7032}
7033
7034/// Matches type \c bool.
7035///
7036/// Given
7037/// \code
7038/// struct S { bool func(); };
7039/// \endcode
7040/// functionDecl(returns(booleanType()))
7041/// matches "bool func();"
7042AST_MATCHER(Type, booleanType) {
7043 return Node.isBooleanType();
7044}
7045
7046/// Matches type \c void.
7047///
7048/// Given
7049/// \code
7050/// struct S { void func(); };
7051/// \endcode
7052/// functionDecl(returns(voidType()))
7053/// matches "void func();"
7054AST_MATCHER(Type, voidType) {
7055 return Node.isVoidType();
7056}
7057
7058template <typename NodeType>
7059using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
7060
7061/// Matches builtin Types.
7062///
7063/// Given
7064/// \code
7065/// struct A {};
7066/// A a;
7067/// int b;
7068/// float c;
7069/// bool d;
7070/// \endcode
7071/// builtinType()
7072/// matches "int b", "float c" and "bool d"
7074
7075/// Matches all kinds of arrays.
7076///
7077/// Given
7078/// \code
7079/// int a[] = { 2, 3 };
7080/// int b[4];
7081/// void f() { int c[a[0]]; }
7082/// \endcode
7083/// arrayType()
7084/// matches "int a[]", "int b[4]" and "int c[a[0]]";
7086
7087/// Matches C99 complex types.
7088///
7089/// Given
7090/// \code
7091/// _Complex float f;
7092/// \endcode
7093/// complexType()
7094/// matches "_Complex float f"
7096
7097/// Matches any real floating-point type (float, double, long double).
7098///
7099/// Given
7100/// \code
7101/// int i;
7102/// float f;
7103/// \endcode
7104/// realFloatingPointType()
7105/// matches "float f" but not "int i"
7106AST_MATCHER(Type, realFloatingPointType) {
7107 return Node.isRealFloatingType();
7108}
7109
7110/// Matches arrays and C99 complex types that have a specific element
7111/// type.
7112///
7113/// Given
7114/// \code
7115/// struct A {};
7116/// A a[7];
7117/// int b[7];
7118/// \endcode
7119/// arrayType(hasElementType(builtinType()))
7120/// matches "int b[7]"
7121///
7122/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
7123AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
7125 ComplexType));
7126
7127/// Matches C arrays with a specified constant size.
7128///
7129/// Given
7130/// \code
7131/// void() {
7132/// int a[2];
7133/// int b[] = { 2, 3 };
7134/// int c[b[0]];
7135/// }
7136/// \endcode
7137/// constantArrayType()
7138/// matches "int a[2]"
7140
7141/// Matches nodes that have the specified size.
7142///
7143/// Given
7144/// \code
7145/// int a[42];
7146/// int b[2 * 21];
7147/// int c[41], d[43];
7148/// char *s = "abcd";
7149/// wchar_t *ws = L"abcd";
7150/// char *w = "a";
7151/// \endcode
7152/// constantArrayType(hasSize(42))
7153/// matches "int a[42]" and "int b[2 * 21]"
7154/// stringLiteral(hasSize(4))
7155/// matches "abcd", L"abcd"
7159 unsigned, N) {
7160 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
7161}
7162
7163/// Matches C++ arrays whose size is a value-dependent expression.
7164///
7165/// Given
7166/// \code
7167/// template<typename T, int Size>
7168/// class array {
7169/// T data[Size];
7170/// };
7171/// \endcode
7172/// dependentSizedArrayType()
7173/// matches "T data[Size]"
7175
7176/// Matches C++ extended vector type where either the type or size is
7177/// dependent.
7178///
7179/// Given
7180/// \code
7181/// template<typename T, int Size>
7182/// class vector {
7183/// typedef T __attribute__((ext_vector_type(Size))) type;
7184/// };
7185/// \endcode
7186/// dependentSizedExtVectorType()
7187/// matches "T __attribute__((ext_vector_type(Size)))"
7190
7191/// Matches C arrays with unspecified size.
7192///
7193/// Given
7194/// \code
7195/// int a[] = { 2, 3 };
7196/// int b[42];
7197/// void f(int c[]) { int d[a[0]]; };
7198/// \endcode
7199/// incompleteArrayType()
7200/// matches "int a[]" and "int c[]"
7202
7203/// Matches C arrays with a specified size that is not an
7204/// integer-constant-expression.
7205///
7206/// Given
7207/// \code
7208/// void f() {
7209/// int a[] = { 2, 3 }
7210/// int b[42];
7211/// int c[a[0]];
7212/// }
7213/// \endcode
7214/// variableArrayType()
7215/// matches "int c[a[0]]"
7217
7218/// Matches \c VariableArrayType nodes that have a specific size
7219/// expression.
7220///
7221/// Given
7222/// \code
7223/// void f(int b) {
7224/// int a[b];
7225/// }
7226/// \endcode
7227/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
7228/// varDecl(hasName("b")))))))
7229/// matches "int a[b]"
7231 internal::Matcher<Expr>, InnerMatcher) {
7232 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
7233}
7234
7235/// Matches atomic types.
7236///
7237/// Given
7238/// \code
7239/// _Atomic(int) i;
7240/// \endcode
7241/// atomicType()
7242/// matches "_Atomic(int) i"
7244
7245/// Matches atomic types with a specific value type.
7246///
7247/// Given
7248/// \code
7249/// _Atomic(int) i;
7250/// _Atomic(float) f;
7251/// \endcode
7252/// atomicType(hasValueType(isInteger()))
7253/// matches "_Atomic(int) i"
7254///
7255/// Usable as: Matcher<AtomicType>
7258
7259/// Matches types nodes representing C++11 auto types.
7260///
7261/// Given:
7262/// \code
7263/// auto n = 4;
7264/// int v[] = { 2, 3 }
7265/// for (auto i : v) { }
7266/// \endcode
7267/// autoType()
7268/// matches "auto n" and "auto i"
7270
7271/// Matches types nodes representing C++11 decltype(<expr>) types.
7272///
7273/// Given:
7274/// \code
7275/// short i = 1;
7276/// int j = 42;
7277/// decltype(i + j) result = i + j;
7278/// \endcode
7279/// decltypeType()
7280/// matches "decltype(i + j)"
7282
7283/// Matches \c AutoType nodes where the deduced type is a specific type.
7284///
7285/// Note: There is no \c TypeLoc for the deduced type and thus no
7286/// \c getDeducedLoc() matcher.
7287///
7288/// Given
7289/// \code
7290/// auto a = 1;
7291/// auto b = 2.0;
7292/// \endcode
7293/// autoType(hasDeducedType(isInteger()))
7294/// matches "auto a"
7295///
7296/// Usable as: Matcher<AutoType>
7297AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
7299
7300/// Matches \c DecltypeType or \c UsingType nodes to find the underlying type.
7301///
7302/// Given
7303/// \code
7304/// decltype(1) a = 1;
7305/// decltype(2.0) b = 2.0;
7306/// \endcode
7307/// decltypeType(hasUnderlyingType(isInteger()))
7308/// matches the type of "a"
7309///
7310/// Usable as: Matcher<DecltypeType>, Matcher<UsingType>
7313 UsingType));
7314
7315/// Matches \c FunctionType nodes.
7316///
7317/// Given
7318/// \code
7319/// int (*f)(int);
7320/// void g();
7321/// \endcode
7322/// functionType()
7323/// matches "int (*f)(int)" and the type of "g".
7325
7326/// Matches \c FunctionProtoType nodes.
7327///
7328/// Given
7329/// \code
7330/// int (*f)(int);
7331/// void g();
7332/// \endcode
7333/// functionProtoType()
7334/// matches "int (*f)(int)" and the type of "g" in C++ mode.
7335/// In C mode, "g" is not matched because it does not contain a prototype.
7337
7338/// Matches \c ParenType nodes.
7339///
7340/// Given
7341/// \code
7342/// int (*ptr_to_array)[4];
7343/// int *array_of_ptrs[4];
7344/// \endcode
7345///
7346/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
7347/// \c array_of_ptrs.
7349
7350/// Matches \c ParenType nodes where the inner type is a specific type.
7351///
7352/// Given
7353/// \code
7354/// int (*ptr_to_array)[4];
7355/// int (*ptr_to_func)(int);
7356/// \endcode
7357///
7358/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
7359/// \c ptr_to_func but not \c ptr_to_array.
7360///
7361/// Usable as: Matcher<ParenType>
7362AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
7364
7365/// Matches block pointer types, i.e. types syntactically represented as
7366/// "void (^)(int)".
7367///
7368/// The \c pointee is always required to be a \c FunctionType.
7370
7371/// Matches member pointer types.
7372/// Given
7373/// \code
7374/// struct A { int i; }
7375/// A::* ptr = A::i;
7376/// \endcode
7377/// memberPointerType()
7378/// matches "A::* ptr"
7380
7381/// Matches pointer types, but does not match Objective-C object pointer
7382/// types.
7383///
7384/// Given
7385/// \code
7386/// int *a;
7387/// int &b = *a;
7388/// int c = 5;
7389///
7390/// @interface Foo
7391/// @end
7392/// Foo *f;
7393/// \endcode
7394/// pointerType()
7395/// matches "int *a", but does not match "Foo *f".
7397
7398/// Matches an Objective-C object pointer type, which is different from
7399/// a pointer type, despite being syntactically similar.
7400///
7401/// Given
7402/// \code
7403/// int *a;
7404///
7405/// @interface Foo
7406/// @end
7407/// Foo *f;
7408/// \endcode
7409/// pointerType()
7410/// matches "Foo *f", but does not match "int *a".
7412
7413/// Matches both lvalue and rvalue reference types.
7414///
7415/// Given
7416/// \code
7417/// int *a;
7418/// int &b = *a;
7419/// int &&c = 1;
7420/// auto &d = b;
7421/// auto &&e = c;
7422/// auto &&f = 2;
7423/// int g = 5;
7424/// \endcode
7425///
7426/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
7428
7429/// Matches lvalue reference types.
7430///
7431/// Given:
7432/// \code
7433/// int *a;
7434/// int &b = *a;
7435/// int &&c = 1;
7436/// auto &d = b;
7437/// auto &&e = c;
7438/// auto &&f = 2;
7439/// int g = 5;
7440/// \endcode
7441///
7442/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
7443/// matched since the type is deduced as int& by reference collapsing rules.
7445
7446/// Matches rvalue reference types.
7447///
7448/// Given:
7449/// \code
7450/// int *a;
7451/// int &b = *a;
7452/// int &&c = 1;
7453/// auto &d = b;
7454/// auto &&e = c;
7455/// auto &&f = 2;
7456/// int g = 5;
7457/// \endcode
7458///
7459/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
7460/// matched as it is deduced to int& by reference collapsing rules.
7462
7463/// Narrows PointerType (and similar) matchers to those where the
7464/// \c pointee matches a given matcher.
7465///
7466/// Given
7467/// \code
7468/// int *a;
7469/// int const *b;
7470/// float const *f;
7471/// \endcode
7472/// pointerType(pointee(isConstQualified(), isInteger()))
7473/// matches "int const *b"
7474///
7475/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
7476/// Matcher<PointerType>, Matcher<ReferenceType>
7478 pointee, getPointee,
7482
7483/// Matches typedef types.
7484///
7485/// Given
7486/// \code
7487/// typedef int X;
7488/// \endcode
7489/// typedefType()
7490/// matches "typedef int X"
7492
7493/// Matches qualified types when the qualifier is applied via a macro.
7494///
7495/// Given
7496/// \code
7497/// #define CDECL __attribute__((cdecl))
7498/// typedef void (CDECL *X)();
7499/// typedef void (__attribute__((cdecl)) *Y)();
7500/// \endcode
7501/// macroQualifiedType()
7502/// matches the type of the typedef declaration of \c X but not \c Y.
7504
7505/// Matches enum types.
7506///
7507/// Given
7508/// \code
7509/// enum C { Green };
7510/// enum class S { Red };
7511///
7512/// C c;
7513/// S s;
7514/// \endcode
7515//
7516/// \c enumType() matches the type of the variable declarations of both \c c and
7517/// \c s.
7519
7520/// Matches template specialization types.
7521///
7522/// Given
7523/// \code
7524/// template <typename T>
7525/// class C { };
7526///
7527/// template class C<int>; // A
7528/// C<char> var; // B
7529/// \endcode
7530///
7531/// \c templateSpecializationType() matches the type of the explicit
7532/// instantiation in \c A and the type of the variable declaration in \c B.
7535
7536/// Matches C++17 deduced template specialization types, e.g. deduced class
7537/// template types.
7538///
7539/// Given
7540/// \code
7541/// template <typename T>
7542/// class C { public: C(T); };
7543///
7544/// C c(123);
7545/// \endcode
7546/// \c deducedTemplateSpecializationType() matches the type in the declaration
7547/// of the variable \c c.
7550
7551/// Matches types nodes representing unary type transformations.
7552///
7553/// Given:
7554/// \code
7555/// typedef __underlying_type(T) type;
7556/// \endcode
7557/// unaryTransformType()
7558/// matches "__underlying_type(T)"
7560
7561/// Matches record types (e.g. structs, classes).
7562///
7563/// Given
7564/// \code
7565/// class C {};
7566/// struct S {};
7567///
7568/// C c;
7569/// S s;
7570/// \endcode
7571///
7572/// \c recordType() matches the type of the variable declarations of both \c c
7573/// and \c s.
7575
7576/// Matches tag types (record and enum types).
7577///
7578/// Given
7579/// \code
7580/// enum E {};
7581/// class C {};
7582///
7583/// E e;
7584/// C c;
7585/// \endcode
7586///
7587/// \c tagType() matches the type of the variable declarations of both \c e
7588/// and \c c.
7589extern const AstTypeMatcher<TagType> tagType;
7590
7591/// Matches types specified with an elaborated type keyword or with a
7592/// qualified name.
7593///
7594/// Given
7595/// \code
7596/// namespace N {
7597/// namespace M {
7598/// class D {};
7599/// }
7600/// }
7601/// class C {};
7602///
7603/// class C c;
7604/// N::M::D d;
7605/// \endcode
7606///
7607/// \c elaboratedType() matches the type of the variable declarations of both
7608/// \c c and \c d.
7610
7611/// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
7612/// matches \c InnerMatcher if the qualifier exists.
7613///
7614/// Given
7615/// \code
7616/// namespace N {
7617/// namespace M {
7618/// class D {};
7619/// }
7620/// }
7621/// N::M::D d;
7622/// \endcode
7623///
7624/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
7625/// matches the type of the variable declaration of \c d.
7627 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
7628 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
7629 return InnerMatcher.matches(*Qualifier, Finder, Builder);
7630
7631 return false;
7632}
7633
7634/// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
7635///
7636/// Given
7637/// \code
7638/// namespace N {
7639/// namespace M {
7640/// class D {};
7641/// }
7642/// }
7643/// N::M::D d;
7644/// \endcode
7645///
7646/// \c elaboratedType(namesType(recordType(
7647/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
7648/// declaration of \c d.
7649AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
7650 InnerMatcher) {
7651 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
7652}
7653
7654/// Matches types specified through a using declaration.
7655///
7656/// Given
7657/// \code
7658/// namespace a { struct S {}; }
7659/// using a::S;
7660/// S s;
7661/// \endcode
7662///
7663/// \c usingType() matches the type of the variable declaration of \c s.
7665
7666/// Matches types that represent the result of substituting a type for a
7667/// template type parameter.
7668///
7669/// Given
7670/// \code
7671/// template <typename T>
7672/// void F(T t) {
7673/// int i = 1 + t;
7674/// }
7675/// \endcode
7676///
7677/// \c substTemplateTypeParmType() matches the type of 't' but not '1'
7680
7681/// Matches template type parameter substitutions that have a replacement
7682/// type that matches the provided matcher.
7683///
7684/// Given
7685/// \code
7686/// template <typename T>
7687/// double F(T t);
7688/// int i;
7689/// double j = F(i);
7690/// \endcode
7691///
7692/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
7694 hasReplacementType, getReplacementType,
7696
7697/// Matches template type parameter types.
7698///
7699/// Example matches T, but not int.
7700/// (matcher = templateTypeParmType())
7701/// \code
7702/// template <typename T> void f(int i);
7703/// \endcode
7705
7706/// Matches injected class name types.
7707///
7708/// Example matches S s, but not S<T> s.
7709/// (matcher = parmVarDecl(hasType(injectedClassNameType())))
7710/// \code
7711/// template <typename T> struct S {
7712/// void f(S s);
7713/// void g(S<T> s);
7714/// };
7715/// \endcode
7717
7718/// Matches decayed type
7719/// Example matches i[] in declaration of f.
7720/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
7721/// Example matches i[1].
7722/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
7723/// \code
7724/// void f(int i[]) {
7725/// i[1] = 0;
7726/// }
7727/// \endcode
7729
7730/// Matches the decayed type, whoes decayed type matches \c InnerMatcher
7731AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
7732 InnerType) {
7733 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
7734}
7735
7736/// Matches a dependent name type
7737///
7738/// Example matches T::type
7739/// \code
7740/// template <typename T> struct declToImport {
7741/// typedef typename T::type dependent_name;
7742/// };
7743/// \endcode
7745
7746/// Matches a dependent template specialization type
7747///
7748/// Example matches A<T>::template B<T>
7749/// \code
7750/// template<typename T> struct A;
7751/// template<typename T> struct declToImport {
7752/// typename A<T>::template B<T> a;
7753/// };
7754/// \endcode
7757
7758/// Matches declarations whose declaration context, interpreted as a
7759/// Decl, matches \c InnerMatcher.
7760///
7761/// Given
7762/// \code
7763/// namespace N {
7764/// namespace M {
7765/// class D {};
7766/// }
7767/// }
7768/// \endcode
7769///
7770/// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
7771/// declaration of \c class \c D.
7772AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
7773 const DeclContext *DC = Node.getDeclContext();
7774 if (!DC) return false;
7775 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
7776}
7777
7778/// Matches nested name specifiers.
7779///
7780/// Given
7781/// \code
7782/// namespace ns {
7783/// struct A { static void f(); };
7784/// void A::f() {}
7785/// void g() { A::f(); }
7786/// }
7787/// ns::A a;
7788/// \endcode
7789/// nestedNameSpecifier()
7790/// matches "ns::" and both "A::"
7791extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
7793
7794/// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
7795extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
7797
7798/// Matches \c NestedNameSpecifierLocs for which the given inner
7799/// NestedNameSpecifier-matcher matches.
7801 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
7802 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
7803 return internal::BindableMatcher<NestedNameSpecifierLoc>(
7804 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
7805 InnerMatcher));
7806}
7807
7808/// Matches nested name specifiers that specify a type matching the
7809/// given \c QualType matcher without qualifiers.
7810///
7811/// Given
7812/// \code
7813/// struct A { struct B { struct C {}; }; };
7814/// A::B::C c;
7815/// \endcode
7816/// nestedNameSpecifier(specifiesType(
7817/// hasDeclaration(cxxRecordDecl(hasName("A")))
7818/// ))
7819/// matches "A::"
7821 internal::Matcher<QualType>, InnerMatcher) {
7822 if (!Node.getAsType())
7823 return false;
7824 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
7825}
7826
7827/// Matches nested name specifier locs that specify a type matching the
7828/// given \c TypeLoc.
7829///
7830/// Given
7831/// \code
7832/// struct A { struct B { struct C {}; }; };
7833/// A::B::C c;
7834/// \endcode
7835/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
7836/// hasDeclaration(cxxRecordDecl(hasName("A")))))))
7837/// matches "A::"
7839 internal::Matcher<TypeLoc>, InnerMatcher) {
7840 return Node && Node.getNestedNameSpecifier()->getAsType() &&
7841 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
7842}
7843
7844/// Matches on the prefix of a \c NestedNameSpecifier.
7845///
7846/// Given
7847/// \code
7848/// struct A { struct B { struct C {}; }; };
7849/// A::B::C c;
7850/// \endcode
7851/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
7852/// matches "A::"
7854 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
7855 0) {
7856 const NestedNameSpecifier *NextNode = Node.getPrefix();
7857 if (!NextNode)
7858 return false;
7859 return InnerMatcher.matches(*NextNode, Finder, Builder);
7860}
7861
7862/// Matches on the prefix of a \c NestedNameSpecifierLoc.
7863///
7864/// Given
7865/// \code
7866/// struct A { struct B { struct C {}; }; };
7867/// A::B::C c;
7868/// \endcode
7869/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
7870/// matches "A::"
7872 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
7873 1) {
7874 NestedNameSpecifierLoc NextNode = Node.getPrefix();
7875 if (!NextNode)
7876 return false;
7877 return InnerMatcher.matches(NextNode, Finder, Builder);
7878}
7879
7880/// Matches nested name specifiers that specify a namespace matching the
7881/// given namespace matcher.
7882///
7883/// Given
7884/// \code
7885/// namespace ns { struct A {}; }
7886/// ns::A a;
7887/// \endcode
7888/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
7889/// matches "ns::"
7891 internal::Matcher<NamespaceDecl>, InnerMatcher) {
7892 if (!Node.getAsNamespace())
7893 return false;
7894 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
7895}
7896
7897/// Matches attributes.
7898/// Attributes may be attached with a variety of different syntaxes (including
7899/// keywords, C++11 attributes, GNU ``__attribute``` and MSVC `__declspec``,
7900/// and ``#pragma``s). They may also be implicit.
7901///
7902/// Given
7903/// \code
7904/// struct [[nodiscard]] Foo{};
7905/// void bar(int * __attribute__((nonnull)) );
7906/// __declspec(noinline) void baz();
7907///
7908/// #pragma omp declare simd
7909/// int min();
7910/// \endcode
7911/// attr()
7912/// matches "nodiscard", "nonnull", "noinline", and the whole "#pragma" line.
7913extern const internal::VariadicAllOfMatcher<Attr> attr;
7914
7915/// Overloads for the \c equalsNode matcher.
7916/// FIXME: Implement for other node types.
7917/// @{
7918
7919/// Matches if a node equals another node.
7920///
7921/// \c Decl has pointer identity in the AST.
7922AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
7923 return &Node == Other;
7924}
7925/// Matches if a node equals another node.
7926///
7927/// \c Stmt has pointer identity in the AST.
7928AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
7929 return &Node == Other;
7930}
7931/// Matches if a node equals another node.
7932///
7933/// \c Type has pointer identity in the AST.
7934AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
7935 return &Node == Other;
7936}
7937
7938/// @}
7939
7940/// Matches each case or default statement belonging to the given switch
7941/// statement. This matcher may produce multiple matches.
7942///
7943/// Given
7944/// \code
7945/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
7946/// \endcode
7947/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
7948/// matches four times, with "c" binding each of "case 1:", "case 2:",
7949/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
7950/// "switch (1)", "switch (2)" and "switch (2)".
7951AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
7952 InnerMatcher) {
7953 BoundNodesTreeBuilder Result;
7954 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
7955 // iteration order. We should use the more general iterating matchers once
7956 // they are capable of expressing this matcher (for example, it should ignore
7957 // case statements belonging to nested switch statements).
7958 bool Matched = false;
7959 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
7960 SC = SC->getNextSwitchCase()) {
7961 BoundNodesTreeBuilder CaseBuilder(*Builder);
7962 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
7963 if (CaseMatched) {
7964 Matched = true;
7965 Result.addMatch(CaseBuilder);
7966 }
7967 }
7968 *Builder = std::move(Result);
7969 return Matched;
7970}
7971
7972/// Matches each constructor initializer in a constructor definition.
7973///
7974/// Given
7975/// \code
7976/// class A { A() : i(42), j(42) {} int i; int j; };
7977/// \endcode
7978/// cxxConstructorDecl(forEachConstructorInitializer(
7979/// forField(decl().bind("x"))
7980/// ))
7981/// will trigger two matches, binding for 'i' and 'j' respectively.
7982AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
7983 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
7984 BoundNodesTreeBuilder Result;
7985 bool Matched = false;
7986 for (const auto *I : Node.inits()) {
7987 if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
7988 continue;
7989 BoundNodesTreeBuilder InitBuilder(*Builder);
7990 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
7991 Matched = true;
7992 Result.addMatch(InitBuilder);
7993 }
7994 }
7995 *Builder = std::move(Result);
7996 return Matched;
7997}
7998
7999/// Matches constructor declarations that are copy constructors.
8000///
8001/// Given
8002/// \code
8003/// struct S {
8004/// S(); // #1
8005/// S(const S &); // #2
8006/// S(S &&); // #3
8007/// };
8008/// \endcode
8009/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
8010AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
8011 return Node.isCopyConstructor();
8012}
8013
8014/// Matches constructor declarations that are move constructors.
8015///
8016/// Given
8017/// \code
8018/// struct S {
8019/// S(); // #1
8020/// S(const S &); // #2
8021/// S(S &&); // #3
8022/// };
8023/// \endcode
8024/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
8025AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
8026 return Node.isMoveConstructor();
8027}
8028
8029/// Matches constructor declarations that are default constructors.
8030///
8031/// Given
8032/// \code
8033/// struct S {
8034/// S(); // #1
8035/// S(const S &); // #2
8036/// S(S &&); // #3
8037/// };
8038/// \endcode
8039/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
8040AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
8041 return Node.isDefaultConstructor();
8042}
8043
8044/// Matches constructors that delegate to another constructor.
8045///
8046/// Given
8047/// \code
8048/// struct S {
8049/// S(); // #1
8050/// S(int) {} // #2
8051/// S(S &&) : S() {} // #3
8052/// };
8053/// S::S() : S(0) {} // #4
8054/// \endcode
8055/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
8056/// #1 or #2.
8057AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
8058 return Node.isDelegatingConstructor();
8059}
8060
8061/// Matches constructor, conversion function, and deduction guide declarations
8062/// that have an explicit specifier if this explicit specifier is resolved to
8063/// true.
8064///
8065/// Given
8066/// \code
8067/// template<bool b>
8068/// struct S {
8069/// S(int); // #1
8070/// explicit S(double); // #2
8071/// operator int(); // #3
8072/// explicit operator bool(); // #4
8073/// explicit(false) S(bool) // # 7
8074/// explicit(true) S(char) // # 8
8075/// explicit(b) S(S) // # 9
8076/// };
8077/// S(int) -> S<true> // #5
8078/// explicit S(double) -> S<false> // #6
8079/// \endcode
8080/// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
8081/// cxxConversionDecl(isExplicit()) will match #4, but not #3.
8082/// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
8086 return Node.isExplicit();
8087}
8088
8089/// Matches the expression in an explicit specifier if present in the given
8090/// declaration.
8091///
8092/// Given
8093/// \code
8094/// template<bool b>
8095/// struct S {
8096/// S(int); // #1
8097/// explicit S(double); // #2
8098/// operator int(); // #3
8099/// explicit operator bool(); // #4
8100/// explicit(false) S(bool) // # 7
8101/// explicit(true) S(char) // # 8
8102/// explicit(b) S(S) // # 9
8103/// };
8104/// S(int) -> S<true> // #5
8105/// explicit S(double) -> S<false> // #6
8106/// \endcode
8107/// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
8108/// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
8109/// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
8110AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
8111 InnerMatcher) {
8113 if (!ES.getExpr())
8114 return false;
8115
8116 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
8117
8118 return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
8119}
8120
8121/// Matches functions, variables and namespace declarations that are marked with
8122/// the inline keyword.
8123///
8124/// Given
8125/// \code
8126/// inline void f();
8127/// void g();
8128/// namespace n {
8129/// inline namespace m {}
8130/// }
8131/// inline int Foo = 5;
8132/// \endcode
8133/// functionDecl(isInline()) will match ::f().
8134/// namespaceDecl(isInline()) will match n::m.
8135/// varDecl(isInline()) will match Foo;
8138 VarDecl)) {
8139 // This is required because the spelling of the function used to determine
8140 // whether inline is specified or not differs between the polymorphic types.
8141 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
8142 return FD->isInlineSpecified();
8143 if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
8144 return NSD->isInline();
8145 if (const auto *VD = dyn_cast<VarDecl>(&Node))
8146 return VD->isInline();
8147 llvm_unreachable("Not a valid polymorphic type");
8148}
8149
8150/// Matches anonymous namespace declarations.
8151///
8152/// Given
8153/// \code
8154/// namespace n {
8155/// namespace {} // #1
8156/// }
8157/// \endcode
8158/// namespaceDecl(isAnonymous()) will match #1 but not ::n.
8160 return Node.isAnonymousNamespace();
8161}
8162
8163/// Matches declarations in the namespace `std`, but not in nested namespaces.
8164///
8165/// Given