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

source code of clang/include/clang/ASTMatchers/ASTMatchers.h