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