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, ast_matchers::internal::Matcher<Expr>,
4584 InnerMacher) {
4585 const auto *const Init = Node.getInit();
4586 return Init && InnerMacher.matches(Node: *Init, Finder, Builder);
4587}
4588
4589/// Matches the operand that contains the parameter pack.
4590///
4591/// Example matches `(0 + ... + args)`
4592/// (matcher = cxxFoldExpr(hasPattern(expr())))
4593/// with hasPattern(...)
4594/// matching `args`
4595/// \code
4596/// template <typename... Args>
4597/// auto sum(Args... args) {
4598/// return (0 + ... + args);
4599/// }
4600///
4601/// template <typename... Args>
4602/// auto multiply(Args... args) {
4603/// return (args * ... * 1);
4604/// }
4605/// \endcode
4606AST_MATCHER_P(CXXFoldExpr, hasPattern, ast_matchers::internal::Matcher<Expr>,
4607 InnerMacher) {
4608 const Expr *const Pattern = Node.getPattern();
4609 return Pattern && InnerMacher.matches(Node: *Pattern, Finder, Builder);
4610}
4611
4612/// Matches right-folding fold expressions.
4613///
4614/// Example matches `(args * ... * 1)`
4615/// (matcher = cxxFoldExpr(isRightFold()))
4616/// \code
4617/// template <typename... Args>
4618/// auto sum(Args... args) {
4619/// return (0 + ... + args);
4620/// }
4621///
4622/// template <typename... Args>
4623/// auto multiply(Args... args) {
4624/// return (args * ... * 1);
4625/// }
4626/// \endcode
4627AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
4628
4629/// Matches left-folding fold expressions.
4630///
4631/// Example matches `(0 + ... + args)`
4632/// (matcher = cxxFoldExpr(isLeftFold()))
4633/// \code
4634/// template <typename... Args>
4635/// auto sum(Args... args) {
4636/// return (0 + ... + args);
4637/// }
4638///
4639/// template <typename... Args>
4640/// auto multiply(Args... args) {
4641/// return (args * ... * 1);
4642/// }
4643/// \endcode
4644AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
4645
4646/// Matches unary fold expressions, i.e. fold expressions without an
4647/// initializer.
4648///
4649/// Example matches `(args * ...)`
4650/// (matcher = cxxFoldExpr(isUnaryFold()))
4651/// \code
4652/// template <typename... Args>
4653/// auto sum(Args... args) {
4654/// return (0 + ... + args);
4655/// }
4656///
4657/// template <typename... Args>
4658/// auto multiply(Args... args) {
4659/// return (args * ...);
4660/// }
4661/// \endcode
4662AST_MATCHER(CXXFoldExpr, isUnaryFold) { return Node.getInit() == nullptr; }
4663
4664/// Matches binary fold expressions, i.e. fold expressions with an initializer.
4665///
4666/// Example matches `(0 + ... + args)`
4667/// (matcher = cxxFoldExpr(isBinaryFold()))
4668/// \code
4669/// template <typename... Args>
4670/// auto sum(Args... args) {
4671/// return (0 + ... + args);
4672/// }
4673///
4674/// template <typename... Args>
4675/// auto multiply(Args... args) {
4676/// return (args * ...);
4677/// }
4678/// \endcode
4679AST_MATCHER(CXXFoldExpr, isBinaryFold) { return Node.getInit() != nullptr; }
4680
4681/// Matches the n'th item of an initializer list expression.
4682///
4683/// Example matches y.
4684/// (matcher = initListExpr(hasInit(0, expr())))
4685/// \code
4686/// int x{y}.
4687/// \endcode
4688AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
4689 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
4690 return N < Node.getNumInits() &&
4691 InnerMatcher.matches(Node: *Node.getInit(Init: N), Finder, Builder);
4692}
4693
4694/// Matches declaration statements that contain a specific number of
4695/// declarations.
4696///
4697/// Example: Given
4698/// \code
4699/// int a, b;
4700/// int c;
4701/// int d = 2, e;
4702/// \endcode
4703/// declCountIs(2)
4704/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4705AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4706 return std::distance(first: Node.decl_begin(), last: Node.decl_end()) == (ptrdiff_t)N;
4707}
4708
4709/// Matches the n'th declaration of a declaration statement.
4710///
4711/// Note that this does not work for global declarations because the AST
4712/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4713/// DeclStmt's.
4714/// Example: Given non-global declarations
4715/// \code
4716/// int a, b = 0;
4717/// int c;
4718/// int d = 2, e;
4719/// \endcode
4720/// declStmt(containsDeclaration(
4721/// 0, varDecl(hasInitializer(anything()))))
4722/// matches only 'int d = 2, e;', and
4723/// declStmt(containsDeclaration(1, varDecl()))
4724/// \code
4725/// matches 'int a, b = 0' as well as 'int d = 2, e;'
4726/// but 'int c;' is not matched.
4727/// \endcode
4728AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4729 internal::Matcher<Decl>, InnerMatcher) {
4730 const unsigned NumDecls = std::distance(first: Node.decl_begin(), last: Node.decl_end());
4731 if (N >= NumDecls)
4732 return false;
4733 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4734 std::advance(i&: Iterator, n: N);
4735 return InnerMatcher.matches(Node: **Iterator, Finder, Builder);
4736}
4737
4738/// Matches a C++ catch statement that has a catch-all handler.
4739///
4740/// Given
4741/// \code
4742/// try {
4743/// // ...
4744/// } catch (int) {
4745/// // ...
4746/// } catch (...) {
4747/// // ...
4748/// }
4749/// \endcode
4750/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4751AST_MATCHER(CXXCatchStmt, isCatchAll) {
4752 return Node.getExceptionDecl() == nullptr;
4753}
4754
4755/// Matches a constructor initializer.
4756///
4757/// Given
4758/// \code
4759/// struct Foo {
4760/// Foo() : foo_(1) { }
4761/// int foo_;
4762/// };
4763/// \endcode
4764/// cxxRecordDecl(has(cxxConstructorDecl(
4765/// hasAnyConstructorInitializer(anything())
4766/// )))
4767/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4768AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4769 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4770 auto MatchIt = matchesFirstInPointerRange(Matcher: InnerMatcher, Start: Node.init_begin(),
4771 End: Node.init_end(), Finder, Builder);
4772 if (MatchIt == Node.init_end())
4773 return false;
4774 return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4775}
4776
4777/// Matches the field declaration of a constructor initializer.
4778///
4779/// Given
4780/// \code
4781/// struct Foo {
4782/// Foo() : foo_(1) { }
4783/// int foo_;
4784/// };
4785/// \endcode
4786/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4787/// forField(hasName("foo_"))))))
4788/// matches Foo
4789/// with forField matching foo_
4790AST_MATCHER_P(CXXCtorInitializer, forField,
4791 internal::Matcher<FieldDecl>, InnerMatcher) {
4792 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4793 return (NodeAsDecl != nullptr &&
4794 InnerMatcher.matches(Node: *NodeAsDecl, Finder, Builder));
4795}
4796
4797/// Matches the initializer expression of a constructor initializer.
4798///
4799/// Given
4800/// \code
4801/// struct Foo {
4802/// Foo() : foo_(1) { }
4803/// int foo_;
4804/// };
4805/// \endcode
4806/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4807/// withInitializer(integerLiteral(equals(1)))))))
4808/// matches Foo
4809/// with withInitializer matching (1)
4810AST_MATCHER_P(CXXCtorInitializer, withInitializer,
4811 internal::Matcher<Expr>, InnerMatcher) {
4812 const Expr* NodeAsExpr = Node.getInit();
4813 return (NodeAsExpr != nullptr &&
4814 InnerMatcher.matches(Node: *NodeAsExpr, Finder, Builder));
4815}
4816
4817/// Matches a constructor initializer if it is explicitly written in
4818/// code (as opposed to implicitly added by the compiler).
4819///
4820/// Given
4821/// \code
4822/// struct Foo {
4823/// Foo() { }
4824/// Foo(int) : foo_("A") { }
4825/// string foo_;
4826/// };
4827/// \endcode
4828/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4829/// will match Foo(int), but not Foo()
4830AST_MATCHER(CXXCtorInitializer, isWritten) {
4831 return Node.isWritten();
4832}
4833
4834/// Matches a constructor initializer if it is initializing a base, as
4835/// opposed to a member.
4836///
4837/// Given
4838/// \code
4839/// struct B {};
4840/// struct D : B {
4841/// int I;
4842/// D(int i) : I(i) {}
4843/// };
4844/// struct E : B {
4845/// E() : B() {}
4846/// };
4847/// \endcode
4848/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4849/// will match E(), but not match D(int).
4850AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4851 return Node.isBaseInitializer();
4852}
4853
4854/// Matches a constructor initializer if it is initializing a member, as
4855/// opposed to a base.
4856///
4857/// Given
4858/// \code
4859/// struct B {};
4860/// struct D : B {
4861/// int I;
4862/// D(int i) : I(i) {}
4863/// };
4864/// struct E : B {
4865/// E() : B() {}
4866/// };
4867/// \endcode
4868/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4869/// will match D(int), but not match E().
4870AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4871 return Node.isMemberInitializer();
4872}
4873
4874/// Matches any argument of a call expression or a constructor call
4875/// expression, or an ObjC-message-send expression.
4876///
4877/// Given
4878/// \code
4879/// void x(int, int, int) { int y; x(1, y, 42); }
4880/// \endcode
4881/// callExpr(hasAnyArgument(declRefExpr()))
4882/// matches x(1, y, 42)
4883/// with hasAnyArgument(...)
4884/// matching y
4885///
4886/// For ObjectiveC, given
4887/// \code
4888/// @interface I - (void) f:(int) y; @end
4889/// void foo(I *i) { [i f:12]; }
4890/// \endcode
4891/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4892/// matches [i f:12]
4893AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
4894 AST_POLYMORPHIC_SUPPORTED_TYPES(
4895 CallExpr, CXXConstructExpr,
4896 CXXUnresolvedConstructExpr, ObjCMessageExpr),
4897 internal::Matcher<Expr>, InnerMatcher) {
4898 for (const Expr *Arg : Node.arguments()) {
4899 if (Finder->isTraversalIgnoringImplicitNodes() &&
4900 isa<CXXDefaultArgExpr>(Val: Arg))
4901 break;
4902 BoundNodesTreeBuilder Result(*Builder);
4903 if (InnerMatcher.matches(Node: *Arg, Finder, Builder: &Result)) {
4904 *Builder = std::move(Result);
4905 return true;
4906 }
4907 }
4908 return false;
4909}
4910
4911/// Matches lambda captures.
4912///
4913/// Given
4914/// \code
4915/// int main() {
4916/// int x;
4917/// auto f = [x](){};
4918/// auto g = [x = 1](){};
4919/// }
4920/// \endcode
4921/// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4922/// `lambdaCapture()` matches `x` and `x=1`.
4923extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4924
4925/// Matches any capture in a lambda expression.
4926///
4927/// Given
4928/// \code
4929/// void foo() {
4930/// int t = 5;
4931/// auto f = [=](){ return t; };
4932/// }
4933/// \endcode
4934/// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4935/// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4936/// both match `[=](){ return t; }`.
4937AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4938 InnerMatcher) {
4939 for (const LambdaCapture &Capture : Node.captures()) {
4940 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4941 if (InnerMatcher.matches(Node: Capture, Finder, Builder: &Result)) {
4942 *Builder = std::move(Result);
4943 return true;
4944 }
4945 }
4946 return false;
4947}
4948
4949/// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4950/// `VarDecl` can be a separate variable that is captured by value or
4951/// reference, or a synthesized variable if the capture has an initializer.
4952///
4953/// Given
4954/// \code
4955/// void foo() {
4956/// int x;
4957/// auto f = [x](){};
4958/// auto g = [x = 1](){};
4959/// }
4960/// \endcode
4961/// In the matcher
4962/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4963/// capturesVar(hasName("x")) matches `x` and `x = 1`.
4964AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
4965 InnerMatcher) {
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 all arguments and their respective ParmVarDecl.
5038///
5039/// Given
5040/// \code
5041/// void f(int i);
5042/// int y;
5043/// f(y);
5044/// \endcode
5045/// callExpr(
5046/// forEachArgumentWithParam(
5047/// declRefExpr(to(varDecl(hasName("y")))),
5048/// parmVarDecl(hasType(isInteger()))
5049/// ))
5050/// matches f(y);
5051/// with declRefExpr(...)
5052/// matching int y
5053/// and parmVarDecl(...)
5054/// matching int i
5055AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
5056 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
5057 CXXConstructExpr),
5058 internal::Matcher<Expr>, ArgMatcher,
5059 internal::Matcher<ParmVarDecl>, ParamMatcher) {
5060 BoundNodesTreeBuilder Result;
5061 // The first argument of an overloaded member operator is the implicit object
5062 // argument of the method which should not be matched against a parameter, so
5063 // we skip over it here.
5064 BoundNodesTreeBuilder Matches;
5065 unsigned ArgIndex = cxxOperatorCallExpr(callee(InnerMatcher: cxxMethodDecl()))
5066 .matches(Node, Finder, Builder: &Matches)
5067 ? 1
5068 : 0;
5069 int ParamIndex = 0;
5070 bool Matched = false;
5071 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
5072 BoundNodesTreeBuilder ArgMatches(*Builder);
5073 if (ArgMatcher.matches(Node: *(Node.getArg(ArgIndex)->IgnoreParenCasts()),
5074 Finder, Builder: &ArgMatches)) {
5075 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5076 if (expr(anyOf(cxxConstructExpr(hasDeclaration(InnerMatcher: cxxConstructorDecl(
5077 hasParameter(N: ParamIndex, InnerMatcher: ParamMatcher)))),
5078 callExpr(callee(InnerMatcher: functionDecl(
5079 hasParameter(N: ParamIndex, InnerMatcher: ParamMatcher))))))
5080 .matches(Node, Finder, Builder: &ParamMatches)) {
5081 Result.addMatch(Bindings: ParamMatches);
5082 Matched = true;
5083 }
5084 }
5085 ++ParamIndex;
5086 }
5087 *Builder = std::move(Result);
5088 return Matched;
5089}
5090
5091/// Matches all arguments and their respective types for a \c CallExpr or
5092/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
5093/// it works on calls through function pointers as well.
5094///
5095/// The difference is, that function pointers do not provide access to a
5096/// \c ParmVarDecl, but only the \c QualType for each argument.
5097///
5098/// Given
5099/// \code
5100/// void f(int i);
5101/// int y;
5102/// f(y);
5103/// void (*f_ptr)(int) = f;
5104/// f_ptr(y);
5105/// \endcode
5106/// callExpr(
5107/// forEachArgumentWithParamType(
5108/// declRefExpr(to(varDecl(hasName("y")))),
5109/// qualType(isInteger()).bind("type)
5110/// ))
5111/// matches f(y) and f_ptr(y)
5112/// with declRefExpr(...)
5113/// matching int y
5114/// and qualType(...)
5115/// matching int
5116AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
5117 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
5118 CXXConstructExpr),
5119 internal::Matcher<Expr>, ArgMatcher,
5120 internal::Matcher<QualType>, ParamMatcher) {
5121 BoundNodesTreeBuilder Result;
5122 // The first argument of an overloaded member operator is the implicit object
5123 // argument of the method which should not be matched against a parameter, so
5124 // we skip over it here.
5125 BoundNodesTreeBuilder Matches;
5126 unsigned ArgIndex = cxxOperatorCallExpr(callee(InnerMatcher: cxxMethodDecl()))
5127 .matches(Node, Finder, Builder: &Matches)
5128 ? 1
5129 : 0;
5130
5131 const FunctionProtoType *FProto = nullptr;
5132
5133 if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
5134 if (const auto *Value =
5135 dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
5136 QualType QT = Value->getType().getCanonicalType();
5137
5138 // This does not necessarily lead to a `FunctionProtoType`,
5139 // e.g. K&R functions do not have a function prototype.
5140 if (QT->isFunctionPointerType())
5141 FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
5142
5143 if (QT->isMemberFunctionPointerType()) {
5144 const auto *MP = QT->getAs<MemberPointerType>();
5145 assert(MP && "Must be member-pointer if its a memberfunctionpointer");
5146 FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
5147 assert(FProto &&
5148 "The call must have happened through a member function "
5149 "pointer");
5150 }
5151 }
5152 }
5153
5154 unsigned ParamIndex = 0;
5155 bool Matched = false;
5156 unsigned NumArgs = Node.getNumArgs();
5157 if (FProto && FProto->isVariadic())
5158 NumArgs = std::min(a: NumArgs, b: FProto->getNumParams());
5159
5160 for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
5161 BoundNodesTreeBuilder ArgMatches(*Builder);
5162 if (ArgMatcher.matches(Node: *(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
5163 Builder: &ArgMatches)) {
5164 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5165
5166 // This test is cheaper compared to the big matcher in the next if.
5167 // Therefore, please keep this order.
5168 if (FProto && FProto->getNumParams() > ParamIndex) {
5169 QualType ParamType = FProto->getParamType(i: ParamIndex);
5170 if (ParamMatcher.matches(Node: ParamType, Finder, Builder: &ParamMatches)) {
5171 Result.addMatch(Bindings: ParamMatches);
5172 Matched = true;
5173 continue;
5174 }
5175 }
5176 if (expr(anyOf(cxxConstructExpr(hasDeclaration(InnerMatcher: cxxConstructorDecl(
5177 hasParameter(N: ParamIndex, InnerMatcher: hasType(InnerMatcher: ParamMatcher))))),
5178 callExpr(callee(InnerMatcher: functionDecl(
5179 hasParameter(N: ParamIndex, InnerMatcher: hasType(InnerMatcher: ParamMatcher)))))))
5180 .matches(Node, Finder, Builder: &ParamMatches)) {
5181 Result.addMatch(Bindings: ParamMatches);
5182 Matched = true;
5183 continue;
5184 }
5185 }
5186 }
5187 *Builder = std::move(Result);
5188 return Matched;
5189}
5190
5191/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
5192/// list. The parameter list could be that of either a block, function, or
5193/// objc-method.
5194///
5195///
5196/// Given
5197///
5198/// \code
5199/// void f(int a, int b, int c) {
5200/// }
5201/// \endcode
5202///
5203/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
5204///
5205/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
5206AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
5207 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
5208
5209 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
5210 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5211 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
5212 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5213 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
5214 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5215
5216 return false;
5217}
5218
5219/// Matches any parameter of a function or an ObjC method declaration or a
5220/// block.
5221///
5222/// Does not match the 'this' parameter of a method.
5223///
5224/// Given
5225/// \code
5226/// class X { void f(int x, int y, int z) {} };
5227/// \endcode
5228/// cxxMethodDecl(hasAnyParameter(hasName("y")))
5229/// matches f(int x, int y, int z) {}
5230/// with hasAnyParameter(...)
5231/// matching int y
5232///
5233/// For ObjectiveC, given
5234/// \code
5235/// @interface I - (void) f:(int) y; @end
5236/// \endcode
5237//
5238/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5239/// matches the declaration of method f with hasParameter
5240/// matching y.
5241///
5242/// For blocks, given
5243/// \code
5244/// b = ^(int y) { printf("%d", y) };
5245/// \endcode
5246///
5247/// the matcher blockDecl(hasAnyParameter(hasName("y")))
5248/// matches the declaration of the block b with hasParameter
5249/// matching y.
5250AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
5251 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5252 ObjCMethodDecl,
5253 BlockDecl),
5254 internal::Matcher<ParmVarDecl>,
5255 InnerMatcher) {
5256 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5257 Node.param_end(), Finder,
5258 Builder) != Node.param_end();
5259}
5260
5261/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5262/// specific parameter count.
5263///
5264/// Given
5265/// \code
5266/// void f(int i) {}
5267/// void g(int i, int j) {}
5268/// void h(int i, int j);
5269/// void j(int i);
5270/// void k(int x, int y, int z, ...);
5271/// \endcode
5272/// functionDecl(parameterCountIs(2))
5273/// matches \c g and \c h
5274/// functionProtoType(parameterCountIs(2))
5275/// matches \c g and \c h
5276/// functionProtoType(parameterCountIs(3))
5277/// matches \c k
5278AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
5279 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5280 FunctionProtoType),
5281 unsigned, N) {
5282 return Node.getNumParams() == N;
5283}
5284
5285/// Matches classTemplateSpecialization, templateSpecializationType and
5286/// functionDecl nodes where the template argument matches the inner matcher.
5287/// This matcher may produce multiple matches.
5288///
5289/// Given
5290/// \code
5291/// template <typename T, unsigned N, unsigned M>
5292/// struct Matrix {};
5293///
5294/// constexpr unsigned R = 2;
5295/// Matrix<int, R * 2, R * 4> M;
5296///
5297/// template <typename T, typename U>
5298/// void f(T&& t, U&& u) {}
5299///
5300/// bool B = false;
5301/// f(R, B);
5302/// \endcode
5303/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5304/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5305/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5306/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5307/// and 'bool'
5308AST_POLYMORPHIC_MATCHER_P(
5309 forEachTemplateArgument,
5310 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
5311 TemplateSpecializationType, FunctionDecl),
5312 clang::ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
5313 ArrayRef<TemplateArgument> TemplateArgs =
5314 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5315 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5316 bool Matched = false;
5317 for (const auto &Arg : TemplateArgs) {
5318 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5319 if (InnerMatcher.matches(Node: Arg, Finder, Builder: &ArgBuilder)) {
5320 Matched = true;
5321 Result.addMatch(Bindings: ArgBuilder);
5322 }
5323 }
5324 *Builder = std::move(Result);
5325 return Matched;
5326}
5327
5328/// Matches \c FunctionDecls that have a noreturn attribute.
5329///
5330/// Given
5331/// \code
5332/// void nope();
5333/// [[noreturn]] void a();
5334/// __attribute__((noreturn)) void b();
5335/// struct c { [[noreturn]] c(); };
5336/// \endcode
5337/// functionDecl(isNoReturn())
5338/// matches all of those except
5339/// \code
5340/// void nope();
5341/// \endcode
5342AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5343
5344/// Matches the return type of a function declaration.
5345///
5346/// Given:
5347/// \code
5348/// class X { int f() { return 1; } };
5349/// \endcode
5350/// cxxMethodDecl(returns(asString("int")))
5351/// matches int f() { return 1; }
5352AST_MATCHER_P(FunctionDecl, returns,
5353 internal::Matcher<QualType>, InnerMatcher) {
5354 return InnerMatcher.matches(Node: Node.getReturnType(), Finder, Builder);
5355}
5356
5357/// Matches extern "C" function or variable declarations.
5358///
5359/// Given:
5360/// \code
5361/// extern "C" void f() {}
5362/// extern "C" { void g() {} }
5363/// void h() {}
5364/// extern "C" int x = 1;
5365/// extern "C" int y = 2;
5366/// int z = 3;
5367/// \endcode
5368/// functionDecl(isExternC())
5369/// matches the declaration of f and g, but not the declaration of h.
5370/// varDecl(isExternC())
5371/// matches the declaration of x and y, but not the declaration of z.
5372AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5373 VarDecl)) {
5374 return Node.isExternC();
5375}
5376
5377/// Matches variable/function declarations that have "static" storage
5378/// class specifier ("static" keyword) written in the source.
5379///
5380/// Given:
5381/// \code
5382/// static void f() {}
5383/// static int i = 0;
5384/// extern int j;
5385/// int k;
5386/// \endcode
5387/// functionDecl(isStaticStorageClass())
5388/// matches the function declaration f.
5389/// varDecl(isStaticStorageClass())
5390/// matches the variable declaration i.
5391AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5392 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5393 VarDecl)) {
5394 return Node.getStorageClass() == SC_Static;
5395}
5396
5397/// Matches deleted function declarations.
5398///
5399/// Given:
5400/// \code
5401/// void Func();
5402/// void DeletedFunc() = delete;
5403/// \endcode
5404/// functionDecl(isDeleted())
5405/// matches the declaration of DeletedFunc, but not Func.
5406AST_MATCHER(FunctionDecl, isDeleted) {
5407 return Node.isDeleted();
5408}
5409
5410/// Matches defaulted function declarations.
5411///
5412/// Given:
5413/// \code
5414/// class A { ~A(); };
5415/// class B { ~B() = default; };
5416/// \endcode
5417/// functionDecl(isDefaulted())
5418/// matches the declaration of ~B, but not ~A.
5419AST_MATCHER(FunctionDecl, isDefaulted) {
5420 return Node.isDefaulted();
5421}
5422
5423/// Matches weak function declarations.
5424///
5425/// Given:
5426/// \code
5427/// void foo() __attribute__((__weakref__("__foo")));
5428/// void bar();
5429/// \endcode
5430/// functionDecl(isWeak())
5431/// matches the weak declaration "foo", but not "bar".
5432AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5433
5434/// Matches functions that have a dynamic exception specification.
5435///
5436/// Given:
5437/// \code
5438/// void f();
5439/// void g() noexcept;
5440/// void h() noexcept(true);
5441/// void i() noexcept(false);
5442/// void j() throw();
5443/// void k() throw(int);
5444/// void l() throw(...);
5445/// \endcode
5446/// functionDecl(hasDynamicExceptionSpec()) and
5447/// functionProtoType(hasDynamicExceptionSpec())
5448/// match the declarations of j, k, and l, but not f, g, h, or i.
5449AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5450 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5451 FunctionProtoType)) {
5452 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5453 return FnTy->hasDynamicExceptionSpec();
5454 return false;
5455}
5456
5457/// Matches functions that have a non-throwing exception specification.
5458///
5459/// Given:
5460/// \code
5461/// void f();
5462/// void g() noexcept;
5463/// void h() throw();
5464/// void i() throw(int);
5465/// void j() noexcept(false);
5466/// \endcode
5467/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5468/// match the declarations of g, and h, but not f, i or j.
5469AST_POLYMORPHIC_MATCHER(isNoThrow,
5470 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
5471 FunctionProtoType)) {
5472 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5473
5474 // If the function does not have a prototype, then it is assumed to be a
5475 // throwing function (as it would if the function did not have any exception
5476 // specification).
5477 if (!FnTy)
5478 return false;
5479
5480 // Assume the best for any unresolved exception specification.
5481 if (isUnresolvedExceptionSpec(ESpecType: FnTy->getExceptionSpecType()))
5482 return true;
5483
5484 return FnTy->isNothrow();
5485}
5486
5487/// Matches consteval function declarations and if consteval/if ! consteval
5488/// statements.
5489///
5490/// Given:
5491/// \code
5492/// consteval int a();
5493/// void b() { if consteval {} }
5494/// void c() { if ! consteval {} }
5495/// void d() { if ! consteval {} else {} }
5496/// \endcode
5497/// functionDecl(isConsteval())
5498/// matches the declaration of "int a()".
5499/// ifStmt(isConsteval())
5500/// matches the if statement in "void b()", "void c()", "void d()".
5501AST_POLYMORPHIC_MATCHER(isConsteval,
5502 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, IfStmt)) {
5503 return Node.isConsteval();
5504}
5505
5506/// Matches constexpr variable and function declarations,
5507/// and if constexpr.
5508///
5509/// Given:
5510/// \code
5511/// constexpr int foo = 42;
5512/// constexpr int bar();
5513/// void baz() { if constexpr(1 > 0) {} }
5514/// \endcode
5515/// varDecl(isConstexpr())
5516/// matches the declaration of foo.
5517/// functionDecl(isConstexpr())
5518/// matches the declaration of bar.
5519/// ifStmt(isConstexpr())
5520/// matches the if statement in baz.
5521AST_POLYMORPHIC_MATCHER(isConstexpr,
5522 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
5523 FunctionDecl,
5524 IfStmt)) {
5525 return Node.isConstexpr();
5526}
5527
5528/// Matches constinit variable declarations.
5529///
5530/// Given:
5531/// \code
5532/// constinit int foo = 42;
5533/// constinit const char* bar = "bar";
5534/// int baz = 42;
5535/// [[clang::require_constant_initialization]] int xyz = 42;
5536/// \endcode
5537/// varDecl(isConstinit())
5538/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5539AST_MATCHER(VarDecl, isConstinit) {
5540 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5541 return CIA->isConstinit();
5542 return false;
5543}
5544
5545/// Matches selection statements with initializer.
5546///
5547/// Given:
5548/// \code
5549/// void foo() {
5550/// if (int i = foobar(); i > 0) {}
5551/// switch (int i = foobar(); i) {}
5552/// for (auto& a = get_range(); auto& x : a) {}
5553/// }
5554/// void bar() {
5555/// if (foobar() > 0) {}
5556/// switch (foobar()) {}
5557/// for (auto& x : get_range()) {}
5558/// }
5559/// \endcode
5560/// ifStmt(hasInitStatement(anything()))
5561/// matches the if statement in foo but not in bar.
5562/// switchStmt(hasInitStatement(anything()))
5563/// matches the switch statement in foo but not in bar.
5564/// cxxForRangeStmt(hasInitStatement(anything()))
5565/// matches the range for statement in foo but not in bar.
5566AST_POLYMORPHIC_MATCHER_P(hasInitStatement,
5567 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt,
5568 CXXForRangeStmt),
5569 internal::Matcher<Stmt>, InnerMatcher) {
5570 const Stmt *Init = Node.getInit();
5571 return Init != nullptr && InnerMatcher.matches(Node: *Init, Finder, Builder);
5572}
5573
5574/// Matches the condition expression of an if statement, for loop,
5575/// switch statement or conditional operator.
5576///
5577/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5578/// \code
5579/// if (true) {}
5580/// \endcode
5581AST_POLYMORPHIC_MATCHER_P(
5582 hasCondition,
5583 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
5584 SwitchStmt, AbstractConditionalOperator),
5585 internal::Matcher<Expr>, InnerMatcher) {
5586 const Expr *const Condition = Node.getCond();
5587 return (Condition != nullptr &&
5588 InnerMatcher.matches(Node: *Condition, Finder, Builder));
5589}
5590
5591/// Matches the then-statement of an if statement.
5592///
5593/// Examples matches the if statement
5594/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5595/// \code
5596/// if (false) true; else false;
5597/// \endcode
5598AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5599 const Stmt *const Then = Node.getThen();
5600 return (Then != nullptr && InnerMatcher.matches(Node: *Then, Finder, Builder));
5601}
5602
5603/// Matches the else-statement of an if statement.
5604///
5605/// Examples matches the if statement
5606/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5607/// \code
5608/// if (false) false; else true;
5609/// \endcode
5610AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5611 const Stmt *const Else = Node.getElse();
5612 return (Else != nullptr && InnerMatcher.matches(Node: *Else, Finder, Builder));
5613}
5614
5615/// Matches if a node equals a previously bound node.
5616///
5617/// Matches a node if it equals the node previously bound to \p ID.
5618///
5619/// Given
5620/// \code
5621/// class X { int a; int b; };
5622/// \endcode
5623/// cxxRecordDecl(
5624/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5625/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5626/// matches the class \c X, as \c a and \c b have the same type.
5627///
5628/// Note that when multiple matches are involved via \c forEach* matchers,
5629/// \c equalsBoundNodes acts as a filter.
5630/// For example:
5631/// compoundStmt(
5632/// forEachDescendant(varDecl().bind("d")),
5633/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5634/// will trigger a match for each combination of variable declaration
5635/// and reference to that variable declaration within a compound statement.
5636AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
5637 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
5638 QualType),
5639 std::string, ID) {
5640 // FIXME: Figure out whether it makes sense to allow this
5641 // on any other node types.
5642 // For *Loc it probably does not make sense, as those seem
5643 // unique. For NestedNameSepcifier it might make sense, as
5644 // those also have pointer identity, but I'm not sure whether
5645 // they're ever reused.
5646 internal::NotEqualsBoundNodePredicate Predicate;
5647 Predicate.ID = ID;
5648 Predicate.Node = DynTypedNode::create(Node);
5649 return Builder->removeBindings(Predicate);
5650}
5651
5652/// Matches the condition variable statement in an if statement.
5653///
5654/// Given
5655/// \code
5656/// if (A* a = GetAPointer()) {}
5657/// \endcode
5658/// hasConditionVariableStatement(...)
5659/// matches 'A* a = GetAPointer()'.
5660AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5661 internal::Matcher<DeclStmt>, InnerMatcher) {
5662 const DeclStmt* const DeclarationStatement =
5663 Node.getConditionVariableDeclStmt();
5664 return DeclarationStatement != nullptr &&
5665 InnerMatcher.matches(Node: *DeclarationStatement, Finder, Builder);
5666}
5667
5668/// Matches the index expression of an array subscript expression.
5669///
5670/// Given
5671/// \code
5672/// int i[5];
5673/// void f() { i[1] = 42; }
5674/// \endcode
5675/// arraySubscriptExpression(hasIndex(integerLiteral()))
5676/// matches \c i[1] with the \c integerLiteral() matching \c 1
5677AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
5678 internal::Matcher<Expr>, InnerMatcher) {
5679 if (const Expr* Expression = Node.getIdx())
5680 return InnerMatcher.matches(Node: *Expression, Finder, Builder);
5681 return false;
5682}
5683
5684/// Matches the base expression of an array subscript expression.
5685///
5686/// Given
5687/// \code
5688/// int i[5];
5689/// void f() { i[1] = 42; }
5690/// \endcode
5691/// arraySubscriptExpression(hasBase(implicitCastExpr(
5692/// hasSourceExpression(declRefExpr()))))
5693/// matches \c i[1] with the \c declRefExpr() matching \c i
5694AST_MATCHER_P(ArraySubscriptExpr, hasBase,
5695 internal::Matcher<Expr>, InnerMatcher) {
5696 if (const Expr* Expression = Node.getBase())
5697 return InnerMatcher.matches(Node: *Expression, Finder, Builder);
5698 return false;
5699}
5700
5701/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5702/// definition that has a given body. Note that in case of functions or
5703/// coroutines this matcher only matches the definition itself and not the
5704/// other declarations of the same function or coroutine.
5705///
5706/// Given
5707/// \code
5708/// for (;;) {}
5709/// \endcode
5710/// forStmt(hasBody(compoundStmt()))
5711/// matches 'for (;;) {}'
5712/// with compoundStmt()
5713/// matching '{}'
5714///
5715/// Given
5716/// \code
5717/// void f();
5718/// void f() {}
5719/// \endcode
5720/// functionDecl(hasBody(compoundStmt()))
5721/// matches 'void f() {}'
5722/// with compoundStmt()
5723/// matching '{}'
5724/// but does not match 'void f();'
5725AST_POLYMORPHIC_MATCHER_P(
5726 hasBody,
5727 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt, WhileStmt, CXXForRangeStmt,
5728 FunctionDecl, CoroutineBodyStmt),
5729 internal::Matcher<Stmt>, InnerMatcher) {
5730 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5731 return false;
5732 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5733 return (Statement != nullptr &&
5734 InnerMatcher.matches(Node: *Statement, Finder, Builder));
5735}
5736
5737/// Matches a function declaration that has a given body present in the AST.
5738/// Note that this matcher matches all the declarations of a function whose
5739/// body is present in the AST.
5740///
5741/// Given
5742/// \code
5743/// void f();
5744/// void f() {}
5745/// void g();
5746/// \endcode
5747/// functionDecl(hasAnyBody(compoundStmt()))
5748/// matches both 'void f();'
5749/// and 'void f() {}'
5750/// with compoundStmt()
5751/// matching '{}'
5752/// but does not match 'void g();'
5753AST_MATCHER_P(FunctionDecl, hasAnyBody,
5754 internal::Matcher<Stmt>, InnerMatcher) {
5755 const Stmt *const Statement = Node.getBody();
5756 return (Statement != nullptr &&
5757 InnerMatcher.matches(Node: *Statement, Finder, Builder));
5758}
5759
5760
5761/// Matches compound statements where at least one substatement matches
5762/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5763///
5764/// Given
5765/// \code
5766/// { {}; 1+2; }
5767/// \endcode
5768/// hasAnySubstatement(compoundStmt())
5769/// matches '{ {}; 1+2; }'
5770/// with compoundStmt()
5771/// matching '{}'
5772AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5773 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
5774 StmtExpr),
5775 internal::Matcher<Stmt>, InnerMatcher) {
5776 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5777 return CS && matchesFirstInPointerRange(Matcher: InnerMatcher, Start: CS->body_begin(),
5778 End: CS->body_end(), Finder,
5779 Builder) != CS->body_end();
5780}
5781
5782/// Checks that a compound statement contains a specific number of
5783/// child statements.
5784///
5785/// Example: Given
5786/// \code
5787/// { for (;;) {} }
5788/// \endcode
5789/// compoundStmt(statementCountIs(0)))
5790/// matches '{}'
5791/// but does not match the outer compound statement.
5792AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5793 return Node.size() == N;
5794}
5795
5796/// Matches literals that are equal to the given value of type ValueT.
5797///
5798/// Given
5799/// \code
5800/// f('\0', false, 3.14, 42);
5801/// \endcode
5802/// characterLiteral(equals(0))
5803/// matches '\0'
5804/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5805/// match false
5806/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5807/// match 3.14
5808/// integerLiteral(equals(42))
5809/// matches 42
5810///
5811/// Note that you cannot directly match a negative numeric literal because the
5812/// minus sign is not part of the literal: It is a unary operator whose operand
5813/// is the positive numeric literal. Instead, you must use a unaryOperator()
5814/// matcher to match the minus sign:
5815///
5816/// unaryOperator(hasOperatorName("-"),
5817/// hasUnaryOperand(integerLiteral(equals(13))))
5818///
5819/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5820/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5821template <typename ValueT>
5822internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5823 void(internal::AllNodeBaseTypes), ValueT>
5824equals(const ValueT &Value) {
5825 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5826 void(internal::AllNodeBaseTypes), ValueT>(
5827 Value);
5828}
5829
5830AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
5831 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5832 CXXBoolLiteralExpr,
5833 IntegerLiteral),
5834 bool, Value, 0) {
5835 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5836 .matchesNode(Node);
5837}
5838
5839AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
5840 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5841 CXXBoolLiteralExpr,
5842 IntegerLiteral),
5843 unsigned, Value, 1) {
5844 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5845 .matchesNode(Node);
5846}
5847
5848AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
5849 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5850 CXXBoolLiteralExpr,
5851 FloatingLiteral,
5852 IntegerLiteral),
5853 double, Value, 2) {
5854 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5855 .matchesNode(Node);
5856}
5857
5858/// Matches the operator Name of operator expressions and fold expressions
5859/// (binary or unary).
5860///
5861/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5862/// \code
5863/// !(a || b)
5864/// \endcode
5865///
5866/// Example matches `(0 + ... + args)`
5867/// (matcher = cxxFoldExpr(hasOperatorName("+")))
5868/// \code
5869/// template <typename... Args>
5870/// auto sum(Args... args) {
5871/// return (0 + ... + args);
5872/// }
5873/// \endcode
5874AST_POLYMORPHIC_MATCHER_P(
5875 hasOperatorName,
5876 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5877 CXXRewrittenBinaryOperator, CXXFoldExpr,
5878 UnaryOperator),
5879 std::string, Name) {
5880 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5881 return *OpName == Name;
5882 return false;
5883}
5884
5885/// Matches operator expressions (binary or unary) that have any of the
5886/// specified names.
5887///
5888/// hasAnyOperatorName("+", "-")
5889/// Is equivalent to
5890/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5891extern const internal::VariadicFunction<
5892 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5893 AST_POLYMORPHIC_SUPPORTED_TYPES(
5894 BinaryOperator, CXXOperatorCallExpr,
5895 CXXRewrittenBinaryOperator, UnaryOperator),
5896 std::vector<std::string>>,
5897 StringRef, internal::hasAnyOperatorNameFunc>
5898 hasAnyOperatorName;
5899
5900/// Matches all kinds of assignment operators.
5901///
5902/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5903/// \code
5904/// if (a == b)
5905/// a += b;
5906/// \endcode
5907///
5908/// Example 2: matches s1 = s2
5909/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5910/// \code
5911/// struct S { S& operator=(const S&); };
5912/// void x() { S s1, s2; s1 = s2; }
5913/// \endcode
5914AST_POLYMORPHIC_MATCHER(
5915 isAssignmentOperator,
5916 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5917 CXXRewrittenBinaryOperator)) {
5918 return Node.isAssignmentOp();
5919}
5920
5921/// Matches comparison operators.
5922///
5923/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5924/// \code
5925/// if (a == b)
5926/// a += b;
5927/// \endcode
5928///
5929/// Example 2: matches s1 < s2
5930/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5931/// \code
5932/// struct S { bool operator<(const S& other); };
5933/// void x(S s1, S s2) { bool b1 = s1 < s2; }
5934/// \endcode
5935AST_POLYMORPHIC_MATCHER(
5936 isComparisonOperator,
5937 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5938 CXXRewrittenBinaryOperator)) {
5939 return Node.isComparisonOp();
5940}
5941
5942/// Matches the left hand side of binary operator expressions.
5943///
5944/// Example matches a (matcher = binaryOperator(hasLHS()))
5945/// \code
5946/// a || b
5947/// \endcode
5948AST_POLYMORPHIC_MATCHER_P(
5949 hasLHS,
5950 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5951 CXXRewrittenBinaryOperator,
5952 ArraySubscriptExpr, CXXFoldExpr),
5953 internal::Matcher<Expr>, InnerMatcher) {
5954 const Expr *LeftHandSide = internal::getLHS(Node);
5955 return (LeftHandSide != nullptr &&
5956 InnerMatcher.matches(Node: *LeftHandSide, Finder, Builder));
5957}
5958
5959/// Matches the right hand side of binary operator expressions.
5960///
5961/// Example matches b (matcher = binaryOperator(hasRHS()))
5962/// \code
5963/// a || b
5964/// \endcode
5965AST_POLYMORPHIC_MATCHER_P(
5966 hasRHS,
5967 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5968 CXXRewrittenBinaryOperator,
5969 ArraySubscriptExpr, CXXFoldExpr),
5970 internal::Matcher<Expr>, InnerMatcher) {
5971 const Expr *RightHandSide = internal::getRHS(Node);
5972 return (RightHandSide != nullptr &&
5973 InnerMatcher.matches(Node: *RightHandSide, Finder, Builder));
5974}
5975
5976/// Matches if either the left hand side or the right hand side of a
5977/// binary operator or fold expression matches.
5978AST_POLYMORPHIC_MATCHER_P(
5979 hasEitherOperand,
5980 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
5981 CXXFoldExpr, CXXRewrittenBinaryOperator),
5982 internal::Matcher<Expr>, InnerMatcher) {
5983 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5984 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
5985 .matches(Node, Finder, Builder);
5986}
5987
5988/// Matches if both matchers match with opposite sides of the binary operator
5989/// or fold expression.
5990///
5991/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
5992/// integerLiteral(equals(2)))
5993/// \code
5994/// 1 + 2 // Match
5995/// 2 + 1 // Match
5996/// 1 + 1 // No match
5997/// 2 + 2 // No match
5998/// \endcode
5999AST_POLYMORPHIC_MATCHER_P2(
6000 hasOperands,
6001 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6002 CXXFoldExpr, CXXRewrittenBinaryOperator),
6003 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
6004 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6005 anyOf(allOf(hasLHS(InnerMatcher: Matcher1), hasRHS(InnerMatcher: Matcher2)),
6006 allOf(hasLHS(InnerMatcher: Matcher2), hasRHS(InnerMatcher: Matcher1))))
6007 .matches(Node, Finder, Builder);
6008}
6009
6010/// Matches if the operand of a unary operator matches.
6011///
6012/// Example matches true (matcher = hasUnaryOperand(
6013/// cxxBoolLiteral(equals(true))))
6014/// \code
6015/// !true
6016/// \endcode
6017AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,
6018 AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator,
6019 CXXOperatorCallExpr),
6020 internal::Matcher<Expr>, InnerMatcher) {
6021 const Expr *const Operand = internal::getSubExpr(Node);
6022 return (Operand != nullptr &&
6023 InnerMatcher.matches(Node: *Operand, Finder, Builder));
6024}
6025
6026/// Matches if the cast's source expression
6027/// or opaque value's source expression matches the given matcher.
6028///
6029/// Example 1: matches "a string"
6030/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
6031/// \code
6032/// class URL { URL(string); };
6033/// URL url = "a string";
6034/// \endcode
6035///
6036/// Example 2: matches 'b' (matcher =
6037/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
6038/// \code
6039/// int a = b ?: 1;
6040/// \endcode
6041AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
6042 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
6043 OpaqueValueExpr),
6044 internal::Matcher<Expr>, InnerMatcher) {
6045 const Expr *const SubExpression =
6046 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
6047 return (SubExpression != nullptr &&
6048 InnerMatcher.matches(Node: *SubExpression, Finder, Builder));
6049}
6050
6051/// Matches casts that has a given cast kind.
6052///
6053/// Example: matches the implicit cast around \c 0
6054/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
6055/// \code
6056/// int *p = 0;
6057/// \endcode
6058///
6059/// If the matcher is use from clang-query, CastKind parameter
6060/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
6061AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
6062 return Node.getCastKind() == Kind;
6063}
6064
6065/// Matches casts whose destination type matches a given matcher.
6066///
6067/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
6068/// actual casts "explicit" casts.)
6069AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
6070 internal::Matcher<QualType>, InnerMatcher) {
6071 const QualType NodeType = Node.getTypeAsWritten();
6072 return InnerMatcher.matches(Node: NodeType, Finder, Builder);
6073}
6074
6075/// Matches implicit casts whose destination type matches a given
6076/// matcher.
6077AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
6078 internal::Matcher<QualType>, InnerMatcher) {
6079 return InnerMatcher.matches(Node: Node.getType(), Finder, Builder);
6080}
6081
6082/// Matches TagDecl object that are spelled with "struct."
6083///
6084/// Example matches S, but not C, U or E.
6085/// \code
6086/// struct S {};
6087/// class C {};
6088/// union U {};
6089/// enum E {};
6090/// \endcode
6091AST_MATCHER(TagDecl, isStruct) {
6092 return Node.isStruct();
6093}
6094
6095/// Matches TagDecl object that are spelled with "union."
6096///
6097/// Example matches U, but not C, S or E.
6098/// \code
6099/// struct S {};
6100/// class C {};
6101/// union U {};
6102/// enum E {};
6103/// \endcode
6104AST_MATCHER(TagDecl, isUnion) {
6105 return Node.isUnion();
6106}
6107
6108/// Matches TagDecl object that are spelled with "class."
6109///
6110/// Example matches C, but not S, U or E.
6111/// \code
6112/// struct S {};
6113/// class C {};
6114/// union U {};
6115/// enum E {};
6116/// \endcode
6117AST_MATCHER(TagDecl, isClass) {
6118 return Node.isClass();
6119}
6120
6121/// Matches TagDecl object that are spelled with "enum."
6122///
6123/// Example matches E, but not C, S or U.
6124/// \code
6125/// struct S {};
6126/// class C {};
6127/// union U {};
6128/// enum E {};
6129/// \endcode
6130AST_MATCHER(TagDecl, isEnum) {
6131 return Node.isEnum();
6132}
6133
6134/// Matches the true branch expression of a conditional operator.
6135///
6136/// Example 1 (conditional ternary operator): matches a
6137/// \code
6138/// condition ? a : b
6139/// \endcode
6140///
6141/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
6142/// \code
6143/// condition ?: b
6144/// \endcode
6145AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
6146 internal::Matcher<Expr>, InnerMatcher) {
6147 const Expr *Expression = Node.getTrueExpr();
6148 return (Expression != nullptr &&
6149 InnerMatcher.matches(Node: *Expression, Finder, Builder));
6150}
6151
6152/// Matches the false branch expression of a conditional operator
6153/// (binary or ternary).
6154///
6155/// Example matches b
6156/// \code
6157/// condition ? a : b
6158/// condition ?: b
6159/// \endcode
6160AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
6161 internal::Matcher<Expr>, InnerMatcher) {
6162 const Expr *Expression = Node.getFalseExpr();
6163 return (Expression != nullptr &&
6164 InnerMatcher.matches(Node: *Expression, Finder, Builder));
6165}
6166
6167/// Matches if a declaration has a body attached.
6168///
6169/// Example matches A, va, fa
6170/// \code
6171/// class A {};
6172/// class B; // Doesn't match, as it has no body.
6173/// int va;
6174/// extern int vb; // Doesn't match, as it doesn't define the variable.
6175/// void fa() {}
6176/// void fb(); // Doesn't match, as it has no body.
6177/// @interface X
6178/// - (void)ma; // Doesn't match, interface is declaration.
6179/// @end
6180/// @implementation X
6181/// - (void)ma {}
6182/// @end
6183/// \endcode
6184///
6185/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
6186/// Matcher<ObjCMethodDecl>
6187AST_POLYMORPHIC_MATCHER(isDefinition,
6188 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
6189 ObjCMethodDecl,
6190 FunctionDecl)) {
6191 return Node.isThisDeclarationADefinition();
6192}
6193
6194/// Matches if a function declaration is variadic.
6195///
6196/// Example matches f, but not g or h. The function i will not match, even when
6197/// compiled in C mode.
6198/// \code
6199/// void f(...);
6200/// void g(int);
6201/// template <typename... Ts> void h(Ts...);
6202/// void i();
6203/// \endcode
6204AST_MATCHER(FunctionDecl, isVariadic) {
6205 return Node.isVariadic();
6206}
6207
6208/// Matches the class declaration that the given method declaration
6209/// belongs to.
6210///
6211/// FIXME: Generalize this for other kinds of declarations.
6212/// FIXME: What other kind of declarations would we need to generalize
6213/// this to?
6214///
6215/// Example matches A() in the last line
6216/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
6217/// ofClass(hasName("A"))))))
6218/// \code
6219/// class A {
6220/// public:
6221/// A();
6222/// };
6223/// A a = A();
6224/// \endcode
6225AST_MATCHER_P(CXXMethodDecl, ofClass,
6226 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
6227
6228 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
6229
6230 const CXXRecordDecl *Parent = Node.getParent();
6231 return (Parent != nullptr &&
6232 InnerMatcher.matches(Node: *Parent, Finder, Builder));
6233}
6234
6235/// Matches each method overridden by the given method. This matcher may
6236/// produce multiple matches.
6237///
6238/// Given
6239/// \code
6240/// class A { virtual void f(); };
6241/// class B : public A { void f(); };
6242/// class C : public B { void f(); };
6243/// \endcode
6244/// cxxMethodDecl(ofClass(hasName("C")),
6245/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6246/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
6247/// that B::f is not overridden by C::f).
6248///
6249/// The check can produce multiple matches in case of multiple inheritance, e.g.
6250/// \code
6251/// class A1 { virtual void f(); };
6252/// class A2 { virtual void f(); };
6253/// class C : public A1, public A2 { void f(); };
6254/// \endcode
6255/// cxxMethodDecl(ofClass(hasName("C")),
6256/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6257/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
6258/// once with "b" binding "A2::f" and "d" binding "C::f".
6259AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
6260 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
6261 BoundNodesTreeBuilder Result;
6262 bool Matched = false;
6263 for (const auto *Overridden : Node.overridden_methods()) {
6264 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
6265 const bool OverriddenMatched =
6266 InnerMatcher.matches(Node: *Overridden, Finder, Builder: &OverriddenBuilder);
6267 if (OverriddenMatched) {
6268 Matched = true;
6269 Result.addMatch(Bindings: OverriddenBuilder);
6270 }
6271 }
6272 *Builder = std::move(Result);
6273 return Matched;
6274}
6275
6276/// Matches declarations of virtual methods and C++ base specifers that specify
6277/// virtual inheritance.
6278///
6279/// Example:
6280/// \code
6281/// class A {
6282/// public:
6283/// virtual void x(); // matches x
6284/// };
6285/// \endcode
6286///
6287/// Example:
6288/// \code
6289/// class Base {};
6290/// class DirectlyDerived : virtual Base {}; // matches Base
6291/// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
6292/// \endcode
6293///
6294/// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
6295AST_POLYMORPHIC_MATCHER(isVirtual,
6296 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
6297 CXXBaseSpecifier)) {
6298 return Node.isVirtual();
6299}
6300
6301/// Matches if the given method declaration has an explicit "virtual".
6302///
6303/// Given
6304/// \code
6305/// class A {
6306/// public:
6307/// virtual void x();
6308/// };
6309/// class B : public A {
6310/// public:
6311/// void x();
6312/// };
6313/// \endcode
6314/// matches A::x but not B::x
6315AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
6316 return Node.isVirtualAsWritten();
6317}
6318
6319AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
6320 return Node.isInheritingConstructor();
6321}
6322
6323/// Matches if the given method or class declaration is final.
6324///
6325/// Given:
6326/// \code
6327/// class A final {};
6328///
6329/// struct B {
6330/// virtual void f();
6331/// };
6332///
6333/// struct C : B {
6334/// void f() final;
6335/// };
6336/// \endcode
6337/// matches A and C::f, but not B, C, or B::f
6338AST_POLYMORPHIC_MATCHER(isFinal,
6339 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
6340 CXXMethodDecl)) {
6341 return Node.template hasAttr<FinalAttr>();
6342}
6343
6344/// Matches if the given method declaration is pure.
6345///
6346/// Given
6347/// \code
6348/// class A {
6349/// public:
6350/// virtual void x() = 0;
6351/// };
6352/// \endcode
6353/// matches A::x
6354AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPureVirtual(); }
6355
6356/// Matches if the given method declaration is const.
6357///
6358/// Given
6359/// \code
6360/// struct A {
6361/// void foo() const;
6362/// void bar();
6363/// };
6364/// \endcode
6365///
6366/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
6367AST_MATCHER(CXXMethodDecl, isConst) {
6368 return Node.isConst();
6369}
6370
6371/// Matches if the given method declaration declares a copy assignment
6372/// operator.
6373///
6374/// Given
6375/// \code
6376/// struct A {
6377/// A &operator=(const A &);
6378/// A &operator=(A &&);
6379/// };
6380/// \endcode
6381///
6382/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
6383/// the second one.
6384AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
6385 return Node.isCopyAssignmentOperator();
6386}
6387
6388/// Matches if the given method declaration declares a move assignment
6389/// operator.
6390///
6391/// Given
6392/// \code
6393/// struct A {
6394/// A &operator=(const A &);
6395/// A &operator=(A &&);
6396/// };
6397/// \endcode
6398///
6399/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
6400/// the first one.
6401AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
6402 return Node.isMoveAssignmentOperator();
6403}
6404
6405/// Matches if the given method declaration overrides another method.
6406///
6407/// Given
6408/// \code
6409/// class A {
6410/// public:
6411/// virtual void x();
6412/// };
6413/// class B : public A {
6414/// public:
6415/// virtual void x();
6416/// };
6417/// \endcode
6418/// matches B::x
6419AST_MATCHER(CXXMethodDecl, isOverride) {
6420 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
6421}
6422
6423/// Matches method declarations that are user-provided.
6424///
6425/// Given
6426/// \code
6427/// struct S {
6428/// S(); // #1
6429/// S(const S &) = default; // #2
6430/// S(S &&) = delete; // #3
6431/// };
6432/// \endcode
6433/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
6434AST_MATCHER(CXXMethodDecl, isUserProvided) {
6435 return Node.isUserProvided();
6436}
6437
6438/// Matches member expressions that are called with '->' as opposed
6439/// to '.'.
6440///
6441/// Member calls on the implicit this pointer match as called with '->'.
6442///
6443/// Given
6444/// \code
6445/// class Y {
6446/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
6447/// template <class T> void f() { this->f<T>(); f<T>(); }
6448/// int a;
6449/// static int b;
6450/// };
6451/// template <class T>
6452/// class Z {
6453/// void x() { this->m; }
6454/// };
6455/// \endcode
6456/// memberExpr(isArrow())
6457/// matches this->x, x, y.x, a, this->b
6458/// cxxDependentScopeMemberExpr(isArrow())
6459/// matches this->m
6460/// unresolvedMemberExpr(isArrow())
6461/// matches this->f<T>, f<T>
6462AST_POLYMORPHIC_MATCHER(
6463 isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
6464 CXXDependentScopeMemberExpr)) {
6465 return Node.isArrow();
6466}
6467
6468/// Matches QualType nodes that are of integer type.
6469///
6470/// Given
6471/// \code
6472/// void a(int);
6473/// void b(long);
6474/// void c(double);
6475/// \endcode
6476/// functionDecl(hasAnyParameter(hasType(isInteger())))
6477/// matches "a(int)", "b(long)", but not "c(double)".
6478AST_MATCHER(QualType, isInteger) {
6479 return Node->isIntegerType();
6480}
6481
6482/// Matches QualType nodes that are of unsigned integer type.
6483///
6484/// Given
6485/// \code
6486/// void a(int);
6487/// void b(unsigned long);
6488/// void c(double);
6489/// \endcode
6490/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6491/// matches "b(unsigned long)", but not "a(int)" and "c(double)".
6492AST_MATCHER(QualType, isUnsignedInteger) {
6493 return Node->isUnsignedIntegerType();
6494}
6495
6496/// Matches QualType nodes that are of signed integer type.
6497///
6498/// Given
6499/// \code
6500/// void a(int);
6501/// void b(unsigned long);
6502/// void c(double);
6503/// \endcode
6504/// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6505/// matches "a(int)", but not "b(unsigned long)" and "c(double)".
6506AST_MATCHER(QualType, isSignedInteger) {
6507 return Node->isSignedIntegerType();
6508}
6509
6510/// Matches QualType nodes that are of character type.
6511///
6512/// Given
6513/// \code
6514/// void a(char);
6515/// void b(wchar_t);
6516/// void c(double);
6517/// \endcode
6518/// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6519/// matches "a(char)", "b(wchar_t)", but not "c(double)".
6520AST_MATCHER(QualType, isAnyCharacter) {
6521 return Node->isAnyCharacterType();
6522}
6523
6524/// Matches QualType nodes that are of any pointer type; this includes
6525/// the Objective-C object pointer type, which is different despite being
6526/// syntactically similar.
6527///
6528/// Given
6529/// \code
6530/// int *i = nullptr;
6531///
6532/// @interface Foo
6533/// @end
6534/// Foo *f;
6535///
6536/// int j;
6537/// \endcode
6538/// varDecl(hasType(isAnyPointer()))
6539/// matches "int *i" and "Foo *f", but not "int j".
6540AST_MATCHER(QualType, isAnyPointer) {
6541 return Node->isAnyPointerType();
6542}
6543
6544/// Matches QualType nodes that are const-qualified, i.e., that
6545/// include "top-level" const.
6546///
6547/// Given
6548/// \code
6549/// void a(int);
6550/// void b(int const);
6551/// void c(const int);
6552/// void d(const int*);
6553/// void e(int const) {};
6554/// \endcode
6555/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6556/// matches "void b(int const)", "void c(const int)" and
6557/// "void e(int const) {}". It does not match d as there
6558/// is no top-level const on the parameter type "const int *".
6559AST_MATCHER(QualType, isConstQualified) {
6560 return Node.isConstQualified();
6561}
6562
6563/// Matches QualType nodes that are volatile-qualified, i.e., that
6564/// include "top-level" volatile.
6565///
6566/// Given
6567/// \code
6568/// void a(int);
6569/// void b(int volatile);
6570/// void c(volatile int);
6571/// void d(volatile int*);
6572/// void e(int volatile) {};
6573/// \endcode
6574/// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6575/// matches "void b(int volatile)", "void c(volatile int)" and
6576/// "void e(int volatile) {}". It does not match d as there
6577/// is no top-level volatile on the parameter type "volatile int *".
6578AST_MATCHER(QualType, isVolatileQualified) {
6579 return Node.isVolatileQualified();
6580}
6581
6582/// Matches QualType nodes that have local CV-qualifiers attached to
6583/// the node, not hidden within a typedef.
6584///
6585/// Given
6586/// \code
6587/// typedef const int const_int;
6588/// const_int i;
6589/// int *const j;
6590/// int *volatile k;
6591/// int m;
6592/// \endcode
6593/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
6594/// \c i is const-qualified but the qualifier is not local.
6595AST_MATCHER(QualType, hasLocalQualifiers) {
6596 return Node.hasLocalQualifiers();
6597}
6598
6599/// Matches a member expression where the member is matched by a
6600/// given matcher.
6601///
6602/// Given
6603/// \code
6604/// struct { int first, second; } first, second;
6605/// int i(second.first);
6606/// int j(first.second);
6607/// \endcode
6608/// memberExpr(member(hasName("first")))
6609/// matches second.first
6610/// but not first.second (because the member name there is "second").
6611AST_MATCHER_P(MemberExpr, member,
6612 internal::Matcher<ValueDecl>, InnerMatcher) {
6613 return InnerMatcher.matches(Node: *Node.getMemberDecl(), Finder, Builder);
6614}
6615
6616/// Matches a member expression where the object expression is matched by a
6617/// given matcher. Implicit object expressions are included; that is, it matches
6618/// use of implicit `this`.
6619///
6620/// Given
6621/// \code
6622/// struct X {
6623/// int m;
6624/// int f(X x) { x.m; return m; }
6625/// };
6626/// \endcode
6627/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
6628/// matches `x.m`, but not `m`; however,
6629/// memberExpr(hasObjectExpression(hasType(pointsTo(
6630// cxxRecordDecl(hasName("X"))))))
6631/// matches `m` (aka. `this->m`), but not `x.m`.
6632AST_POLYMORPHIC_MATCHER_P(
6633 hasObjectExpression,
6634 AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
6635 CXXDependentScopeMemberExpr),
6636 internal::Matcher<Expr>, InnerMatcher) {
6637 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
6638 if (E->isImplicitAccess())
6639 return false;
6640 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
6641 if (E->isImplicitAccess())
6642 return false;
6643 return InnerMatcher.matches(Node: *Node.getBase(), Finder, Builder);
6644}
6645
6646/// Matches any using shadow declaration.
6647///
6648/// Given
6649/// \code
6650/// namespace X { void b(); }
6651/// using X::b;
6652/// \endcode
6653/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
6654/// matches \code using X::b \endcode
6655AST_MATCHER_P(BaseUsingDecl, hasAnyUsingShadowDecl,
6656 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
6657 return matchesFirstInPointerRange(Matcher: InnerMatcher, Start: Node.shadow_begin(),
6658 End: Node.shadow_end(), Finder,
6659 Builder) != Node.shadow_end();
6660}
6661
6662/// Matches a using shadow declaration where the target declaration is
6663/// matched by the given matcher.
6664///
6665/// Given
6666/// \code
6667/// namespace X { int a; void b(); }
6668/// using X::a;
6669/// using X::b;
6670/// \endcode
6671/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
6672/// matches \code using X::b \endcode
6673/// but not \code using X::a \endcode
6674AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
6675 internal::Matcher<NamedDecl>, InnerMatcher) {
6676 return InnerMatcher.matches(Node: *Node.getTargetDecl(), Finder, Builder);
6677}
6678
6679/// Matches template instantiations of function, class, or static
6680/// member variable template instantiations.
6681///
6682/// Given
6683/// \code
6684/// template <typename T> class X {}; class A {}; X<A> x;
6685/// \endcode
6686/// or
6687/// \code
6688/// template <typename T> class X {}; class A {}; template class X<A>;
6689/// \endcode
6690/// or
6691/// \code
6692/// template <typename T> class X {}; class A {}; extern template class X<A>;
6693/// \endcode
6694/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6695/// matches the template instantiation of X<A>.
6696///
6697/// But given
6698/// \code
6699/// template <typename T> class X {}; class A {};
6700/// template <> class X<A> {}; X<A> x;
6701/// \endcode
6702/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6703/// does not match, as X<A> is an explicit template specialization.
6704///
6705/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6706AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
6707 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
6708 CXXRecordDecl)) {
6709 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
6710 Node.getTemplateSpecializationKind() ==
6711 TSK_ExplicitInstantiationDefinition ||
6712 Node.getTemplateSpecializationKind() ==
6713 TSK_ExplicitInstantiationDeclaration);
6714}
6715
6716/// Matches declarations that are template instantiations or are inside
6717/// template instantiations.
6718///
6719/// Given
6720/// \code
6721/// template<typename T> void A(T t) { T i; }
6722/// A(0);
6723/// A(0U);
6724/// \endcode
6725/// functionDecl(isInstantiated())
6726/// matches 'A(int) {...};' and 'A(unsigned) {...}'.
6727AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
6728 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6729 functionDecl(isTemplateInstantiation())));
6730 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
6731}
6732
6733/// Matches statements inside of a template instantiation.
6734///
6735/// Given
6736/// \code
6737/// int j;
6738/// template<typename T> void A(T t) { T i; j += 42;}
6739/// A(0);
6740/// A(0U);
6741/// \endcode
6742/// declStmt(isInTemplateInstantiation())
6743/// matches 'int i;' and 'unsigned i'.
6744/// unless(stmt(isInTemplateInstantiation()))
6745/// will NOT match j += 42; as it's shared between the template definition and
6746/// instantiation.
6747AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
6748 return stmt(
6749 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6750 functionDecl(isTemplateInstantiation())))));
6751}
6752
6753/// Matches explicit template specializations of function, class, or
6754/// static member variable template instantiations.
6755///
6756/// Given
6757/// \code
6758/// template<typename T> void A(T t) { }
6759/// template<> void A(int N) { }
6760/// \endcode
6761/// functionDecl(isExplicitTemplateSpecialization())
6762/// matches the specialization A<int>().
6763///
6764/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6765AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
6766 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
6767 CXXRecordDecl)) {
6768 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
6769}
6770
6771/// Matches \c TypeLocs for which the given inner
6772/// QualType-matcher matches.
6773AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
6774 internal::Matcher<QualType>, InnerMatcher, 0) {
6775 return internal::BindableMatcher<TypeLoc>(
6776 new internal::TypeLocTypeMatcher(InnerMatcher));
6777}
6778
6779/// Matches `QualifiedTypeLoc`s in the clang AST.
6780///
6781/// Given
6782/// \code
6783/// const int x = 0;
6784/// \endcode
6785/// qualifiedTypeLoc()
6786/// matches `const int`.
6787extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, QualifiedTypeLoc>
6788 qualifiedTypeLoc;
6789
6790/// Matches `QualifiedTypeLoc`s that have an unqualified `TypeLoc` matching
6791/// `InnerMatcher`.
6792///
6793/// Given
6794/// \code
6795/// int* const x;
6796/// const int y;
6797/// \endcode
6798/// qualifiedTypeLoc(hasUnqualifiedLoc(pointerTypeLoc()))
6799/// matches the `TypeLoc` of the variable declaration of `x`, but not `y`.
6800AST_MATCHER_P(QualifiedTypeLoc, hasUnqualifiedLoc, internal::Matcher<TypeLoc>,
6801 InnerMatcher) {
6802 return InnerMatcher.matches(Node: Node.getUnqualifiedLoc(), Finder, Builder);
6803}
6804
6805/// Matches a function declared with the specified return `TypeLoc`.
6806///
6807/// Given
6808/// \code
6809/// int f() { return 5; }
6810/// void g() {}
6811/// \endcode
6812/// functionDecl(hasReturnTypeLoc(loc(asString("int"))))
6813/// matches the declaration of `f`, but not `g`.
6814AST_MATCHER_P(FunctionDecl, hasReturnTypeLoc, internal::Matcher<TypeLoc>,
6815 ReturnMatcher) {
6816 auto Loc = Node.getFunctionTypeLoc();
6817 return Loc && ReturnMatcher.matches(Node: Loc.getReturnLoc(), Finder, Builder);
6818}
6819
6820/// Matches pointer `TypeLoc`s.
6821///
6822/// Given
6823/// \code
6824/// int* x;
6825/// \endcode
6826/// pointerTypeLoc()
6827/// matches `int*`.
6828extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, PointerTypeLoc>
6829 pointerTypeLoc;
6830
6831/// Matches pointer `TypeLoc`s that have a pointee `TypeLoc` matching
6832/// `PointeeMatcher`.
6833///
6834/// Given
6835/// \code
6836/// int* x;
6837/// \endcode
6838/// pointerTypeLoc(hasPointeeLoc(loc(asString("int"))))
6839/// matches `int*`.
6840AST_MATCHER_P(PointerTypeLoc, hasPointeeLoc, internal::Matcher<TypeLoc>,
6841 PointeeMatcher) {
6842 return PointeeMatcher.matches(Node: Node.getPointeeLoc(), Finder, Builder);
6843}
6844
6845/// Matches reference `TypeLoc`s.
6846///
6847/// Given
6848/// \code
6849/// int x = 3;
6850/// int& l = x;
6851/// int&& r = 3;
6852/// \endcode
6853/// referenceTypeLoc()
6854/// matches `int&` and `int&&`.
6855extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ReferenceTypeLoc>
6856 referenceTypeLoc;
6857
6858/// Matches reference `TypeLoc`s that have a referent `TypeLoc` matching
6859/// `ReferentMatcher`.
6860///
6861/// Given
6862/// \code
6863/// int x = 3;
6864/// int& xx = x;
6865/// \endcode
6866/// referenceTypeLoc(hasReferentLoc(loc(asString("int"))))
6867/// matches `int&`.
6868AST_MATCHER_P(ReferenceTypeLoc, hasReferentLoc, internal::Matcher<TypeLoc>,
6869 ReferentMatcher) {
6870 return ReferentMatcher.matches(Node: Node.getPointeeLoc(), Finder, Builder);
6871}
6872
6873/// Matches template specialization `TypeLoc`s.
6874///
6875/// Given
6876/// \code
6877/// template <typename T> class C {};
6878/// C<char> var;
6879/// \endcode
6880/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(typeLoc())))
6881/// matches `C<char> var`.
6882extern const internal::VariadicDynCastAllOfMatcher<
6883 TypeLoc, TemplateSpecializationTypeLoc>
6884 templateSpecializationTypeLoc;
6885
6886/// Matches template specialization `TypeLoc`s that have at least one
6887/// `TemplateArgumentLoc` matching the given `InnerMatcher`.
6888///
6889/// Given
6890/// \code
6891/// template<typename T> class A {};
6892/// A<int> a;
6893/// \endcode
6894/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasAnyTemplateArgumentLoc(
6895/// hasTypeLoc(loc(asString("int")))))))
6896/// matches `A<int> a`.
6897AST_MATCHER_P(TemplateSpecializationTypeLoc, hasAnyTemplateArgumentLoc,
6898 internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
6899 for (unsigned Index = 0, N = Node.getNumArgs(); Index < N; ++Index) {
6900 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
6901 if (InnerMatcher.matches(Node: Node.getArgLoc(i: Index), Finder, Builder: &Result)) {
6902 *Builder = std::move(Result);
6903 return true;
6904 }
6905 }
6906 return false;
6907}
6908
6909/// Matches template specialization `TypeLoc`s where the n'th
6910/// `TemplateArgumentLoc` matches the given `InnerMatcher`.
6911///
6912/// Given
6913/// \code
6914/// template<typename T, typename U> class A {};
6915/// A<double, int> b;
6916/// A<int, double> c;
6917/// \endcode
6918/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasTemplateArgumentLoc(0,
6919/// hasTypeLoc(loc(asString("double")))))))
6920/// matches `A<double, int> b`, but not `A<int, double> c`.
6921AST_POLYMORPHIC_MATCHER_P2(
6922 hasTemplateArgumentLoc,
6923 AST_POLYMORPHIC_SUPPORTED_TYPES(DeclRefExpr, TemplateSpecializationTypeLoc),
6924 unsigned, Index, internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
6925 return internal::MatchTemplateArgLocAt(Node, Index, InnerMatcher, Finder,
6926 Builder);
6927}
6928
6929/// Matches C or C++ elaborated `TypeLoc`s.
6930///
6931/// Given
6932/// \code
6933/// struct s {};
6934/// struct s ss;
6935/// \endcode
6936/// elaboratedTypeLoc()
6937/// matches the `TypeLoc` of the variable declaration of `ss`.
6938extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ElaboratedTypeLoc>
6939 elaboratedTypeLoc;
6940
6941/// Matches elaborated `TypeLoc`s that have a named `TypeLoc` matching
6942/// `InnerMatcher`.
6943///
6944/// Given
6945/// \code
6946/// template <typename T>
6947/// class C {};
6948/// class C<int> c;
6949///
6950/// class D {};
6951/// class D d;
6952/// \endcode
6953/// elaboratedTypeLoc(hasNamedTypeLoc(templateSpecializationTypeLoc()));
6954/// matches the `TypeLoc` of the variable declaration of `c`, but not `d`.
6955AST_MATCHER_P(ElaboratedTypeLoc, hasNamedTypeLoc, internal::Matcher<TypeLoc>,
6956 InnerMatcher) {
6957 return InnerMatcher.matches(Node: Node.getNamedTypeLoc(), Finder, Builder);
6958}
6959
6960/// Matches type \c bool.
6961///
6962/// Given
6963/// \code
6964/// struct S { bool func(); };
6965/// \endcode
6966/// functionDecl(returns(booleanType()))
6967/// matches "bool func();"
6968AST_MATCHER(Type, booleanType) {
6969 return Node.isBooleanType();
6970}
6971
6972/// Matches type \c void.
6973///
6974/// Given
6975/// \code
6976/// struct S { void func(); };
6977/// \endcode
6978/// functionDecl(returns(voidType()))
6979/// matches "void func();"
6980AST_MATCHER(Type, voidType) {
6981 return Node.isVoidType();
6982}
6983
6984template <typename NodeType>
6985using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
6986
6987/// Matches builtin Types.
6988///
6989/// Given
6990/// \code
6991/// struct A {};
6992/// A a;
6993/// int b;
6994/// float c;
6995/// bool d;
6996/// \endcode
6997/// builtinType()
6998/// matches "int b", "float c" and "bool d"
6999extern const AstTypeMatcher<BuiltinType> builtinType;
7000
7001/// Matches all kinds of arrays.
7002///
7003/// Given
7004/// \code
7005/// int a[] = { 2, 3 };
7006/// int b[4];
7007/// void f() { int c[a[0]]; }
7008/// \endcode
7009/// arrayType()
7010/// matches "int a[]", "int b[4]" and "int c[a[0]]";
7011extern const AstTypeMatcher<ArrayType> arrayType;
7012
7013/// Matches C99 complex types.
7014///
7015/// Given
7016/// \code
7017/// _Complex float f;
7018/// \endcode
7019/// complexType()
7020/// matches "_Complex float f"
7021extern const AstTypeMatcher<ComplexType> complexType;
7022
7023/// Matches any real floating-point type (float, double, long double).
7024///
7025/// Given
7026/// \code
7027/// int i;
7028/// float f;
7029/// \endcode
7030/// realFloatingPointType()
7031/// matches "float f" but not "int i"
7032AST_MATCHER(Type, realFloatingPointType) {
7033 return Node.isRealFloatingType();
7034}
7035
7036/// Matches arrays and C99 complex types that have a specific element
7037/// type.
7038///
7039/// Given
7040/// \code
7041/// struct A {};
7042/// A a[7];
7043/// int b[7];
7044/// \endcode
7045/// arrayType(hasElementType(builtinType()))
7046/// matches "int b[7]"
7047///
7048/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
7049AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
7050 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
7051 ComplexType));
7052
7053/// Matches C arrays with a specified constant size.
7054///
7055/// Given
7056/// \code
7057/// void() {
7058/// int a[2];
7059/// int b[] = { 2, 3 };
7060/// int c[b[0]];
7061/// }
7062/// \endcode
7063/// constantArrayType()
7064/// matches "int a[2]"
7065extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
7066
7067/// Matches nodes that have the specified size.
7068///
7069/// Given
7070/// \code
7071/// int a[42];
7072/// int b[2 * 21];
7073/// int c[41], d[43];
7074/// char *s = "abcd";
7075/// wchar_t *ws = L"abcd";
7076/// char *w = "a";
7077/// \endcode
7078/// constantArrayType(hasSize(42))
7079/// matches "int a[42]" and "int b[2 * 21]"
7080/// stringLiteral(hasSize(4))
7081/// matches "abcd", L"abcd"
7082AST_POLYMORPHIC_MATCHER_P(hasSize,
7083 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
7084 StringLiteral),
7085 unsigned, N) {
7086 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
7087}
7088
7089/// Matches C++ arrays whose size is a value-dependent expression.
7090///
7091/// Given
7092/// \code
7093/// template<typename T, int Size>
7094/// class array {
7095/// T data[Size];
7096/// };
7097/// \endcode
7098/// dependentSizedArrayType()
7099/// matches "T data[Size]"
7100extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
7101
7102/// Matches C++ extended vector type where either the type or size is
7103/// dependent.
7104///
7105/// Given
7106/// \code
7107/// template<typename T, int Size>
7108/// class vector {
7109/// typedef T __attribute__((ext_vector_type(Size))) type;
7110/// };
7111/// \endcode
7112/// dependentSizedExtVectorType()
7113/// matches "T __attribute__((ext_vector_type(Size)))"
7114extern const AstTypeMatcher<DependentSizedExtVectorType>
7115 dependentSizedExtVectorType;
7116
7117/// Matches C arrays with unspecified size.
7118///
7119/// Given
7120/// \code
7121/// int a[] = { 2, 3 };
7122/// int b[42];
7123/// void f(int c[]) { int d[a[0]]; };
7124/// \endcode
7125/// incompleteArrayType()
7126/// matches "int a[]" and "int c[]"
7127extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
7128
7129/// Matches C arrays with a specified size that is not an
7130/// integer-constant-expression.
7131///
7132/// Given
7133/// \code
7134/// void f() {
7135/// int a[] = { 2, 3 }
7136/// int b[42];
7137/// int c[a[0]];
7138/// }
7139/// \endcode
7140/// variableArrayType()
7141/// matches "int c[a[0]]"
7142extern const AstTypeMatcher<VariableArrayType> variableArrayType;
7143
7144/// Matches \c VariableArrayType nodes that have a specific size
7145/// expression.
7146///
7147/// Given
7148/// \code
7149/// void f(int b) {
7150/// int a[b];
7151/// }
7152/// \endcode
7153/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
7154/// varDecl(hasName("b")))))))
7155/// matches "int a[b]"
7156AST_MATCHER_P(VariableArrayType, hasSizeExpr,
7157 internal::Matcher<Expr>, InnerMatcher) {
7158 return InnerMatcher.matches(Node: *Node.getSizeExpr(), Finder, Builder);
7159}
7160
7161/// Matches atomic types.
7162///
7163/// Given
7164/// \code
7165/// _Atomic(int) i;
7166/// \endcode
7167/// atomicType()
7168/// matches "_Atomic(int) i"
7169extern const AstTypeMatcher<AtomicType> atomicType;
7170
7171/// Matches atomic types with a specific value type.
7172///
7173/// Given
7174/// \code
7175/// _Atomic(int) i;
7176/// _Atomic(float) f;
7177/// \endcode
7178/// atomicType(hasValueType(isInteger()))
7179/// matches "_Atomic(int) i"
7180///
7181/// Usable as: Matcher<AtomicType>
7182AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
7183 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
7184
7185/// Matches types nodes representing C++11 auto types.
7186///
7187/// Given:
7188/// \code
7189/// auto n = 4;
7190/// int v[] = { 2, 3 }
7191/// for (auto i : v) { }
7192/// \endcode
7193/// autoType()
7194/// matches "auto n" and "auto i"
7195extern const AstTypeMatcher<AutoType> autoType;
7196
7197/// Matches types nodes representing C++11 decltype(<expr>) types.
7198///
7199/// Given:
7200/// \code
7201/// short i = 1;
7202/// int j = 42;
7203/// decltype(i + j) result = i + j;
7204/// \endcode
7205/// decltypeType()
7206/// matches "decltype(i + j)"
7207extern const AstTypeMatcher<DecltypeType> decltypeType;
7208
7209/// Matches \c AutoType nodes where the deduced type is a specific type.
7210///
7211/// Note: There is no \c TypeLoc for the deduced type and thus no
7212/// \c getDeducedLoc() matcher.
7213///
7214/// Given
7215/// \code
7216/// auto a = 1;
7217/// auto b = 2.0;
7218/// \endcode
7219/// autoType(hasDeducedType(isInteger()))
7220/// matches "auto a"
7221///
7222/// Usable as: Matcher<AutoType>
7223AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
7224 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
7225
7226/// Matches \c DecltypeType or \c UsingType nodes to find the underlying type.
7227///
7228/// Given
7229/// \code
7230/// decltype(1) a = 1;
7231/// decltype(2.0) b = 2.0;
7232/// \endcode
7233/// decltypeType(hasUnderlyingType(isInteger()))
7234/// matches the type of "a"
7235///
7236/// Usable as: Matcher<DecltypeType>, Matcher<UsingType>
7237AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
7238 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType,
7239 UsingType));
7240
7241/// Matches \c FunctionType nodes.
7242///
7243/// Given
7244/// \code
7245/// int (*f)(int);
7246/// void g();
7247/// \endcode
7248/// functionType()
7249/// matches "int (*f)(int)" and the type of "g".
7250extern const AstTypeMatcher<FunctionType> functionType;
7251
7252/// Matches \c FunctionProtoType nodes.
7253///
7254/// Given
7255/// \code
7256/// int (*f)(int);
7257/// void g();
7258/// \endcode
7259/// functionProtoType()
7260/// matches "int (*f)(int)" and the type of "g" in C++ mode.
7261/// In C mode, "g" is not matched because it does not contain a prototype.
7262extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
7263
7264/// Matches \c ParenType nodes.
7265///
7266/// Given
7267/// \code
7268/// int (*ptr_to_array)[4];
7269/// int *array_of_ptrs[4];
7270/// \endcode
7271///
7272/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
7273/// \c array_of_ptrs.
7274extern const AstTypeMatcher<ParenType> parenType;
7275
7276/// Matches \c ParenType nodes where the inner type is a specific type.
7277///
7278/// Given
7279/// \code
7280/// int (*ptr_to_array)[4];
7281/// int (*ptr_to_func)(int);
7282/// \endcode
7283///
7284/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
7285/// \c ptr_to_func but not \c ptr_to_array.
7286///
7287/// Usable as: Matcher<ParenType>
7288AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
7289 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
7290
7291/// Matches block pointer types, i.e. types syntactically represented as
7292/// "void (^)(int)".
7293///
7294/// The \c pointee is always required to be a \c FunctionType.
7295extern const AstTypeMatcher<BlockPointerType> blockPointerType;
7296
7297/// Matches member pointer types.
7298/// Given
7299/// \code
7300/// struct A { int i; }
7301/// A::* ptr = A::i;
7302/// \endcode
7303/// memberPointerType()
7304/// matches "A::* ptr"
7305extern const AstTypeMatcher<MemberPointerType> memberPointerType;
7306
7307/// Matches pointer types, but does not match Objective-C object pointer
7308/// types.
7309///
7310/// Given
7311/// \code
7312/// int *a;
7313/// int &b = *a;
7314/// int c = 5;
7315///
7316/// @interface Foo
7317/// @end
7318/// Foo *f;
7319/// \endcode
7320/// pointerType()
7321/// matches "int *a", but does not match "Foo *f".
7322extern const AstTypeMatcher<PointerType> pointerType;
7323
7324/// Matches an Objective-C object pointer type, which is different from
7325/// a pointer type, despite being syntactically similar.
7326///
7327/// Given
7328/// \code
7329/// int *a;
7330///
7331/// @interface Foo
7332/// @end
7333/// Foo *f;
7334/// \endcode
7335/// pointerType()
7336/// matches "Foo *f", but does not match "int *a".
7337extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
7338
7339/// Matches both lvalue and rvalue reference types.
7340///
7341/// Given
7342/// \code
7343/// int *a;
7344/// int &b = *a;
7345/// int &&c = 1;
7346/// auto &d = b;
7347/// auto &&e = c;
7348/// auto &&f = 2;
7349/// int g = 5;
7350/// \endcode
7351///
7352/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
7353extern const AstTypeMatcher<ReferenceType> referenceType;
7354
7355/// Matches lvalue reference types.
7356///
7357/// Given:
7358/// \code
7359/// int *a;
7360/// int &b = *a;
7361/// int &&c = 1;
7362/// auto &d = b;
7363/// auto &&e = c;
7364/// auto &&f = 2;
7365/// int g = 5;
7366/// \endcode
7367///
7368/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
7369/// matched since the type is deduced as int& by reference collapsing rules.
7370extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
7371
7372/// Matches rvalue reference types.
7373///
7374/// Given:
7375/// \code
7376/// int *a;
7377/// int &b = *a;
7378/// int &&c = 1;
7379/// auto &d = b;
7380/// auto &&e = c;
7381/// auto &&f = 2;
7382/// int g = 5;
7383/// \endcode
7384///
7385/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
7386/// matched as it is deduced to int& by reference collapsing rules.
7387extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
7388
7389/// Narrows PointerType (and similar) matchers to those where the
7390/// \c pointee matches a given matcher.
7391///
7392/// Given
7393/// \code
7394/// int *a;
7395/// int const *b;
7396/// float const *f;
7397/// \endcode
7398/// pointerType(pointee(isConstQualified(), isInteger()))
7399/// matches "int const *b"
7400///
7401/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
7402/// Matcher<PointerType>, Matcher<ReferenceType>
7403AST_TYPELOC_TRAVERSE_MATCHER_DECL(
7404 pointee, getPointee,
7405 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
7406 PointerType, ReferenceType));
7407
7408/// Matches typedef types.
7409///
7410/// Given
7411/// \code
7412/// typedef int X;
7413/// \endcode
7414/// typedefType()
7415/// matches "typedef int X"
7416extern const AstTypeMatcher<TypedefType> typedefType;
7417
7418/// Matches qualified types when the qualifier is applied via a macro.
7419///
7420/// Given
7421/// \code
7422/// #define CDECL __attribute__((cdecl))
7423/// typedef void (CDECL *X)();
7424/// typedef void (__attribute__((cdecl)) *Y)();
7425/// \endcode
7426/// macroQualifiedType()
7427/// matches the type of the typedef declaration of \c X but not \c Y.
7428extern const AstTypeMatcher<MacroQualifiedType> macroQualifiedType;
7429
7430/// Matches enum types.
7431///
7432/// Given
7433/// \code
7434/// enum C { Green };
7435/// enum class S { Red };
7436///
7437/// C c;
7438/// S s;
7439/// \endcode
7440//
7441/// \c enumType() matches the type of the variable declarations of both \c c and
7442/// \c s.
7443extern const AstTypeMatcher<EnumType> enumType;
7444
7445/// Matches template specialization types.
7446///
7447/// Given
7448/// \code
7449/// template <typename T>
7450/// class C { };
7451///
7452/// template class C<int>; // A
7453/// C<char> var; // B
7454/// \endcode
7455///
7456/// \c templateSpecializationType() matches the type of the explicit
7457/// instantiation in \c A and the type of the variable declaration in \c B.
7458extern const AstTypeMatcher<TemplateSpecializationType>
7459 templateSpecializationType;
7460
7461/// Matches C++17 deduced template specialization types, e.g. deduced class
7462/// template types.
7463///
7464/// Given
7465/// \code
7466/// template <typename T>
7467/// class C { public: C(T); };
7468///
7469/// C c(123);
7470/// \endcode
7471/// \c deducedTemplateSpecializationType() matches the type in the declaration
7472/// of the variable \c c.
7473extern const AstTypeMatcher<DeducedTemplateSpecializationType>
7474 deducedTemplateSpecializationType;
7475
7476/// Matches types nodes representing unary type transformations.
7477///
7478/// Given:
7479/// \code
7480/// typedef __underlying_type(T) type;
7481/// \endcode
7482/// unaryTransformType()
7483/// matches "__underlying_type(T)"
7484extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
7485
7486/// Matches record types (e.g. structs, classes).
7487///
7488/// Given
7489/// \code
7490/// class C {};
7491/// struct S {};
7492///
7493/// C c;
7494/// S s;
7495/// \endcode
7496///
7497/// \c recordType() matches the type of the variable declarations of both \c c
7498/// and \c s.
7499extern const AstTypeMatcher<RecordType> recordType;
7500
7501/// Matches tag types (record and enum types).
7502///
7503/// Given
7504/// \code
7505/// enum E {};
7506/// class C {};
7507///
7508/// E e;
7509/// C c;
7510/// \endcode
7511///
7512/// \c tagType() matches the type of the variable declarations of both \c e
7513/// and \c c.
7514extern const AstTypeMatcher<TagType> tagType;
7515
7516/// Matches types specified with an elaborated type keyword or with a
7517/// qualified name.
7518///
7519/// Given
7520/// \code
7521/// namespace N {
7522/// namespace M {
7523/// class D {};
7524/// }
7525/// }
7526/// class C {};
7527///
7528/// class C c;
7529/// N::M::D d;
7530/// \endcode
7531///
7532/// \c elaboratedType() matches the type of the variable declarations of both
7533/// \c c and \c d.
7534extern const AstTypeMatcher<ElaboratedType> elaboratedType;
7535
7536/// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
7537/// matches \c InnerMatcher if the qualifier exists.
7538///
7539/// Given
7540/// \code
7541/// namespace N {
7542/// namespace M {
7543/// class D {};
7544/// }
7545/// }
7546/// N::M::D d;
7547/// \endcode
7548///
7549/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
7550/// matches the type of the variable declaration of \c d.
7551AST_MATCHER_P(ElaboratedType, hasQualifier,
7552 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
7553 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
7554 return InnerMatcher.matches(Node: *Qualifier, Finder, Builder);
7555
7556 return false;
7557}
7558
7559/// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
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(namesType(recordType(
7572/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
7573/// declaration of \c d.
7574AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
7575 InnerMatcher) {
7576 return InnerMatcher.matches(Node: Node.getNamedType(), Finder, Builder);
7577}
7578
7579/// Matches types specified through a using declaration.
7580///
7581/// Given
7582/// \code
7583/// namespace a { struct S {}; }
7584/// using a::S;
7585/// S s;
7586/// \endcode
7587///
7588/// \c usingType() matches the type of the variable declaration of \c s.
7589extern const AstTypeMatcher<UsingType> usingType;
7590
7591/// Matches types that represent the result of substituting a type for a
7592/// template type parameter.
7593///
7594/// Given
7595/// \code
7596/// template <typename T>
7597/// void F(T t) {
7598/// int i = 1 + t;
7599/// }
7600/// \endcode
7601///
7602/// \c substTemplateTypeParmType() matches the type of 't' but not '1'
7603extern const AstTypeMatcher<SubstTemplateTypeParmType>
7604 substTemplateTypeParmType;
7605
7606/// Matches template type parameter substitutions that have a replacement
7607/// type that matches the provided matcher.
7608///
7609/// Given
7610/// \code
7611/// template <typename T>
7612/// double F(T t);
7613/// int i;
7614/// double j = F(i);
7615/// \endcode
7616///
7617/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
7618AST_TYPE_TRAVERSE_MATCHER(
7619 hasReplacementType, getReplacementType,
7620 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
7621
7622/// Matches template type parameter types.
7623///
7624/// Example matches T, but not int.
7625/// (matcher = templateTypeParmType())
7626/// \code
7627/// template <typename T> void f(int i);
7628/// \endcode
7629extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
7630
7631/// Matches injected class name types.
7632///
7633/// Example matches S s, but not S<T> s.
7634/// (matcher = parmVarDecl(hasType(injectedClassNameType())))
7635/// \code
7636/// template <typename T> struct S {
7637/// void f(S s);
7638/// void g(S<T> s);
7639/// };
7640/// \endcode
7641extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
7642
7643/// Matches decayed type
7644/// Example matches i[] in declaration of f.
7645/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
7646/// Example matches i[1].
7647/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
7648/// \code
7649/// void f(int i[]) {
7650/// i[1] = 0;
7651/// }
7652/// \endcode
7653extern const AstTypeMatcher<DecayedType> decayedType;
7654
7655/// Matches the decayed type, whoes decayed type matches \c InnerMatcher
7656AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
7657 InnerType) {
7658 return InnerType.matches(Node: Node.getDecayedType(), Finder, Builder);
7659}
7660
7661/// Matches declarations whose declaration context, interpreted as a
7662/// Decl, matches \c InnerMatcher.
7663///
7664/// Given
7665/// \code
7666/// namespace N {
7667/// namespace M {
7668/// class D {};
7669/// }
7670/// }
7671/// \endcode
7672///
7673/// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
7674/// declaration of \c class \c D.
7675AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
7676 const DeclContext *DC = Node.getDeclContext();
7677 if (!DC) return false;
7678 return InnerMatcher.matches(Node: *Decl::castFromDeclContext(DC), Finder, Builder);
7679}
7680
7681/// Matches nested name specifiers.
7682///
7683/// Given
7684/// \code
7685/// namespace ns {
7686/// struct A { static void f(); };
7687/// void A::f() {}
7688/// void g() { A::f(); }
7689/// }
7690/// ns::A a;
7691/// \endcode
7692/// nestedNameSpecifier()
7693/// matches "ns::" and both "A::"
7694extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
7695 nestedNameSpecifier;
7696
7697/// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
7698extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
7699 nestedNameSpecifierLoc;
7700
7701/// Matches \c NestedNameSpecifierLocs for which the given inner
7702/// NestedNameSpecifier-matcher matches.
7703AST_MATCHER_FUNCTION_P_OVERLOAD(
7704 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
7705 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
7706 return internal::BindableMatcher<NestedNameSpecifierLoc>(
7707 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
7708 InnerMatcher));
7709}
7710
7711/// Matches nested name specifiers that specify a type matching the
7712/// given \c QualType matcher without qualifiers.
7713///
7714/// Given
7715/// \code
7716/// struct A { struct B { struct C {}; }; };
7717/// A::B::C c;
7718/// \endcode
7719/// nestedNameSpecifier(specifiesType(
7720/// hasDeclaration(cxxRecordDecl(hasName("A")))
7721/// ))
7722/// matches "A::"
7723AST_MATCHER_P(NestedNameSpecifier, specifiesType,
7724 internal::Matcher<QualType>, InnerMatcher) {
7725 if (!Node.getAsType())
7726 return false;
7727 return InnerMatcher.matches(Node: QualType(Node.getAsType(), 0), Finder, Builder);
7728}
7729
7730/// Matches nested name specifier locs that specify a type matching the
7731/// given \c TypeLoc.
7732///
7733/// Given
7734/// \code
7735/// struct A { struct B { struct C {}; }; };
7736/// A::B::C c;
7737/// \endcode
7738/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
7739/// hasDeclaration(cxxRecordDecl(hasName("A")))))))
7740/// matches "A::"
7741AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
7742 internal::Matcher<TypeLoc>, InnerMatcher) {
7743 return Node && Node.getNestedNameSpecifier()->getAsType() &&
7744 InnerMatcher.matches(Node: Node.getTypeLoc(), Finder, Builder);
7745}
7746
7747/// Matches on the prefix of a \c NestedNameSpecifier.
7748///
7749/// Given
7750/// \code
7751/// struct A { struct B { struct C {}; }; };
7752/// A::B::C c;
7753/// \endcode
7754/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
7755/// matches "A::"
7756AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
7757 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
7758 0) {
7759 const NestedNameSpecifier *NextNode = Node.getPrefix();
7760 if (!NextNode)
7761 return false;
7762 return InnerMatcher.matches(Node: *NextNode, Finder, Builder);
7763}
7764
7765/// Matches on the prefix of a \c NestedNameSpecifierLoc.
7766///
7767/// Given
7768/// \code
7769/// struct A { struct B { struct C {}; }; };
7770/// A::B::C c;
7771/// \endcode
7772/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
7773/// matches "A::"
7774AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
7775 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
7776 1) {
7777 NestedNameSpecifierLoc NextNode = Node.getPrefix();
7778 if (!NextNode)
7779 return false;
7780 return InnerMatcher.matches(Node: NextNode, Finder, Builder);
7781}
7782
7783/// Matches nested name specifiers that specify a namespace matching the
7784/// given namespace matcher.
7785///
7786/// Given
7787/// \code
7788/// namespace ns { struct A {}; }
7789/// ns::A a;
7790/// \endcode
7791/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
7792/// matches "ns::"
7793AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
7794 internal::Matcher<NamespaceDecl>, InnerMatcher) {
7795 if (!Node.getAsNamespace())
7796 return false;
7797 return InnerMatcher.matches(Node: *Node.getAsNamespace(), Finder, Builder);
7798}
7799
7800/// Matches attributes.
7801/// Attributes may be attached with a variety of different syntaxes (including
7802/// keywords, C++11 attributes, GNU ``__attribute``` and MSVC `__declspec``,
7803/// and ``#pragma``s). They may also be implicit.
7804///
7805/// Given
7806/// \code
7807/// struct [[nodiscard]] Foo{};
7808/// void bar(int * __attribute__((nonnull)) );
7809/// __declspec(noinline) void baz();
7810///
7811/// #pragma omp declare simd
7812/// int min();
7813/// \endcode
7814/// attr()
7815/// matches "nodiscard", "nonnull", "noinline", and the whole "#pragma" line.
7816extern const internal::VariadicAllOfMatcher<Attr> attr;
7817
7818/// Overloads for the \c equalsNode matcher.
7819/// FIXME: Implement for other node types.
7820/// @{
7821
7822/// Matches if a node equals another node.
7823///
7824/// \c Decl has pointer identity in the AST.
7825AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
7826 return &Node == Other;
7827}
7828/// Matches if a node equals another node.
7829///
7830/// \c Stmt has pointer identity in the AST.
7831AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
7832 return &Node == Other;
7833}
7834/// Matches if a node equals another node.
7835///
7836/// \c Type has pointer identity in the AST.
7837AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
7838 return &Node == Other;
7839}
7840
7841/// @}
7842
7843/// Matches each case or default statement belonging to the given switch
7844/// statement. This matcher may produce multiple matches.
7845///
7846/// Given
7847/// \code
7848/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
7849/// \endcode
7850/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
7851/// matches four times, with "c" binding each of "case 1:", "case 2:",
7852/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
7853/// "switch (1)", "switch (2)" and "switch (2)".
7854AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
7855 InnerMatcher) {
7856 BoundNodesTreeBuilder Result;
7857 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
7858 // iteration order. We should use the more general iterating matchers once
7859 // they are capable of expressing this matcher (for example, it should ignore
7860 // case statements belonging to nested switch statements).
7861 bool Matched = false;
7862 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
7863 SC = SC->getNextSwitchCase()) {
7864 BoundNodesTreeBuilder CaseBuilder(*Builder);
7865 bool CaseMatched = InnerMatcher.matches(Node: *SC, Finder, Builder: &CaseBuilder);
7866 if (CaseMatched) {
7867 Matched = true;
7868 Result.addMatch(Bindings: CaseBuilder);
7869 }
7870 }
7871 *Builder = std::move(Result);
7872 return Matched;
7873}
7874
7875/// Matches each constructor initializer in a constructor definition.
7876///
7877/// Given
7878/// \code
7879/// class A { A() : i(42), j(42) {} int i; int j; };
7880/// \endcode
7881/// cxxConstructorDecl(forEachConstructorInitializer(
7882/// forField(decl().bind("x"))
7883/// ))
7884/// will trigger two matches, binding for 'i' and 'j' respectively.
7885AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
7886 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
7887 BoundNodesTreeBuilder Result;
7888 bool Matched = false;
7889 for (const auto *I : Node.inits()) {
7890 if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
7891 continue;
7892 BoundNodesTreeBuilder InitBuilder(*Builder);
7893 if (InnerMatcher.matches(Node: *I, Finder, Builder: &InitBuilder)) {
7894 Matched = true;
7895 Result.addMatch(Bindings: InitBuilder);
7896 }
7897 }
7898 *Builder = std::move(Result);
7899 return Matched;
7900}
7901
7902/// Matches constructor declarations that are copy constructors.
7903///
7904/// Given
7905/// \code
7906/// struct S {
7907/// S(); // #1
7908/// S(const S &); // #2
7909/// S(S &&); // #3
7910/// };
7911/// \endcode
7912/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
7913AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
7914 return Node.isCopyConstructor();
7915}
7916
7917/// Matches constructor declarations that are move constructors.
7918///
7919/// Given
7920/// \code
7921/// struct S {
7922/// S(); // #1
7923/// S(const S &); // #2
7924/// S(S &&); // #3
7925/// };
7926/// \endcode
7927/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
7928AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
7929 return Node.isMoveConstructor();
7930}
7931
7932/// Matches constructor declarations that are default constructors.
7933///
7934/// Given
7935/// \code
7936/// struct S {
7937/// S(); // #1
7938/// S(const S &); // #2
7939/// S(S &&); // #3
7940/// };
7941/// \endcode
7942/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
7943AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
7944 return Node.isDefaultConstructor();
7945}
7946
7947/// Matches constructors that delegate to another constructor.
7948///
7949/// Given
7950/// \code
7951/// struct S {
7952/// S(); // #1
7953/// S(int) {} // #2
7954/// S(S &&) : S() {} // #3
7955/// };
7956/// S::S() : S(0) {} // #4
7957/// \endcode
7958/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
7959/// #1 or #2.
7960AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
7961 return Node.isDelegatingConstructor();
7962}
7963
7964/// Matches constructor, conversion function, and deduction guide declarations
7965/// that have an explicit specifier if this explicit specifier is resolved to
7966/// true.
7967///
7968/// Given
7969/// \code
7970/// template<bool b>
7971/// struct S {
7972/// S(int); // #1
7973/// explicit S(double); // #2
7974/// operator int(); // #3
7975/// explicit operator bool(); // #4
7976/// explicit(false) S(bool) // # 7
7977/// explicit(true) S(char) // # 8
7978/// explicit(b) S(S) // # 9
7979/// };
7980/// S(int) -> S<true> // #5
7981/// explicit S(double) -> S<false> // #6
7982/// \endcode
7983/// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
7984/// cxxConversionDecl(isExplicit()) will match #4, but not #3.
7985/// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
7986AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
7987 CXXConstructorDecl, CXXConversionDecl,
7988 CXXDeductionGuideDecl)) {
7989 return Node.isExplicit();
7990}
7991
7992/// Matches the expression in an explicit specifier if present in the given
7993/// declaration.
7994///
7995/// Given
7996/// \code
7997/// template<bool b>
7998/// struct S {
7999/// S(int); // #1
8000/// explicit S(double); // #2
8001/// operator int(); // #3
8002/// explicit operator bool(); // #4
8003/// explicit(false) S(bool) // # 7
8004/// explicit(true) S(char) // # 8
8005/// explicit(b) S(S) // # 9
8006/// };
8007/// S(int) -> S<true> // #5
8008/// explicit S(double) -> S<false> // #6
8009/// \endcode
8010/// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
8011/// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
8012/// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
8013AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
8014 InnerMatcher) {
8015 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: &Node);
8016 if (!ES.getExpr())
8017 return false;
8018
8019 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
8020
8021 return InnerMatcher.matches(Node: *ES.getExpr(), Finder, Builder);
8022}
8023
8024/// Matches functions, variables and namespace declarations that are marked with
8025/// the inline keyword.
8026///
8027/// Given
8028/// \code
8029/// inline void f();
8030/// void g();
8031/// namespace n {
8032/// inline namespace m {}
8033/// }
8034/// inline int Foo = 5;
8035/// \endcode
8036/// functionDecl(isInline()) will match ::f().
8037/// namespaceDecl(isInline()) will match n::m.
8038/// varDecl(isInline()) will match Foo;
8039AST_POLYMORPHIC_MATCHER(isInline, AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
8040 FunctionDecl,
8041 VarDecl)) {
8042 // This is required because the spelling of the function used to determine
8043 // whether inline is specified or not differs between the polymorphic types.
8044 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
8045 return FD->isInlineSpecified();
8046 if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
8047 return NSD->isInline();
8048 if (const auto *VD = dyn_cast<VarDecl>(&Node))
8049 return VD->isInline();
8050 llvm_unreachable("Not a valid polymorphic type");
8051}
8052
8053/// Matches anonymous namespace declarations.
8054///
8055/// Given
8056/// \code
8057/// namespace n {
8058/// namespace {} // #1
8059/// }
8060/// \endcode
8061/// namespaceDecl(isAnonymous()) will match #1 but not ::n.
8062AST_MATCHER(NamespaceDecl, isAnonymous) {
8063 return Node.isAnonymousNamespace();
8064}
8065
8066/// Matches declarations in the namespace `std`, but not in nested namespaces.
8067///
8068/// Given
8069/// \code
8070/// class vector {};
8071/// namespace foo {
8072/// class vector {};
8073/// namespace std {
8074/// class vector {};
8075/// }
8076/// }
8077/// namespace std {
8078/// inline namespace __1 {
8079/// class vector {}; // #1
8080/// namespace experimental {
8081/// class vector {};
8082/// }
8083/// }
8084/// }
8085/// \endcode
8086/// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
8087AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
8088
8089/// Matches declarations in an anonymous namespace.
8090///
8091/// Given
8092/// \code
8093/// class vector {};
8094/// namespace foo {
8095/// class vector {};
8096/// namespace {
8097/// class vector {}; // #1
8098/// }
8099/// }
8100/// namespace {
8101/// class vector {}; // #2
8102/// namespace foo {
8103/// class vector{}; // #3
8104/// }
8105/// }
8106/// \endcode
8107/// cxxRecordDecl(hasName("vector"), isInAnonymousNamespace()) will match
8108/// #1, #2 and #3.
8109AST_MATCHER(Decl, isInAnonymousNamespace) {
8110 return Node.isInAnonymousNamespace();
8111}
8112
8113/// If the given case statement does not use the GNU case range
8114/// extension, matches the constant given in the statement.
8115///
8116/// Given
8117/// \code
8118/// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
8119/// \endcode
8120/// caseStmt(hasCaseConstant(integerLiteral()))
8121/// matches "case 1:"
8122AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
8123 InnerMatcher) {
8124 if (Node.getRHS())
8125 return false;
8126
8127 return InnerMatcher.matches(Node: *Node.getLHS(), Finder, Builder);
8128}
8129
8130/// Matches declaration that has a given attribute.
8131///
8132/// Given
8133/// \code
8134/// __attribute__((device)) void f() { ... }
8135/// \endcode
8136/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
8137/// f. If the matcher is used from clang-query, attr::Kind parameter should be
8138/// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
8139AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
8140 for (const auto *Attr : Node.attrs()) {
8141 if (Attr->getKind() == AttrKind)
8142 return true;
8143 }
8144 return false;
8145}
8146
8147/// Matches the return value expression of a return statement
8148///
8149/// Given
8150/// \code
8151/// return a + b;
8152/// \endcode
8153/// hasReturnValue(binaryOperator())
8154/// matches 'return a + b'
8155/// with binaryOperator()
8156/// matching 'a + b'
8157AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
8158 InnerMatcher) {
8159 if (const auto *RetValue = Node.getRetValue())
8160 return InnerMatcher.matches(Node: *RetValue, Finder, Builder);
8161 return false;
8162}
8163
8164/// Matches CUDA kernel call expression.
8165///
8166/// Example matches,
8167/// \code
8168/// kernel<<<i,j>>>();
8169/// \endcode
8170extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
8171 cudaKernelCallExpr;
8172
8173/// Matches expressions that resolve to a null pointer constant, such as
8174/// GNU's __null, C++11's nullptr, or C's NULL macro.
8175///
8176/// Given:
8177/// \code
8178/// void *v1 = NULL;
8179/// void *v2 = nullptr;
8180/// void *v3 = __null; // GNU extension
8181/// char *cp = (char *)0;
8182/// int *ip = 0;
8183/// int i = 0;
8184/// \endcode
8185/// expr(nullPointerConstant())
8186/// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
8187/// initializer for i.
8188AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
8189 return anyOf(
8190 gnuNullExpr(), cxxNullPtrLiteralExpr(),
8191 integerLiteral(equals(Value: 0), hasParent(expr(hasType(InnerMatcher: pointerType())))));
8192}
8193
8194/// Matches the DecompositionDecl the binding belongs to.
8195///
8196/// For example, in:
8197/// \code
8198/// void foo()
8199/// {
8200/// int arr[3];
8201/// auto &[f, s, t] = arr;
8202///
8203/// f = 42;
8204/// }
8205/// \endcode
8206/// The matcher:
8207/// \code
8208/// bindingDecl(hasName("f"),
8209/// forDecomposition(decompositionDecl())
8210/// \endcode
8211/// matches 'f' in 'auto &[f, s, t]'.
8212AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>,
8213 InnerMatcher) {
8214 if (const ValueDecl *VD = Node.getDecomposedDecl())
8215 return InnerMatcher.matches(Node: *VD, Finder, Builder);
8216 return false;
8217}
8218
8219/// Matches the Nth binding of a DecompositionDecl.
8220///
8221/// For example, in:
8222/// \code
8223/// void foo()
8224/// {
8225/// int arr[3];
8226/// auto &[f, s, t] = arr;
8227///
8228/// f = 42;
8229/// }
8230/// \endcode
8231/// The matcher:
8232/// \code
8233/// decompositionDecl(hasBinding(0,
8234/// bindingDecl(hasName("f").bind("fBinding"))))
8235/// \endcode
8236/// matches the decomposition decl with 'f' bound to "fBinding".
8237AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N,
8238 internal::Matcher<BindingDecl>, InnerMatcher) {
8239 if (Node.bindings().size() <= N)
8240 return false;
8241 return InnerMatcher.matches(Node: *Node.bindings()[N], Finder, Builder);
8242}
8243
8244/// Matches any binding of a DecompositionDecl.
8245///
8246/// For example, in:
8247/// \code
8248/// void foo()
8249/// {
8250/// int arr[3];
8251/// auto &[f, s, t] = arr;
8252///
8253/// f = 42;
8254/// }
8255/// \endcode
8256/// The matcher:
8257/// \code
8258/// decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding"))))
8259/// \endcode
8260/// matches the decomposition decl with 'f' bound to "fBinding".
8261AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>,
8262 InnerMatcher) {
8263 return llvm::any_of(Range: Node.bindings(), P: [&](const auto *Binding) {
8264 return InnerMatcher.matches(Node: *Binding, Finder, Builder);
8265 });
8266}
8267
8268/// Matches declaration of the function the statement belongs to.
8269///
8270/// Deprecated. Use forCallable() to correctly handle the situation when
8271/// the declaration is not a function (but a block or an Objective-C method).
8272/// forFunction() not only fails to take non-functions into account but also
8273/// may match the wrong declaration in their presence.
8274///
8275/// Given:
8276/// \code
8277/// F& operator=(const F& o) {
8278/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
8279/// return *this;
8280/// }
8281/// \endcode
8282/// returnStmt(forFunction(hasName("operator=")))
8283/// matches 'return *this'
8284/// but does not match 'return v > 0'
8285AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
8286 InnerMatcher) {
8287 const auto &Parents = Finder->getASTContext().getParents(Node);
8288
8289 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
8290 while (!Stack.empty()) {
8291 const auto &CurNode = Stack.back();
8292 Stack.pop_back();
8293 if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
8294 if (InnerMatcher.matches(Node: *FuncDeclNode, Finder, Builder)) {
8295 return true;
8296 }
8297 } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
8298 if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
8299 Builder)) {
8300 return true;
8301 }
8302 } else {
8303 llvm::append_range(C&: Stack, R: Finder->getASTContext().getParents(Node: CurNode));
8304 }
8305 }
8306 return false;
8307}
8308
8309/// Matches declaration of the function, method, or block the statement
8310/// belongs to.
8311///
8312/// Given:
8313/// \code
8314/// F& operator=(const F& o) {
8315/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
8316/// return *this;
8317/// }
8318/// \endcode
8319/// returnStmt(forCallable(functionDecl(hasName("operator="))))
8320/// matches 'return *this'
8321/// but does not match 'return v > 0'
8322///
8323/// Given:
8324/// \code
8325/// -(void) foo {
8326/// int x = 1;
8327/// dispatch_sync(queue, ^{ int y = 2; });
8328/// }
8329/// \endcode
8330/// declStmt(forCallable(objcMethodDecl()))
8331/// matches 'int x = 1'
8332/// but does not match 'int y = 2'.
8333/// whereas declStmt(forCallable(blockDecl()))
8334/// matches 'int y = 2'
8335/// but does not match 'int x = 1'.
8336AST_MATCHER_P(Stmt, forCallable, internal::Matcher<Decl>, InnerMatcher) {
8337 const auto &Parents = Finder->getASTContext().getParents(Node);
8338
8339 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
8340 while (!Stack.empty()) {
8341 const auto &CurNode = Stack.back();
8342 Stack.pop_back();
8343 if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
8344 if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
8345 return true;
8346 }
8347 } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
8348 if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
8349 Builder)) {
8350 return true;
8351 }
8352 } else if (const auto *ObjCMethodDeclNode = CurNode.get<ObjCMethodDecl>()) {
8353 if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, Builder)) {
8354 return true;
8355 }
8356 } else if (const auto *BlockDeclNode = CurNode.get<BlockDecl>()) {
8357 if (InnerMatcher.matches(*BlockDeclNode, Finder, Builder)) {
8358 return true;
8359 }
8360 } else {
8361 llvm::append_range(C&: Stack, R: Finder->getASTContext().getParents(Node: CurNode));
8362 }
8363 }
8364 return false;
8365}
8366
8367/// Matches a declaration that has external formal linkage.
8368///
8369/// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
8370/// \code
8371/// void f() {
8372/// int x;
8373/// static int y;
8374/// }
8375/// int z;
8376/// \endcode
8377///
8378/// Example matches f() because it has external formal linkage despite being
8379/// unique to the translation unit as though it has internal likage
8380/// (matcher = functionDecl(hasExternalFormalLinkage()))
8381///
8382/// \code
8383/// namespace {
8384/// void f() {}
8385/// }
8386/// \endcode
8387AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
8388 return Node.hasExternalFormalLinkage();
8389}
8390
8391/// Matches a declaration that has default arguments.
8392///
8393/// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
8394/// \code
8395/// void x(int val) {}
8396/// void y(int val = 0) {}
8397/// \endcode
8398///
8399/// Deprecated. Use hasInitializer() instead to be able to
8400/// match on the contents of the default argument. For example:
8401///
8402/// \code
8403/// void x(int val = 7) {}
8404/// void y(int val = 42) {}
8405/// \endcode
8406/// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
8407/// matches the parameter of y
8408///
8409/// A matcher such as
8410/// parmVarDecl(hasInitializer(anything()))
8411/// is equivalent to parmVarDecl(hasDefaultArgument()).
8412AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
8413 return Node.hasDefaultArg();
8414}
8415
8416/// Matches array new expressions.
8417///
8418/// Given:
8419/// \code
8420/// MyClass *p1 = new MyClass[10];
8421/// \endcode
8422/// cxxNewExpr(isArray())
8423/// matches the expression 'new MyClass[10]'.
8424AST_MATCHER(CXXNewExpr, isArray) {
8425 return Node.isArray();
8426}
8427
8428/// Matches placement new expression arguments.
8429///
8430/// Given:
8431/// \code
8432/// MyClass *p1 = new (Storage, 16) MyClass();
8433/// \endcode
8434/// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
8435/// matches the expression 'new (Storage, 16) MyClass()'.
8436AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
8437 internal::Matcher<Expr>, InnerMatcher) {
8438 return Node.getNumPlacementArgs() > Index &&
8439 InnerMatcher.matches(Node: *Node.getPlacementArg(I: Index), Finder, Builder);
8440}
8441
8442/// Matches any placement new expression arguments.
8443///
8444/// Given:
8445/// \code
8446/// MyClass *p1 = new (Storage) MyClass();
8447/// \endcode
8448/// cxxNewExpr(hasAnyPlacementArg(anything()))
8449/// matches the expression 'new (Storage, 16) MyClass()'.
8450AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
8451 InnerMatcher) {
8452 return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
8453 return InnerMatcher.matches(Node: *Arg, Finder, Builder);
8454 });
8455}
8456
8457/// Matches array new expressions with a given array size.
8458///
8459/// Given:
8460/// \code
8461/// MyClass *p1 = new MyClass[10];
8462/// \endcode
8463/// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
8464/// matches the expression 'new MyClass[10]'.
8465AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
8466 return Node.isArray() && *Node.getArraySize() &&
8467 InnerMatcher.matches(Node: **Node.getArraySize(), Finder, Builder);
8468}
8469
8470/// Matches a class declaration that is defined.
8471///
8472/// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
8473/// \code
8474/// class x {};
8475/// class y;
8476/// \endcode
8477AST_MATCHER(CXXRecordDecl, hasDefinition) {
8478 return Node.hasDefinition();
8479}
8480
8481/// Matches C++11 scoped enum declaration.
8482///
8483/// Example matches Y (matcher = enumDecl(isScoped()))
8484/// \code
8485/// enum X {};
8486/// enum class Y {};
8487/// \endcode
8488AST_MATCHER(EnumDecl, isScoped) {
8489 return Node.isScoped();
8490}
8491
8492/// Matches a function declared with a trailing return type.
8493///
8494/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
8495/// \code
8496/// int X() {}
8497/// auto Y() -> int {}
8498/// \endcode
8499AST_MATCHER(FunctionDecl, hasTrailingReturn) {
8500 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
8501 return F->hasTrailingReturn();
8502 return false;
8503}
8504
8505/// Matches expressions that match InnerMatcher that are possibly wrapped in an
8506/// elidable constructor and other corresponding bookkeeping nodes.
8507///
8508/// In C++17, elidable copy constructors are no longer being generated in the
8509/// AST as it is not permitted by the standard. They are, however, part of the
8510/// AST in C++14 and earlier. So, a matcher must abstract over these differences
8511/// to work in all language modes. This matcher skips elidable constructor-call
8512/// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
8513/// various implicit nodes inside the constructor calls, all of which will not
8514/// appear in the C++17 AST.
8515///
8516/// Given
8517///
8518/// \code
8519/// struct H {};
8520/// H G();
8521/// void f() {
8522/// H D = G();
8523/// }
8524/// \endcode
8525///
8526/// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
8527/// matches ``H D = G()`` in C++11 through C++17 (and beyond).
8528AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
8529 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
8530 // E tracks the node that we are examining.
8531 const Expr *E = &Node;
8532 // If present, remove an outer `ExprWithCleanups` corresponding to the
8533 // underlying `CXXConstructExpr`. This check won't cover all cases of added
8534 // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
8535 // EWC is placed on the outermost node of the expression, which this may not
8536 // be), but, it still improves the coverage of this matcher.
8537 if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(Val: &Node))
8538 E = CleanupsExpr->getSubExpr();
8539 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(Val: E)) {
8540 if (CtorExpr->isElidable()) {
8541 if (const auto *MaterializeTemp =
8542 dyn_cast<MaterializeTemporaryExpr>(Val: CtorExpr->getArg(Arg: 0))) {
8543 return InnerMatcher.matches(Node: *MaterializeTemp->getSubExpr(), Finder,
8544 Builder);
8545 }
8546 }
8547 }
8548 return InnerMatcher.matches(Node, Finder, Builder);
8549}
8550
8551//----------------------------------------------------------------------------//
8552// OpenMP handling.
8553//----------------------------------------------------------------------------//
8554
8555/// Matches any ``#pragma omp`` executable directive.
8556///
8557/// Given
8558///
8559/// \code
8560/// #pragma omp parallel
8561/// #pragma omp parallel default(none)
8562/// #pragma omp taskyield
8563/// \endcode
8564///
8565/// ``ompExecutableDirective()`` matches ``omp parallel``,
8566/// ``omp parallel default(none)`` and ``omp taskyield``.
8567extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
8568 ompExecutableDirective;
8569
8570/// Matches standalone OpenMP directives,
8571/// i.e., directives that can't have a structured block.
8572///
8573/// Given
8574///
8575/// \code
8576/// #pragma omp parallel
8577/// {}
8578/// #pragma omp taskyield
8579/// \endcode
8580///
8581/// ``ompExecutableDirective(isStandaloneDirective()))`` matches
8582/// ``omp taskyield``.
8583AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
8584 return Node.isStandaloneDirective();
8585}
8586
8587/// Matches the structured-block of the OpenMP executable directive
8588///
8589/// Prerequisite: the executable directive must not be standalone directive.
8590/// If it is, it will never match.
8591///
8592/// Given
8593///
8594/// \code
8595/// #pragma omp parallel
8596/// ;
8597/// #pragma omp parallel
8598/// {}
8599/// \endcode
8600///
8601/// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
8602AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
8603 internal::Matcher<Stmt>, InnerMatcher) {
8604 if (Node.isStandaloneDirective())
8605 return false; // Standalone directives have no structured blocks.
8606 return InnerMatcher.matches(Node: *Node.getStructuredBlock(), Finder, Builder);
8607}
8608
8609/// Matches any clause in an OpenMP directive.
8610///
8611/// Given
8612///
8613/// \code
8614/// #pragma omp parallel
8615/// #pragma omp parallel default(none)
8616/// \endcode
8617///
8618/// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
8619/// ``omp parallel default(none)``.
8620AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
8621 internal::Matcher<OMPClause>, InnerMatcher) {
8622 ArrayRef<OMPClause *> Clauses = Node.clauses();
8623 return matchesFirstInPointerRange(Matcher: InnerMatcher, Start: Clauses.begin(),
8624 End: Clauses.end(), Finder,
8625 Builder) != Clauses.end();
8626}
8627
8628/// Matches OpenMP ``default`` clause.
8629///
8630/// Given
8631///
8632/// \code
8633/// #pragma omp parallel default(none)
8634/// #pragma omp parallel default(shared)
8635/// #pragma omp parallel default(private)
8636/// #pragma omp parallel default(firstprivate)
8637/// #pragma omp parallel
8638/// \endcode
8639///
8640/// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``,
8641/// `` default(private)`` and ``default(firstprivate)``
8642extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
8643 ompDefaultClause;
8644
8645/// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
8646///
8647/// Given
8648///
8649/// \code
8650/// #pragma omp parallel
8651/// #pragma omp parallel default(none)
8652/// #pragma omp parallel default(shared)
8653/// #pragma omp parallel default(private)
8654/// #pragma omp parallel default(firstprivate)
8655/// \endcode
8656///
8657/// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
8658AST_MATCHER(OMPDefaultClause, isNoneKind) {
8659 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
8660}
8661
8662/// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
8663///
8664/// Given
8665///
8666/// \code
8667/// #pragma omp parallel
8668/// #pragma omp parallel default(none)
8669/// #pragma omp parallel default(shared)
8670/// #pragma omp parallel default(private)
8671/// #pragma omp parallel default(firstprivate)
8672/// \endcode
8673///
8674/// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
8675AST_MATCHER(OMPDefaultClause, isSharedKind) {
8676 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
8677}
8678
8679/// Matches if the OpenMP ``default`` clause has ``private`` kind
8680/// specified.
8681///
8682/// Given
8683///
8684/// \code
8685/// #pragma omp parallel
8686/// #pragma omp parallel default(none)
8687/// #pragma omp parallel default(shared)
8688/// #pragma omp parallel default(private)
8689/// #pragma omp parallel default(firstprivate)
8690/// \endcode
8691///
8692/// ``ompDefaultClause(isPrivateKind())`` matches only
8693/// ``default(private)``.
8694AST_MATCHER(OMPDefaultClause, isPrivateKind) {
8695 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_private;
8696}
8697
8698/// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
8699/// specified.
8700///
8701/// Given
8702///
8703/// \code
8704/// #pragma omp parallel
8705/// #pragma omp parallel default(none)
8706/// #pragma omp parallel default(shared)
8707/// #pragma omp parallel default(private)
8708/// #pragma omp parallel default(firstprivate)
8709/// \endcode
8710///
8711/// ``ompDefaultClause(isFirstPrivateKind())`` matches only
8712/// ``default(firstprivate)``.
8713AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
8714 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
8715}
8716
8717/// Matches if the OpenMP directive is allowed to contain the specified OpenMP
8718/// clause kind.
8719///
8720/// Given
8721///
8722/// \code
8723/// #pragma omp parallel
8724/// #pragma omp parallel for
8725/// #pragma omp for
8726/// \endcode
8727///
8728/// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
8729/// ``omp parallel`` and ``omp parallel for``.
8730///
8731/// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
8732/// should be passed as a quoted string. e.g.,
8733/// ``isAllowedToContainClauseKind("OMPC_default").``
8734AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
8735 OpenMPClauseKind, CKind) {
8736 return llvm::omp::isAllowedClauseForDirective(
8737 Node.getDirectiveKind(), CKind,
8738 Finder->getASTContext().getLangOpts().OpenMP);
8739}
8740
8741//----------------------------------------------------------------------------//
8742// End OpenMP handling.
8743//----------------------------------------------------------------------------//
8744
8745} // namespace ast_matchers
8746} // namespace clang
8747
8748#endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
8749

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