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// use the id(...) matcher around the match expressions that match the nodes
23// you want to 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(id("child", recordDecl())))
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 id(...) 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/Decl.h"
51#include "clang/AST/DeclCXX.h"
52#include "clang/AST/DeclFriend.h"
53#include "clang/AST/DeclObjC.h"
54#include "clang/AST/DeclTemplate.h"
55#include "clang/AST/Expr.h"
56#include "clang/AST/ExprCXX.h"
57#include "clang/AST/ExprObjC.h"
58#include "clang/AST/NestedNameSpecifier.h"
59#include "clang/AST/OperationKinds.h"
60#include "clang/AST/Stmt.h"
61#include "clang/AST/StmtCXX.h"
62#include "clang/AST/StmtObjC.h"
63#include "clang/AST/TemplateBase.h"
64#include "clang/AST/TemplateName.h"
65#include "clang/AST/Type.h"
66#include "clang/AST/TypeLoc.h"
67#include "clang/ASTMatchers/ASTMatchersInternal.h"
68#include "clang/ASTMatchers/ASTMatchersMacros.h"
69#include "clang/Basic/AttrKinds.h"
70#include "clang/Basic/ExceptionSpecificationType.h"
71#include "clang/Basic/IdentifierTable.h"
72#include "clang/Basic/LLVM.h"
73#include "clang/Basic/SourceManager.h"
74#include "clang/Basic/Specifiers.h"
75#include "clang/Basic/TypeTraits.h"
76#include "llvm/ADT/ArrayRef.h"
77#include "llvm/ADT/SmallVector.h"
78#include "llvm/ADT/StringRef.h"
79#include "llvm/Support/Casting.h"
80#include "llvm/Support/Compiler.h"
81#include "llvm/Support/ErrorHandling.h"
82#include "llvm/Support/Regex.h"
83#include <cassert>
84#include <cstddef>
85#include <iterator>
86#include <limits>
87#include <string>
88#include <utility>
89#include <vector>
90
91namespace clang {
92namespace ast_matchers {
93
94/// Maps string IDs to AST nodes matched by parts of a matcher.
95///
96/// The bound nodes are generated by calling \c bind("id") on the node matchers
97/// of the nodes we want to access later.
98///
99/// The instances of BoundNodes are created by \c MatchFinder when the user's
100/// callbacks are executed every time a match is found.
101class BoundNodes {
102public:
103 /// Returns the AST node bound to \c ID.
104 ///
105 /// Returns NULL if there was no node bound to \c ID or if there is a node but
106 /// it cannot be converted to the specified type.
107 template <typename T>
108 const T *getNodeAs(StringRef ID) const {
109 return MyBoundNodes.getNodeAs<T>(ID);
110 }
111
112 /// Type of mapping from binding identifiers to bound nodes. This type
113 /// is an associative container with a key type of \c std::string and a value
114 /// type of \c clang::ast_type_traits::DynTypedNode
115 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
116
117 /// Retrieve mapping from binding identifiers to bound nodes.
118 const IDToNodeMap &getMap() const {
119 return MyBoundNodes.getMap();
120 }
121
122private:
123 friend class internal::BoundNodesTreeBuilder;
124
125 /// Create BoundNodes from a pre-filled map of bindings.
126 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
127 : MyBoundNodes(MyBoundNodes) {}
128
129 internal::BoundNodesMap MyBoundNodes;
130};
131
132/// If the provided matcher matches a node, binds the node to \c ID.
133///
134/// FIXME: Do we want to support this now that we have bind()?
135template <typename T>
136internal::Matcher<T> id(StringRef ID,
137 const internal::BindableMatcher<T> &InnerMatcher) {
138 return InnerMatcher.bind(ID);
139}
140
141/// Types of matchers for the top-level classes in the AST class
142/// hierarchy.
143/// @{
144using DeclarationMatcher = internal::Matcher<Decl>;
145using StatementMatcher = internal::Matcher<Stmt>;
146using TypeMatcher = internal::Matcher<QualType>;
147using TypeLocMatcher = internal::Matcher<TypeLoc>;
148using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
149using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
150using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
151/// @}
152
153/// Matches any node.
154///
155/// Useful when another matcher requires a child matcher, but there's no
156/// additional constraint. This will often be used with an explicit conversion
157/// to an \c internal::Matcher<> type such as \c TypeMatcher.
158///
159/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
160/// \code
161/// "int* p" and "void f()" in
162/// int* p;
163/// void f();
164/// \endcode
165///
166/// Usable as: Any Matcher
167inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
168
169/// Matches the top declaration context.
170///
171/// Given
172/// \code
173/// int X;
174/// namespace NS {
175/// int Y;
176/// } // namespace NS
177/// \endcode
178/// decl(hasDeclContext(translationUnitDecl()))
179/// matches "int X", but not "int Y".
180extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
181 translationUnitDecl;
182
183/// Matches typedef declarations.
184///
185/// Given
186/// \code
187/// typedef int X;
188/// using Y = int;
189/// \endcode
190/// typedefDecl()
191/// matches "typedef int X", but not "using Y = int"
192extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
193 typedefDecl;
194
195/// Matches typedef name declarations.
196///
197/// Given
198/// \code
199/// typedef int X;
200/// using Y = int;
201/// \endcode
202/// typedefNameDecl()
203/// matches "typedef int X" and "using Y = int"
204extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
205 typedefNameDecl;
206
207/// Matches type alias declarations.
208///
209/// Given
210/// \code
211/// typedef int X;
212/// using Y = int;
213/// \endcode
214/// typeAliasDecl()
215/// matches "using Y = int", but not "typedef int X"
216extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
217 typeAliasDecl;
218
219/// Matches type alias template declarations.
220///
221/// typeAliasTemplateDecl() matches
222/// \code
223/// template <typename T>
224/// using Y = X<T>;
225/// \endcode
226extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
227 typeAliasTemplateDecl;
228
229/// Matches AST nodes that were expanded within the main-file.
230///
231/// Example matches X but not Y
232/// (matcher = cxxRecordDecl(isExpansionInMainFile())
233/// \code
234/// #include <Y.h>
235/// class X {};
236/// \endcode
237/// Y.h:
238/// \code
239/// class Y {};
240/// \endcode
241///
242/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
243AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
244 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
245 auto &SourceManager = Finder->getASTContext().getSourceManager();
246 return SourceManager.isInMainFile(
247 SourceManager.getExpansionLoc(Node.getBeginLoc()));
248}
249
250/// Matches AST nodes that were expanded within system-header-files.
251///
252/// Example matches Y but not X
253/// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
254/// \code
255/// #include <SystemHeader.h>
256/// class X {};
257/// \endcode
258/// SystemHeader.h:
259/// \code
260/// class Y {};
261/// \endcode
262///
263/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
264AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
265 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
266 auto &SourceManager = Finder->getASTContext().getSourceManager();
267 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
268 if (ExpansionLoc.isInvalid()) {
269 return false;
270 }
271 return SourceManager.isInSystemHeader(ExpansionLoc);
272}
273
274/// Matches AST nodes that were expanded within files whose name is
275/// partially matching a given regex.
276///
277/// Example matches Y but not X
278/// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
279/// \code
280/// #include "ASTMatcher.h"
281/// class X {};
282/// \endcode
283/// ASTMatcher.h:
284/// \code
285/// class Y {};
286/// \endcode
287///
288/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
289AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
290 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
291 std::string, RegExp) {
292 auto &SourceManager = Finder->getASTContext().getSourceManager();
293 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
294 if (ExpansionLoc.isInvalid()) {
295 return false;
296 }
297 auto FileEntry =
298 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
299 if (!FileEntry) {
300 return false;
301 }
302
303 auto Filename = FileEntry->getName();
304 llvm::Regex RE(RegExp);
305 return RE.match(Filename);
306}
307
308/// Matches declarations.
309///
310/// Examples matches \c X, \c C, and the friend declaration inside \c C;
311/// \code
312/// void X();
313/// class C {
314/// friend X;
315/// };
316/// \endcode
317extern const internal::VariadicAllOfMatcher<Decl> decl;
318
319/// Matches a declaration of a linkage specification.
320///
321/// Given
322/// \code
323/// extern "C" {}
324/// \endcode
325/// linkageSpecDecl()
326/// matches "extern "C" {}"
327extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
328 linkageSpecDecl;
329
330/// Matches a declaration of anything that could have a name.
331///
332/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
333/// \code
334/// typedef int X;
335/// struct S {
336/// union {
337/// int i;
338/// } U;
339/// };
340/// \endcode
341extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
342
343/// Matches a declaration of label.
344///
345/// Given
346/// \code
347/// goto FOO;
348/// FOO: bar();
349/// \endcode
350/// labelDecl()
351/// matches 'FOO:'
352extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
353
354/// Matches a declaration of a namespace.
355///
356/// Given
357/// \code
358/// namespace {}
359/// namespace test {}
360/// \endcode
361/// namespaceDecl()
362/// matches "namespace {}" and "namespace test {}"
363extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
364 namespaceDecl;
365
366/// Matches a declaration of a namespace alias.
367///
368/// Given
369/// \code
370/// namespace test {}
371/// namespace alias = ::test;
372/// \endcode
373/// namespaceAliasDecl()
374/// matches "namespace alias" but not "namespace test"
375extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
376 namespaceAliasDecl;
377
378/// Matches class, struct, and union declarations.
379///
380/// Example matches \c X, \c Z, \c U, and \c S
381/// \code
382/// class X;
383/// template<class T> class Z {};
384/// struct S {};
385/// union U {};
386/// \endcode
387extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
388
389/// Matches C++ class declarations.
390///
391/// Example matches \c X, \c Z
392/// \code
393/// class X;
394/// template<class T> class Z {};
395/// \endcode
396extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
397 cxxRecordDecl;
398
399/// Matches C++ class template declarations.
400///
401/// Example matches \c Z
402/// \code
403/// template<class T> class Z {};
404/// \endcode
405extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
406 classTemplateDecl;
407
408/// Matches C++ class template specializations.
409///
410/// Given
411/// \code
412/// template<typename T> class A {};
413/// template<> class A<double> {};
414/// A<int> a;
415/// \endcode
416/// classTemplateSpecializationDecl()
417/// matches the specializations \c A<int> and \c A<double>
418extern const internal::VariadicDynCastAllOfMatcher<
419 Decl, ClassTemplateSpecializationDecl>
420 classTemplateSpecializationDecl;
421
422/// Matches C++ class template partial specializations.
423///
424/// Given
425/// \code
426/// template<class T1, class T2, int I>
427/// class A {};
428///
429/// template<class T, int I>
430/// class A<T, T*, I> {};
431///
432/// template<>
433/// class A<int, int, 1> {};
434/// \endcode
435/// classTemplatePartialSpecializationDecl()
436/// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
437extern const internal::VariadicDynCastAllOfMatcher<
438 Decl, ClassTemplatePartialSpecializationDecl>
439 classTemplatePartialSpecializationDecl;
440
441/// Matches declarator declarations (field, variable, function
442/// and non-type template parameter declarations).
443///
444/// Given
445/// \code
446/// class X { int y; };
447/// \endcode
448/// declaratorDecl()
449/// matches \c int y.
450extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
451 declaratorDecl;
452
453/// Matches parameter variable declarations.
454///
455/// Given
456/// \code
457/// void f(int x);
458/// \endcode
459/// parmVarDecl()
460/// matches \c int x.
461extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
462 parmVarDecl;
463
464/// Matches C++ access specifier declarations.
465///
466/// Given
467/// \code
468/// class C {
469/// public:
470/// int a;
471/// };
472/// \endcode
473/// accessSpecDecl()
474/// matches 'public:'
475extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
476 accessSpecDecl;
477
478/// Matches constructor initializers.
479///
480/// Examples matches \c i(42).
481/// \code
482/// class C {
483/// C() : i(42) {}
484/// int i;
485/// };
486/// \endcode
487extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
488 cxxCtorInitializer;
489
490/// Matches template arguments.
491///
492/// Given
493/// \code
494/// template <typename T> struct C {};
495/// C<int> c;
496/// \endcode
497/// templateArgument()
498/// matches 'int' in C<int>.
499extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
500
501/// Matches template name.
502///
503/// Given
504/// \code
505/// template <typename T> class X { };
506/// X<int> xi;
507/// \endcode
508/// templateName()
509/// matches 'X' in X<int>.
510extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
511
512/// Matches non-type template parameter declarations.
513///
514/// Given
515/// \code
516/// template <typename T, int N> struct C {};
517/// \endcode
518/// nonTypeTemplateParmDecl()
519/// matches 'N', but not 'T'.
520extern const internal::VariadicDynCastAllOfMatcher<Decl,
521 NonTypeTemplateParmDecl>
522 nonTypeTemplateParmDecl;
523
524/// Matches template type parameter declarations.
525///
526/// Given
527/// \code
528/// template <typename T, int N> struct C {};
529/// \endcode
530/// templateTypeParmDecl()
531/// matches 'T', but not 'N'.
532extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
533 templateTypeParmDecl;
534
535/// Matches public C++ declarations.
536///
537/// Given
538/// \code
539/// class C {
540/// public: int a;
541/// protected: int b;
542/// private: int c;
543/// };
544/// \endcode
545/// fieldDecl(isPublic())
546/// matches 'int a;'
547AST_MATCHER(Decl, isPublic) {
548 return Node.getAccess() == AS_public;
549}
550
551/// Matches protected C++ declarations.
552///
553/// Given
554/// \code
555/// class C {
556/// public: int a;
557/// protected: int b;
558/// private: int c;
559/// };
560/// \endcode
561/// fieldDecl(isProtected())
562/// matches 'int b;'
563AST_MATCHER(Decl, isProtected) {
564 return Node.getAccess() == AS_protected;
565}
566
567/// Matches private C++ declarations.
568///
569/// Given
570/// \code
571/// class C {
572/// public: int a;
573/// protected: int b;
574/// private: int c;
575/// };
576/// \endcode
577/// fieldDecl(isPrivate())
578/// matches 'int c;'
579AST_MATCHER(Decl, isPrivate) {
580 return Node.getAccess() == AS_private;
581}
582
583/// Matches non-static data members that are bit-fields.
584///
585/// Given
586/// \code
587/// class C {
588/// int a : 2;
589/// int b;
590/// };
591/// \endcode
592/// fieldDecl(isBitField())
593/// matches 'int a;' but not 'int b;'.
594AST_MATCHER(FieldDecl, isBitField) {
595 return Node.isBitField();
596}
597
598/// Matches non-static data members that are bit-fields of the specified
599/// bit width.
600///
601/// Given
602/// \code
603/// class C {
604/// int a : 2;
605/// int b : 4;
606/// int c : 2;
607/// };
608/// \endcode
609/// fieldDecl(hasBitWidth(2))
610/// matches 'int a;' and 'int c;' but not 'int b;'.
611AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
612 return Node.isBitField() &&
613 Node.getBitWidthValue(Finder->getASTContext()) == Width;
614}
615
616/// Matches non-static data members that have an in-class initializer.
617///
618/// Given
619/// \code
620/// class C {
621/// int a = 2;
622/// int b = 3;
623/// int c;
624/// };
625/// \endcode
626/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
627/// matches 'int a;' but not 'int b;'.
628/// fieldDecl(hasInClassInitializer(anything()))
629/// matches 'int a;' and 'int b;' but not 'int c;'.
630AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
631 InnerMatcher) {
632 const Expr *Initializer = Node.getInClassInitializer();
633 return (Initializer != nullptr &&
634 InnerMatcher.matches(*Initializer, Finder, Builder));
635}
636
637/// Determines whether the function is "main", which is the entry point
638/// into an executable program.
639AST_MATCHER(FunctionDecl, isMain) {
640 return Node.isMain();
641}
642
643/// Matches the specialized template of a specialization declaration.
644///
645/// Given
646/// \code
647/// template<typename T> class A {}; #1
648/// template<> class A<int> {}; #2
649/// \endcode
650/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
651/// matches '#2' with classTemplateDecl() matching the class template
652/// declaration of 'A' at #1.
653AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
654 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
655 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
656 return (Decl != nullptr &&
657 InnerMatcher.matches(*Decl, Finder, Builder));
658}
659
660/// Matches a declaration that has been implicitly added
661/// by the compiler (eg. implicit default/copy constructors).
662AST_MATCHER(Decl, isImplicit) {
663 return Node.isImplicit();
664}
665
666/// Matches classTemplateSpecializations, templateSpecializationType and
667/// functionDecl that have at least one TemplateArgument matching the given
668/// InnerMatcher.
669///
670/// Given
671/// \code
672/// template<typename T> class A {};
673/// template<> class A<double> {};
674/// A<int> a;
675///
676/// template<typename T> f() {};
677/// void func() { f<int>(); };
678/// \endcode
679///
680/// \endcode
681/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
682/// refersToType(asString("int"))))
683/// matches the specialization \c A<int>
684///
685/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
686/// matches the specialization \c f<int>
687AST_POLYMORPHIC_MATCHER_P(
688 hasAnyTemplateArgument,
689 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
690 TemplateSpecializationType,
691 FunctionDecl),
692 internal::Matcher<TemplateArgument>, InnerMatcher) {
693 ArrayRef<TemplateArgument> List =
694 internal::getTemplateSpecializationArgs(Node);
695 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
696 Builder);
697}
698
699/// Matches expressions that match InnerMatcher after any implicit AST
700/// nodes are stripped off.
701///
702/// Parentheses and explicit casts are not discarded.
703/// Given
704/// \code
705/// class C {};
706/// C a = C();
707/// C b;
708/// C c = b;
709/// \endcode
710/// The matchers
711/// \code
712/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
713/// \endcode
714/// would match the declarations for a, b, and c.
715/// While
716/// \code
717/// varDecl(hasInitializer(cxxConstructExpr()))
718/// \endcode
719/// only match the declarations for b and c.
720AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
721 InnerMatcher) {
722 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
723}
724
725/// Matches expressions that match InnerMatcher after any implicit casts
726/// are stripped off.
727///
728/// Parentheses and explicit casts are not discarded.
729/// Given
730/// \code
731/// int arr[5];
732/// int a = 0;
733/// char b = 0;
734/// const int c = a;
735/// int *d = arr;
736/// long e = (long) 0l;
737/// \endcode
738/// The matchers
739/// \code
740/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
741/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
742/// \endcode
743/// would match the declarations for a, b, c, and d, but not e.
744/// While
745/// \code
746/// varDecl(hasInitializer(integerLiteral()))
747/// varDecl(hasInitializer(declRefExpr()))
748/// \endcode
749/// only match the declarations for b, c, and d.
750AST_MATCHER_P(Expr, ignoringImpCasts,
751 internal::Matcher<Expr>, InnerMatcher) {
752 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
753}
754
755/// Matches expressions that match InnerMatcher after parentheses and
756/// casts are stripped off.
757///
758/// Implicit and non-C Style casts are also discarded.
759/// Given
760/// \code
761/// int a = 0;
762/// char b = (0);
763/// void* c = reinterpret_cast<char*>(0);
764/// char d = char(0);
765/// \endcode
766/// The matcher
767/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
768/// would match the declarations for a, b, c, and d.
769/// while
770/// varDecl(hasInitializer(integerLiteral()))
771/// only match the declaration for a.
772AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
773 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
774}
775
776/// Matches expressions that match InnerMatcher after implicit casts and
777/// parentheses are stripped off.
778///
779/// Explicit casts are not discarded.
780/// Given
781/// \code
782/// int arr[5];
783/// int a = 0;
784/// char b = (0);
785/// const int c = a;
786/// int *d = (arr);
787/// long e = ((long) 0l);
788/// \endcode
789/// The matchers
790/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
791/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
792/// would match the declarations for a, b, c, and d, but not e.
793/// while
794/// varDecl(hasInitializer(integerLiteral()))
795/// varDecl(hasInitializer(declRefExpr()))
796/// would only match the declaration for a.
797AST_MATCHER_P(Expr, ignoringParenImpCasts,
798 internal::Matcher<Expr>, InnerMatcher) {
799 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
800}
801
802/// Matches types that match InnerMatcher after any parens are stripped.
803///
804/// Given
805/// \code
806/// void (*fp)(void);
807/// \endcode
808/// The matcher
809/// \code
810/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
811/// \endcode
812/// would match the declaration for fp.
813AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
814 InnerMatcher, 0) {
815 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
816}
817
818/// Overload \c ignoringParens for \c Expr.
819///
820/// Given
821/// \code
822/// const char* str = ("my-string");
823/// \endcode
824/// The matcher
825/// \code
826/// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
827/// \endcode
828/// would match the implicit cast resulting from the assignment.
829AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
830 InnerMatcher, 1) {
831 const Expr *E = Node.IgnoreParens();
832 return InnerMatcher.matches(*E, Finder, Builder);
833}
834
835/// Matches expressions that are instantiation-dependent even if it is
836/// neither type- nor value-dependent.
837///
838/// In the following example, the expression sizeof(sizeof(T() + T()))
839/// is instantiation-dependent (since it involves a template parameter T),
840/// but is neither type- nor value-dependent, since the type of the inner
841/// sizeof is known (std::size_t) and therefore the size of the outer
842/// sizeof is known.
843/// \code
844/// template<typename T>
845/// void f(T x, T y) { sizeof(sizeof(T() + T()); }
846/// \endcode
847/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
848AST_MATCHER(Expr, isInstantiationDependent) {
849 return Node.isInstantiationDependent();
850}
851
852/// Matches expressions that are type-dependent because the template type
853/// is not yet instantiated.
854///
855/// For example, the expressions "x" and "x + y" are type-dependent in
856/// the following code, but "y" is not type-dependent:
857/// \code
858/// template<typename T>
859/// void add(T x, int y) {
860/// x + y;
861/// }
862/// \endcode
863/// expr(isTypeDependent()) matches x + y
864AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
865
866/// Matches expression that are value-dependent because they contain a
867/// non-type template parameter.
868///
869/// For example, the array bound of "Chars" in the following example is
870/// value-dependent.
871/// \code
872/// template<int Size> int f() { return Size; }
873/// \endcode
874/// expr(isValueDependent()) matches return Size
875AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
876
877/// Matches classTemplateSpecializations, templateSpecializationType and
878/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
879///
880/// Given
881/// \code
882/// template<typename T, typename U> class A {};
883/// A<bool, int> b;
884/// A<int, bool> c;
885///
886/// template<typename T> void f() {}
887/// void func() { f<int>(); };
888/// \endcode
889/// classTemplateSpecializationDecl(hasTemplateArgument(
890/// 1, refersToType(asString("int"))))
891/// matches the specialization \c A<bool, int>
892///
893/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
894/// matches the specialization \c f<int>
895AST_POLYMORPHIC_MATCHER_P2(
896 hasTemplateArgument,
897 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
898 TemplateSpecializationType,
899 FunctionDecl),
900 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
901 ArrayRef<TemplateArgument> List =
902 internal::getTemplateSpecializationArgs(Node);
903 if (List.size() <= N)
904 return false;
905 return InnerMatcher.matches(List[N], Finder, Builder);
906}
907
908/// Matches if the number of template arguments equals \p N.
909///
910/// Given
911/// \code
912/// template<typename T> struct C {};
913/// C<int> c;
914/// \endcode
915/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
916/// matches C<int>.
917AST_POLYMORPHIC_MATCHER_P(
918 templateArgumentCountIs,
919 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
920 TemplateSpecializationType),
921 unsigned, N) {
922 return internal::getTemplateSpecializationArgs(Node).size() == N;
923}
924
925/// Matches a TemplateArgument that refers to a certain type.
926///
927/// Given
928/// \code
929/// struct X {};
930/// template<typename T> struct A {};
931/// A<X> a;
932/// \endcode
933/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
934/// refersToType(class(hasName("X")))))
935/// matches the specialization \c A<X>
936AST_MATCHER_P(TemplateArgument, refersToType,
937 internal::Matcher<QualType>, InnerMatcher) {
938 if (Node.getKind() != TemplateArgument::Type)
939 return false;
940 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
941}
942
943/// Matches a TemplateArgument that refers to a certain template.
944///
945/// Given
946/// \code
947/// template<template <typename> class S> class X {};
948/// template<typename T> class Y {};
949/// X<Y> xi;
950/// \endcode
951/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
952/// refersToTemplate(templateName())))
953/// matches the specialization \c X<Y>
954AST_MATCHER_P(TemplateArgument, refersToTemplate,
955 internal::Matcher<TemplateName>, InnerMatcher) {
956 if (Node.getKind() != TemplateArgument::Template)
957 return false;
958 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
959}
960
961/// Matches a canonical TemplateArgument that refers to a certain
962/// declaration.
963///
964/// Given
965/// \code
966/// struct B { int next; };
967/// template<int(B::*next_ptr)> struct A {};
968/// A<&B::next> a;
969/// \endcode
970/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
971/// refersToDeclaration(fieldDecl(hasName("next")))))
972/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
973/// \c B::next
974AST_MATCHER_P(TemplateArgument, refersToDeclaration,
975 internal::Matcher<Decl>, InnerMatcher) {
976 if (Node.getKind() == TemplateArgument::Declaration)
977 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
978 return false;
979}
980
981/// Matches a sugar TemplateArgument that refers to a certain expression.
982///
983/// Given
984/// \code
985/// struct B { int next; };
986/// template<int(B::*next_ptr)> struct A {};
987/// A<&B::next> a;
988/// \endcode
989/// templateSpecializationType(hasAnyTemplateArgument(
990/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
991/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
992/// \c B::next
993AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
994 if (Node.getKind() == TemplateArgument::Expression)
995 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
996 return false;
997}
998
999/// Matches a TemplateArgument that is an integral value.
1000///
1001/// Given
1002/// \code
1003/// template<int T> struct C {};
1004/// C<42> c;
1005/// \endcode
1006/// classTemplateSpecializationDecl(
1007/// hasAnyTemplateArgument(isIntegral()))
1008/// matches the implicit instantiation of C in C<42>
1009/// with isIntegral() matching 42.
1010AST_MATCHER(TemplateArgument, isIntegral) {
1011 return Node.getKind() == TemplateArgument::Integral;
1012}
1013
1014/// Matches a TemplateArgument that referes to an integral type.
1015///
1016/// Given
1017/// \code
1018/// template<int T> struct C {};
1019/// C<42> c;
1020/// \endcode
1021/// classTemplateSpecializationDecl(
1022/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1023/// matches the implicit instantiation of C in C<42>.
1024AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1025 internal::Matcher<QualType>, InnerMatcher) {
1026 if (Node.getKind() != TemplateArgument::Integral)
1027 return false;
1028 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1029}
1030
1031/// Matches a TemplateArgument of integral type with a given value.
1032///
1033/// Note that 'Value' is a string as the template argument's value is
1034/// an arbitrary precision integer. 'Value' must be euqal to the canonical
1035/// representation of that integral value in base 10.
1036///
1037/// Given
1038/// \code
1039/// template<int T> struct C {};
1040/// C<42> c;
1041/// \endcode
1042/// classTemplateSpecializationDecl(
1043/// hasAnyTemplateArgument(equalsIntegralValue("42")))
1044/// matches the implicit instantiation of C in C<42>.
1045AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1046 std::string, Value) {
1047 if (Node.getKind() != TemplateArgument::Integral)
1048 return false;
1049 return Node.getAsIntegral().toString(10) == Value;
1050}
1051
1052/// Matches an Objective-C autorelease pool statement.
1053///
1054/// Given
1055/// \code
1056/// @autoreleasepool {
1057/// int x = 0;
1058/// }
1059/// \endcode
1060/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1061/// inside the autorelease pool.
1062extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1063 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1064
1065/// Matches any value declaration.
1066///
1067/// Example matches A, B, C and F
1068/// \code
1069/// enum X { A, B, C };
1070/// void F();
1071/// \endcode
1072extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1073
1074/// Matches C++ constructor declarations.
1075///
1076/// Example matches Foo::Foo() and Foo::Foo(int)
1077/// \code
1078/// class Foo {
1079/// public:
1080/// Foo();
1081/// Foo(int);
1082/// int DoSomething();
1083/// };
1084/// \endcode
1085extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1086 cxxConstructorDecl;
1087
1088/// Matches explicit C++ destructor declarations.
1089///
1090/// Example matches Foo::~Foo()
1091/// \code
1092/// class Foo {
1093/// public:
1094/// virtual ~Foo();
1095/// };
1096/// \endcode
1097extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1098 cxxDestructorDecl;
1099
1100/// Matches enum declarations.
1101///
1102/// Example matches X
1103/// \code
1104/// enum X {
1105/// A, B, C
1106/// };
1107/// \endcode
1108extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1109
1110/// Matches enum constants.
1111///
1112/// Example matches A, B, C
1113/// \code
1114/// enum X {
1115/// A, B, C
1116/// };
1117/// \endcode
1118extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1119 enumConstantDecl;
1120
1121/// Matches method declarations.
1122///
1123/// Example matches y
1124/// \code
1125/// class X { void y(); };
1126/// \endcode
1127extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1128 cxxMethodDecl;
1129
1130/// Matches conversion operator declarations.
1131///
1132/// Example matches the operator.
1133/// \code
1134/// class X { operator int() const; };
1135/// \endcode
1136extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1137 cxxConversionDecl;
1138
1139/// Matches variable declarations.
1140///
1141/// Note: this does not match declarations of member variables, which are
1142/// "field" declarations in Clang parlance.
1143///
1144/// Example matches a
1145/// \code
1146/// int a;
1147/// \endcode
1148extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1149
1150/// Matches field declarations.
1151///
1152/// Given
1153/// \code
1154/// class X { int m; };
1155/// \endcode
1156/// fieldDecl()
1157/// matches 'm'.
1158extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1159
1160/// Matches indirect field declarations.
1161///
1162/// Given
1163/// \code
1164/// struct X { struct { int a; }; };
1165/// \endcode
1166/// indirectFieldDecl()
1167/// matches 'a'.
1168extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1169 indirectFieldDecl;
1170
1171/// Matches function declarations.
1172///
1173/// Example matches f
1174/// \code
1175/// void f();
1176/// \endcode
1177extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1178 functionDecl;
1179
1180/// Matches C++ function template declarations.
1181///
1182/// Example matches f
1183/// \code
1184/// template<class T> void f(T t) {}
1185/// \endcode
1186extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1187 functionTemplateDecl;
1188
1189/// Matches friend declarations.
1190///
1191/// Given
1192/// \code
1193/// class X { friend void foo(); };
1194/// \endcode
1195/// friendDecl()
1196/// matches 'friend void foo()'.
1197extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1198
1199/// Matches statements.
1200///
1201/// Given
1202/// \code
1203/// { ++a; }
1204/// \endcode
1205/// stmt()
1206/// matches both the compound statement '{ ++a; }' and '++a'.
1207extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1208
1209/// Matches declaration statements.
1210///
1211/// Given
1212/// \code
1213/// int a;
1214/// \endcode
1215/// declStmt()
1216/// matches 'int a'.
1217extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1218
1219/// Matches member expressions.
1220///
1221/// Given
1222/// \code
1223/// class Y {
1224/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1225/// int a; static int b;
1226/// };
1227/// \endcode
1228/// memberExpr()
1229/// matches this->x, x, y.x, a, this->b
1230extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1231
1232/// Matches unresolved member expressions.
1233///
1234/// Given
1235/// \code
1236/// struct X {
1237/// template <class T> void f();
1238/// void g();
1239/// };
1240/// template <class T> void h() { X x; x.f<T>(); x.g(); }
1241/// \endcode
1242/// unresolvedMemberExpr()
1243/// matches x.f<T>
1244extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1245 unresolvedMemberExpr;
1246
1247/// Matches member expressions where the actual member referenced could not be
1248/// resolved because the base expression or the member name was dependent.
1249///
1250/// Given
1251/// \code
1252/// template <class T> void f() { T t; t.g(); }
1253/// \endcode
1254/// cxxDependentScopeMemberExpr()
1255/// matches t.g
1256extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1257 CXXDependentScopeMemberExpr>
1258 cxxDependentScopeMemberExpr;
1259
1260/// Matches call expressions.
1261///
1262/// Example matches x.y() and y()
1263/// \code
1264/// X x;
1265/// x.y();
1266/// y();
1267/// \endcode
1268extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1269
1270/// Matches call expressions which were resolved using ADL.
1271///
1272/// Example matches y(x) but not y(42) or NS::y(x).
1273/// \code
1274/// namespace NS {
1275/// struct X {};
1276/// void y(X);
1277/// }
1278///
1279/// void y(...);
1280///
1281/// void test() {
1282/// NS::X x;
1283/// y(x); // Matches
1284/// NS::y(x); // Doesn't match
1285/// y(42); // Doesn't match
1286/// using NS::y;
1287/// y(x); // Found by both unqualified lookup and ADL, doesn't match
1288// }
1289/// \endcode
1290AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1291
1292/// Matches lambda expressions.
1293///
1294/// Example matches [&](){return 5;}
1295/// \code
1296/// [&](){return 5;}
1297/// \endcode
1298extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1299
1300/// Matches member call expressions.
1301///
1302/// Example matches x.y()
1303/// \code
1304/// X x;
1305/// x.y();
1306/// \endcode
1307extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1308 cxxMemberCallExpr;
1309
1310/// Matches ObjectiveC Message invocation expressions.
1311///
1312/// The innermost message send invokes the "alloc" class method on the
1313/// NSString class, while the outermost message send invokes the
1314/// "initWithString" instance method on the object returned from
1315/// NSString's "alloc". This matcher should match both message sends.
1316/// \code
1317/// [[NSString alloc] initWithString:@"Hello"]
1318/// \endcode
1319extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1320 objcMessageExpr;
1321
1322/// Matches Objective-C interface declarations.
1323///
1324/// Example matches Foo
1325/// \code
1326/// @interface Foo
1327/// @end
1328/// \endcode
1329extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1330 objcInterfaceDecl;
1331
1332/// Matches Objective-C implementation declarations.
1333///
1334/// Example matches Foo
1335/// \code
1336/// @implementation Foo
1337/// @end
1338/// \endcode
1339extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1340 objcImplementationDecl;
1341
1342/// Matches Objective-C protocol declarations.
1343///
1344/// Example matches FooDelegate
1345/// \code
1346/// @protocol FooDelegate
1347/// @end
1348/// \endcode
1349extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1350 objcProtocolDecl;
1351
1352/// Matches Objective-C category declarations.
1353///
1354/// Example matches Foo (Additions)
1355/// \code
1356/// @interface Foo (Additions)
1357/// @end
1358/// \endcode
1359extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1360 objcCategoryDecl;
1361
1362/// Matches Objective-C category definitions.
1363///
1364/// Example matches Foo (Additions)
1365/// \code
1366/// @implementation Foo (Additions)
1367/// @end
1368/// \endcode
1369extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1370 objcCategoryImplDecl;
1371
1372/// Matches Objective-C method declarations.
1373///
1374/// Example matches both declaration and definition of -[Foo method]
1375/// \code
1376/// @interface Foo
1377/// - (void)method;
1378/// @end
1379///
1380/// @implementation Foo
1381/// - (void)method {}
1382/// @end
1383/// \endcode
1384extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1385 objcMethodDecl;
1386
1387/// Matches block declarations.
1388///
1389/// Example matches the declaration of the nameless block printing an input
1390/// integer.
1391///
1392/// \code
1393/// myFunc(^(int p) {
1394/// printf("%d", p);
1395/// })
1396/// \endcode
1397extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1398 blockDecl;
1399
1400/// Matches Objective-C instance variable declarations.
1401///
1402/// Example matches _enabled
1403/// \code
1404/// @implementation Foo {
1405/// BOOL _enabled;
1406/// }
1407/// @end
1408/// \endcode
1409extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1410 objcIvarDecl;
1411
1412/// Matches Objective-C property declarations.
1413///
1414/// Example matches enabled
1415/// \code
1416/// @interface Foo
1417/// @property BOOL enabled;
1418/// @end
1419/// \endcode
1420extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1421 objcPropertyDecl;
1422
1423/// Matches Objective-C \@throw statements.
1424///
1425/// Example matches \@throw
1426/// \code
1427/// @throw obj;
1428/// \endcode
1429extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1430 objcThrowStmt;
1431
1432/// Matches Objective-C @try statements.
1433///
1434/// Example matches @try
1435/// \code
1436/// @try {}
1437/// @catch (...) {}
1438/// \endcode
1439extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1440 objcTryStmt;
1441
1442/// Matches Objective-C @catch statements.
1443///
1444/// Example matches @catch
1445/// \code
1446/// @try {}
1447/// @catch (...) {}
1448/// \endcode
1449extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1450 objcCatchStmt;
1451
1452/// Matches Objective-C @finally statements.
1453///
1454/// Example matches @finally
1455/// \code
1456/// @try {}
1457/// @finally {}
1458/// \endcode
1459extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1460 objcFinallyStmt;
1461
1462/// Matches expressions that introduce cleanups to be run at the end
1463/// of the sub-expression's evaluation.
1464///
1465/// Example matches std::string()
1466/// \code
1467/// const std::string str = std::string();
1468/// \endcode
1469extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1470 exprWithCleanups;
1471
1472/// Matches init list expressions.
1473///
1474/// Given
1475/// \code
1476/// int a[] = { 1, 2 };
1477/// struct B { int x, y; };
1478/// B b = { 5, 6 };
1479/// \endcode
1480/// initListExpr()
1481/// matches "{ 1, 2 }" and "{ 5, 6 }"
1482extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1483 initListExpr;
1484
1485/// Matches the syntactic form of init list expressions
1486/// (if expression have it).
1487AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1488 internal::Matcher<Expr>, InnerMatcher) {
1489 const Expr *SyntForm = Node.getSyntacticForm();
1490 return (SyntForm != nullptr &&
1491 InnerMatcher.matches(*SyntForm, Finder, Builder));
1492}
1493
1494/// Matches C++ initializer list expressions.
1495///
1496/// Given
1497/// \code
1498/// std::vector<int> a({ 1, 2, 3 });
1499/// std::vector<int> b = { 4, 5 };
1500/// int c[] = { 6, 7 };
1501/// std::pair<int, int> d = { 8, 9 };
1502/// \endcode
1503/// cxxStdInitializerListExpr()
1504/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1505extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1506 CXXStdInitializerListExpr>
1507 cxxStdInitializerListExpr;
1508
1509/// Matches implicit initializers of init list expressions.
1510///
1511/// Given
1512/// \code
1513/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1514/// \endcode
1515/// implicitValueInitExpr()
1516/// matches "[0].y" (implicitly)
1517extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1518 implicitValueInitExpr;
1519
1520/// Matches paren list expressions.
1521/// ParenListExprs don't have a predefined type and are used for late parsing.
1522/// In the final AST, they can be met in template declarations.
1523///
1524/// Given
1525/// \code
1526/// template<typename T> class X {
1527/// void f() {
1528/// X x(*this);
1529/// int a = 0, b = 1; int i = (a, b);
1530/// }
1531/// };
1532/// \endcode
1533/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1534/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1535extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1536 parenListExpr;
1537
1538/// Matches substitutions of non-type template parameters.
1539///
1540/// Given
1541/// \code
1542/// template <int N>
1543/// struct A { static const int n = N; };
1544/// struct B : public A<42> {};
1545/// \endcode
1546/// substNonTypeTemplateParmExpr()
1547/// matches "N" in the right-hand side of "static const int n = N;"
1548extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1549 SubstNonTypeTemplateParmExpr>
1550 substNonTypeTemplateParmExpr;
1551
1552/// Matches using declarations.
1553///
1554/// Given
1555/// \code
1556/// namespace X { int x; }
1557/// using X::x;
1558/// \endcode
1559/// usingDecl()
1560/// matches \code using X::x \endcode
1561extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1562
1563/// Matches using namespace declarations.
1564///
1565/// Given
1566/// \code
1567/// namespace X { int x; }
1568/// using namespace X;
1569/// \endcode
1570/// usingDirectiveDecl()
1571/// matches \code using namespace X \endcode
1572extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1573 usingDirectiveDecl;
1574
1575/// Matches reference to a name that can be looked up during parsing
1576/// but could not be resolved to a specific declaration.
1577///
1578/// Given
1579/// \code
1580/// template<typename T>
1581/// T foo() { T a; return a; }
1582/// template<typename T>
1583/// void bar() {
1584/// foo<T>();
1585/// }
1586/// \endcode
1587/// unresolvedLookupExpr()
1588/// matches \code foo<T>() \endcode
1589extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1590 unresolvedLookupExpr;
1591
1592/// Matches unresolved using value declarations.
1593///
1594/// Given
1595/// \code
1596/// template<typename X>
1597/// class C : private X {
1598/// using X::x;
1599/// };
1600/// \endcode
1601/// unresolvedUsingValueDecl()
1602/// matches \code using X::x \endcode
1603extern const internal::VariadicDynCastAllOfMatcher<Decl,
1604 UnresolvedUsingValueDecl>
1605 unresolvedUsingValueDecl;
1606
1607/// Matches unresolved using value declarations that involve the
1608/// typename.
1609///
1610/// Given
1611/// \code
1612/// template <typename T>
1613/// struct Base { typedef T Foo; };
1614///
1615/// template<typename T>
1616/// struct S : private Base<T> {
1617/// using typename Base<T>::Foo;
1618/// };
1619/// \endcode
1620/// unresolvedUsingTypenameDecl()
1621/// matches \code using Base<T>::Foo \endcode
1622extern const internal::VariadicDynCastAllOfMatcher<Decl,
1623 UnresolvedUsingTypenameDecl>
1624 unresolvedUsingTypenameDecl;
1625
1626/// Matches a constant expression wrapper.
1627///
1628/// Example matches the constant in the case statement:
1629/// (matcher = constantExpr())
1630/// \code
1631/// switch (a) {
1632/// case 37: break;
1633/// }
1634/// \endcode
1635extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1636 constantExpr;
1637
1638/// Matches parentheses used in expressions.
1639///
1640/// Example matches (foo() + 1)
1641/// \code
1642/// int foo() { return 1; }
1643/// int a = (foo() + 1);
1644/// \endcode
1645extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1646
1647/// Matches constructor call expressions (including implicit ones).
1648///
1649/// Example matches string(ptr, n) and ptr within arguments of f
1650/// (matcher = cxxConstructExpr())
1651/// \code
1652/// void f(const string &a, const string &b);
1653/// char *ptr;
1654/// int n;
1655/// f(string(ptr, n), ptr);
1656/// \endcode
1657extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1658 cxxConstructExpr;
1659
1660/// Matches unresolved constructor call expressions.
1661///
1662/// Example matches T(t) in return statement of f
1663/// (matcher = cxxUnresolvedConstructExpr())
1664/// \code
1665/// template <typename T>
1666/// void f(const T& t) { return T(t); }
1667/// \endcode
1668extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1669 CXXUnresolvedConstructExpr>
1670 cxxUnresolvedConstructExpr;
1671
1672/// Matches implicit and explicit this expressions.
1673///
1674/// Example matches the implicit this expression in "return i".
1675/// (matcher = cxxThisExpr())
1676/// \code
1677/// struct foo {
1678/// int i;
1679/// int f() { return i; }
1680/// };
1681/// \endcode
1682extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1683 cxxThisExpr;
1684
1685/// Matches nodes where temporaries are created.
1686///
1687/// Example matches FunctionTakesString(GetStringByValue())
1688/// (matcher = cxxBindTemporaryExpr())
1689/// \code
1690/// FunctionTakesString(GetStringByValue());
1691/// FunctionTakesStringByPointer(GetStringPointer());
1692/// \endcode
1693extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1694 cxxBindTemporaryExpr;
1695
1696/// Matches nodes where temporaries are materialized.
1697///
1698/// Example: Given
1699/// \code
1700/// struct T {void func();};
1701/// T f();
1702/// void g(T);
1703/// \endcode
1704/// materializeTemporaryExpr() matches 'f()' in these statements
1705/// \code
1706/// T u(f());
1707/// g(f());
1708/// f().func();
1709/// \endcode
1710/// but does not match
1711/// \code
1712/// f();
1713/// \endcode
1714extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1715 MaterializeTemporaryExpr>
1716 materializeTemporaryExpr;
1717
1718/// Matches new expressions.
1719///
1720/// Given
1721/// \code
1722/// new X;
1723/// \endcode
1724/// cxxNewExpr()
1725/// matches 'new X'.
1726extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1727
1728/// Matches delete expressions.
1729///
1730/// Given
1731/// \code
1732/// delete X;
1733/// \endcode
1734/// cxxDeleteExpr()
1735/// matches 'delete X'.
1736extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1737 cxxDeleteExpr;
1738
1739/// Matches array subscript expressions.
1740///
1741/// Given
1742/// \code
1743/// int i = a[1];
1744/// \endcode
1745/// arraySubscriptExpr()
1746/// matches "a[1]"
1747extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1748 arraySubscriptExpr;
1749
1750/// Matches the value of a default argument at the call site.
1751///
1752/// Example matches the CXXDefaultArgExpr placeholder inserted for the
1753/// default value of the second parameter in the call expression f(42)
1754/// (matcher = cxxDefaultArgExpr())
1755/// \code
1756/// void f(int x, int y = 0);
1757/// f(42);
1758/// \endcode
1759extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1760 cxxDefaultArgExpr;
1761
1762/// Matches overloaded operator calls.
1763///
1764/// Note that if an operator isn't overloaded, it won't match. Instead, use
1765/// binaryOperator matcher.
1766/// Currently it does not match operators such as new delete.
1767/// FIXME: figure out why these do not match?
1768///
1769/// Example matches both operator<<((o << b), c) and operator<<(o, b)
1770/// (matcher = cxxOperatorCallExpr())
1771/// \code
1772/// ostream &operator<< (ostream &out, int i) { };
1773/// ostream &o; int b = 1, c = 1;
1774/// o << b << c;
1775/// \endcode
1776extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1777 cxxOperatorCallExpr;
1778
1779/// Matches expressions.
1780///
1781/// Example matches x()
1782/// \code
1783/// void f() { x(); }
1784/// \endcode
1785extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1786
1787/// Matches expressions that refer to declarations.
1788///
1789/// Example matches x in if (x)
1790/// \code
1791/// bool x;
1792/// if (x) {}
1793/// \endcode
1794extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1795 declRefExpr;
1796
1797/// Matches a reference to an ObjCIvar.
1798///
1799/// Example: matches "a" in "init" method:
1800/// \code
1801/// @implementation A {
1802/// NSString *a;
1803/// }
1804/// - (void) init {
1805/// a = @"hello";
1806/// }
1807/// \endcode
1808extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1809 objcIvarRefExpr;
1810
1811/// Matches a reference to a block.
1812///
1813/// Example: matches "^{}":
1814/// \code
1815/// void f() { ^{}(); }
1816/// \endcode
1817extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
1818
1819/// Matches if statements.
1820///
1821/// Example matches 'if (x) {}'
1822/// \code
1823/// if (x) {}
1824/// \endcode
1825extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1826
1827/// Matches for statements.
1828///
1829/// Example matches 'for (;;) {}'
1830/// \code
1831/// for (;;) {}
1832/// int i[] = {1, 2, 3}; for (auto a : i);
1833/// \endcode
1834extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1835
1836/// Matches the increment statement of a for loop.
1837///
1838/// Example:
1839/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1840/// matches '++x' in
1841/// \code
1842/// for (x; x < N; ++x) { }
1843/// \endcode
1844AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1845 InnerMatcher) {
1846 const Stmt *const Increment = Node.getInc();
1847 return (Increment != nullptr &&
1848 InnerMatcher.matches(*Increment, Finder, Builder));
1849}
1850
1851/// Matches the initialization statement of a for loop.
1852///
1853/// Example:
1854/// forStmt(hasLoopInit(declStmt()))
1855/// matches 'int x = 0' in
1856/// \code
1857/// for (int x = 0; x < N; ++x) { }
1858/// \endcode
1859AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1860 InnerMatcher) {
1861 const Stmt *const Init = Node.getInit();
1862 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1863}
1864
1865/// Matches range-based for statements.
1866///
1867/// cxxForRangeStmt() matches 'for (auto a : i)'
1868/// \code
1869/// int i[] = {1, 2, 3}; for (auto a : i);
1870/// for(int j = 0; j < 5; ++j);
1871/// \endcode
1872extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1873 cxxForRangeStmt;
1874
1875/// Matches the initialization statement of a for loop.
1876///
1877/// Example:
1878/// forStmt(hasLoopVariable(anything()))
1879/// matches 'int x' in
1880/// \code
1881/// for (int x : a) { }
1882/// \endcode
1883AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1884 InnerMatcher) {
1885 const VarDecl *const Var = Node.getLoopVariable();
1886 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1887}
1888
1889/// Matches the range initialization statement of a for loop.
1890///
1891/// Example:
1892/// forStmt(hasRangeInit(anything()))
1893/// matches 'a' in
1894/// \code
1895/// for (int x : a) { }
1896/// \endcode
1897AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1898 InnerMatcher) {
1899 const Expr *const Init = Node.getRangeInit();
1900 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1901}
1902
1903/// Matches while statements.
1904///
1905/// Given
1906/// \code
1907/// while (true) {}
1908/// \endcode
1909/// whileStmt()
1910/// matches 'while (true) {}'.
1911extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1912
1913/// Matches do statements.
1914///
1915/// Given
1916/// \code
1917/// do {} while (true);
1918/// \endcode
1919/// doStmt()
1920/// matches 'do {} while(true)'
1921extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1922
1923/// Matches break statements.
1924///
1925/// Given
1926/// \code
1927/// while (true) { break; }
1928/// \endcode
1929/// breakStmt()
1930/// matches 'break'
1931extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1932
1933/// Matches continue statements.
1934///
1935/// Given
1936/// \code
1937/// while (true) { continue; }
1938/// \endcode
1939/// continueStmt()
1940/// matches 'continue'
1941extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1942 continueStmt;
1943
1944/// Matches return statements.
1945///
1946/// Given
1947/// \code
1948/// return 1;
1949/// \endcode
1950/// returnStmt()
1951/// matches 'return 1'
1952extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1953
1954/// Matches goto statements.
1955///
1956/// Given
1957/// \code
1958/// goto FOO;
1959/// FOO: bar();
1960/// \endcode
1961/// gotoStmt()
1962/// matches 'goto FOO'
1963extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1964
1965/// Matches label statements.
1966///
1967/// Given
1968/// \code
1969/// goto FOO;
1970/// FOO: bar();
1971/// \endcode
1972/// labelStmt()
1973/// matches 'FOO:'
1974extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1975
1976/// Matches address of label statements (GNU extension).
1977///
1978/// Given
1979/// \code
1980/// FOO: bar();
1981/// void *ptr = &&FOO;
1982/// goto *bar;
1983/// \endcode
1984/// addrLabelExpr()
1985/// matches '&&FOO'
1986extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
1987 addrLabelExpr;
1988
1989/// Matches switch statements.
1990///
1991/// Given
1992/// \code
1993/// switch(a) { case 42: break; default: break; }
1994/// \endcode
1995/// switchStmt()
1996/// matches 'switch(a)'.
1997extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1998
1999/// Matches case and default statements inside switch statements.
2000///
2001/// Given
2002/// \code
2003/// switch(a) { case 42: break; default: break; }
2004/// \endcode
2005/// switchCase()
2006/// matches 'case 42:' and 'default:'.
2007extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2008
2009/// Matches case statements inside switch statements.
2010///
2011/// Given
2012/// \code
2013/// switch(a) { case 42: break; default: break; }
2014/// \endcode
2015/// caseStmt()
2016/// matches 'case 42:'.
2017extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2018
2019/// Matches default statements inside switch statements.
2020///
2021/// Given
2022/// \code
2023/// switch(a) { case 42: break; default: break; }
2024/// \endcode
2025/// defaultStmt()
2026/// matches 'default:'.
2027extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2028 defaultStmt;
2029
2030/// Matches compound statements.
2031///
2032/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2033/// \code
2034/// for (;;) {{}}
2035/// \endcode
2036extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2037 compoundStmt;
2038
2039/// Matches catch statements.
2040///
2041/// \code
2042/// try {} catch(int i) {}
2043/// \endcode
2044/// cxxCatchStmt()
2045/// matches 'catch(int i)'
2046extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2047 cxxCatchStmt;
2048
2049/// Matches try statements.
2050///
2051/// \code
2052/// try {} catch(int i) {}
2053/// \endcode
2054/// cxxTryStmt()
2055/// matches 'try {}'
2056extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2057
2058/// Matches throw expressions.
2059///
2060/// \code
2061/// try { throw 5; } catch(int i) {}
2062/// \endcode
2063/// cxxThrowExpr()
2064/// matches 'throw 5'
2065extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2066 cxxThrowExpr;
2067
2068/// Matches null statements.
2069///
2070/// \code
2071/// foo();;
2072/// \endcode
2073/// nullStmt()
2074/// matches the second ';'
2075extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2076
2077/// Matches asm statements.
2078///
2079/// \code
2080/// int i = 100;
2081/// __asm("mov al, 2");
2082/// \endcode
2083/// asmStmt()
2084/// matches '__asm("mov al, 2")'
2085extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2086
2087/// Matches bool literals.
2088///
2089/// Example matches true
2090/// \code
2091/// true
2092/// \endcode
2093extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2094 cxxBoolLiteral;
2095
2096/// Matches string literals (also matches wide string literals).
2097///
2098/// Example matches "abcd", L"abcd"
2099/// \code
2100/// char *s = "abcd";
2101/// wchar_t *ws = L"abcd";
2102/// \endcode
2103extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2104 stringLiteral;
2105
2106/// Matches character literals (also matches wchar_t).
2107///
2108/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2109/// though.
2110///
2111/// Example matches 'a', L'a'
2112/// \code
2113/// char ch = 'a';
2114/// wchar_t chw = L'a';
2115/// \endcode
2116extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2117 characterLiteral;
2118
2119/// Matches integer literals of all sizes / encodings, e.g.
2120/// 1, 1L, 0x1 and 1U.
2121///
2122/// Does not match character-encoded integers such as L'a'.
2123extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2124 integerLiteral;
2125
2126/// Matches float literals of all sizes / encodings, e.g.
2127/// 1.0, 1.0f, 1.0L and 1e10.
2128///
2129/// Does not match implicit conversions such as
2130/// \code
2131/// float a = 10;
2132/// \endcode
2133extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2134 floatLiteral;
2135
2136/// Matches imaginary literals, which are based on integer and floating
2137/// point literals e.g.: 1i, 1.0i
2138extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2139 imaginaryLiteral;
2140
2141/// Matches user defined literal operator call.
2142///
2143/// Example match: "foo"_suffix
2144extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2145 userDefinedLiteral;
2146
2147/// Matches compound (i.e. non-scalar) literals
2148///
2149/// Example match: {1}, (1, 2)
2150/// \code
2151/// int array[4] = {1};
2152/// vector int myvec = (vector int)(1, 2);
2153/// \endcode
2154extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2155 compoundLiteralExpr;
2156
2157/// Matches nullptr literal.
2158extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2159 cxxNullPtrLiteralExpr;
2160
2161/// Matches GNU __null expression.
2162extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2163 gnuNullExpr;
2164
2165/// Matches atomic builtins.
2166/// Example matches __atomic_load_n(ptr, 1)
2167/// \code
2168/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2169/// \endcode
2170extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2171
2172/// Matches statement expression (GNU extension).
2173///
2174/// Example match: ({ int X = 4; X; })
2175/// \code
2176/// int C = ({ int X = 4; X; });
2177/// \endcode
2178extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2179
2180/// Matches binary operator expressions.
2181///
2182/// Example matches a || b
2183/// \code
2184/// !(a || b)
2185/// \endcode
2186extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2187 binaryOperator;
2188
2189/// Matches unary operator expressions.
2190///
2191/// Example matches !a
2192/// \code
2193/// !a || b
2194/// \endcode
2195extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2196 unaryOperator;
2197
2198/// Matches conditional operator expressions.
2199///
2200/// Example matches a ? b : c
2201/// \code
2202/// (a ? b : c) + 42
2203/// \endcode
2204extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2205 conditionalOperator;
2206
2207/// Matches binary conditional operator expressions (GNU extension).
2208///
2209/// Example matches a ?: b
2210/// \code
2211/// (a ?: b) + 42;
2212/// \endcode
2213extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2214 BinaryConditionalOperator>
2215 binaryConditionalOperator;
2216
2217/// Matches opaque value expressions. They are used as helpers
2218/// to reference another expressions and can be met
2219/// in BinaryConditionalOperators, for example.
2220///
2221/// Example matches 'a'
2222/// \code
2223/// (a ?: c) + 42;
2224/// \endcode
2225extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2226 opaqueValueExpr;
2227
2228/// Matches a C++ static_assert declaration.
2229///
2230/// Example:
2231/// staticAssertExpr()
2232/// matches
2233/// static_assert(sizeof(S) == sizeof(int))
2234/// in
2235/// \code
2236/// struct S {
2237/// int x;
2238/// };
2239/// static_assert(sizeof(S) == sizeof(int));
2240/// \endcode
2241extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2242 staticAssertDecl;
2243
2244/// Matches a reinterpret_cast expression.
2245///
2246/// Either the source expression or the destination type can be matched
2247/// using has(), but hasDestinationType() is more specific and can be
2248/// more readable.
2249///
2250/// Example matches reinterpret_cast<char*>(&p) in
2251/// \code
2252/// void* p = reinterpret_cast<char*>(&p);
2253/// \endcode
2254extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2255 cxxReinterpretCastExpr;
2256
2257/// Matches a C++ static_cast expression.
2258///
2259/// \see hasDestinationType
2260/// \see reinterpretCast
2261///
2262/// Example:
2263/// cxxStaticCastExpr()
2264/// matches
2265/// static_cast<long>(8)
2266/// in
2267/// \code
2268/// long eight(static_cast<long>(8));
2269/// \endcode
2270extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2271 cxxStaticCastExpr;
2272
2273/// Matches a dynamic_cast expression.
2274///
2275/// Example:
2276/// cxxDynamicCastExpr()
2277/// matches
2278/// dynamic_cast<D*>(&b);
2279/// in
2280/// \code
2281/// struct B { virtual ~B() {} }; struct D : B {};
2282/// B b;
2283/// D* p = dynamic_cast<D*>(&b);
2284/// \endcode
2285extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2286 cxxDynamicCastExpr;
2287
2288/// Matches a const_cast expression.
2289///
2290/// Example: Matches const_cast<int*>(&r) in
2291/// \code
2292/// int n = 42;
2293/// const int &r(n);
2294/// int* p = const_cast<int*>(&r);
2295/// \endcode
2296extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2297 cxxConstCastExpr;
2298
2299/// Matches a C-style cast expression.
2300///
2301/// Example: Matches (int) 2.2f in
2302/// \code
2303/// int i = (int) 2.2f;
2304/// \endcode
2305extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2306 cStyleCastExpr;
2307
2308/// Matches explicit cast expressions.
2309///
2310/// Matches any cast expression written in user code, whether it be a
2311/// C-style cast, a functional-style cast, or a keyword cast.
2312///
2313/// Does not match implicit conversions.
2314///
2315/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2316/// Clang uses the term "cast" to apply to implicit conversions as well as to
2317/// actual cast expressions.
2318///
2319/// \see hasDestinationType.
2320///
2321/// Example: matches all five of the casts in
2322/// \code
2323/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2324/// \endcode
2325/// but does not match the implicit conversion in
2326/// \code
2327/// long ell = 42;
2328/// \endcode
2329extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2330 explicitCastExpr;
2331
2332/// Matches the implicit cast nodes of Clang's AST.
2333///
2334/// This matches many different places, including function call return value
2335/// eliding, as well as any type conversions.
2336extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2337 implicitCastExpr;
2338
2339/// Matches any cast nodes of Clang's AST.
2340///
2341/// Example: castExpr() matches each of the following:
2342/// \code
2343/// (int) 3;
2344/// const_cast<Expr *>(SubExpr);
2345/// char c = 0;
2346/// \endcode
2347/// but does not match
2348/// \code
2349/// int i = (0);
2350/// int k = 0;
2351/// \endcode
2352extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2353
2354/// Matches functional cast expressions
2355///
2356/// Example: Matches Foo(bar);
2357/// \code
2358/// Foo f = bar;
2359/// Foo g = (Foo) bar;
2360/// Foo h = Foo(bar);
2361/// \endcode
2362extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2363 cxxFunctionalCastExpr;
2364
2365/// Matches functional cast expressions having N != 1 arguments
2366///
2367/// Example: Matches Foo(bar, bar)
2368/// \code
2369/// Foo h = Foo(bar, bar);
2370/// \endcode
2371extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2372 cxxTemporaryObjectExpr;
2373
2374/// Matches predefined identifier expressions [C99 6.4.2.2].
2375///
2376/// Example: Matches __func__
2377/// \code
2378/// printf("%s", __func__);
2379/// \endcode
2380extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2381 predefinedExpr;
2382
2383/// Matches C99 designated initializer expressions [C99 6.7.8].
2384///
2385/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2386/// \code
2387/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2388/// \endcode
2389extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2390 designatedInitExpr;
2391
2392/// Matches designated initializer expressions that contain
2393/// a specific number of designators.
2394///
2395/// Example: Given
2396/// \code
2397/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2398/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2399/// \endcode
2400/// designatorCountIs(2)
2401/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2402/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2403AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2404 return Node.size() == N;
2405}
2406
2407/// Matches \c QualTypes in the clang AST.
2408extern const internal::VariadicAllOfMatcher<QualType> qualType;
2409
2410/// Matches \c Types in the clang AST.
2411extern const internal::VariadicAllOfMatcher<Type> type;
2412
2413/// Matches \c TypeLocs in the clang AST.
2414extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2415
2416/// Matches if any of the given matchers matches.
2417///
2418/// Unlike \c anyOf, \c eachOf will generate a match result for each
2419/// matching submatcher.
2420///
2421/// For example, in:
2422/// \code
2423/// class A { int a; int b; };
2424/// \endcode
2425/// The matcher:
2426/// \code
2427/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2428/// has(fieldDecl(hasName("b")).bind("v"))))
2429/// \endcode
2430/// will generate two results binding "v", the first of which binds
2431/// the field declaration of \c a, the second the field declaration of
2432/// \c b.
2433///
2434/// Usable as: Any Matcher
2435extern const internal::VariadicOperatorMatcherFunc<
2436 2, std::numeric_limits<unsigned>::max()>
2437 eachOf;
2438
2439/// Matches if any of the given matchers matches.
2440///
2441/// Usable as: Any Matcher
2442extern const internal::VariadicOperatorMatcherFunc<
2443 2, std::numeric_limits<unsigned>::max()>
2444 anyOf;
2445
2446/// Matches if all given matchers match.
2447///
2448/// Usable as: Any Matcher
2449extern const internal::VariadicOperatorMatcherFunc<
2450 2, std::numeric_limits<unsigned>::max()>
2451 allOf;
2452
2453/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2454///
2455/// Given
2456/// \code
2457/// Foo x = bar;
2458/// int y = sizeof(x) + alignof(x);
2459/// \endcode
2460/// unaryExprOrTypeTraitExpr()
2461/// matches \c sizeof(x) and \c alignof(x)
2462extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2463 UnaryExprOrTypeTraitExpr>
2464 unaryExprOrTypeTraitExpr;
2465
2466/// Matches unary expressions that have a specific type of argument.
2467///
2468/// Given
2469/// \code
2470/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2471/// \endcode
2472/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2473/// matches \c sizeof(a) and \c alignof(c)
2474AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2475 internal::Matcher<QualType>, InnerMatcher) {
2476 const QualType ArgumentType = Node.getTypeOfArgument();
2477 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2478}
2479
2480/// Matches unary expressions of a certain kind.
2481///
2482/// Given
2483/// \code
2484/// int x;
2485/// int s = sizeof(x) + alignof(x)
2486/// \endcode
2487/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2488/// matches \c sizeof(x)
2489AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2490 return Node.getKind() == Kind;
2491}
2492
2493/// Same as unaryExprOrTypeTraitExpr, but only matching
2494/// alignof.
2495inline internal::Matcher<Stmt> alignOfExpr(
2496 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2497 return stmt(unaryExprOrTypeTraitExpr(
2498 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2499 InnerMatcher)));
2500}
2501
2502/// Same as unaryExprOrTypeTraitExpr, but only matching
2503/// sizeof.
2504inline internal::Matcher<Stmt> sizeOfExpr(
2505 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2506 return stmt(unaryExprOrTypeTraitExpr(
2507 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2508}
2509
2510/// Matches NamedDecl nodes that have the specified name.
2511///
2512/// Supports specifying enclosing namespaces or classes by prefixing the name
2513/// with '<enclosing>::'.
2514/// Does not match typedefs of an underlying type with the given name.
2515///
2516/// Example matches X (Name == "X")
2517/// \code
2518/// class X;
2519/// \endcode
2520///
2521/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2522/// \code
2523/// namespace a { namespace b { class X; } }
2524/// \endcode
2525inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2526 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2527}
2528
2529/// Matches NamedDecl nodes that have any of the specified names.
2530///
2531/// This matcher is only provided as a performance optimization of hasName.
2532/// \code
2533/// hasAnyName(a, b, c)
2534/// \endcode
2535/// is equivalent to, but faster than
2536/// \code
2537/// anyOf(hasName(a), hasName(b), hasName(c))
2538/// \endcode
2539extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2540 internal::hasAnyNameFunc>
2541 hasAnyName;
2542
2543/// Matches NamedDecl nodes whose fully qualified names contain
2544/// a substring matched by the given RegExp.
2545///
2546/// Supports specifying enclosing namespaces or classes by
2547/// prefixing the name with '<enclosing>::'. Does not match typedefs
2548/// of an underlying type with the given name.
2549///
2550/// Example matches X (regexp == "::X")
2551/// \code
2552/// class X;
2553/// \endcode
2554///
2555/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2556/// \code
2557/// namespace foo { namespace bar { class X; } }
2558/// \endcode
2559AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2560 assert(!RegExp.empty());
2561 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2562 llvm::Regex RE(RegExp);
2563 return RE.match(FullNameString);
2564}
2565
2566/// Matches overloaded operator names.
2567///
2568/// Matches overloaded operator names specified in strings without the
2569/// "operator" prefix: e.g. "<<".
2570///
2571/// Given:
2572/// \code
2573/// class A { int operator*(); };
2574/// const A &operator<<(const A &a, const A &b);
2575/// A a;
2576/// a << a; // <-- This matches
2577/// \endcode
2578///
2579/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2580/// specified line and
2581/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2582/// matches the declaration of \c A.
2583///
2584/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2585inline internal::PolymorphicMatcherWithParam1<
2586 internal::HasOverloadedOperatorNameMatcher, StringRef,
2587 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2588hasOverloadedOperatorName(StringRef Name) {
2589 return internal::PolymorphicMatcherWithParam1<
2590 internal::HasOverloadedOperatorNameMatcher, StringRef,
2591 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2592}
2593
2594/// Matches C++ classes that are directly or indirectly derived from
2595/// a class matching \c Base.
2596///
2597/// Note that a class is not considered to be derived from itself.
2598///
2599/// Example matches Y, Z, C (Base == hasName("X"))
2600/// \code
2601/// class X;
2602/// class Y : public X {}; // directly derived
2603/// class Z : public Y {}; // indirectly derived
2604/// typedef X A;
2605/// typedef A B;
2606/// class C : public B {}; // derived from a typedef of X
2607/// \endcode
2608///
2609/// In the following example, Bar matches isDerivedFrom(hasName("X")):
2610/// \code
2611/// class Foo;
2612/// typedef Foo X;
2613/// class Bar : public Foo {}; // derived from a type that X is a typedef of
2614/// \endcode
2615AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2616 internal::Matcher<NamedDecl>, Base) {
2617 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2618}
2619
2620/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2621AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2622 assert(!BaseName.empty());
2623 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2624}
2625
2626/// Similar to \c isDerivedFrom(), but also matches classes that directly
2627/// match \c Base.
2628AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2629 internal::Matcher<NamedDecl>, Base, 0) {
2630 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2631 .matches(Node, Finder, Builder);
2632}
2633
2634/// Overloaded method as shortcut for
2635/// \c isSameOrDerivedFrom(hasName(...)).
2636AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2637 BaseName, 1) {
2638 assert(!BaseName.empty());
2639 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2640}
2641
2642/// Matches the first method of a class or struct that satisfies \c
2643/// InnerMatcher.
2644///
2645/// Given:
2646/// \code
2647/// class A { void func(); };
2648/// class B { void member(); };
2649/// \endcode
2650///
2651/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2652/// \c A but not \c B.
2653AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2654 InnerMatcher) {
2655 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2656 Node.method_end(), Finder, Builder);
2657}
2658
2659/// Matches the generated class of lambda expressions.
2660///
2661/// Given:
2662/// \code
2663/// auto x = []{};
2664/// \endcode
2665///
2666/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2667/// \c decltype(x)
2668AST_MATCHER(CXXRecordDecl, isLambda) {
2669 return Node.isLambda();
2670}
2671
2672/// Matches AST nodes that have child AST nodes that match the
2673/// provided matcher.
2674///
2675/// Example matches X, Y
2676/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2677/// \code
2678/// class X {}; // Matches X, because X::X is a class of name X inside X.
2679/// class Y { class X {}; };
2680/// class Z { class Y { class X {}; }; }; // Does not match Z.
2681/// \endcode
2682///
2683/// ChildT must be an AST base type.
2684///
2685/// Usable as: Any Matcher
2686/// Note that has is direct matcher, so it also matches things like implicit
2687/// casts and paren casts. If you are matching with expr then you should
2688/// probably consider using ignoringParenImpCasts like:
2689/// has(ignoringParenImpCasts(expr())).
2690extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2691
2692/// Matches AST nodes that have descendant AST nodes that match the
2693/// provided matcher.
2694///
2695/// Example matches X, Y, Z
2696/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2697/// \code
2698/// class X {}; // Matches X, because X::X is a class of name X inside X.
2699/// class Y { class X {}; };
2700/// class Z { class Y { class X {}; }; };
2701/// \endcode
2702///
2703/// DescendantT must be an AST base type.
2704///
2705/// Usable as: Any Matcher
2706extern const internal::ArgumentAdaptingMatcherFunc<
2707 internal::HasDescendantMatcher>
2708 hasDescendant;
2709
2710/// Matches AST nodes that have child AST nodes that match the
2711/// provided matcher.
2712///
2713/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2714/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2715/// \code
2716/// class X {};
2717/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
2718/// // inside Y.
2719/// class Z { class Y { class X {}; }; }; // Does not match Z.
2720/// \endcode
2721///
2722/// ChildT must be an AST base type.
2723///
2724/// As opposed to 'has', 'forEach' will cause a match for each result that
2725/// matches instead of only on the first one.
2726///
2727/// Usable as: Any Matcher
2728extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2729 forEach;
2730
2731/// Matches AST nodes that have descendant AST nodes that match the
2732/// provided matcher.
2733///
2734/// Example matches X, A, A::X, B, B::C, B::C::X
2735/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2736/// \code
2737/// class X {};
2738/// class A { class X {}; }; // Matches A, because A::X is a class of name
2739/// // X inside A.
2740/// class B { class C { class X {}; }; };
2741/// \endcode
2742///
2743/// DescendantT must be an AST base type.
2744///
2745/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2746/// each result that matches instead of only on the first one.
2747///
2748/// Note: Recursively combined ForEachDescendant can cause many matches:
2749/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2750/// forEachDescendant(cxxRecordDecl())
2751/// )))
2752/// will match 10 times (plus injected class name matches) on:
2753/// \code
2754/// class A { class B { class C { class D { class E {}; }; }; }; };
2755/// \endcode
2756///
2757/// Usable as: Any Matcher
2758extern const internal::ArgumentAdaptingMatcherFunc<
2759 internal::ForEachDescendantMatcher>
2760 forEachDescendant;
2761
2762/// Matches if the node or any descendant matches.
2763///
2764/// Generates results for each match.
2765///
2766/// For example, in:
2767/// \code
2768/// class A { class B {}; class C {}; };
2769/// \endcode
2770/// The matcher:
2771/// \code
2772/// cxxRecordDecl(hasName("::A"),
2773/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2774/// \endcode
2775/// will generate results for \c A, \c B and \c C.
2776///
2777/// Usable as: Any Matcher
2778template <typename T>
2779internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2780 return eachOf(Matcher, forEachDescendant(Matcher));
2781}
2782
2783/// Matches AST nodes that have a parent that matches the provided
2784/// matcher.
2785///
2786/// Given
2787/// \code
2788/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2789/// \endcode
2790/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2791///
2792/// Usable as: Any Matcher
2793extern const internal::ArgumentAdaptingMatcherFunc<
2794 internal::HasParentMatcher,
2795 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2796 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2797 hasParent;
2798
2799/// Matches AST nodes that have an ancestor that matches the provided
2800/// matcher.
2801///
2802/// Given
2803/// \code
2804/// void f() { if (true) { int x = 42; } }
2805/// void g() { for (;;) { int x = 43; } }
2806/// \endcode
2807/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2808///
2809/// Usable as: Any Matcher
2810extern const internal::ArgumentAdaptingMatcherFunc<
2811 internal::HasAncestorMatcher,
2812 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2813 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2814 hasAncestor;
2815
2816/// Matches if the provided matcher does not match.
2817///
2818/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2819/// \code
2820/// class X {};
2821/// class Y {};
2822/// \endcode
2823///
2824/// Usable as: Any Matcher
2825extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2826
2827/// Matches a node if the declaration associated with that node
2828/// matches the given matcher.
2829///
2830/// The associated declaration is:
2831/// - for type nodes, the declaration of the underlying type
2832/// - for CallExpr, the declaration of the callee
2833/// - for MemberExpr, the declaration of the referenced member
2834/// - for CXXConstructExpr, the declaration of the constructor
2835/// - for CXXNewExpr, the declaration of the operator new
2836/// - for ObjCIvarExpr, the declaration of the ivar
2837///
2838/// For type nodes, hasDeclaration will generally match the declaration of the
2839/// sugared type. Given
2840/// \code
2841/// class X {};
2842/// typedef X Y;
2843/// Y y;
2844/// \endcode
2845/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2846/// typedefDecl. A common use case is to match the underlying, desugared type.
2847/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2848/// \code
2849/// varDecl(hasType(hasUnqualifiedDesugaredType(
2850/// recordType(hasDeclaration(decl())))))
2851/// \endcode
2852/// In this matcher, the decl will match the CXXRecordDecl of class X.
2853///
2854/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2855/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2856/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2857/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2858/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2859/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2860/// Matcher<UnresolvedUsingType>
2861inline internal::PolymorphicMatcherWithParam1<
2862 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2863 void(internal::HasDeclarationSupportedTypes)>
2864hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2865 return internal::PolymorphicMatcherWithParam1<
2866 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2867 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2868}
2869
2870/// Matches a \c NamedDecl whose underlying declaration matches the given
2871/// matcher.
2872///
2873/// Given
2874/// \code
2875/// namespace N { template<class T> void f(T t); }
2876/// template <class T> void g() { using N::f; f(T()); }
2877/// \endcode
2878/// \c unresolvedLookupExpr(hasAnyDeclaration(
2879/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2880/// matches the use of \c f in \c g() .
2881AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2882 InnerMatcher) {
2883 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2884
2885 return UnderlyingDecl != nullptr &&
2886 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2887}
2888
2889/// Matches on the implicit object argument of a member call expression, after
2890/// stripping off any parentheses or implicit casts.
2891///
2892/// Given
2893/// \code
2894/// class Y { public: void m(); };
2895/// Y g();
2896/// class X : public Y {};
2897/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
2898/// \endcode
2899/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
2900/// matches `y.m()` and `(g()).m()`.
2901/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
2902/// matches `x.m()`.
2903/// cxxMemberCallExpr(on(callExpr()))
2904/// matches `(g()).m()`.
2905///
2906/// FIXME: Overload to allow directly matching types?
2907AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2908 InnerMatcher) {
2909 const Expr *ExprNode = Node.getImplicitObjectArgument()
2910 ->IgnoreParenImpCasts();
2911 return (ExprNode != nullptr &&
2912 InnerMatcher.matches(*ExprNode, Finder, Builder));
2913}
2914
2915
2916/// Matches on the receiver of an ObjectiveC Message expression.
2917///
2918/// Example
2919/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2920/// matches the [webView ...] message invocation.
2921/// \code
2922/// NSString *webViewJavaScript = ...
2923/// UIWebView *webView = ...
2924/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2925/// \endcode
2926AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2927 InnerMatcher) {
2928 const QualType TypeDecl = Node.getReceiverType();
2929 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2930}
2931
2932/// Returns true when the Objective-C message is sent to an instance.
2933///
2934/// Example
2935/// matcher = objcMessagaeExpr(isInstanceMessage())
2936/// matches
2937/// \code
2938/// NSString *x = @"hello";
2939/// [x containsString:@"h"];
2940/// \endcode
2941/// but not
2942/// \code
2943/// [NSString stringWithFormat:@"format"];
2944/// \endcode
2945AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
2946 return Node.isInstanceMessage();
2947}
2948
2949/// Matches if the Objective-C message is sent to an instance,
2950/// and the inner matcher matches on that instance.
2951///
2952/// For example the method call in
2953/// \code
2954/// NSString *x = @"hello";
2955/// [x containsString:@"h"];
2956/// \endcode
2957/// is matched by
2958/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
2959AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
2960 InnerMatcher) {
2961 const Expr *ReceiverNode = Node.getInstanceReceiver();
2962 return (ReceiverNode != nullptr &&
2963 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
2964 Builder));
2965}
2966
2967/// Matches when BaseName == Selector.getAsString()
2968///
2969/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2970/// matches the outer message expr in the code below, but NOT the message
2971/// invocation for self.bodyView.
2972/// \code
2973/// [self.bodyView loadHTMLString:html baseURL:NULL];
2974/// \endcode
2975AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2976 Selector Sel = Node.getSelector();
2977 return BaseName.compare(Sel.getAsString()) == 0;
2978}
2979
2980
2981/// Matches when at least one of the supplied string equals to the
2982/// Selector.getAsString()
2983///
2984/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
2985/// matches both of the expressions below:
2986/// \code
2987/// [myObj methodA:argA];
2988/// [myObj methodB:argB];
2989/// \endcode
2990extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
2991 StringRef,
2992 internal::hasAnySelectorFunc>
2993 hasAnySelector;
2994
2995/// Matches ObjC selectors whose name contains
2996/// a substring matched by the given RegExp.
2997/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2998/// matches the outer message expr in the code below, but NOT the message
2999/// invocation for self.bodyView.
3000/// \code
3001/// [self.bodyView loadHTMLString:html baseURL:NULL];
3002/// \endcode
3003AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
3004 assert(!RegExp.empty());
3005 std::string SelectorString = Node.getSelector().getAsString();
3006 llvm::Regex RE(RegExp);
3007 return RE.match(SelectorString);
3008}
3009
3010/// Matches when the selector is the empty selector
3011///
3012/// Matches only when the selector of the objCMessageExpr is NULL. This may
3013/// represent an error condition in the tree!
3014AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3015 return Node.getSelector().isNull();
3016}
3017
3018/// Matches when the selector is a Unary Selector
3019///
3020/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3021/// matches self.bodyView in the code below, but NOT the outer message
3022/// invocation of "loadHTMLString:baseURL:".
3023/// \code
3024/// [self.bodyView loadHTMLString:html baseURL:NULL];
3025/// \endcode
3026AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3027 return Node.getSelector().isUnarySelector();
3028}
3029
3030/// Matches when the selector is a keyword selector
3031///
3032/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3033/// message expression in
3034///
3035/// \code
3036/// UIWebView *webView = ...;
3037/// CGRect bodyFrame = webView.frame;
3038/// bodyFrame.size.height = self.bodyContentHeight;
3039/// webView.frame = bodyFrame;
3040/// // ^---- matches here
3041/// \endcode
3042AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3043 return Node.getSelector().isKeywordSelector();
3044}
3045
3046/// Matches when the selector has the specified number of arguments
3047///
3048/// matcher = objCMessageExpr(numSelectorArgs(0));
3049/// matches self.bodyView in the code below
3050///
3051/// matcher = objCMessageExpr(numSelectorArgs(2));
3052/// matches the invocation of "loadHTMLString:baseURL:" but not that
3053/// of self.bodyView
3054/// \code
3055/// [self.bodyView loadHTMLString:html baseURL:NULL];
3056/// \endcode
3057AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3058 return Node.getSelector().getNumArgs() == N;
3059}
3060
3061/// Matches if the call expression's callee expression matches.
3062///
3063/// Given
3064/// \code
3065/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3066/// void f() { f(); }
3067/// \endcode
3068/// callExpr(callee(expr()))
3069/// matches this->x(), x(), y.x(), f()
3070/// with callee(...)
3071/// matching this->x, x, y.x, f respectively
3072///
3073/// Note: Callee cannot take the more general internal::Matcher<Expr>
3074/// because this introduces ambiguous overloads with calls to Callee taking a
3075/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3076/// implemented in terms of implicit casts.
3077AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3078 InnerMatcher) {
3079 const Expr *ExprNode = Node.getCallee();
3080 return (ExprNode != nullptr &&
3081 InnerMatcher.matches(*ExprNode, Finder, Builder));
3082}
3083
3084/// Matches if the call expression's callee's declaration matches the
3085/// given matcher.
3086///
3087/// Example matches y.x() (matcher = callExpr(callee(
3088/// cxxMethodDecl(hasName("x")))))
3089/// \code
3090/// class Y { public: void x(); };
3091/// void z() { Y y; y.x(); }
3092/// \endcode
3093AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3094 1) {
3095 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3096}
3097
3098/// Matches if the expression's or declaration's type matches a type
3099/// matcher.
3100///
3101/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3102/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3103/// and U (matcher = typedefDecl(hasType(asString("int")))
3104/// and friend class X (matcher = friendDecl(hasType("X"))
3105/// \code
3106/// class X {};
3107/// void y(X &x) { x; X z; }
3108/// typedef int U;
3109/// class Y { friend class X; };
3110/// \endcode
3111AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3112 hasType,
3113 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3114 ValueDecl),
3115 internal::Matcher<QualType>, InnerMatcher, 0) {
3116 QualType QT = internal::getUnderlyingType(Node);
3117 if (!QT.isNull())
3118 return InnerMatcher.matches(QT, Finder, Builder);
3119 return false;
3120}
3121
3122/// Overloaded to match the declaration of the expression's or value
3123/// declaration's type.
3124///
3125/// In case of a value declaration (for example a variable declaration),
3126/// this resolves one layer of indirection. For example, in the value
3127/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3128/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3129/// declaration of x.
3130///
3131/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3132/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3133/// and friend class X (matcher = friendDecl(hasType("X"))
3134/// \code
3135/// class X {};
3136/// void y(X &x) { x; X z; }
3137/// class Y { friend class X; };
3138/// \endcode
3139///
3140/// Usable as: Matcher<Expr>, Matcher<ValueDecl>
3141AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3142 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
3143 internal::Matcher<Decl>, InnerMatcher, 1) {
3144 QualType QT = internal::getUnderlyingType(Node);
3145 if (!QT.isNull())
3146 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3147 return false;
3148}
3149
3150/// Matches if the type location of the declarator decl's type matches
3151/// the inner matcher.
3152///
3153/// Given
3154/// \code
3155/// int x;
3156/// \endcode
3157/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3158/// matches int x
3159AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3160 if (!Node.getTypeSourceInfo())
3161 // This happens for example for implicit destructors.
3162 return false;
3163 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3164}
3165
3166/// Matches if the matched type is represented by the given string.
3167///
3168/// Given
3169/// \code
3170/// class Y { public: void x(); };
3171/// void z() { Y* y; y->x(); }
3172/// \endcode
3173/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3174/// matches y->x()
3175AST_MATCHER_P(QualType, asString, std::string, Name) {
3176 return Name == Node.getAsString();
3177}
3178
3179/// Matches if the matched type is a pointer type and the pointee type
3180/// matches the specified matcher.
3181///
3182/// Example matches y->x()
3183/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3184/// cxxRecordDecl(hasName("Y")))))))
3185/// \code
3186/// class Y { public: void x(); };
3187/// void z() { Y *y; y->x(); }
3188/// \endcode
3189AST_MATCHER_P(
3190 QualType, pointsTo, internal::Matcher<QualType>,
3191 InnerMatcher) {
3192 return (!Node.isNull() && Node->isAnyPointerType() &&
3193 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3194}
3195
3196/// Overloaded to match the pointee type's declaration.
3197AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3198 InnerMatcher, 1) {
3199 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3200 .matches(Node, Finder, Builder);
3201}
3202
3203/// Matches if the matched type matches the unqualified desugared
3204/// type of the matched node.
3205///
3206/// For example, in:
3207/// \code
3208/// class A {};
3209/// using B = A;
3210/// \endcode
3211/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3212/// both B and A.
3213AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3214 InnerMatcher) {
3215 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3216 Builder);
3217}
3218
3219/// Matches if the matched type is a reference type and the referenced
3220/// type matches the specified matcher.
3221///
3222/// Example matches X &x and const X &y
3223/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3224/// \code
3225/// class X {
3226/// void a(X b) {
3227/// X &x = b;
3228/// const X &y = b;
3229/// }
3230/// };
3231/// \endcode
3232AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3233 InnerMatcher) {
3234 return (!Node.isNull() && Node->isReferenceType() &&
3235 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3236}
3237
3238/// Matches QualTypes whose canonical type matches InnerMatcher.
3239///
3240/// Given:
3241/// \code
3242/// typedef int &int_ref;
3243/// int a;
3244/// int_ref b = a;
3245/// \endcode
3246///
3247/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3248/// declaration of b but \c
3249/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3250AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3251 InnerMatcher) {
3252 if (Node.isNull())
3253 return false;
3254 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3255}
3256
3257/// Overloaded to match the referenced type's declaration.
3258AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3259 InnerMatcher, 1) {
3260 return references(qualType(hasDeclaration(InnerMatcher)))
3261 .matches(Node, Finder, Builder);
3262}
3263
3264/// Matches on the implicit object argument of a member call expression. Unlike
3265/// `on`, matches the argument directly without stripping away anything.
3266///
3267/// Given
3268/// \code
3269/// class Y { public: void m(); };
3270/// Y g();
3271/// class X : public Y { void g(); };
3272/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
3273/// \endcode
3274/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
3275/// cxxRecordDecl(hasName("Y")))))
3276/// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
3277/// cxxMemberCallExpr(on(callExpr()))
3278/// does not match `(g()).m()`, because the parens are not ignored.
3279///
3280/// FIXME: Overload to allow directly matching types?
3281AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3282 internal::Matcher<Expr>, InnerMatcher) {
3283 const Expr *ExprNode = Node.getImplicitObjectArgument();
3284 return (ExprNode != nullptr &&
3285 InnerMatcher.matches(*ExprNode, Finder, Builder));
3286}
3287
3288/// Matches if the type of the expression's implicit object argument either
3289/// matches the InnerMatcher, or is a pointer to a type that matches the
3290/// InnerMatcher.
3291///
3292/// Given
3293/// \code
3294/// class Y { public: void m(); };
3295/// class X : public Y { void g(); };
3296/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
3297/// \endcode
3298/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3299/// cxxRecordDecl(hasName("Y")))))
3300/// matches `y.m()`, `p->m()` and `x.m()`.
3301/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3302/// cxxRecordDecl(hasName("X")))))
3303/// matches `x.g()`.
3304AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3305 internal::Matcher<QualType>, InnerMatcher, 0) {
3306 return onImplicitObjectArgument(
3307 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3308 .matches(Node, Finder, Builder);
3309}
3310
3311/// Overloaded to match the type's declaration.
3312AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3313 internal::Matcher<Decl>, InnerMatcher, 1) {
3314 return onImplicitObjectArgument(
3315 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3316 .matches(Node, Finder, Builder);
3317}
3318
3319/// Matches a DeclRefExpr that refers to a declaration that matches the
3320/// specified matcher.
3321///
3322/// Example matches x in if(x)
3323/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3324/// \code
3325/// bool x;
3326/// if (x) {}
3327/// \endcode
3328AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3329 InnerMatcher) {
3330 const Decl *DeclNode = Node.getDecl();
3331 return (DeclNode != nullptr &&
3332 InnerMatcher.matches(*DeclNode, Finder, Builder));
3333}
3334
3335/// Matches a \c DeclRefExpr that refers to a declaration through a
3336/// specific using shadow declaration.
3337///
3338/// Given
3339/// \code
3340/// namespace a { void f() {} }
3341/// using a::f;
3342/// void g() {
3343/// f(); // Matches this ..
3344/// a::f(); // .. but not this.
3345/// }
3346/// \endcode
3347/// declRefExpr(throughUsingDecl(anything()))
3348/// matches \c f()
3349AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3350 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3351 const NamedDecl *FoundDecl = Node.getFoundDecl();
3352 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3353 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3354 return false;
3355}
3356
3357/// Matches an \c OverloadExpr if any of the declarations in the set of
3358/// overloads matches the given matcher.
3359///
3360/// Given
3361/// \code
3362/// template <typename T> void foo(T);
3363/// template <typename T> void bar(T);
3364/// template <typename T> void baz(T t) {
3365/// foo(t);
3366/// bar(t);
3367/// }
3368/// \endcode
3369/// unresolvedLookupExpr(hasAnyDeclaration(
3370/// functionTemplateDecl(hasName("foo"))))
3371/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3372AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3373 InnerMatcher) {
3374 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3375 Node.decls_end(), Finder, Builder);
3376}
3377
3378/// Matches the Decl of a DeclStmt which has a single declaration.
3379///
3380/// Given
3381/// \code
3382/// int a, b;
3383/// int c;
3384/// \endcode
3385/// declStmt(hasSingleDecl(anything()))
3386/// matches 'int c;' but not 'int a, b;'.
3387AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3388 if (Node.isSingleDecl()) {
3389 const Decl *FoundDecl = Node.getSingleDecl();
3390 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3391 }
3392 return false;
3393}
3394
3395/// Matches a variable declaration that has an initializer expression
3396/// that matches the given matcher.
3397///
3398/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3399/// \code
3400/// bool y() { return true; }
3401/// bool x = y();
3402/// \endcode
3403AST_MATCHER_P(
3404 VarDecl, hasInitializer, internal::Matcher<Expr>,
3405 InnerMatcher) {
3406 const Expr *Initializer = Node.getAnyInitializer();
3407 return (Initializer != nullptr &&
3408 InnerMatcher.matches(*Initializer, Finder, Builder));
3409}
3410
3411/// \brief Matches a static variable with local scope.
3412///
3413/// Example matches y (matcher = varDecl(isStaticLocal()))
3414/// \code
3415/// void f() {
3416/// int x;
3417/// static int y;
3418/// }
3419/// static int z;
3420/// \endcode
3421AST_MATCHER(VarDecl, isStaticLocal) {
3422 return Node.isStaticLocal();
3423}
3424
3425/// Matches a variable declaration that has function scope and is a
3426/// non-static local variable.
3427///
3428/// Example matches x (matcher = varDecl(hasLocalStorage())
3429/// \code
3430/// void f() {
3431/// int x;
3432/// static int y;
3433/// }
3434/// int z;
3435/// \endcode
3436AST_MATCHER(VarDecl, hasLocalStorage) {
3437 return Node.hasLocalStorage();
3438}
3439
3440/// Matches a variable declaration that does not have local storage.
3441///
3442/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3443/// \code
3444/// void f() {
3445/// int x;
3446/// static int y;
3447/// }
3448/// int z;
3449/// \endcode
3450AST_MATCHER(VarDecl, hasGlobalStorage) {
3451 return Node.hasGlobalStorage();
3452}
3453
3454/// Matches a variable declaration that has automatic storage duration.
3455///
3456/// Example matches x, but not y, z, or a.
3457/// (matcher = varDecl(hasAutomaticStorageDuration())
3458/// \code
3459/// void f() {
3460/// int x;
3461/// static int y;
3462/// thread_local int z;
3463/// }
3464/// int a;
3465/// \endcode
3466AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3467 return Node.getStorageDuration() == SD_Automatic;
3468}
3469
3470/// Matches a variable declaration that has static storage duration.
3471/// It includes the variable declared at namespace scope and those declared
3472/// with "static" and "extern" storage class specifiers.
3473///
3474/// \code
3475/// void f() {
3476/// int x;
3477/// static int y;
3478/// thread_local int z;
3479/// }
3480/// int a;
3481/// static int b;
3482/// extern int c;
3483/// varDecl(hasStaticStorageDuration())
3484/// matches the function declaration y, a, b and c.
3485/// \endcode
3486AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3487 return Node.getStorageDuration() == SD_Static;
3488}
3489
3490/// Matches a variable declaration that has thread storage duration.
3491///
3492/// Example matches z, but not x, z, or a.
3493/// (matcher = varDecl(hasThreadStorageDuration())
3494/// \code
3495/// void f() {
3496/// int x;
3497/// static int y;
3498/// thread_local int z;
3499/// }
3500/// int a;
3501/// \endcode
3502AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3503 return Node.getStorageDuration() == SD_Thread;
3504}
3505
3506/// Matches a variable declaration that is an exception variable from
3507/// a C++ catch block, or an Objective-C \@catch statement.
3508///
3509/// Example matches x (matcher = varDecl(isExceptionVariable())
3510/// \code
3511/// void f(int y) {
3512/// try {
3513/// } catch (int x) {
3514/// }
3515/// }
3516/// \endcode
3517AST_MATCHER(VarDecl, isExceptionVariable) {
3518 return Node.isExceptionVariable();
3519}
3520
3521/// Checks that a call expression or a constructor call expression has
3522/// a specific number of arguments (including absent default arguments).
3523///
3524/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3525/// \code
3526/// void f(int x, int y);
3527/// f(0, 0);
3528/// \endcode
3529AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3530 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3531 CXXConstructExpr,
3532 ObjCMessageExpr),
3533 unsigned, N) {
3534 return Node.getNumArgs() == N;
3535}
3536
3537/// Matches the n'th argument of a call expression or a constructor
3538/// call expression.
3539///
3540/// Example matches y in x(y)
3541/// (matcher = callExpr(hasArgument(0, declRefExpr())))
3542/// \code
3543/// void x(int) { int y; x(y); }
3544/// \endcode
3545AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3546 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3547 CXXConstructExpr,
3548 ObjCMessageExpr),
3549 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3550 return (N < Node.getNumArgs() &&
3551 InnerMatcher.matches(
3552 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3553}
3554
3555/// Matches the n'th item of an initializer list expression.
3556///
3557/// Example matches y.
3558/// (matcher = initListExpr(hasInit(0, expr())))
3559/// \code
3560/// int x{y}.
3561/// \endcode
3562AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
3563 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
3564 return N < Node.getNumInits() &&
3565 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
3566}
3567
3568/// Matches declaration statements that contain a specific number of
3569/// declarations.
3570///
3571/// Example: Given
3572/// \code
3573/// int a, b;
3574/// int c;
3575/// int d = 2, e;
3576/// \endcode
3577/// declCountIs(2)
3578/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3579AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3580 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3581}
3582
3583/// Matches the n'th declaration of a declaration statement.
3584///
3585/// Note that this does not work for global declarations because the AST
3586/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3587/// DeclStmt's.
3588/// Example: Given non-global declarations
3589/// \code
3590/// int a, b = 0;
3591/// int c;
3592/// int d = 2, e;
3593/// \endcode
3594/// declStmt(containsDeclaration(
3595/// 0, varDecl(hasInitializer(anything()))))
3596/// matches only 'int d = 2, e;', and
3597/// declStmt(containsDeclaration(1, varDecl()))
3598/// \code
3599/// matches 'int a, b = 0' as well as 'int d = 2, e;'
3600/// but 'int c;' is not matched.
3601/// \endcode
3602AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3603 internal::Matcher<Decl>, InnerMatcher) {
3604 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3605 if (N >= NumDecls)
3606 return false;
3607 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3608 std::advance(Iterator, N);
3609 return InnerMatcher.matches(**Iterator, Finder, Builder);
3610}
3611
3612/// Matches a C++ catch statement that has a catch-all handler.
3613///
3614/// Given
3615/// \code
3616/// try {
3617/// // ...
3618/// } catch (int) {
3619/// // ...
3620/// } catch (...) {
3621/// // ...
3622/// }
3623/// \endcode
3624/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3625AST_MATCHER(CXXCatchStmt, isCatchAll) {
3626 return Node.getExceptionDecl() == nullptr;
3627}
3628
3629/// Matches a constructor initializer.
3630///
3631/// Given
3632/// \code
3633/// struct Foo {
3634/// Foo() : foo_(1) { }
3635/// int foo_;
3636/// };
3637/// \endcode
3638/// cxxRecordDecl(has(cxxConstructorDecl(
3639/// hasAnyConstructorInitializer(anything())
3640/// )))
3641/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3642AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3643 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3644 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3645 Node.init_end(), Finder, Builder);
3646}
3647
3648/// Matches the field declaration of a constructor initializer.
3649///
3650/// Given
3651/// \code
3652/// struct Foo {
3653/// Foo() : foo_(1) { }
3654/// int foo_;
3655/// };
3656/// \endcode
3657/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3658/// forField(hasName("foo_"))))))
3659/// matches Foo
3660/// with forField matching foo_
3661AST_MATCHER_P(CXXCtorInitializer, forField,
3662 internal::Matcher<FieldDecl>, InnerMatcher) {
3663 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3664 return (NodeAsDecl != nullptr &&
3665 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3666}
3667
3668/// Matches the initializer expression of a constructor initializer.
3669///
3670/// Given
3671/// \code
3672/// struct Foo {
3673/// Foo() : foo_(1) { }
3674/// int foo_;
3675/// };
3676/// \endcode
3677/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3678/// withInitializer(integerLiteral(equals(1)))))))
3679/// matches Foo
3680/// with withInitializer matching (1)
3681AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3682 internal::Matcher<Expr>, InnerMatcher) {
3683 const Expr* NodeAsExpr = Node.getInit();
3684 return (NodeAsExpr != nullptr &&
3685 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3686}
3687
3688/// Matches a constructor initializer if it is explicitly written in
3689/// code (as opposed to implicitly added by the compiler).
3690///
3691/// Given
3692/// \code
3693/// struct Foo {
3694/// Foo() { }
3695/// Foo(int) : foo_("A") { }
3696/// string foo_;
3697/// };
3698/// \endcode
3699/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3700/// will match Foo(int), but not Foo()
3701AST_MATCHER(CXXCtorInitializer, isWritten) {
3702 return Node.isWritten();
3703}
3704
3705/// Matches a constructor initializer if it is initializing a base, as
3706/// opposed to a member.
3707///
3708/// Given
3709/// \code
3710/// struct B {};
3711/// struct D : B {
3712/// int I;
3713/// D(int i) : I(i) {}
3714/// };
3715/// struct E : B {
3716/// E() : B() {}
3717/// };
3718/// \endcode
3719/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3720/// will match E(), but not match D(int).
3721AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3722 return Node.isBaseInitializer();
3723}
3724
3725/// Matches a constructor initializer if it is initializing a member, as
3726/// opposed to a base.
3727///
3728/// Given
3729/// \code
3730/// struct B {};
3731/// struct D : B {
3732/// int I;
3733/// D(int i) : I(i) {}
3734/// };
3735/// struct E : B {
3736/// E() : B() {}
3737/// };
3738/// \endcode
3739/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3740/// will match D(int), but not match E().
3741AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3742 return Node.isMemberInitializer();
3743}
3744
3745/// Matches any argument of a call expression or a constructor call
3746/// expression, or an ObjC-message-send expression.
3747///
3748/// Given
3749/// \code
3750/// void x(int, int, int) { int y; x(1, y, 42); }
3751/// \endcode
3752/// callExpr(hasAnyArgument(declRefExpr()))
3753/// matches x(1, y, 42)
3754/// with hasAnyArgument(...)
3755/// matching y
3756///
3757/// For ObjectiveC, given
3758/// \code
3759/// @interface I - (void) f:(int) y; @end
3760/// void foo(I *i) { [i f:12]; }
3761/// \endcode
3762/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3763/// matches [i f:12]
3764AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3765 AST_POLYMORPHIC_SUPPORTED_TYPES(
3766 CallExpr, CXXConstructExpr,
3767 CXXUnresolvedConstructExpr, ObjCMessageExpr),
3768 internal::Matcher<Expr>, InnerMatcher) {
3769 for (const Expr *Arg : Node.arguments()) {
3770 BoundNodesTreeBuilder Result(*Builder);
3771 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3772 *Builder = std::move(Result);
3773 return true;
3774 }
3775 }
3776 return false;
3777}
3778
3779/// Matches a constructor call expression which uses list initialization.
3780AST_MATCHER(CXXConstructExpr, isListInitialization) {
3781 return Node.isListInitialization();
3782}
3783
3784/// Matches a constructor call expression which requires
3785/// zero initialization.
3786///
3787/// Given
3788/// \code
3789/// void foo() {
3790/// struct point { double x; double y; };
3791/// point pt[2] = { { 1.0, 2.0 } };
3792/// }
3793/// \endcode
3794/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3795/// will match the implicit array filler for pt[1].
3796AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3797 return Node.requiresZeroInitialization();
3798}
3799
3800/// Matches the n'th parameter of a function or an ObjC method
3801/// declaration or a block.
3802///
3803/// Given
3804/// \code
3805/// class X { void f(int x) {} };
3806/// \endcode
3807/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3808/// matches f(int x) {}
3809/// with hasParameter(...)
3810/// matching int x
3811///
3812/// For ObjectiveC, given
3813/// \code
3814/// @interface I - (void) f:(int) y; @end
3815/// \endcode
3816//
3817/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3818/// matches the declaration of method f with hasParameter
3819/// matching y.
3820AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3821 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3822 ObjCMethodDecl,
3823 BlockDecl),
3824 unsigned, N, internal::Matcher<ParmVarDecl>,
3825 InnerMatcher) {
3826 return (N < Node.parameters().size()
3827 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3828}
3829
3830/// Matches all arguments and their respective ParmVarDecl.
3831///
3832/// Given
3833/// \code
3834/// void f(int i);
3835/// int y;
3836/// f(y);
3837/// \endcode
3838/// callExpr(
3839/// forEachArgumentWithParam(
3840/// declRefExpr(to(varDecl(hasName("y")))),
3841/// parmVarDecl(hasType(isInteger()))
3842/// ))
3843/// matches f(y);
3844/// with declRefExpr(...)
3845/// matching int y
3846/// and parmVarDecl(...)
3847/// matching int i
3848AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3849 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3850 CXXConstructExpr),
3851 internal::Matcher<Expr>, ArgMatcher,
3852 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3853 BoundNodesTreeBuilder Result;
3854 // The first argument of an overloaded member operator is the implicit object
3855 // argument of the method which should not be matched against a parameter, so
3856 // we skip over it here.
3857 BoundNodesTreeBuilder Matches;
3858 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3859 .matches(Node, Finder, &Matches)
3860 ? 1
3861 : 0;
3862 int ParamIndex = 0;
3863 bool Matched = false;
3864 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3865 BoundNodesTreeBuilder ArgMatches(*Builder);
3866 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3867 Finder, &ArgMatches)) {
3868 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3869 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3870 hasParameter(ParamIndex, ParamMatcher)))),
3871 callExpr(callee(functionDecl(
3872 hasParameter(ParamIndex, ParamMatcher))))))
3873 .matches(Node, Finder, &ParamMatches)) {
3874 Result.addMatch(ParamMatches);
3875 Matched = true;
3876 }
3877 }
3878 ++ParamIndex;
3879 }
3880 *Builder = std::move(Result);
3881 return Matched;
3882}
3883
3884/// Matches any parameter of a function or an ObjC method declaration or a
3885/// block.
3886///
3887/// Does not match the 'this' parameter of a method.
3888///
3889/// Given
3890/// \code
3891/// class X { void f(int x, int y, int z) {} };
3892/// \endcode
3893/// cxxMethodDecl(hasAnyParameter(hasName("y")))
3894/// matches f(int x, int y, int z) {}
3895/// with hasAnyParameter(...)
3896/// matching int y
3897///
3898/// For ObjectiveC, given
3899/// \code
3900/// @interface I - (void) f:(int) y; @end
3901/// \endcode
3902//
3903/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
3904/// matches the declaration of method f with hasParameter
3905/// matching y.
3906///
3907/// For blocks, given
3908/// \code
3909/// b = ^(int y) { printf("%d", y) };
3910/// \endcode
3911///
3912/// the matcher blockDecl(hasAnyParameter(hasName("y")))
3913/// matches the declaration of the block b with hasParameter
3914/// matching y.
3915AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
3916 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3917 ObjCMethodDecl,
3918 BlockDecl),
3919 internal::Matcher<ParmVarDecl>,
3920 InnerMatcher) {
3921 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3922 Node.param_end(), Finder, Builder);
3923}
3924
3925/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3926/// specific parameter count.
3927///
3928/// Given
3929/// \code
3930/// void f(int i) {}
3931/// void g(int i, int j) {}
3932/// void h(int i, int j);
3933/// void j(int i);
3934/// void k(int x, int y, int z, ...);
3935/// \endcode
3936/// functionDecl(parameterCountIs(2))
3937/// matches \c g and \c h
3938/// functionProtoType(parameterCountIs(2))
3939/// matches \c g and \c h
3940/// functionProtoType(parameterCountIs(3))
3941/// matches \c k
3942AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3943 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3944 FunctionProtoType),
3945 unsigned, N) {
3946 return Node.getNumParams() == N;
3947}
3948
3949/// Matches \c FunctionDecls that have a noreturn attribute.
3950///
3951/// Given
3952/// \code
3953/// void nope();
3954/// [[noreturn]] void a();
3955/// __attribute__((noreturn)) void b();
3956/// struct c { [[noreturn]] c(); };
3957/// \endcode
3958/// functionDecl(isNoReturn())
3959/// matches all of those except
3960/// \code
3961/// void nope();
3962/// \endcode
3963AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
3964
3965/// Matches the return type of a function declaration.
3966///
3967/// Given:
3968/// \code
3969/// class X { int f() { return 1; } };
3970/// \endcode
3971/// cxxMethodDecl(returns(asString("int")))
3972/// matches int f() { return 1; }
3973AST_MATCHER_P(FunctionDecl, returns,
3974 internal::Matcher<QualType>, InnerMatcher) {
3975 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3976}
3977
3978/// Matches extern "C" function or variable declarations.
3979///
3980/// Given:
3981/// \code
3982/// extern "C" void f() {}
3983/// extern "C" { void g() {} }
3984/// void h() {}
3985<