Warning: This file is not a C or C++ file. It does not have highlighting.

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

Warning: This file is not a C or C++ file. It does not have highlighting.

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