clang 18.0.0git
ASTMatchers.h
Go to the documentation of this file.
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
49#include "clang/AST/Attr.h"
51#include "clang/AST/Decl.h"
52#include "clang/AST/DeclCXX.h"
54#include "clang/AST/DeclObjC.h"
56#include "clang/AST/Expr.h"
57#include "clang/AST/ExprCXX.h"
58#include "clang/AST/ExprObjC.h"
64#include "clang/AST/Stmt.h"
65#include "clang/AST/StmtCXX.h"
66#include "clang/AST/StmtObjC.h"
70#include "clang/AST/Type.h"
71#include "clang/AST/TypeLoc.h"
78#include "clang/Basic/LLVM.h"
82#include "llvm/ADT/ArrayRef.h"
83#include "llvm/ADT/SmallVector.h"
84#include "llvm/ADT/StringExtras.h"
85#include "llvm/ADT/StringRef.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/Compiler.h"
88#include "llvm/Support/ErrorHandling.h"
89#include "llvm/Support/Regex.h"
90#include <cassert>
91#include <cstddef>
92#include <iterator>
93#include <limits>
94#include <optional>
95#include <string>
96#include <utility>
97#include <vector>
98
99namespace clang {
100namespace ast_matchers {
101
102/// Maps string IDs to AST nodes matched by parts of a matcher.
103///
104/// The bound nodes are generated by calling \c bind("id") on the node matchers
105/// of the nodes we want to access later.
106///
107/// The instances of BoundNodes are created by \c MatchFinder when the user's
108/// callbacks are executed every time a match is found.
110public:
111 /// Returns the AST node bound to \c ID.
112 ///
113 /// Returns NULL if there was no node bound to \c ID or if there is a node but
114 /// it cannot be converted to the specified type.
115 template <typename T>
116 const T *getNodeAs(StringRef ID) const {
117 return MyBoundNodes.getNodeAs<T>(ID);
118 }
119
120 /// Type of mapping from binding identifiers to bound nodes. This type
121 /// is an associative container with a key type of \c std::string and a value
122 /// type of \c clang::DynTypedNode
123 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
124
125 /// Retrieve mapping from binding identifiers to bound nodes.
126 const IDToNodeMap &getMap() const {
127 return MyBoundNodes.getMap();
128 }
129
130private:
132
133 /// Create BoundNodes from a pre-filled map of bindings.
134 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
135 : MyBoundNodes(MyBoundNodes) {}
136
137 internal::BoundNodesMap MyBoundNodes;
138};
139
140/// Types of matchers for the top-level classes in the AST class
141/// hierarchy.
142/// @{
143using DeclarationMatcher = internal::Matcher<Decl>;
144using StatementMatcher = internal::Matcher<Stmt>;
145using TypeMatcher = internal::Matcher<QualType>;
146using TypeLocMatcher = internal::Matcher<TypeLoc>;
147using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
148using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
149using CXXBaseSpecifierMatcher = internal::Matcher<CXXBaseSpecifier>;
150using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
151using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
152using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
153using LambdaCaptureMatcher = internal::Matcher<LambdaCapture>;
154using AttrMatcher = internal::Matcher<Attr>;
155/// @}
156
157/// Matches any node.
158///
159/// Useful when another matcher requires a child matcher, but there's no
160/// additional constraint. This will often be used with an explicit conversion
161/// to an \c internal::Matcher<> type such as \c TypeMatcher.
162///
163/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
164/// \code
165/// "int* p" and "void f()" in
166/// int* p;
167/// void f();
168/// \endcode
169///
170/// Usable as: Any Matcher
171inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
172
173/// Matches the top declaration context.
174///
175/// Given
176/// \code
177/// int X;
178/// namespace NS {
179/// int Y;
180/// } // namespace NS
181/// \endcode
182/// decl(hasDeclContext(translationUnitDecl()))
183/// matches "int X", but not "int Y".
184extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
186
187/// Matches typedef declarations.
188///
189/// Given
190/// \code
191/// typedef int X;
192/// using Y = int;
193/// \endcode
194/// typedefDecl()
195/// matches "typedef int X", but not "using Y = int"
196extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
198
199/// Matches typedef name declarations.
200///
201/// Given
202/// \code
203/// typedef int X;
204/// using Y = int;
205/// \endcode
206/// typedefNameDecl()
207/// matches "typedef int X" and "using Y = int"
208extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
210
211/// Matches type alias declarations.
212///
213/// Given
214/// \code
215/// typedef int X;
216/// using Y = int;
217/// \endcode
218/// typeAliasDecl()
219/// matches "using Y = int", but not "typedef int X"
220extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
222
223/// Matches type alias template declarations.
224///
225/// typeAliasTemplateDecl() matches
226/// \code
227/// template <typename T>
228/// using Y = X<T>;
229/// \endcode
230extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
232
233/// Matches AST nodes that were expanded within the main-file.
234///
235/// Example matches X but not Y
236/// (matcher = cxxRecordDecl(isExpansionInMainFile())
237/// \code
238/// #include <Y.h>
239/// class X {};
240/// \endcode
241/// Y.h:
242/// \code
243/// class Y {};
244/// \endcode
245///
246/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
247AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
249 auto &SourceManager = Finder->getASTContext().getSourceManager();
251 SourceManager.getExpansionLoc(Node.getBeginLoc()));
252}
253
254/// Matches AST nodes that were expanded within system-header-files.
255///
256/// Example matches Y but not X
257/// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
258/// \code
259/// #include <SystemHeader.h>
260/// class X {};
261/// \endcode
262/// SystemHeader.h:
263/// \code
264/// class Y {};
265/// \endcode
266///
267/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
268AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
270 auto &SourceManager = Finder->getASTContext().getSourceManager();
271 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
272 if (ExpansionLoc.isInvalid()) {
273 return false;
274 }
275 return SourceManager.isInSystemHeader(ExpansionLoc);
276}
277
278/// Matches AST nodes that were expanded within files whose name is
279/// partially matching a given regex.
280///
281/// Example matches Y but not X
282/// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
283/// \code
284/// #include "ASTMatcher.h"
285/// class X {};
286/// \endcode
287/// ASTMatcher.h:
288/// \code
289/// class Y {};
290/// \endcode
291///
292/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
293AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
295 TypeLoc),
296 RegExp) {
297 auto &SourceManager = Finder->getASTContext().getSourceManager();
298 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
299 if (ExpansionLoc.isInvalid()) {
300 return false;
301 }
302 auto FileEntry =
304 if (!FileEntry) {
305 return false;
306 }
307
308 auto Filename = FileEntry->getName();
309 return RegExp->match(Filename);
310}
311
312/// Matches statements that are (transitively) expanded from the named macro.
313/// Does not match if only part of the statement is expanded from that macro or
314/// if different parts of the statement are expanded from different
315/// appearances of the macro.
316AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
318 std::string, MacroName) {
319 // Verifies that the statement' beginning and ending are both expanded from
320 // the same instance of the given macro.
321 auto& Context = Finder->getASTContext();
322 std::optional<SourceLocation> B =
323 internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
324 if (!B) return false;
325 std::optional<SourceLocation> E =
326 internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
327 if (!E) return false;
328 return *B == *E;
329}
330
331/// Matches declarations.
332///
333/// Examples matches \c X, \c C, and the friend declaration inside \c C;
334/// \code
335/// void X();
336/// class C {
337/// friend X;
338/// };
339/// \endcode
340extern const internal::VariadicAllOfMatcher<Decl> decl;
341
342/// Matches decomposition-declarations.
343///
344/// Examples matches the declaration node with \c foo and \c bar, but not
345/// \c number.
346/// (matcher = declStmt(has(decompositionDecl())))
347///
348/// \code
349/// int number = 42;
350/// auto [foo, bar] = std::make_pair{42, 42};
351/// \endcode
352extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl>
354
355/// Matches binding declarations
356/// Example matches \c foo and \c bar
357/// (matcher = bindingDecl()
358///
359/// \code
360/// auto [foo, bar] = std::make_pair{42, 42};
361/// \endcode
362extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl>
364
365/// Matches a declaration of a linkage specification.
366///
367/// Given
368/// \code
369/// extern "C" {}
370/// \endcode
371/// linkageSpecDecl()
372/// matches "extern "C" {}"
373extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
375
376/// Matches a declaration of anything that could have a name.
377///
378/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
379/// \code
380/// typedef int X;
381/// struct S {
382/// union {
383/// int i;
384/// } U;
385/// };
386/// \endcode
387extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
388
389/// Matches a declaration of label.
390///
391/// Given
392/// \code
393/// goto FOO;
394/// FOO: bar();
395/// \endcode
396/// labelDecl()
397/// matches 'FOO:'
398extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
399
400/// Matches a declaration of a namespace.
401///
402/// Given
403/// \code
404/// namespace {}
405/// namespace test {}
406/// \endcode
407/// namespaceDecl()
408/// matches "namespace {}" and "namespace test {}"
409extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
411
412/// Matches a declaration of a namespace alias.
413///
414/// Given
415/// \code
416/// namespace test {}
417/// namespace alias = ::test;
418/// \endcode
419/// namespaceAliasDecl()
420/// matches "namespace alias" but not "namespace test"
421extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
423
424/// Matches class, struct, and union declarations.
425///
426/// Example matches \c X, \c Z, \c U, and \c S
427/// \code
428/// class X;
429/// template<class T> class Z {};
430/// struct S {};
431/// union U {};
432/// \endcode
433extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
434
435/// Matches C++ class declarations.
436///
437/// Example matches \c X, \c Z
438/// \code
439/// class X;
440/// template<class T> class Z {};
441/// \endcode
442extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
444
445/// Matches C++ class template declarations.
446///
447/// Example matches \c Z
448/// \code
449/// template<class T> class Z {};
450/// \endcode
451extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
453
454/// Matches C++ class template specializations.
455///
456/// Given
457/// \code
458/// template<typename T> class A {};
459/// template<> class A<double> {};
460/// A<int> a;
461/// \endcode
462/// classTemplateSpecializationDecl()
463/// matches the specializations \c A<int> and \c A<double>
464extern const internal::VariadicDynCastAllOfMatcher<
467
468/// Matches C++ class template partial specializations.
469///
470/// Given
471/// \code
472/// template<class T1, class T2, int I>
473/// class A {};
474///
475/// template<class T, int I>
476/// class A<T, T*, I> {};
477///
478/// template<>
479/// class A<int, int, 1> {};
480/// \endcode
481/// classTemplatePartialSpecializationDecl()
482/// matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
483extern const internal::VariadicDynCastAllOfMatcher<
486
487/// Matches declarator declarations (field, variable, function
488/// and non-type template parameter declarations).
489///
490/// Given
491/// \code
492/// class X { int y; };
493/// \endcode
494/// declaratorDecl()
495/// matches \c int y.
496extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
498
499/// Matches parameter variable declarations.
500///
501/// Given
502/// \code
503/// void f(int x);
504/// \endcode
505/// parmVarDecl()
506/// matches \c int x.
507extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
509
510/// Matches C++ access specifier declarations.
511///
512/// Given
513/// \code
514/// class C {
515/// public:
516/// int a;
517/// };
518/// \endcode
519/// accessSpecDecl()
520/// matches 'public:'
521extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
523
524/// Matches class bases.
525///
526/// Examples matches \c public virtual B.
527/// \code
528/// class B {};
529/// class C : public virtual B {};
530/// \endcode
531extern const internal::VariadicAllOfMatcher<CXXBaseSpecifier> cxxBaseSpecifier;
532
533/// Matches constructor initializers.
534///
535/// Examples matches \c i(42).
536/// \code
537/// class C {
538/// C() : i(42) {}
539/// int i;
540/// };
541/// \endcode
542extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
544
545/// Matches template arguments.
546///
547/// Given
548/// \code
549/// template <typename T> struct C {};
550/// C<int> c;
551/// \endcode
552/// templateArgument()
553/// matches 'int' in C<int>.
554extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
555
556/// Matches template arguments (with location info).
557///
558/// Given
559/// \code
560/// template <typename T> struct C {};
561/// C<int> c;
562/// \endcode
563/// templateArgumentLoc()
564/// matches 'int' in C<int>.
565extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
567
568/// Matches template name.
569///
570/// Given
571/// \code
572/// template <typename T> class X { };
573/// X<int> xi;
574/// \endcode
575/// templateName()
576/// matches 'X' in X<int>.
577extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
578
579/// Matches non-type template parameter declarations.
580///
581/// Given
582/// \code
583/// template <typename T, int N> struct C {};
584/// \endcode
585/// nonTypeTemplateParmDecl()
586/// matches 'N', but not 'T'.
587extern const internal::VariadicDynCastAllOfMatcher<Decl,
590
591/// Matches template type parameter declarations.
592///
593/// Given
594/// \code
595/// template <typename T, int N> struct C {};
596/// \endcode
597/// templateTypeParmDecl()
598/// matches 'T', but not 'N'.
599extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
601
602/// Matches template template parameter declarations.
603///
604/// Given
605/// \code
606/// template <template <typename> class Z, int N> struct C {};
607/// \endcode
608/// templateTypeParmDecl()
609/// matches 'Z', but not 'N'.
610extern const internal::VariadicDynCastAllOfMatcher<Decl,
613
614/// Matches public C++ declarations and C++ base specifers that specify public
615/// inheritance.
616///
617/// Examples:
618/// \code
619/// class C {
620/// public: int a; // fieldDecl(isPublic()) matches 'a'
621/// protected: int b;
622/// private: int c;
623/// };
624/// \endcode
625///
626/// \code
627/// class Base {};
628/// class Derived1 : public Base {}; // matches 'Base'
629/// struct Derived2 : Base {}; // matches 'Base'
630/// \endcode
634 return getAccessSpecifier(Node) == AS_public;
635}
636
637/// Matches protected C++ declarations and C++ base specifers that specify
638/// protected inheritance.
639///
640/// Examples:
641/// \code
642/// class C {
643/// public: int a;
644/// protected: int b; // fieldDecl(isProtected()) matches 'b'
645/// private: int c;
646/// };
647/// \endcode
648///
649/// \code
650/// class Base {};
651/// class Derived : protected Base {}; // matches 'Base'
652/// \endcode
656 return getAccessSpecifier(Node) == AS_protected;
657}
658
659/// Matches private C++ declarations and C++ base specifers that specify private
660/// inheritance.
661///
662/// Examples:
663/// \code
664/// class C {
665/// public: int a;
666/// protected: int b;
667/// private: int c; // fieldDecl(isPrivate()) matches 'c'
668/// };
669/// \endcode
670///
671/// \code
672/// struct Base {};
673/// struct Derived1 : private Base {}; // matches 'Base'
674/// class Derived2 : Base {}; // matches 'Base'
675/// \endcode
679 return getAccessSpecifier(Node) == AS_private;
680}
681
682/// Matches non-static data members that are bit-fields.
683///
684/// Given
685/// \code
686/// class C {
687/// int a : 2;
688/// int b;
689/// };
690/// \endcode
691/// fieldDecl(isBitField())
692/// matches 'int a;' but not 'int b;'.
693AST_MATCHER(FieldDecl, isBitField) {
694 return Node.isBitField();
695}
696
697/// Matches non-static data members that are bit-fields of the specified
698/// bit width.
699///
700/// Given
701/// \code
702/// class C {
703/// int a : 2;
704/// int b : 4;
705/// int c : 2;
706/// };
707/// \endcode
708/// fieldDecl(hasBitWidth(2))
709/// matches 'int a;' and 'int c;' but not 'int b;'.
710AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
711 return Node.isBitField() &&
712 Node.getBitWidthValue(Finder->getASTContext()) == Width;
713}
714
715/// Matches non-static data members that have an in-class initializer.
716///
717/// Given
718/// \code
719/// class C {
720/// int a = 2;
721/// int b = 3;
722/// int c;
723/// };
724/// \endcode
725/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
726/// matches 'int a;' but not 'int b;'.
727/// fieldDecl(hasInClassInitializer(anything()))
728/// matches 'int a;' and 'int b;' but not 'int c;'.
729AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
730 InnerMatcher) {
731 const Expr *Initializer = Node.getInClassInitializer();
732 return (Initializer != nullptr &&
733 InnerMatcher.matches(*Initializer, Finder, Builder));
734}
735
736/// Determines whether the function is "main", which is the entry point
737/// into an executable program.
739 return Node.isMain();
740}
741
742/// Matches the specialized template of a specialization declaration.
743///
744/// Given
745/// \code
746/// template<typename T> class A {}; #1
747/// template<> class A<int> {}; #2
748/// \endcode
749/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
750/// matches '#2' with classTemplateDecl() matching the class template
751/// declaration of 'A' at #1.
753 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
754 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
755 return (Decl != nullptr &&
756 InnerMatcher.matches(*Decl, Finder, Builder));
757}
758
759/// Matches an entity that has been implicitly added by the compiler (e.g.
760/// implicit default/copy constructors).
763 LambdaCapture)) {
764 return Node.isImplicit();
765}
766
767/// Matches classTemplateSpecializations, templateSpecializationType and
768/// functionDecl that have at least one TemplateArgument matching the given
769/// InnerMatcher.
770///
771/// Given
772/// \code
773/// template<typename T> class A {};
774/// template<> class A<double> {};
775/// A<int> a;
776///
777/// template<typename T> f() {};
778/// void func() { f<int>(); };
779/// \endcode
780///
781/// \endcode
782/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
783/// refersToType(asString("int"))))
784/// matches the specialization \c A<int>
785///
786/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
787/// matches the specialization \c f<int>
789 hasAnyTemplateArgument,
793 internal::Matcher<TemplateArgument>, InnerMatcher) {
795 internal::getTemplateSpecializationArgs(Node);
796 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
797 Builder) != List.end();
798}
799
800/// Causes all nested matchers to be matched with the specified traversal kind.
801///
802/// Given
803/// \code
804/// void foo()
805/// {
806/// int i = 3.0;
807/// }
808/// \endcode
809/// The matcher
810/// \code
811/// traverse(TK_IgnoreUnlessSpelledInSource,
812/// varDecl(hasInitializer(floatLiteral().bind("init")))
813/// )
814/// \endcode
815/// matches the variable declaration with "init" bound to the "3.0".
816template <typename T>
817internal::Matcher<T> traverse(TraversalKind TK,
818 const internal::Matcher<T> &InnerMatcher) {
819 return internal::DynTypedMatcher::constructRestrictedWrapper(
820 new internal::TraversalMatcher<T>(TK, InnerMatcher),
821 InnerMatcher.getID().first)
822 .template unconditionalConvertTo<T>();
823}
824
825template <typename T>
826internal::BindableMatcher<T>
827traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
828 return internal::BindableMatcher<T>(
829 internal::DynTypedMatcher::constructRestrictedWrapper(
830 new internal::TraversalMatcher<T>(TK, InnerMatcher),
831 InnerMatcher.getID().first)
832 .template unconditionalConvertTo<T>());
833}
834
835template <typename... T>
836internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
838 const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
839 return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
840 TK, InnerMatcher);
841}
842
843template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
844 typename T, typename ToTypes>
845internal::TraversalWrapper<
846 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
847traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
848 ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
849 return internal::TraversalWrapper<
850 internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
851 ToTypes>>(TK, InnerMatcher);
852}
853
854template <template <typename T, typename... P> class MatcherT, typename... P,
855 typename ReturnTypesF>
856internal::TraversalWrapper<
857 internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>
858traverse(TraversalKind TK,
859 const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>
860 &InnerMatcher) {
861 return internal::TraversalWrapper<
862 internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK,
863 InnerMatcher);
864}
865
866template <typename... T>
867internal::Matcher<typename internal::GetClade<T...>::Type>
868traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
869 return traverse(TK, InnerMatcher.with());
870}
871
872/// Matches expressions that match InnerMatcher after any implicit AST
873/// nodes are stripped off.
874///
875/// Parentheses and explicit casts are not discarded.
876/// Given
877/// \code
878/// class C {};
879/// C a = C();
880/// C b;
881/// C c = b;
882/// \endcode
883/// The matchers
884/// \code
885/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
886/// \endcode
887/// would match the declarations for a, b, and c.
888/// While
889/// \code
890/// varDecl(hasInitializer(cxxConstructExpr()))
891/// \endcode
892/// only match the declarations for b and c.
893AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
894 InnerMatcher) {
895 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
896}
897
898/// Matches expressions that match InnerMatcher after any implicit casts
899/// are stripped off.
900///
901/// Parentheses and explicit casts are not discarded.
902/// Given
903/// \code
904/// int arr[5];
905/// int a = 0;
906/// char b = 0;
907/// const int c = a;
908/// int *d = arr;
909/// long e = (long) 0l;
910/// \endcode
911/// The matchers
912/// \code
913/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
914/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
915/// \endcode
916/// would match the declarations for a, b, c, and d, but not e.
917/// While
918/// \code
919/// varDecl(hasInitializer(integerLiteral()))
920/// varDecl(hasInitializer(declRefExpr()))
921/// \endcode
922/// only match the declarations for a.
923AST_MATCHER_P(Expr, ignoringImpCasts,
924 internal::Matcher<Expr>, InnerMatcher) {
925 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
926}
927
928/// Matches expressions that match InnerMatcher after parentheses and
929/// casts are stripped off.
930///
931/// Implicit and non-C Style casts are also discarded.
932/// Given
933/// \code
934/// int a = 0;
935/// char b = (0);
936/// void* c = reinterpret_cast<char*>(0);
937/// char d = char(0);
938/// \endcode
939/// The matcher
940/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
941/// would match the declarations for a, b, c, and d.
942/// while
943/// varDecl(hasInitializer(integerLiteral()))
944/// only match the declaration for a.
945AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
946 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
947}
948
949/// Matches expressions that match InnerMatcher after implicit casts and
950/// parentheses are stripped off.
951///
952/// Explicit casts are not discarded.
953/// Given
954/// \code
955/// int arr[5];
956/// int a = 0;
957/// char b = (0);
958/// const int c = a;
959/// int *d = (arr);
960/// long e = ((long) 0l);
961/// \endcode
962/// The matchers
963/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
964/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
965/// would match the declarations for a, b, c, and d, but not e.
966/// while
967/// varDecl(hasInitializer(integerLiteral()))
968/// varDecl(hasInitializer(declRefExpr()))
969/// would only match the declaration for a.
970AST_MATCHER_P(Expr, ignoringParenImpCasts,
971 internal::Matcher<Expr>, InnerMatcher) {
972 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
973}
974
975/// Matches types that match InnerMatcher after any parens are stripped.
976///
977/// Given
978/// \code
979/// void (*fp)(void);
980/// \endcode
981/// The matcher
982/// \code
983/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
984/// \endcode
985/// would match the declaration for fp.
986AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
987 InnerMatcher, 0) {
988 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
989}
990
991/// Overload \c ignoringParens for \c Expr.
992///
993/// Given
994/// \code
995/// const char* str = ("my-string");
996/// \endcode
997/// The matcher
998/// \code
999/// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
1000/// \endcode
1001/// would match the implicit cast resulting from the assignment.
1002AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
1003 InnerMatcher, 1) {
1004 const Expr *E = Node.IgnoreParens();
1005 return InnerMatcher.matches(*E, Finder, Builder);
1006}
1007
1008/// Matches expressions that are instantiation-dependent even if it is
1009/// neither type- nor value-dependent.
1010///
1011/// In the following example, the expression sizeof(sizeof(T() + T()))
1012/// is instantiation-dependent (since it involves a template parameter T),
1013/// but is neither type- nor value-dependent, since the type of the inner
1014/// sizeof is known (std::size_t) and therefore the size of the outer
1015/// sizeof is known.
1016/// \code
1017/// template<typename T>
1018/// void f(T x, T y) { sizeof(sizeof(T() + T()); }
1019/// \endcode
1020/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
1021AST_MATCHER(Expr, isInstantiationDependent) {
1022 return Node.isInstantiationDependent();
1023}
1024
1025/// Matches expressions that are type-dependent because the template type
1026/// is not yet instantiated.
1027///
1028/// For example, the expressions "x" and "x + y" are type-dependent in
1029/// the following code, but "y" is not type-dependent:
1030/// \code
1031/// template<typename T>
1032/// void add(T x, int y) {
1033/// x + y;
1034/// }
1035/// \endcode
1036/// expr(isTypeDependent()) matches x + y
1037AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
1038
1039/// Matches expression that are value-dependent because they contain a
1040/// non-type template parameter.
1041///
1042/// For example, the array bound of "Chars" in the following example is
1043/// value-dependent.
1044/// \code
1045/// template<int Size> int f() { return Size; }
1046/// \endcode
1047/// expr(isValueDependent()) matches return Size
1048AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
1049
1050/// Matches classTemplateSpecializations, templateSpecializationType and
1051/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
1052///
1053/// Given
1054/// \code
1055/// template<typename T, typename U> class A {};
1056/// A<bool, int> b;
1057/// A<int, bool> c;
1058///
1059/// template<typename T> void f() {}
1060/// void func() { f<int>(); };
1061/// \endcode
1062/// classTemplateSpecializationDecl(hasTemplateArgument(
1063/// 1, refersToType(asString("int"))))
1064/// matches the specialization \c A<bool, int>
1065///
1066/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1067/// matches the specialization \c f<int>
1069 hasTemplateArgument,
1072 FunctionDecl),
1073 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1075 internal::getTemplateSpecializationArgs(Node);
1076 if (List.size() <= N)
1077 return false;
1078 return InnerMatcher.matches(List[N], Finder, Builder);
1079}
1080
1081/// Matches if the number of template arguments equals \p N.
1082///
1083/// Given
1084/// \code
1085/// template<typename T> struct C {};
1086/// C<int> c;
1087/// \endcode
1088/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1089/// matches C<int>.
1091 templateArgumentCountIs,
1094 unsigned, N) {
1095 return internal::getTemplateSpecializationArgs(Node).size() == N;
1096}
1097
1098/// Matches a TemplateArgument that refers to a certain type.
1099///
1100/// Given
1101/// \code
1102/// struct X {};
1103/// template<typename T> struct A {};
1104/// A<X> a;
1105/// \endcode
1106/// classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
1107/// recordType(hasDeclaration(recordDecl(hasName("X")))))))
1108/// matches the specialization of \c struct A generated by \c A<X>.
1110 internal::Matcher<QualType>, InnerMatcher) {
1111 if (Node.getKind() != TemplateArgument::Type)
1112 return false;
1113 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1114}
1115
1116/// Matches a TemplateArgument that refers to a certain template.
1117///
1118/// Given
1119/// \code
1120/// template<template <typename> class S> class X {};
1121/// template<typename T> class Y {};
1122/// X<Y> xi;
1123/// \endcode
1124/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1125/// refersToTemplate(templateName())))
1126/// matches the specialization \c X<Y>
1128 internal::Matcher<TemplateName>, InnerMatcher) {
1129 if (Node.getKind() != TemplateArgument::Template)
1130 return false;
1131 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1132}
1133
1134/// Matches a canonical TemplateArgument that refers to a certain
1135/// declaration.
1136///
1137/// Given
1138/// \code
1139/// struct B { int next; };
1140/// template<int(B::*next_ptr)> struct A {};
1141/// A<&B::next> a;
1142/// \endcode
1143/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1144/// refersToDeclaration(fieldDecl(hasName("next")))))
1145/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1146/// \c B::next
1147AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1148 internal::Matcher<Decl>, InnerMatcher) {
1149 if (Node.getKind() == TemplateArgument::Declaration)
1150 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1151 return false;
1152}
1153
1154/// Matches a sugar TemplateArgument that refers to a certain expression.
1155///
1156/// Given
1157/// \code
1158/// struct B { int next; };
1159/// template<int(B::*next_ptr)> struct A {};
1160/// A<&B::next> a;
1161/// \endcode
1162/// templateSpecializationType(hasAnyTemplateArgument(
1163/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1164/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1165/// \c B::next
1166AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1167 if (Node.getKind() == TemplateArgument::Expression)
1168 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1169 return false;
1170}
1171
1172/// Matches a TemplateArgument that is an integral value.
1173///
1174/// Given
1175/// \code
1176/// template<int T> struct C {};
1177/// C<42> c;
1178/// \endcode
1179/// classTemplateSpecializationDecl(
1180/// hasAnyTemplateArgument(isIntegral()))
1181/// matches the implicit instantiation of C in C<42>
1182/// with isIntegral() matching 42.
1184 return Node.getKind() == TemplateArgument::Integral;
1185}
1186
1187/// Matches a TemplateArgument that refers to an integral type.
1188///
1189/// Given
1190/// \code
1191/// template<int T> struct C {};
1192/// C<42> c;
1193/// \endcode
1194/// classTemplateSpecializationDecl(
1195/// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1196/// matches the implicit instantiation of C in C<42>.
1197AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1198 internal::Matcher<QualType>, InnerMatcher) {
1199 if (Node.getKind() != TemplateArgument::Integral)
1200 return false;
1201 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1202}
1203
1204/// Matches a TemplateArgument of integral type with a given value.
1205///
1206/// Note that 'Value' is a string as the template argument's value is
1207/// an arbitrary precision integer. 'Value' must be euqal to the canonical
1208/// representation of that integral value in base 10.
1209///
1210/// Given
1211/// \code
1212/// template<int T> struct C {};
1213/// C<42> c;
1214/// \endcode
1215/// classTemplateSpecializationDecl(
1216/// hasAnyTemplateArgument(equalsIntegralValue("42")))
1217/// matches the implicit instantiation of C in C<42>.
1218AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1219 std::string, Value) {
1220 if (Node.getKind() != TemplateArgument::Integral)
1221 return false;
1222 return toString(Node.getAsIntegral(), 10) == Value;
1223}
1224
1225/// Matches an Objective-C autorelease pool statement.
1226///
1227/// Given
1228/// \code
1229/// @autoreleasepool {
1230/// int x = 0;
1231/// }
1232/// \endcode
1233/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1234/// inside the autorelease pool.
1235extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1237
1238/// Matches any value declaration.
1239///
1240/// Example matches A, B, C and F
1241/// \code
1242/// enum X { A, B, C };
1243/// void F();
1244/// \endcode
1245extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1246
1247/// Matches C++ constructor declarations.
1248///
1249/// Example matches Foo::Foo() and Foo::Foo(int)
1250/// \code
1251/// class Foo {
1252/// public:
1253/// Foo();
1254/// Foo(int);
1255/// int DoSomething();
1256/// };
1257/// \endcode
1258extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1260
1261/// Matches explicit C++ destructor declarations.
1262///
1263/// Example matches Foo::~Foo()
1264/// \code
1265/// class Foo {
1266/// public:
1267/// virtual ~Foo();
1268/// };
1269/// \endcode
1270extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1272
1273/// Matches enum declarations.
1274///
1275/// Example matches X
1276/// \code
1277/// enum X {
1278/// A, B, C
1279/// };
1280/// \endcode
1281extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1282
1283/// Matches enum constants.
1284///
1285/// Example matches A, B, C
1286/// \code
1287/// enum X {
1288/// A, B, C
1289/// };
1290/// \endcode
1291extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1293
1294/// Matches tag declarations.
1295///
1296/// Example matches X, Z, U, S, E
1297/// \code
1298/// class X;
1299/// template<class T> class Z {};
1300/// struct S {};
1301/// union U {};
1302/// enum E {
1303/// A, B, C
1304/// };
1305/// \endcode
1306extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1307
1308/// Matches method declarations.
1309///
1310/// Example matches y
1311/// \code
1312/// class X { void y(); };
1313/// \endcode
1314extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1316
1317/// Matches conversion operator declarations.
1318///
1319/// Example matches the operator.
1320/// \code
1321/// class X { operator int() const; };
1322/// \endcode
1323extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1325
1326/// Matches user-defined and implicitly generated deduction guide.
1327///
1328/// Example matches the deduction guide.
1329/// \code
1330/// template<typename T>
1331/// class X { X(int) };
1332/// X(int) -> X<int>;
1333/// \endcode
1334extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1336
1337/// Matches concept declarations.
1338///
1339/// Example matches integral
1340/// \code
1341/// template<typename T>
1342/// concept integral = std::is_integral_v<T>;
1343/// \endcode
1344extern const internal::VariadicDynCastAllOfMatcher<Decl, ConceptDecl>
1346
1347/// Matches variable declarations.
1348///
1349/// Note: this does not match declarations of member variables, which are
1350/// "field" declarations in Clang parlance.
1351///
1352/// Example matches a
1353/// \code
1354/// int a;
1355/// \endcode
1356extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1357
1358/// Matches field declarations.
1359///
1360/// Given
1361/// \code
1362/// class X { int m; };
1363/// \endcode
1364/// fieldDecl()
1365/// matches 'm'.
1366extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1367
1368/// Matches indirect field declarations.
1369///
1370/// Given
1371/// \code
1372/// struct X { struct { int a; }; };
1373/// \endcode
1374/// indirectFieldDecl()
1375/// matches 'a'.
1376extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1378
1379/// Matches function declarations.
1380///
1381/// Example matches f
1382/// \code
1383/// void f();
1384/// \endcode
1385extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1387
1388/// Matches C++ function template declarations.
1389///
1390/// Example matches f
1391/// \code
1392/// template<class T> void f(T t) {}
1393/// \endcode
1394extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1396
1397/// Matches friend declarations.
1398///
1399/// Given
1400/// \code
1401/// class X { friend void foo(); };
1402/// \endcode
1403/// friendDecl()
1404/// matches 'friend void foo()'.
1405extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1406
1407/// Matches statements.
1408///
1409/// Given
1410/// \code
1411/// { ++a; }
1412/// \endcode
1413/// stmt()
1414/// matches both the compound statement '{ ++a; }' and '++a'.
1415extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1416
1417/// Matches declaration statements.
1418///
1419/// Given
1420/// \code
1421/// int a;
1422/// \endcode
1423/// declStmt()
1424/// matches 'int a'.
1425extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1426
1427/// Matches member expressions.
1428///
1429/// Given
1430/// \code
1431/// class Y {
1432/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1433/// int a; static int b;
1434/// };
1435/// \endcode
1436/// memberExpr()
1437/// matches this->x, x, y.x, a, this->b
1438extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1439
1440/// Matches unresolved member expressions.
1441///
1442/// Given
1443/// \code
1444/// struct X {
1445/// template <class T> void f();
1446/// void g();
1447/// };
1448/// template <class T> void h() { X x; x.f<T>(); x.g(); }
1449/// \endcode
1450/// unresolvedMemberExpr()
1451/// matches x.f<T>
1452extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1454
1455/// Matches member expressions where the actual member referenced could not be
1456/// resolved because the base expression or the member name was dependent.
1457///
1458/// Given
1459/// \code
1460/// template <class T> void f() { T t; t.g(); }
1461/// \endcode
1462/// cxxDependentScopeMemberExpr()
1463/// matches t.g
1464extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1467
1468/// Matches call expressions.
1469///
1470/// Example matches x.y() and y()
1471/// \code
1472/// X x;
1473/// x.y();
1474/// y();
1475/// \endcode
1476extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1477
1478/// Matches call expressions which were resolved using ADL.
1479///
1480/// Example matches y(x) but not y(42) or NS::y(x).
1481/// \code
1482/// namespace NS {
1483/// struct X {};
1484/// void y(X);
1485/// }
1486///
1487/// void y(...);
1488///
1489/// void test() {
1490/// NS::X x;
1491/// y(x); // Matches
1492/// NS::y(x); // Doesn't match
1493/// y(42); // Doesn't match
1494/// using NS::y;
1495/// y(x); // Found by both unqualified lookup and ADL, doesn't match
1496// }
1497/// \endcode
1498AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1499
1500/// Matches lambda expressions.
1501///
1502/// Example matches [&](){return 5;}
1503/// \code
1504/// [&](){return 5;}
1505/// \endcode
1506extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1507
1508/// Matches member call expressions.
1509///
1510/// Example matches x.y()
1511/// \code
1512/// X x;
1513/// x.y();
1514/// \endcode
1515extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1517
1518/// Matches ObjectiveC Message invocation expressions.
1519///
1520/// The innermost message send invokes the "alloc" class method on the
1521/// NSString class, while the outermost message send invokes the
1522/// "initWithString" instance method on the object returned from
1523/// NSString's "alloc". This matcher should match both message sends.
1524/// \code
1525/// [[NSString alloc] initWithString:@"Hello"]
1526/// \endcode
1527extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1529
1530/// Matches ObjectiveC String literal expressions.
1531///
1532/// Example matches @"abcd"
1533/// \code
1534/// NSString *s = @"abcd";
1535/// \endcode
1536extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCStringLiteral>
1538
1539/// Matches Objective-C interface declarations.
1540///
1541/// Example matches Foo
1542/// \code
1543/// @interface Foo
1544/// @end
1545/// \endcode
1546extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1548
1549/// Matches Objective-C implementation declarations.
1550///
1551/// Example matches Foo
1552/// \code
1553/// @implementation Foo
1554/// @end
1555/// \endcode
1556extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1558
1559/// Matches Objective-C protocol declarations.
1560///
1561/// Example matches FooDelegate
1562/// \code
1563/// @protocol FooDelegate
1564/// @end
1565/// \endcode
1566extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1568
1569/// Matches Objective-C category declarations.
1570///
1571/// Example matches Foo (Additions)
1572/// \code
1573/// @interface Foo (Additions)
1574/// @end
1575/// \endcode
1576extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1578
1579/// Matches Objective-C category definitions.
1580///
1581/// Example matches Foo (Additions)
1582/// \code
1583/// @implementation Foo (Additions)
1584/// @end
1585/// \endcode
1586extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1588
1589/// Matches Objective-C method declarations.
1590///
1591/// Example matches both declaration and definition of -[Foo method]
1592/// \code
1593/// @interface Foo
1594/// - (void)method;
1595/// @end
1596///
1597/// @implementation Foo
1598/// - (void)method {}
1599/// @end
1600/// \endcode
1601extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1603
1604/// Matches block declarations.
1605///
1606/// Example matches the declaration of the nameless block printing an input
1607/// integer.
1608///
1609/// \code
1610/// myFunc(^(int p) {
1611/// printf("%d", p);
1612/// })
1613/// \endcode
1614extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1615 blockDecl;
1616
1617/// Matches Objective-C instance variable declarations.
1618///
1619/// Example matches _enabled
1620/// \code
1621/// @implementation Foo {
1622/// BOOL _enabled;
1623/// }
1624/// @end
1625/// \endcode
1626extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1628
1629/// Matches Objective-C property declarations.
1630///
1631/// Example matches enabled
1632/// \code
1633/// @interface Foo
1634/// @property BOOL enabled;
1635/// @end
1636/// \endcode
1637extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1639
1640/// Matches Objective-C \@throw statements.
1641///
1642/// Example matches \@throw
1643/// \code
1644/// @throw obj;
1645/// \endcode
1646extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1648
1649/// Matches Objective-C @try statements.
1650///
1651/// Example matches @try
1652/// \code
1653/// @try {}
1654/// @catch (...) {}
1655/// \endcode
1656extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1658
1659/// Matches Objective-C @catch statements.
1660///
1661/// Example matches @catch
1662/// \code
1663/// @try {}
1664/// @catch (...) {}
1665/// \endcode
1666extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1668
1669/// Matches Objective-C @finally statements.
1670///
1671/// Example matches @finally
1672/// \code
1673/// @try {}
1674/// @finally {}
1675/// \endcode
1676extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1678
1679/// Matches expressions that introduce cleanups to be run at the end
1680/// of the sub-expression's evaluation.
1681///
1682/// Example matches std::string()
1683/// \code
1684/// const std::string str = std::string();
1685/// \endcode
1686extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1688
1689/// Matches init list expressions.
1690///
1691/// Given
1692/// \code
1693/// int a[] = { 1, 2 };
1694/// struct B { int x, y; };
1695/// B b = { 5, 6 };
1696/// \endcode
1697/// initListExpr()
1698/// matches "{ 1, 2 }" and "{ 5, 6 }"
1699extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1701
1702/// Matches the syntactic form of init list expressions
1703/// (if expression have it).
1704AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1705 internal::Matcher<Expr>, InnerMatcher) {
1706 const Expr *SyntForm = Node.getSyntacticForm();
1707 return (SyntForm != nullptr &&
1708 InnerMatcher.matches(*SyntForm, Finder, Builder));
1709}
1710
1711/// Matches C++ initializer list expressions.
1712///
1713/// Given
1714/// \code
1715/// std::vector<int> a({ 1, 2, 3 });
1716/// std::vector<int> b = { 4, 5 };
1717/// int c[] = { 6, 7 };
1718/// std::pair<int, int> d = { 8, 9 };
1719/// \endcode
1720/// cxxStdInitializerListExpr()
1721/// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1722extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1725
1726/// Matches implicit initializers of init list expressions.
1727///
1728/// Given
1729/// \code
1730/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1731/// \endcode
1732/// implicitValueInitExpr()
1733/// matches "[0].y" (implicitly)
1734extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1736
1737/// Matches paren list expressions.
1738/// ParenListExprs don't have a predefined type and are used for late parsing.
1739/// In the final AST, they can be met in template declarations.
1740///
1741/// Given
1742/// \code
1743/// template<typename T> class X {
1744/// void f() {
1745/// X x(*this);
1746/// int a = 0, b = 1; int i = (a, b);
1747/// }
1748/// };
1749/// \endcode
1750/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1751/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1752extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1754
1755/// Matches substitutions of non-type template parameters.
1756///
1757/// Given
1758/// \code
1759/// template <int N>
1760/// struct A { static const int n = N; };
1761/// struct B : public A<42> {};
1762/// \endcode
1763/// substNonTypeTemplateParmExpr()
1764/// matches "N" in the right-hand side of "static const int n = N;"
1765extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1768
1769/// Matches using declarations.
1770///
1771/// Given
1772/// \code
1773/// namespace X { int x; }
1774/// using X::x;
1775/// \endcode
1776/// usingDecl()
1777/// matches \code using X::x \endcode
1778extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1779
1780/// Matches using-enum declarations.
1781///
1782/// Given
1783/// \code
1784/// namespace X { enum x {...}; }
1785/// using enum X::x;
1786/// \endcode
1787/// usingEnumDecl()
1788/// matches \code using enum X::x \endcode
1789extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingEnumDecl>
1791
1792/// Matches using namespace declarations.
1793///
1794/// Given
1795/// \code
1796/// namespace X { int x; }
1797/// using namespace X;
1798/// \endcode
1799/// usingDirectiveDecl()
1800/// matches \code using namespace X \endcode
1801extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1803
1804/// Matches reference to a name that can be looked up during parsing
1805/// but could not be resolved to a specific declaration.
1806///
1807/// Given
1808/// \code
1809/// template<typename T>
1810/// T foo() { T a; return a; }
1811/// template<typename T>
1812/// void bar() {
1813/// foo<T>();
1814/// }
1815/// \endcode
1816/// unresolvedLookupExpr()
1817/// matches \code foo<T>() \endcode
1818extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1820
1821/// Matches unresolved using value declarations.
1822///
1823/// Given
1824/// \code
1825/// template<typename X>
1826/// class C : private X {
1827/// using X::x;
1828/// };
1829/// \endcode
1830/// unresolvedUsingValueDecl()
1831/// matches \code using X::x \endcode
1832extern const internal::VariadicDynCastAllOfMatcher<Decl,
1835
1836/// Matches unresolved using value declarations that involve the
1837/// typename.
1838///
1839/// Given
1840/// \code
1841/// template <typename T>
1842/// struct Base { typedef T Foo; };
1843///
1844/// template<typename T>
1845/// struct S : private Base<T> {
1846/// using typename Base<T>::Foo;
1847/// };
1848/// \endcode
1849/// unresolvedUsingTypenameDecl()
1850/// matches \code using Base<T>::Foo \endcode
1851extern const internal::VariadicDynCastAllOfMatcher<Decl,
1854
1855/// Matches a constant expression wrapper.
1856///
1857/// Example matches the constant in the case statement:
1858/// (matcher = constantExpr())
1859/// \code
1860/// switch (a) {
1861/// case 37: break;
1862/// }
1863/// \endcode
1864extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1866
1867/// Matches parentheses used in expressions.
1868///
1869/// Example matches (foo() + 1)
1870/// \code
1871/// int foo() { return 1; }
1872/// int a = (foo() + 1);
1873/// \endcode
1874extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1875
1876/// Matches constructor call expressions (including implicit ones).
1877///
1878/// Example matches string(ptr, n) and ptr within arguments of f
1879/// (matcher = cxxConstructExpr())
1880/// \code
1881/// void f(const string &a, const string &b);
1882/// char *ptr;
1883/// int n;
1884/// f(string(ptr, n), ptr);
1885/// \endcode
1886extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1888
1889/// Matches unresolved constructor call expressions.
1890///
1891/// Example matches T(t) in return statement of f
1892/// (matcher = cxxUnresolvedConstructExpr())
1893/// \code
1894/// template <typename T>
1895/// void f(const T& t) { return T(t); }
1896/// \endcode
1897extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1900
1901/// Matches implicit and explicit this expressions.
1902///
1903/// Example matches the implicit this expression in "return i".
1904/// (matcher = cxxThisExpr())
1905/// \code
1906/// struct foo {
1907/// int i;
1908/// int f() { return i; }
1909/// };
1910/// \endcode
1911extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1913
1914/// Matches nodes where temporaries are created.
1915///
1916/// Example matches FunctionTakesString(GetStringByValue())
1917/// (matcher = cxxBindTemporaryExpr())
1918/// \code
1919/// FunctionTakesString(GetStringByValue());
1920/// FunctionTakesStringByPointer(GetStringPointer());
1921/// \endcode
1922extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1924
1925/// Matches nodes where temporaries are materialized.
1926///
1927/// Example: Given
1928/// \code
1929/// struct T {void func();};
1930/// T f();
1931/// void g(T);
1932/// \endcode
1933/// materializeTemporaryExpr() matches 'f()' in these statements
1934/// \code
1935/// T u(f());
1936/// g(f());
1937/// f().func();
1938/// \endcode
1939/// but does not match
1940/// \code
1941/// f();
1942/// \endcode
1943extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1946
1947/// Matches new expressions.
1948///
1949/// Given
1950/// \code
1951/// new X;
1952/// \endcode
1953/// cxxNewExpr()
1954/// matches 'new X'.
1955extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1956
1957/// Matches delete expressions.
1958///
1959/// Given
1960/// \code
1961/// delete X;
1962/// \endcode
1963/// cxxDeleteExpr()
1964/// matches 'delete X'.
1965extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1967
1968/// Matches noexcept expressions.
1969///
1970/// Given
1971/// \code
1972/// bool a() noexcept;
1973/// bool b() noexcept(true);
1974/// bool c() noexcept(false);
1975/// bool d() noexcept(noexcept(a()));
1976/// bool e = noexcept(b()) || noexcept(c());
1977/// \endcode
1978/// cxxNoexceptExpr()
1979/// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1980/// doesn't match the noexcept specifier in the declarations a, b, c or d.
1981extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1983
1984/// Matches a loop initializing the elements of an array in a number of contexts:
1985/// * in the implicit copy/move constructor for a class with an array member
1986/// * when a lambda-expression captures an array by value
1987/// * when a decomposition declaration decomposes an array
1988///
1989/// Given
1990/// \code
1991/// void testLambdaCapture() {
1992/// int a[10];
1993/// auto Lam1 = [a]() {
1994/// return;
1995/// };
1996/// }
1997/// \endcode
1998/// arrayInitLoopExpr() matches the implicit loop that initializes each element of
1999/// the implicit array field inside the lambda object, that represents the array `a`
2000/// captured by value.
2001extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitLoopExpr>
2003
2004/// The arrayInitIndexExpr consists of two subexpressions: a common expression
2005/// (the source array) that is evaluated once up-front, and a per-element initializer
2006/// that runs once for each array element. Within the per-element initializer,
2007/// the current index may be obtained via an ArrayInitIndexExpr.
2008///
2009/// Given
2010/// \code
2011/// void testStructBinding() {
2012/// int a[2] = {1, 2};
2013/// auto [x, y] = a;
2014/// }
2015/// \endcode
2016/// arrayInitIndexExpr() matches the array index that implicitly iterates
2017/// over the array `a` to copy each element to the anonymous array
2018/// that backs the structured binding `[x, y]` elements of which are
2019/// referred to by their aliases `x` and `y`.
2020extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArrayInitIndexExpr>
2022
2023/// Matches array subscript expressions.
2024///
2025/// Given
2026/// \code
2027/// int i = a[1];
2028/// \endcode
2029/// arraySubscriptExpr()
2030/// matches "a[1]"
2031extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
2033
2034/// Matches the value of a default argument at the call site.
2035///
2036/// Example matches the CXXDefaultArgExpr placeholder inserted for the
2037/// default value of the second parameter in the call expression f(42)
2038/// (matcher = cxxDefaultArgExpr())
2039/// \code
2040/// void f(int x, int y = 0);
2041/// f(42);
2042/// \endcode
2043extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
2045
2046/// Matches overloaded operator calls.
2047///
2048/// Note that if an operator isn't overloaded, it won't match. Instead, use
2049/// binaryOperator matcher.
2050/// Currently it does not match operators such as new delete.
2051/// FIXME: figure out why these do not match?
2052///
2053/// Example matches both operator<<((o << b), c) and operator<<(o, b)
2054/// (matcher = cxxOperatorCallExpr())
2055/// \code
2056/// ostream &operator<< (ostream &out, int i) { };
2057/// ostream &o; int b = 1, c = 1;
2058/// o << b << c;
2059/// \endcode
2060/// See also the binaryOperation() matcher for more-general matching of binary
2061/// uses of this AST node.
2062extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
2064
2065/// Matches rewritten binary operators
2066///
2067/// Example matches use of "<":
2068/// \code
2069/// #include <compare>
2070/// struct HasSpaceshipMem {
2071/// int a;
2072/// constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
2073/// };
2074/// void compare() {
2075/// HasSpaceshipMem hs1, hs2;
2076/// if (hs1 < hs2)
2077/// return;
2078/// }
2079/// \endcode
2080/// See also the binaryOperation() matcher for more-general matching
2081/// of this AST node.
2082extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2085
2086/// Matches expressions.
2087///
2088/// Example matches x()
2089/// \code
2090/// void f() { x(); }
2091/// \endcode
2092extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2093
2094/// Matches expressions that refer to declarations.
2095///
2096/// Example matches x in if (x)
2097/// \code
2098/// bool x;
2099/// if (x) {}
2100/// \endcode
2101extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2103
2104/// Matches a reference to an ObjCIvar.
2105///
2106/// Example: matches "a" in "init" method:
2107/// \code
2108/// @implementation A {
2109/// NSString *a;
2110/// }
2111/// - (void) init {
2112/// a = @"hello";
2113/// }
2114/// \endcode
2115extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2117
2118/// Matches a reference to a block.
2119///
2120/// Example: matches "^{}":
2121/// \code
2122/// void f() { ^{}(); }
2123/// \endcode
2124extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2125
2126/// Matches if statements.
2127///
2128/// Example matches 'if (x) {}'
2129/// \code
2130/// if (x) {}
2131/// \endcode
2132extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2133
2134/// Matches for statements.
2135///
2136/// Example matches 'for (;;) {}'
2137/// \code
2138/// for (;;) {}
2139/// int i[] = {1, 2, 3}; for (auto a : i);
2140/// \endcode
2141extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2142
2143/// Matches the increment statement of a for loop.
2144///
2145/// Example:
2146/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2147/// matches '++x' in
2148/// \code
2149/// for (x; x < N; ++x) { }
2150/// \endcode
2151AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2152 InnerMatcher) {
2153 const Stmt *const Increment = Node.getInc();
2154 return (Increment != nullptr &&
2155 InnerMatcher.matches(*Increment, Finder, Builder));
2156}
2157
2158/// Matches the initialization statement of a for loop.
2159///
2160/// Example:
2161/// forStmt(hasLoopInit(declStmt()))
2162/// matches 'int x = 0' in
2163/// \code
2164/// for (int x = 0; x < N; ++x) { }
2165/// \endcode
2166AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2167 InnerMatcher) {
2168 const Stmt *const Init = Node.getInit();
2169 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2170}
2171
2172/// Matches range-based for statements.
2173///
2174/// cxxForRangeStmt() matches 'for (auto a : i)'
2175/// \code
2176/// int i[] = {1, 2, 3}; for (auto a : i);
2177/// for(int j = 0; j < 5; ++j);
2178/// \endcode
2179extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2181
2182/// Matches the initialization statement of a for loop.
2183///
2184/// Example:
2185/// forStmt(hasLoopVariable(anything()))
2186/// matches 'int x' in
2187/// \code
2188/// for (int x : a) { }
2189/// \endcode
2190AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2191 InnerMatcher) {
2192 const VarDecl *const Var = Node.getLoopVariable();
2193 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2194}
2195
2196/// Matches the range initialization statement of a for loop.
2197///
2198/// Example:
2199/// forStmt(hasRangeInit(anything()))
2200/// matches 'a' in
2201/// \code
2202/// for (int x : a) { }
2203/// \endcode
2204AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2205 InnerMatcher) {
2206 const Expr *const Init = Node.getRangeInit();
2207 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2208}
2209
2210/// Matches while statements.
2211///
2212/// Given
2213/// \code
2214/// while (true) {}
2215/// \endcode
2216/// whileStmt()
2217/// matches 'while (true) {}'.
2218extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2219
2220/// Matches do statements.
2221///
2222/// Given
2223/// \code
2224/// do {} while (true);
2225/// \endcode
2226/// doStmt()
2227/// matches 'do {} while(true)'
2228extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2229
2230/// Matches break statements.
2231///
2232/// Given
2233/// \code
2234/// while (true) { break; }
2235/// \endcode
2236/// breakStmt()
2237/// matches 'break'
2238extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2239
2240/// Matches continue statements.
2241///
2242/// Given
2243/// \code
2244/// while (true) { continue; }
2245/// \endcode
2246/// continueStmt()
2247/// matches 'continue'
2248extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2250
2251/// Matches co_return statements.
2252///
2253/// Given
2254/// \code
2255/// while (true) { co_return; }
2256/// \endcode
2257/// coreturnStmt()
2258/// matches 'co_return'
2259extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2261
2262/// Matches return statements.
2263///
2264/// Given
2265/// \code
2266/// return 1;
2267/// \endcode
2268/// returnStmt()
2269/// matches 'return 1'
2270extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2271
2272/// Matches goto statements.
2273///
2274/// Given
2275/// \code
2276/// goto FOO;
2277/// FOO: bar();
2278/// \endcode
2279/// gotoStmt()
2280/// matches 'goto FOO'
2281extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2282
2283/// Matches label statements.
2284///
2285/// Given
2286/// \code
2287/// goto FOO;
2288/// FOO: bar();
2289/// \endcode
2290/// labelStmt()
2291/// matches 'FOO:'
2292extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2293
2294/// Matches address of label statements (GNU extension).
2295///
2296/// Given
2297/// \code
2298/// FOO: bar();
2299/// void *ptr = &&FOO;
2300/// goto *bar;
2301/// \endcode
2302/// addrLabelExpr()
2303/// matches '&&FOO'
2304extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2306
2307/// Matches switch statements.
2308///
2309/// Given
2310/// \code
2311/// switch(a) { case 42: break; default: break; }
2312/// \endcode
2313/// switchStmt()
2314/// matches 'switch(a)'.
2315extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2316
2317/// Matches case and default statements inside switch statements.
2318///
2319/// Given
2320/// \code
2321/// switch(a) { case 42: break; default: break; }
2322/// \endcode
2323/// switchCase()
2324/// matches 'case 42:' and 'default:'.
2325extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2326
2327/// Matches case statements inside switch statements.
2328///
2329/// Given
2330/// \code
2331/// switch(a) { case 42: break; default: break; }
2332/// \endcode
2333/// caseStmt()
2334/// matches 'case 42:'.
2335extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2336
2337/// Matches default statements inside switch statements.
2338///
2339/// Given
2340/// \code
2341/// switch(a) { case 42: break; default: break; }
2342/// \endcode
2343/// defaultStmt()
2344/// matches 'default:'.
2345extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2347
2348/// Matches compound statements.
2349///
2350/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2351/// \code
2352/// for (;;) {{}}
2353/// \endcode
2354extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2356
2357/// Matches catch statements.
2358///
2359/// \code
2360/// try {} catch(int i) {}
2361/// \endcode
2362/// cxxCatchStmt()
2363/// matches 'catch(int i)'
2364extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2366
2367/// Matches try statements.
2368///
2369/// \code
2370/// try {} catch(int i) {}
2371/// \endcode
2372/// cxxTryStmt()
2373/// matches 'try {}'
2374extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2375
2376/// Matches throw expressions.
2377///
2378/// \code
2379/// try { throw 5; } catch(int i) {}
2380/// \endcode
2381/// cxxThrowExpr()
2382/// matches 'throw 5'
2383extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2385
2386/// Matches null statements.
2387///
2388/// \code
2389/// foo();;
2390/// \endcode
2391/// nullStmt()
2392/// matches the second ';'
2393extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2394
2395/// Matches asm statements.
2396///
2397/// \code
2398/// int i = 100;
2399/// __asm("mov al, 2");
2400/// \endcode
2401/// asmStmt()
2402/// matches '__asm("mov al, 2")'
2403extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2404
2405/// Matches bool literals.
2406///
2407/// Example matches true
2408/// \code
2409/// true
2410/// \endcode
2411extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2413
2414/// Matches string literals (also matches wide string literals).
2415///
2416/// Example matches "abcd", L"abcd"
2417/// \code
2418/// char *s = "abcd";
2419/// wchar_t *ws = L"abcd";
2420/// \endcode
2421extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2423
2424/// Matches character literals (also matches wchar_t).
2425///
2426/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2427/// though.
2428///
2429/// Example matches 'a', L'a'
2430/// \code
2431/// char ch = 'a';
2432/// wchar_t chw = L'a';
2433/// \endcode
2434extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2436
2437/// Matches integer literals of all sizes / encodings, e.g.
2438/// 1, 1L, 0x1 and 1U.
2439///
2440/// Does not match character-encoded integers such as L'a'.
2441extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2443
2444/// Matches float literals of all sizes / encodings, e.g.
2445/// 1.0, 1.0f, 1.0L and 1e10.
2446///
2447/// Does not match implicit conversions such as
2448/// \code
2449/// float a = 10;
2450/// \endcode
2451extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2453
2454/// Matches imaginary literals, which are based on integer and floating
2455/// point literals e.g.: 1i, 1.0i
2456extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2458
2459/// Matches fixed point literals
2460extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2462
2463/// Matches user defined literal operator call.
2464///
2465/// Example match: "foo"_suffix
2466extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2468
2469/// Matches compound (i.e. non-scalar) literals
2470///
2471/// Example match: {1}, (1, 2)
2472/// \code
2473/// int array[4] = {1};
2474/// vector int myvec = (vector int)(1, 2);
2475/// \endcode
2476extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2478
2479/// Matches co_await expressions.
2480///
2481/// Given
2482/// \code
2483/// co_await 1;
2484/// \endcode
2485/// coawaitExpr()
2486/// matches 'co_await 1'
2487extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2489/// Matches co_await expressions where the type of the promise is dependent
2490extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2492/// Matches co_yield expressions.
2493///
2494/// Given
2495/// \code
2496/// co_yield 1;
2497/// \endcode
2498/// coyieldExpr()
2499/// matches 'co_yield 1'
2500extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2502
2503/// Matches coroutine body statements.
2504///
2505/// coroutineBodyStmt() matches the coroutine below
2506/// \code
2507/// generator<int> gen() {
2508/// co_return;
2509/// }
2510/// \endcode
2511extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoroutineBodyStmt>
2513
2514/// Matches nullptr literal.
2515extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2517
2518/// Matches GNU __builtin_choose_expr.
2519extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2520 chooseExpr;
2521
2522/// Matches builtin function __builtin_convertvector.
2523extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConvertVectorExpr>
2525
2526/// Matches GNU __null expression.
2527extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2529
2530/// Matches C11 _Generic expression.
2531extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2533
2534/// Matches atomic builtins.
2535/// Example matches __atomic_load_n(ptr, 1)
2536/// \code
2537/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2538/// \endcode
2539extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2540
2541/// Matches statement expression (GNU extension).
2542///
2543/// Example match: ({ int X = 4; X; })
2544/// \code
2545/// int C = ({ int X = 4; X; });
2546/// \endcode
2547extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2548
2549/// Matches binary operator expressions.
2550///
2551/// Example matches a || b
2552/// \code
2553/// !(a || b)
2554/// \endcode
2555/// See also the binaryOperation() matcher for more-general matching.
2556extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2558
2559/// Matches unary operator expressions.
2560///
2561/// Example matches !a
2562/// \code
2563/// !a || b
2564/// \endcode
2565extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2567
2568/// Matches conditional operator expressions.
2569///
2570/// Example matches a ? b : c
2571/// \code
2572/// (a ? b : c) + 42
2573/// \endcode
2574extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2576
2577/// Matches binary conditional operator expressions (GNU extension).
2578///
2579/// Example matches a ?: b
2580/// \code
2581/// (a ?: b) + 42;
2582/// \endcode
2583extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2586
2587/// Matches opaque value expressions. They are used as helpers
2588/// to reference another expressions and can be met
2589/// in BinaryConditionalOperators, for example.
2590///
2591/// Example matches 'a'
2592/// \code
2593/// (a ?: c) + 42;
2594/// \endcode
2595extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2597
2598/// Matches a C++ static_assert declaration.
2599///
2600/// Example:
2601/// staticAssertDecl()
2602/// matches
2603/// static_assert(sizeof(S) == sizeof(int))
2604/// in
2605/// \code
2606/// struct S {
2607/// int x;
2608/// };
2609/// static_assert(sizeof(S) == sizeof(int));
2610/// \endcode
2611extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2613
2614/// Matches a reinterpret_cast expression.
2615///
2616/// Either the source expression or the destination type can be matched
2617/// using has(), but hasDestinationType() is more specific and can be
2618/// more readable.
2619///
2620/// Example matches reinterpret_cast<char*>(&p) in
2621/// \code
2622/// void* p = reinterpret_cast<char*>(&p);
2623/// \endcode
2624extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2626
2627/// Matches a C++ static_cast expression.
2628///
2629/// \see hasDestinationType
2630/// \see reinterpretCast
2631///
2632/// Example:
2633/// cxxStaticCastExpr()
2634/// matches
2635/// static_cast<long>(8)
2636/// in
2637/// \code
2638/// long eight(static_cast<long>(8));
2639/// \endcode
2640extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2642
2643/// Matches a dynamic_cast expression.
2644///
2645/// Example:
2646/// cxxDynamicCastExpr()
2647/// matches
2648/// dynamic_cast<D*>(&b);
2649/// in
2650/// \code
2651/// struct B { virtual ~B() {} }; struct D : B {};
2652/// B b;
2653/// D* p = dynamic_cast<D*>(&b);
2654/// \endcode
2655extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2657
2658/// Matches a const_cast expression.
2659///
2660/// Example: Matches const_cast<int*>(&r) in
2661/// \code
2662/// int n = 42;
2663/// const int &r(n);
2664/// int* p = const_cast<int*>(&r);
2665/// \endcode
2666extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2668
2669/// Matches a C-style cast expression.
2670///
2671/// Example: Matches (int) 2.2f in
2672/// \code
2673/// int i = (int) 2.2f;
2674/// \endcode
2675extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2677
2678/// Matches explicit cast expressions.
2679///
2680/// Matches any cast expression written in user code, whether it be a
2681/// C-style cast, a functional-style cast, or a keyword cast.
2682///
2683/// Does not match implicit conversions.
2684///
2685/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2686/// Clang uses the term "cast" to apply to implicit conversions as well as to
2687/// actual cast expressions.
2688///
2689/// \see hasDestinationType.
2690///
2691/// Example: matches all five of the casts in
2692/// \code
2693/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2694/// \endcode
2695/// but does not match the implicit conversion in
2696/// \code
2697/// long ell = 42;
2698/// \endcode
2699extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2701
2702/// Matches the implicit cast nodes of Clang's AST.
2703///
2704/// This matches many different places, including function call return value
2705/// eliding, as well as any type conversions.
2706extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2708
2709/// Matches any cast nodes of Clang's AST.
2710///
2711/// Example: castExpr() matches each of the following:
2712/// \code
2713/// (int) 3;
2714/// const_cast<Expr *>(SubExpr);
2715/// char c = 0;
2716/// \endcode
2717/// but does not match
2718/// \code
2719/// int i = (0);
2720/// int k = 0;
2721/// \endcode
2722extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2723
2724/// Matches functional cast expressions
2725///
2726/// Example: Matches Foo(bar);
2727/// \code
2728/// Foo f = bar;
2729/// Foo g = (Foo) bar;
2730/// Foo h = Foo(bar);
2731/// \endcode
2732extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2734
2735/// Matches functional cast expressions having N != 1 arguments
2736///
2737/// Example: Matches Foo(bar, bar)
2738/// \code
2739/// Foo h = Foo(bar, bar);
2740/// \endcode
2741extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2743
2744/// Matches predefined identifier expressions [C99 6.4.2.2].
2745///
2746/// Example: Matches __func__
2747/// \code
2748/// printf("%s", __func__);
2749/// \endcode
2750extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2752
2753/// Matches C99 designated initializer expressions [C99 6.7.8].
2754///
2755/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2756/// \code
2757/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2758/// \endcode
2759extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2761
2762/// Matches designated initializer expressions that contain
2763/// a specific number of designators.
2764///
2765/// Example: Given
2766/// \code
2767/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2768/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2769/// \endcode
2770/// designatorCountIs(2)
2771/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2772/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2773AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2774 return Node.size() == N;
2775}
2776
2777/// Matches \c QualTypes in the clang AST.
2778extern const internal::VariadicAllOfMatcher<QualType> qualType;
2779
2780/// Matches \c Types in the clang AST.
2781extern const internal::VariadicAllOfMatcher<Type> type;
2782
2783/// Matches \c TypeLocs in the clang AST.
2784extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2785
2786/// Matches if any of the given matchers matches.
2787///
2788/// Unlike \c anyOf, \c eachOf will generate a match result for each
2789/// matching submatcher.
2790///
2791/// For example, in:
2792/// \code
2793/// class A { int a; int b; };
2794/// \endcode
2795/// The matcher:
2796/// \code
2797/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2798/// has(fieldDecl(hasName("b")).bind("v"))))
2799/// \endcode
2800/// will generate two results binding "v", the first of which binds
2801/// the field declaration of \c a, the second the field declaration of
2802/// \c b.
2803///
2804/// Usable as: Any Matcher
2805extern const internal::VariadicOperatorMatcherFunc<
2806 2, std::numeric_limits<unsigned>::max()>
2807 eachOf;
2808
2809/// Matches if any of the given matchers matches.
2810///
2811/// Usable as: Any Matcher
2812extern const internal::VariadicOperatorMatcherFunc<
2813 2, std::numeric_limits<unsigned>::max()>
2814 anyOf;
2815
2816/// Matches if all given matchers match.
2817///
2818/// Usable as: Any Matcher
2819extern const internal::VariadicOperatorMatcherFunc<
2820 2, std::numeric_limits<unsigned>::max()>
2821 allOf;
2822
2823/// Matches any node regardless of the submatcher.
2824///
2825/// However, \c optionally will retain any bindings generated by the submatcher.
2826/// Useful when additional information which may or may not present about a main
2827/// matching node is desired.
2828///
2829/// For example, in:
2830/// \code
2831/// class Foo {
2832/// int bar;
2833/// }
2834/// \endcode
2835/// The matcher:
2836/// \code
2837/// cxxRecordDecl(
2838/// optionally(has(
2839/// fieldDecl(hasName("bar")).bind("var")
2840/// ))).bind("record")
2841/// \endcode
2842/// will produce a result binding for both "record" and "var".
2843/// The matcher will produce a "record" binding for even if there is no data
2844/// member named "bar" in that class.
2845///
2846/// Usable as: Any Matcher
2847extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2848
2849/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2850///
2851/// Given
2852/// \code
2853/// Foo x = bar;
2854/// int y = sizeof(x) + alignof(x);
2855/// \endcode
2856/// unaryExprOrTypeTraitExpr()
2857/// matches \c sizeof(x) and \c alignof(x)
2858extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2861
2862/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2863///
2864/// Given
2865/// \code
2866/// if (true);
2867/// for (; true; );
2868/// \endcode
2869/// with the matcher
2870/// \code
2871/// mapAnyOf(ifStmt, forStmt).with(
2872/// hasCondition(cxxBoolLiteralExpr(equals(true)))
2873/// ).bind("trueCond")
2874/// \endcode
2875/// matches the \c if and the \c for. It is equivalent to:
2876/// \code
2877/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2878/// anyOf(
2879/// ifStmt(trueCond).bind("trueCond"),
2880/// forStmt(trueCond).bind("trueCond")
2881/// );
2882/// \endcode
2883///
2884/// The with() chain-call accepts zero or more matchers which are combined
2885/// as-if with allOf() in each of the node matchers.
2886/// Usable as: Any Matcher
2887template <typename T, typename... U>
2888auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2889 return internal::MapAnyOfHelper<U...>();
2890}
2891
2892/// Matches nodes which can be used with binary operators.
2893///
2894/// The code
2895/// \code
2896/// var1 != var2;
2897/// \endcode
2898/// might be represented in the clang AST as a binaryOperator, a
2899/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2900///
2901/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2902/// least one is a class type (cxxOperatorCallExpr)
2903/// * whether the code appears in a template declaration, if at least one of the
2904/// vars is a dependent-type (binaryOperator)
2905/// * whether the code relies on a rewritten binary operator, such as a
2906/// spaceship operator or an inverted equality operator
2907/// (cxxRewrittenBinaryOperator)
2908///
2909/// This matcher elides details in places where the matchers for the nodes are
2910/// compatible.
2911///
2912/// Given
2913/// \code
2914/// binaryOperation(
2915/// hasOperatorName("!="),
2916/// hasLHS(expr().bind("lhs")),
2917/// hasRHS(expr().bind("rhs"))
2918/// )
2919/// \endcode
2920/// matches each use of "!=" in:
2921/// \code
2922/// struct S{
2923/// bool operator!=(const S&) const;
2924/// };
2925///
2926/// void foo()
2927/// {
2928/// 1 != 2;
2929/// S() != S();
2930/// }
2931///
2932/// template<typename T>
2933/// void templ()
2934/// {
2935/// 1 != 2;
2936/// T() != S();
2937/// }
2938/// struct HasOpEq
2939/// {
2940/// bool operator==(const HasOpEq &) const;
2941/// };
2942///
2943/// void inverse()
2944/// {
2945/// HasOpEq s1;
2946/// HasOpEq s2;
2947/// if (s1 != s2)
2948/// return;
2949/// }
2950///
2951/// struct HasSpaceship
2952/// {
2953/// bool operator<=>(const HasOpEq &) const;
2954/// };
2955///
2956/// void use_spaceship()
2957/// {
2958/// HasSpaceship s1;
2959/// HasSpaceship s2;
2960/// if (s1 != s2)
2961/// return;
2962/// }
2963/// \endcode
2964extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2967
2968/// Matches function calls and constructor calls
2969///
2970/// Because CallExpr and CXXConstructExpr do not share a common
2971/// base class with API accessing arguments etc, AST Matchers for code
2972/// which should match both are typically duplicated. This matcher
2973/// removes the need for duplication.
2974///
2975/// Given code
2976/// \code
2977/// struct ConstructorTakesInt
2978/// {
2979/// ConstructorTakesInt(int i) {}
2980/// };
2981///
2982/// void callTakesInt(int i)
2983/// {
2984/// }
2985///
2986/// void doCall()
2987/// {
2988/// callTakesInt(42);
2989/// }
2990///
2991/// void doConstruct()
2992/// {
2993/// ConstructorTakesInt cti(42);
2994/// }
2995/// \endcode
2996///
2997/// The matcher
2998/// \code
2999/// invocation(hasArgument(0, integerLiteral(equals(42))))
3000/// \endcode
3001/// matches the expression in both doCall and doConstruct
3002extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
3003
3004/// Matches unary expressions that have a specific type of argument.
3005///
3006/// Given
3007/// \code
3008/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
3009/// \endcode
3010/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
3011/// matches \c sizeof(a) and \c alignof(c)
3013 internal::Matcher<QualType>, InnerMatcher) {
3014 const QualType ArgumentType = Node.getTypeOfArgument();
3015 return InnerMatcher.matches(ArgumentType, Finder, Builder);
3016}
3017
3018/// Matches unary expressions of a certain kind.
3019///
3020/// Given
3021/// \code
3022/// int x;
3023/// int s = sizeof(x) + alignof(x)
3024/// \endcode
3025/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
3026/// matches \c sizeof(x)
3027///
3028/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
3029/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
3031 return Node.getKind() == Kind;
3032}
3033
3034/// Same as unaryExprOrTypeTraitExpr, but only matching
3035/// alignof.
3036inline internal::BindableMatcher<Stmt> alignOfExpr(
3037 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3039 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
3040 InnerMatcher)));
3041}
3042
3043/// Same as unaryExprOrTypeTraitExpr, but only matching
3044/// sizeof.
3045inline internal::BindableMatcher<Stmt> sizeOfExpr(
3046 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3048 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
3049}
3050
3051/// Matches NamedDecl nodes that have the specified name.
3052///
3053/// Supports specifying enclosing namespaces or classes by prefixing the name
3054/// with '<enclosing>::'.
3055/// Does not match typedefs of an underlying type with the given name.
3056///
3057/// Example matches X (Name == "X")
3058/// \code
3059/// class X;
3060/// \endcode
3061///
3062/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
3063/// \code
3064/// namespace a { namespace b { class X; } }
3065/// \endcode
3066inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3067 return internal::Matcher<NamedDecl>(
3068 new internal::HasNameMatcher({std::string(Name)}));
3069}
3070
3071/// Matches NamedDecl nodes that have any of the specified names.
3072///
3073/// This matcher is only provided as a performance optimization of hasName.
3074/// \code
3075/// hasAnyName(a, b, c)
3076/// \endcode
3077/// is equivalent to, but faster than
3078/// \code
3079/// anyOf(hasName(a), hasName(b), hasName(c))
3080/// \endcode
3081extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3083 hasAnyName;
3084
3085/// Matches NamedDecl nodes whose fully qualified names contain
3086/// a substring matched by the given RegExp.
3087///
3088/// Supports specifying enclosing namespaces or classes by
3089/// prefixing the name with '<enclosing>::'. Does not match typedefs
3090/// of an underlying type with the given name.
3091///
3092/// Example matches X (regexp == "::X")
3093/// \code
3094/// class X;
3095/// \endcode
3096///
3097/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3098/// \code
3099/// namespace foo { namespace bar { class X; } }
3100/// \endcode
3101AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3102 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3103 return RegExp->match(FullNameString);
3104}
3105
3106/// Matches overloaded operator names.
3107///
3108/// Matches overloaded operator names specified in strings without the
3109/// "operator" prefix: e.g. "<<".
3110///
3111/// Given:
3112/// \code
3113/// class A { int operator*(); };
3114/// const A &operator<<(const A &a, const A &b);
3115/// A a;
3116/// a << a; // <-- This matches
3117/// \endcode
3118///
3119/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3120/// specified line and
3121/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3122/// matches the declaration of \c A.
3123///
3124/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3125inline internal::PolymorphicMatcher<
3126 internal::HasOverloadedOperatorNameMatcher,
3128 std::vector<std::string>>
3130 return internal::PolymorphicMatcher<
3131 internal::HasOverloadedOperatorNameMatcher,
3133 std::vector<std::string>>({std::string(Name)});
3134}
3135
3136/// Matches overloaded operator names.
3137///
3138/// Matches overloaded operator names specified in strings without the
3139/// "operator" prefix: e.g. "<<".
3140///
3141/// hasAnyOverloadedOperatorName("+", "-")
3142/// Is equivalent to
3143/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3144extern const internal::VariadicFunction<
3145 internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3148 std::vector<std::string>>,
3151
3152/// Matches template-dependent, but known, member names.
3153///
3154/// In template declarations, dependent members are not resolved and so can
3155/// not be matched to particular named declarations.
3156///
3157/// This matcher allows to match on the known name of members.
3158///
3159/// Given
3160/// \code
3161/// template <typename T>
3162/// struct S {
3163/// void mem();
3164/// };
3165/// template <typename T>
3166/// void x() {
3167/// S<T> s;
3168/// s.mem();
3169/// }
3170/// \endcode
3171/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3172AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3173 return Node.getMember().getAsString() == N;
3174}
3175
3176/// Matches template-dependent, but known, member names against an already-bound
3177/// node
3178///
3179/// In template declarations, dependent members are not resolved and so can
3180/// not be matched to particular named declarations.
3181///
3182/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3183/// and CXXMethodDecl nodes.
3184///
3185/// Given
3186/// \code
3187/// template <typename T>
3188/// struct S {
3189/// void mem();
3190/// };
3191/// template <typename T>
3192/// void x() {
3193/// S<T> s;
3194/// s.mem();
3195/// }
3196/// \endcode
3197/// The matcher
3198/// @code
3199/// \c cxxDependentScopeMemberExpr(
3200/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3201/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3202/// cxxMethodDecl(hasName("mem")).bind("templMem")
3203/// )))))
3204/// )))),
3205/// memberHasSameNameAsBoundNode("templMem")
3206/// )
3207/// @endcode
3208/// first matches and binds the @c mem member of the @c S template, then
3209/// compares its name to the usage in @c s.mem() in the @c x function template
3210AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3211 std::string, BindingID) {
3212 auto MemberName = Node.getMember().getAsString();
3213
3214 return Builder->removeBindings(
3215 [this, MemberName](const BoundNodesMap &Nodes) {
3216 const auto &BN = Nodes.getNode(this->BindingID);
3217 if (const auto *ND = BN.get<NamedDecl>()) {
3218 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3219 return true;
3220 return ND->getName() != MemberName;
3221 }
3222 return true;
3223 });
3224}
3225
3226/// Matches C++ classes that are directly or indirectly derived from a class
3227/// matching \c Base, or Objective-C classes that directly or indirectly
3228/// subclass a class matching \c Base.
3229///
3230/// Note that a class is not considered to be derived from itself.
3231///
3232/// Example matches Y, Z, C (Base == hasName("X"))
3233/// \code
3234/// class X;
3235/// class Y : public X {}; // directly derived
3236/// class Z : public Y {}; // indirectly derived
3237/// typedef X A;
3238/// typedef A B;
3239/// class C : public B {}; // derived from a typedef of X
3240/// \endcode
3241///
3242/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3243/// \code
3244/// class Foo;
3245/// typedef Foo X;
3246/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3247/// \endcode
3248///
3249/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3250/// \code
3251/// @interface NSObject @end
3252/// @interface Bar : NSObject @end
3253/// \endcode
3254///
3255/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3257 isDerivedFrom,
3259 internal::Matcher<NamedDecl>, Base) {
3260 // Check if the node is a C++ struct/union/class.
3261 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3262 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3263
3264 // The node must be an Objective-C class.
3265 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3266 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3267 /*Directly=*/false);
3268}
3269
3270/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3272 isDerivedFrom,
3274 std::string, BaseName, 1) {
3275 if (BaseName.empty())
3276 return false;
3277
3278 const auto M = isDerivedFrom(hasName(BaseName));
3279
3280 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3281 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3282
3283 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3284 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3285}
3286
3287/// Matches C++ classes that have a direct or indirect base matching \p
3288/// BaseSpecMatcher.
3289///
3290/// Example:
3291/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3292/// \code
3293/// class Foo;
3294/// class Bar : Foo {};
3295/// class Baz : Bar {};
3296/// class SpecialBase;
3297/// class Proxy : SpecialBase {}; // matches Proxy
3298/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3299/// \endcode
3300///
3301// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3302AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3303 BaseSpecMatcher) {
3304 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3305}
3306
3307/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3308///
3309/// Example:
3310/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3311/// \code
3312/// class Foo;
3313/// class Bar : Foo {};
3314/// class Baz : Bar {};
3315/// class SpecialBase;
3316/// class Proxy : SpecialBase {}; // matches Proxy
3317/// class IndirectlyDerived : Proxy {}; // doesn't match
3318/// \endcode
3319AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3320 BaseSpecMatcher) {
3321 return Node.hasDefinition() &&
3322 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3323 return BaseSpecMatcher.matches(Base, Finder, Builder);
3324 });
3325}
3326
3327/// Similar to \c isDerivedFrom(), but also matches classes that directly
3328/// match \c Base.
3330 isSameOrDerivedFrom,
3332 internal::Matcher<NamedDecl>, Base, 0) {
3333 const auto M = anyOf(Base, isDerivedFrom(Base));
3334
3335 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3336 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3337
3338 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3339 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3340}
3341
3342/// Overloaded method as shortcut for
3343/// \c isSameOrDerivedFrom(hasName(...)).
3345 isSameOrDerivedFrom,
3347 std::string, BaseName, 1) {
3348 if (BaseName.empty())
3349 return false;
3350
3351 const auto M = isSameOrDerivedFrom(hasName(BaseName));
3352
3353 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3354 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3355
3356 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3357 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3358}
3359
3360/// Matches C++ or Objective-C classes that are directly derived from a class
3361/// matching \c Base.
3362///
3363/// Note that a class is not considered to be derived from itself.
3364///
3365/// Example matches Y, C (Base == hasName("X"))
3366/// \code
3367/// class X;
3368/// class Y : public X {}; // directly derived
3369/// class Z : public Y {}; // indirectly derived
3370/// typedef X A;
3371/// typedef A B;
3372/// class C : public B {}; // derived from a typedef of X
3373/// \endcode
3374///
3375/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3376/// \code
3377/// class Foo;
3378/// typedef Foo X;
3379/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3380/// \endcode
3382 isDirectlyDerivedFrom,
3384 internal::Matcher<NamedDecl>, Base, 0) {
3385 // Check if the node is a C++ struct/union/class.
3386 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3387 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3388
3389 // The node must be an Objective-C class.
3390 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3391 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3392 /*Directly=*/true);
3393}
3394
3395/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3397 isDirectlyDerivedFrom,
3399 std::string, BaseName, 1) {
3400 if (BaseName.empty())
3401 return false;
3402 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3403
3404 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3405 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3406
3407 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3408 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3409}
3410/// Matches the first method of a class or struct that satisfies \c
3411/// InnerMatcher.
3412///
3413/// Given:
3414/// \code
3415/// class A { void func(); };
3416/// class B { void member(); };
3417/// \endcode
3418///
3419/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3420/// \c A but not \c B.
3421AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3422 InnerMatcher) {
3423 BoundNodesTreeBuilder Result(*Builder);
3424 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3425 Node.method_end(), Finder, &Result);
3426 if (MatchIt == Node.method_end())
3427 return false;
3428
3429 if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3430 return false;
3431 *Builder = std::move(Result);
3432 return true;
3433}
3434
3435/// Matches the generated class of lambda expressions.
3436///
3437/// Given:
3438/// \code
3439/// auto x = []{};
3440/// \endcode
3441///
3442/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3443/// \c decltype(x)
3445 return Node.isLambda();
3446}
3447
3448/// Matches AST nodes that have child AST nodes that match the
3449/// provided matcher.
3450///
3451/// Example matches X, Y
3452/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3453/// \code
3454/// class X {}; // Matches X, because X::X is a class of name X inside X.
3455/// class Y { class X {}; };
3456/// class Z { class Y { class X {}; }; }; // Does not match Z.
3457/// \endcode
3458///
3459/// ChildT must be an AST base type.
3460///
3461/// Usable as: Any Matcher
3462/// Note that has is direct matcher, so it also matches things like implicit
3463/// casts and paren casts. If you are matching with expr then you should
3464/// probably consider using ignoringParenImpCasts like:
3465/// has(ignoringParenImpCasts(expr())).
3466extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3467
3468/// Matches AST nodes that have descendant AST nodes that match the
3469/// provided matcher.
3470///
3471/// Example matches X, Y, Z
3472/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3473/// \code
3474/// class X {}; // Matches X, because X::X is a class of name X inside X.
3475/// class Y { class X {}; };
3476/// class Z { class Y { class X {}; }; };
3477/// \endcode
3478///
3479/// DescendantT must be an AST base type.
3480///
3481/// Usable as: Any Matcher
3482extern const internal::ArgumentAdaptingMatcherFunc<
3483 internal::HasDescendantMatcher>
3485
3486/// Matches AST nodes that have child AST nodes that match the
3487/// provided matcher.
3488///
3489/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3490/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3491/// \code
3492/// class X {};
3493/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3494/// // inside Y.
3495/// class Z { class Y { class X {}; }; }; // Does not match Z.
3496/// \endcode
3497///
3498/// ChildT must be an AST base type.
3499///
3500/// As opposed to 'has', 'forEach' will cause a match for each result that
3501/// matches instead of only on the first one.
3502///
3503/// Usable as: Any Matcher
3504extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3505 forEach;
3506
3507/// Matches AST nodes that have descendant AST nodes that match the
3508/// provided matcher.
3509///
3510/// Example matches X, A, A::X, B, B::C, B::C::X
3511/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3512/// \code
3513/// class X {};
3514/// class A { class X {}; }; // Matches A, because A::X is a class of name
3515/// // X inside A.
3516/// class B { class C { class X {}; }; };
3517/// \endcode
3518///
3519/// DescendantT must be an AST base type.
3520///
3521/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3522/// each result that matches instead of only on the first one.
3523///
3524/// Note: Recursively combined ForEachDescendant can cause many matches:
3525/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3526/// forEachDescendant(cxxRecordDecl())
3527/// )))
3528/// will match 10 times (plus injected class name matches) on:
3529/// \code
3530/// class A { class B { class C { class D { class E {}; }; }; }; };
3531/// \endcode
3532///
3533/// Usable as: Any Matcher
3534extern const internal::ArgumentAdaptingMatcherFunc<
3535 internal::ForEachDescendantMatcher>
3537
3538/// Matches if the node or any descendant matches.
3539///
3540/// Generates results for each match.
3541///
3542/// For example, in:
3543/// \code
3544/// class A { class B {}; class C {}; };
3545/// \endcode
3546/// The matcher:
3547/// \code
3548/// cxxRecordDecl(hasName("::A"),
3549/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3550/// \endcode
3551/// will generate results for \c A, \c B and \c C.
3552///
3553/// Usable as: Any Matcher
3554template <typename T>
3555internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3556 return eachOf(Matcher, forEachDescendant(Matcher));
3557}
3558
3559/// Matches AST nodes that have a parent that matches the provided
3560/// matcher.
3561///
3562/// Given
3563/// \code
3564/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3565/// \endcode
3566/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3567///
3568/// Usable as: Any Matcher
3569extern const internal::ArgumentAdaptingMatcherFunc<
3570 internal::HasParentMatcher,
3571 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3572 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3573 hasParent;
3574
3575/// Matches AST nodes that have an ancestor that matches the provided
3576/// matcher.
3577///
3578/// Given
3579/// \code
3580/// void f() { if (true) { int x = 42; } }
3581/// void g() { for (;;) { int x = 43; } }
3582/// \endcode
3583/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3584///
3585/// Usable as: Any Matcher
3586extern const internal::ArgumentAdaptingMatcherFunc<
3587 internal::HasAncestorMatcher,
3588 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3589 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3591
3592/// Matches if the provided matcher does not match.
3593///
3594/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3595/// \code
3596/// class X {};
3597/// class Y {};
3598/// \endcode
3599///
3600/// Usable as: Any Matcher
3601extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3602
3603/// Matches a node if the declaration associated with that node
3604/// matches the given matcher.
3605///
3606/// The associated declaration is:
3607/// - for type nodes, the declaration of the underlying type
3608/// - for CallExpr, the declaration of the callee
3609/// - for MemberExpr, the declaration of the referenced member
3610/// - for CXXConstructExpr, the declaration of the constructor
3611/// - for CXXNewExpr, the declaration of the operator new
3612/// - for ObjCIvarExpr, the declaration of the ivar
3613///
3614/// For type nodes, hasDeclaration will generally match the declaration of the
3615/// sugared type. Given
3616/// \code
3617/// class X {};
3618/// typedef X Y;
3619/// Y y;
3620/// \endcode
3621/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3622/// typedefDecl. A common use case is to match the underlying, desugared type.
3623/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3624/// \code
3625/// varDecl(hasType(hasUnqualifiedDesugaredType(
3626/// recordType(hasDeclaration(decl())))))
3627/// \endcode
3628/// In this matcher, the decl will match the CXXRecordDecl of class X.
3629///
3630/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3631/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3632/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3633/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3634/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3635/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3636/// Matcher<UnresolvedUsingType>
3637inline internal::PolymorphicMatcher<
3638 internal::HasDeclarationMatcher,
3639 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3640hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3641 return internal::PolymorphicMatcher<
3642 internal::HasDeclarationMatcher,
3643 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3644 InnerMatcher);
3645}
3646
3647/// Matches a \c NamedDecl whose underlying declaration matches the given
3648/// matcher.
3649///
3650/// Given
3651/// \code
3652/// namespace N { template<class T> void f(T t); }
3653/// template <class T> void g() { using N::f; f(T()); }
3654/// \endcode
3655/// \c unresolvedLookupExpr(hasAnyDeclaration(
3656/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3657/// matches the use of \c f in \c g() .
3658AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3659 InnerMatcher) {
3660 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3661
3662 return UnderlyingDecl != nullptr &&
3663 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3664}
3665
3666/// Matches on the implicit object argument of a member call expression, after
3667/// stripping off any parentheses or implicit casts.
3668///
3669/// Given
3670/// \code
3671/// class Y { public: void m(); };
3672/// Y g();
3673/// class X : public Y {};
3674/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3675/// \endcode
3676/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3677/// matches `y.m()` and `(g()).m()`.
3678/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3679/// matches `x.m()`.
3680/// cxxMemberCallExpr(on(callExpr()))
3681/// matches `(g()).m()`.
3682///
3683/// FIXME: Overload to allow directly matching types?
3684AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3685 InnerMatcher) {
3686 const Expr *ExprNode = Node.getImplicitObjectArgument()
3687 ->IgnoreParenImpCasts();
3688 return (ExprNode != nullptr &&
3689 InnerMatcher.matches(*ExprNode, Finder, Builder));
3690}
3691
3692
3693/// Matches on the receiver of an ObjectiveC Message expression.
3694///
3695/// Example
3696/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3697/// matches the [webView ...] message invocation.
3698/// \code
3699/// NSString *webViewJavaScript = ...
3700/// UIWebView *webView = ...
3701/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3702/// \endcode
3703AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3704 InnerMatcher) {
3705 const QualType TypeDecl = Node.getReceiverType();
3706 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3707}
3708
3709/// Returns true when the Objective-C method declaration is a class method.
3710///
3711/// Example
3712/// matcher = objcMethodDecl(isClassMethod())
3713/// matches
3714/// \code
3715/// @interface I + (void)foo; @end
3716/// \endcode
3717/// but not
3718/// \code
3719/// @interface I - (void)bar; @end
3720/// \endcode
3722 return Node.isClassMethod();
3723}
3724
3725/// Returns true when the Objective-C method declaration is an instance method.
3726///
3727/// Example
3728/// matcher = objcMethodDecl(isInstanceMethod())
3729/// matches
3730/// \code
3731/// @interface I - (void)bar; @end
3732/// \endcode
3733/// but not
3734/// \code
3735/// @interface I + (void)foo; @end
3736/// \endcode
3738 return Node.isInstanceMethod();
3739}
3740
3741/// Returns true when the Objective-C message is sent to a class.
3742///
3743/// Example
3744/// matcher = objcMessageExpr(isClassMessage())
3745/// matches
3746/// \code
3747/// [NSString stringWithFormat:@"format"];
3748/// \endcode
3749/// but not
3750/// \code
3751/// NSString *x = @"hello";
3752/// [x containsString:@"h"];
3753/// \endcode
3755 return Node.isClassMessage();
3756}
3757
3758/// Returns true when the Objective-C message is sent to an instance.
3759///
3760/// Example
3761/// matcher = objcMessageExpr(isInstanceMessage())
3762/// matches
3763/// \code
3764/// NSString *x = @"hello";
3765/// [x containsString:@"h"];
3766/// \endcode
3767/// but not
3768/// \code
3769/// [NSString stringWithFormat:@"format"];
3770/// \endcode
3771AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3772 return Node.isInstanceMessage();
3773}
3774
3775/// Matches if the Objective-C message is sent to an instance,
3776/// and the inner matcher matches on that instance.
3777///
3778/// For example the method call in
3779/// \code
3780/// NSString *x = @"hello";
3781/// [x containsString:@"h"];
3782/// \endcode
3783/// is matched by
3784/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3785AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3786 InnerMatcher) {
3787 const Expr *ReceiverNode = Node.getInstanceReceiver();
3788 return (ReceiverNode != nullptr &&
3789 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3790 Builder));
3791}
3792
3793/// Matches when BaseName == Selector.getAsString()
3794///
3795/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3796/// matches the outer message expr in the code below, but NOT the message
3797/// invocation for self.bodyView.
3798/// \code
3799/// [self.bodyView loadHTMLString:html baseURL:NULL];
3800/// \endcode
3801AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3802 Selector Sel = Node.getSelector();
3803 return BaseName == Sel.getAsString();
3804}
3805
3806/// Matches when at least one of the supplied string equals to the
3807/// Selector.getAsString()
3808///
3809/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3810/// matches both of the expressions below:
3811/// \code
3812/// [myObj methodA:argA];
3813/// [myObj methodB:argB];
3814/// \endcode
3815extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3816 StringRef,
3819
3820/// Matches ObjC selectors whose name contains
3821/// a substring matched by the given RegExp.
3822/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3823/// matches the outer message expr in the code below, but NOT the message
3824/// invocation for self.bodyView.
3825/// \code
3826/// [self.bodyView loadHTMLString:html baseURL:NULL];
3827/// \endcode
3828AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3829 std::string SelectorString = Node.getSelector().getAsString();
3830 return RegExp->match(SelectorString);
3831}
3832
3833/// Matches when the selector is the empty selector
3834///
3835/// Matches only when the selector of the objCMessageExpr is NULL. This may
3836/// represent an error condition in the tree!
3837AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3838 return Node.getSelector().isNull();
3839}
3840
3841/// Matches when the selector is a Unary Selector
3842///
3843/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3844/// matches self.bodyView in the code below, but NOT the outer message
3845/// invocation of "loadHTMLString:baseURL:".
3846/// \code
3847/// [self.bodyView loadHTMLString:html baseURL:NULL];
3848/// \endcode
3849AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3850 return Node.getSelector().isUnarySelector();
3851}
3852
3853/// Matches when the selector is a keyword selector
3854///
3855/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3856/// message expression in
3857///
3858/// \code
3859/// UIWebView *webView = ...;
3860/// CGRect bodyFrame = webView.frame;
3861/// bodyFrame.size.height = self.bodyContentHeight;
3862/// webView.frame = bodyFrame;
3863/// // ^---- matches here
3864/// \endcode
3865AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3866 return Node.getSelector().isKeywordSelector();
3867}
3868
3869/// Matches when the selector has the specified number of arguments
3870///
3871/// matcher = objCMessageExpr(numSelectorArgs(0));
3872/// matches self.bodyView in the code below
3873///
3874/// matcher = objCMessageExpr(numSelectorArgs(2));
3875/// matches the invocation of "loadHTMLString:baseURL:" but not that
3876/// of self.bodyView
3877/// \code
3878/// [self.bodyView loadHTMLString:html baseURL:NULL];
3879/// \endcode
3880AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3881 return Node.getSelector().getNumArgs() == N;
3882}
3883
3884/// Matches if the call expression's callee expression matches.
3885///
3886/// Given
3887/// \code
3888/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3889/// void f() { f(); }
3890/// \endcode
3891/// callExpr(callee(expr()))
3892/// matches this->x(), x(), y.x(), f()
3893/// with callee(...)
3894/// matching this->x, x, y.x, f respectively
3895///
3896/// Note: Callee cannot take the more general internal::Matcher<Expr>
3897/// because this introduces ambiguous overloads with calls to Callee taking a
3898/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3899/// implemented in terms of implicit casts.
3900AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3901 InnerMatcher) {
3902 const Expr *ExprNode = Node.getCallee();
3903 return (ExprNode != nullptr &&
3904 InnerMatcher.matches(*ExprNode, Finder, Builder));
3905}
3906
3907/// Matches 1) if the call expression's callee's declaration matches the
3908/// given matcher; or 2) if the Obj-C message expression's callee's method
3909/// declaration matches the given matcher.
3910///
3911/// Example matches y.x() (matcher = callExpr(callee(
3912/// cxxMethodDecl(hasName("x")))))
3913/// \code
3914/// class Y { public: void x(); };
3915/// void z() { Y y; y.x(); }
3916/// \endcode
3917///
3918/// Example 2. Matches [I foo] with
3919/// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3920///
3921/// \code
3922/// @interface I: NSObject
3923/// +(void)foo;
3924/// @end
3925/// ...
3926/// [I foo]
3927/// \endcode
3930 internal::Matcher<Decl>, InnerMatcher, 1) {
3931 if (isa<CallExpr>(&Node))
3932 return callExpr(hasDeclaration(InnerMatcher))
3933 .matches(Node, Finder, Builder);
3934 else {
3935 // The dynamic cast below is guaranteed to succeed as there are only 2
3936 // supported return types.
3937 const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
3938 const Decl *DeclNode = MsgNode->getMethodDecl();
3939 return (DeclNode != nullptr &&
3940 InnerMatcher.matches(*DeclNode, Finder, Builder));
3941 }
3942}
3943
3944/// Matches if the expression's or declaration's type matches a type
3945/// matcher.
3946///
3947/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3948/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3949/// and U (matcher = typedefDecl(hasType(asString("int")))
3950/// and friend class X (matcher = friendDecl(hasType("X"))
3951/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3952/// asString("class X")))
3953/// \code
3954/// class X {};
3955/// void y(X &x) { x; X z; }
3956/// typedef int U;
3957/// class Y { friend class X; };
3958/// class Z : public virtual X {};
3959/// \endcode
3961 hasType,
3964 internal::Matcher<QualType>, InnerMatcher, 0) {
3965 QualType QT = internal::getUnderlyingType(Node);
3966 if (!QT.isNull())
3967 return InnerMatcher.matches(QT, Finder, Builder);
3968 return false;
3969}
3970
3971/// Overloaded to match the declaration of the expression's or value
3972/// declaration's type.
3973///
3974/// In case of a value declaration (for example a variable declaration),
3975/// this resolves one layer of indirection. For example, in the value
3976/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3977/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3978/// declaration of x.
3979///
3980/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3981/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3982/// and friend class X (matcher = friendDecl(hasType("X"))
3983/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
3984/// cxxRecordDecl(hasName("X"))))
3985/// \code
3986/// class X {};
3987/// void y(X &x) { x; X z; }
3988/// class Y { friend class X; };
3989/// class Z : public virtual X {};
3990/// \endcode
3991///
3992/// Example matches class Derived
3993/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
3994/// \code
3995/// class Base {};
3996/// class Derived : Base {};
3997/// \endcode
3998///
3999/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
4000/// Matcher<CXXBaseSpecifier>
4002 hasType,
4005 internal::Matcher<Decl>, InnerMatcher, 1) {
4006 QualType QT = internal::getUnderlyingType(Node);
4007 if (!QT.isNull())
4008 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
4009 return false;
4010}
4011
4012/// Matches if the type location of a node matches the inner matcher.
4013///
4014/// Examples:
4015/// \code
4016/// int x;
4017/// \endcode
4018/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
4019/// matches int x
4020///
4021/// \code
4022/// auto x = int(3);
4023/// \endcode
4024/// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
4025/// matches int(3)
4026///
4027/// \code
4028/// struct Foo { Foo(int, int); };
4029/// auto x = Foo(1, 2);
4030/// \endcode
4031/// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
4032/// matches Foo(1, 2)
4033///
4034/// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
4035/// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
4036/// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
4037/// Matcher<CXXUnresolvedConstructExpr>,
4038/// Matcher<ClassTemplateSpecializationDecl>, Matcher<CompoundLiteralExpr>,
4039/// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
4040/// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
4041/// Matcher<TypedefNameDecl>
4043 hasTypeLoc,
4050 internal::Matcher<TypeLoc>, Inner) {
4051 TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
4052 if (source == nullptr) {
4053 // This happens for example for implicit destructors.
4054 return false;
4055 }
4056 return Inner.matches(source->getTypeLoc(), Finder, Builder);
4057}
4058
4059/// Matches if the matched type is represented by the given string.
4060///
4061/// Given
4062/// \code
4063/// class Y { public: void x(); };
4064/// void z() { Y* y; y->x(); }
4065/// \endcode
4066/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
4067/// matches y->x()
4068AST_MATCHER_P(QualType, asString, std::string, Name) {
4069 return Name == Node.getAsString();
4070}
4071
4072/// Matches if the matched type is a pointer type and the pointee type
4073/// matches the specified matcher.
4074///
4075/// Example matches y->x()
4076/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
4077/// cxxRecordDecl(hasName("Y")))))))
4078/// \code
4079/// class Y { public: void x(); };
4080/// void z() { Y *y; y->x(); }
4081/// \endcode
4083 QualType, pointsTo, internal::Matcher<QualType>,
4084 InnerMatcher) {
4085 return (!Node.isNull() && Node->isAnyPointerType() &&
4086 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4087}
4088
4089/// Overloaded to match the pointee type's declaration.
4090AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
4091 InnerMatcher, 1) {
4092 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
4093 .matches(Node, Finder, Builder);
4094}
4095
4096/// Matches if the matched type matches the unqualified desugared
4097/// type of the matched node.
4098///
4099/// For example, in:
4100/// \code
4101/// class A {};
4102/// using B = A;
4103/// \endcode
4104/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4105/// both B and A.
4106AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4107 InnerMatcher) {
4108 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4109 Builder);
4110}
4111
4112/// Matches if the matched type is a reference type and the referenced
4113/// type matches the specified matcher.
4114///
4115/// Example matches X &x and const X &y
4116/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4117/// \code
4118/// class X {
4119/// void a(X b) {
4120/// X &x = b;
4121/// const X &y = b;
4122/// }
4123/// };
4124/// \endcode
4125AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4126 InnerMatcher) {
4127 return (!Node.isNull() && Node->isReferenceType() &&
4128 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4129}
4130
4131/// Matches QualTypes whose canonical type matches InnerMatcher.
4132///
4133/// Given:
4134/// \code
4135/// typedef int &int_ref;
4136/// int a;
4137/// int_ref b = a;
4138/// \endcode
4139///
4140/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4141/// declaration of b but \c
4142/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4143AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4144 InnerMatcher) {
4145 if (Node.isNull())
4146 return false;
4147 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4148}
4149
4150/// Overloaded to match the referenced type's declaration.
4151AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4152 InnerMatcher, 1) {
4153 return references(qualType(hasDeclaration(InnerMatcher)))
4154 .matches(Node, Finder, Builder);
4155}
4156
4157/// Matches on the implicit object argument of a member call expression. Unlike
4158/// `on`, matches the argument directly without stripping away anything.
4159///
4160/// Given
4161/// \code
4162/// class Y { public: void m(); };
4163/// Y g();
4164/// class X : public Y { void g(); };
4165/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4166/// \endcode
4167/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4168/// cxxRecordDecl(hasName("Y")))))
4169/// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
4170/// cxxMemberCallExpr(on(callExpr()))
4171/// does not match `(g()).m()`, because the parens are not ignored.
4172///
4173/// FIXME: Overload to allow directly matching types?
4174AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4175 internal::Matcher<Expr>, InnerMatcher) {
4176 const Expr *ExprNode = Node.getImplicitObjectArgument();
4177 return (ExprNode != nullptr &&
4178 InnerMatcher.matches(*ExprNode, Finder, Builder));
4179}
4180
4181/// Matches if the type of the expression's implicit object argument either
4182/// matches the InnerMatcher, or is a pointer to a type that matches the
4183/// InnerMatcher.
4184///
4185/// Given
4186/// \code
4187/// class Y { public: void m(); };
4188/// class X : public Y { void g(); };
4189/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4190/// \endcode
4191/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4192/// cxxRecordDecl(hasName("Y")))))
4193/// matches `y.m()`, `p->m()` and `x.m()`.
4194/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4195/// cxxRecordDecl(hasName("X")))))
4196/// matches `x.g()`.
4198 internal::Matcher<QualType>, InnerMatcher, 0) {
4199 return onImplicitObjectArgument(
4200 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4201 .matches(Node, Finder, Builder);
4202}
4203
4204/// Overloaded to match the type's declaration.
4206 internal::Matcher<Decl>, InnerMatcher, 1) {
4207 return onImplicitObjectArgument(
4208 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4209 .matches(Node, Finder, Builder);
4210}
4211
4212/// Matches a DeclRefExpr that refers to a declaration that matches the
4213/// specified matcher.
4214///
4215/// Example matches x in if(x)
4216/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4217/// \code
4218/// bool x;
4219/// if (x) {}
4220/// \endcode
4221AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4222 InnerMatcher) {
4223 const Decl *DeclNode = Node.getDecl();
4224 return (DeclNode != nullptr &&
4225 InnerMatcher.matches(*DeclNode, Finder, Builder));
4226}
4227
4228/// Matches if a node refers to a declaration through a specific
4229/// using shadow declaration.
4230///
4231/// Examples:
4232/// \code
4233/// namespace a { int f(); }
4234/// using a::f;
4235/// int x = f();
4236/// \endcode
4237/// declRefExpr(throughUsingDecl(anything()))
4238/// matches \c f
4239///
4240/// \code
4241/// namespace a { class X{}; }
4242/// using a::X;
4243/// X x;
4244/// \endcode
4245/// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4246/// matches \c X
4247///
4248/// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4251 UsingType),
4252 internal::Matcher<UsingShadowDecl>, Inner) {
4253 const NamedDecl *FoundDecl = Node.getFoundDecl();
4254 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4255 return Inner.matches(*UsingDecl, Finder, Builder);
4256 return false;
4257}
4258
4259/// Matches an \c OverloadExpr if any of the declarations in the set of
4260/// overloads matches the given matcher.
4261///
4262/// Given
4263/// \code
4264/// template <typename T> void foo(T);
4265/// template <typename T> void bar(T);
4266/// template <typename T> void baz(T t) {
4267/// foo(t);
4268/// bar(t);
4269/// }
4270/// \endcode
4271/// unresolvedLookupExpr(hasAnyDeclaration(
4272/// functionTemplateDecl(hasName("foo"))))
4273/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4274AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4275 InnerMatcher) {
4276 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4277 Node.decls_end(), Finder,
4278 Builder) != Node.decls_end();
4279}
4280
4281/// Matches the Decl of a DeclStmt which has a single declaration.
4282///
4283/// Given
4284/// \code
4285/// int a, b;
4286/// int c;
4287/// \endcode
4288/// declStmt(hasSingleDecl(anything()))
4289/// matches 'int c;' but not 'int a, b;'.
4290AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4291 if (Node.isSingleDecl()) {
4292 const Decl *FoundDecl = Node.getSingleDecl();
4293 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4294 }
4295 return false;
4296}
4297
4298/// Matches a variable declaration that has an initializer expression
4299/// that matches the given matcher.
4300///
4301/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4302/// \code
4303/// bool y() { return true; }
4304/// bool x = y();
4305/// \endcode
4307 VarDecl, hasInitializer, internal::Matcher<Expr>,
4308 InnerMatcher) {
4309 const Expr *Initializer = Node.getAnyInitializer();
4310 return (Initializer != nullptr &&
4311 InnerMatcher.matches(*Initializer, Finder, Builder));
4312}
4313
4314/// Matches a variable serving as the implicit variable for a lambda init-
4315/// capture.
4316///
4317/// Example matches x (matcher = varDecl(isInitCapture()))
4318/// \code
4319/// auto f = [x=3]() { return x; };
4320/// \endcode
4321AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4322
4323/// Matches each lambda capture in a lambda expression.
4324///
4325/// Given
4326/// \code
4327/// int main() {
4328/// int x, y;
4329/// float z;
4330/// auto f = [=]() { return x + y + z; };
4331/// }
4332/// \endcode
4333/// lambdaExpr(forEachLambdaCapture(
4334/// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4335/// will trigger two matches, binding for 'x' and 'y' respectively.
4336AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4337 internal::Matcher<LambdaCapture>, InnerMatcher) {
4338 BoundNodesTreeBuilder Result;
4339 bool Matched = false;
4340 for (const auto &Capture : Node.captures()) {
4341 if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4342 continue;
4343 BoundNodesTreeBuilder CaptureBuilder(*Builder);
4344 if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4345 Matched = true;
4346 Result.addMatch(CaptureBuilder);
4347 }
4348 }
4349 *Builder = std::move(Result);
4350 return Matched;
4351}
4352
4353/// \brief Matches a static variable with local scope.
4354///
4355/// Example matches y (matcher = varDecl(isStaticLocal()))
4356/// \code
4357/// void f() {
4358/// int x;
4359/// static int y;
4360/// }
4361/// static int z;
4362/// \endcode
4363AST_MATCHER(VarDecl, isStaticLocal) {
4364 return Node.isStaticLocal();
4365}
4366
4367/// Matches a variable declaration that has function scope and is a
4368/// non-static local variable.
4369///
4370/// Example matches x (matcher = varDecl(hasLocalStorage())
4371/// \code
4372/// void f() {
4373/// int x;
4374/// static int y;
4375/// }
4376/// int z;
4377/// \endcode
4378AST_MATCHER(VarDecl, hasLocalStorage) {
4379 return Node.hasLocalStorage();
4380}
4381
4382/// Matches a variable declaration that does not have local storage.
4383///
4384/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4385/// \code
4386/// void f() {
4387/// int x;
4388/// static int y;
4389/// }
4390/// int z;
4391/// \endcode
4392AST_MATCHER(VarDecl, hasGlobalStorage) {
4393 return Node.hasGlobalStorage();
4394}
4395
4396/// Matches a variable declaration that has automatic storage duration.
4397///
4398/// Example matches x, but not y, z, or a.
4399/// (matcher = varDecl(hasAutomaticStorageDuration())
4400/// \code
4401/// void f() {
4402/// int x;
4403/// static int y;
4404/// thread_local int z;
4405/// }
4406/// int a;
4407/// \endcode
4408AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4409 return Node.getStorageDuration() == SD_Automatic;
4410}
4411
4412/// Matches a variable declaration that has static storage duration.
4413/// It includes the variable declared at namespace scope and those declared
4414/// with "static" and "extern" storage class specifiers.
4415///
4416/// \code
4417/// void f() {
4418/// int x;
4419/// static int y;
4420/// thread_local int z;
4421/// }
4422/// int a;
4423/// static int b;
4424/// extern int c;
4425/// varDecl(hasStaticStorageDuration())
4426/// matches the function declaration y, a, b and c.
4427/// \endcode
4428AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4429 return Node.getStorageDuration() == SD_Static;
4430}
4431
4432/// Matches a variable declaration that has thread storage duration.
4433///
4434/// Example matches z, but not x, z, or a.
4435/// (matcher = varDecl(hasThreadStorageDuration())
4436/// \code
4437/// void f() {
4438/// int x;
4439/// static int y;
4440/// thread_local int z;
4441/// }
4442/// int a;
4443/// \endcode
4444AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4445 return Node.getStorageDuration() == SD_Thread;
4446}
4447
4448/// Matches a variable declaration that is an exception variable from
4449/// a C++ catch block, or an Objective-C \@catch statement.
4450///
4451/// Example matches x (matcher = varDecl(isExceptionVariable())
4452/// \code
4453/// void f(int y) {
4454/// try {
4455/// } catch (int x) {
4456/// }
4457/// }
4458/// \endcode
4459AST_MATCHER(VarDecl, isExceptionVariable) {
4460 return Node.isExceptionVariable();
4461}
4462
4463/// Checks that a call expression or a constructor call expression has
4464/// a specific number of arguments (including absent default arguments).
4465///
4466/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4467/// \code
4468/// void f(int x, int y);
4469/// f(0, 0);
4470/// \endcode
4475 unsigned, N) {
4476 unsigned NumArgs = Node.getNumArgs();
4477 if (!Finder->isTraversalIgnoringImplicitNodes())
4478 return NumArgs == N;
4479 while (NumArgs) {
4480 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4481 break;
4482 --NumArgs;
4483 }
4484 return NumArgs == N;
4485}
4486
4487/// Checks that a call expression or a constructor call expression has at least
4488/// the specified number of arguments (including absent default arguments).
4489///
4490/// Example matches f(0, 0) and g(0, 0, 0)
4491/// (matcher = callExpr(argumentCountAtLeast(2)))
4492/// \code
4493/// void f(int x, int y);
4494/// void g(int x, int y, int z);
4495/// f(0, 0);
4496/// g(0, 0, 0);
4497/// \endcode
4498AST_POLYMORPHIC_MATCHER_P(argumentCountAtLeast,
4502 unsigned, N) {
4503 unsigned NumArgs = Node.getNumArgs();
4504 if (!Finder->isTraversalIgnoringImplicitNodes())
4505 return NumArgs >= N;
4506 while (NumArgs) {
4507 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4508 break;
4509 --NumArgs;
4510 }
4511 return NumArgs >= N;
4512}
4513
4514/// Matches the n'th argument of a call expression or a constructor
4515/// call expression.
4516///
4517/// Example matches y in x(y)
4518/// (matcher = callExpr(hasArgument(0, declRefExpr())))
4519/// \code
4520/// void x(int) { int y; x(y); }
4521/// \endcode
4526 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4527 if (N >= Node.getNumArgs())
4528 return false;
4529 const Expr *Arg = Node.getArg(N);
4530 if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4531 return false;
4532 return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4533}
4534
4535/// Matches the n'th item of an initializer list expression.
4536///
4537/// Example matches y.
4538/// (matcher = initListExpr(hasInit(0, expr())))
4539/// \code
4540/// int x{y}.
4541/// \endcode
4542AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
4543 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
4544 return N < Node.getNumInits() &&
4545 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4546}
4547
4548/// Matches declaration statements that contain a specific number of
4549/// declarations.
4550///
4551/// Example: Given
4552/// \code
4553/// int a, b;
4554/// int c;
4555/// int d = 2, e;
4556/// \endcode
4557/// declCountIs(2)
4558/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4559AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4560 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4561}
4562
4563/// Matches the n'th declaration of a declaration statement.
4564///
4565/// Note that this does not work for global declarations because the AST
4566/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4567/// DeclStmt's.
4568/// Example: Given non-global declarations
4569/// \code
4570/// int a, b = 0;
4571/// int c;
4572/// int d = 2, e;
4573/// \endcode
4574/// declStmt(containsDeclaration(
4575/// 0, varDecl(hasInitializer(anything()))))
4576/// matches only 'int d = 2, e;', and
4577/// declStmt(containsDeclaration(1, varDecl()))
4578/// \code
4579/// matches 'int a, b = 0' as well as 'int d = 2, e;'
4580/// but 'int c;' is not matched.
4581/// \endcode
4582AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4583 internal::Matcher<Decl>, InnerMatcher) {
4584 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4585 if (N >= NumDecls)
4586 return false;
4587 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4588 std::advance(Iterator, N);
4589 return InnerMatcher.matches(**Iterator, Finder, Builder);
4590}
4591
4592/// Matches a C++ catch statement that has a catch-all handler.
4593///
4594/// Given
4595/// \code
4596/// try {
4597/// // ...
4598/// } catch (int) {
4599/// // ...
4600/// } catch (...) {
4601/// // ...
4602/// }
4603/// \endcode
4604/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4606 return Node.getExceptionDecl() == nullptr;
4607}
4608
4609/// Matches a constructor initializer.
4610///
4611/// Given
4612/// \code
4613/// struct Foo {
4614/// Foo() : foo_(1) { }
4615/// int foo_;
4616/// };
4617/// \endcode
4618/// cxxRecordDecl(has(cxxConstructorDecl(
4619/// hasAnyConstructorInitializer(anything())
4620/// )))
4621/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4622AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4623 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4624 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4625 Node.init_end(), Finder, Builder);
4626 if (MatchIt == Node.init_end())
4627 return false;
4628 return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4629}
4630
4631/// Matches the field declaration of a constructor initializer.
4632///
4633/// Given
4634/// \code
4635/// struct Foo {
4636/// Foo() : foo_(1) { }
4637/// int foo_;
4638/// };
4639/// \endcode
4640/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4641/// forField(hasName("foo_"))))))
4642/// matches Foo
4643/// with forField matching foo_
4645 internal::Matcher<FieldDecl>, InnerMatcher) {
4646 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4647 return (NodeAsDecl != nullptr &&
4648 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4649}
4650
4651/// Matches the initializer expression of a constructor initializer.
4652///
4653/// Given
4654/// \code
4655/// struct Foo {
4656/// Foo() : foo_(1) { }
4657/// int foo_;
4658/// };
4659/// \endcode
4660/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4661/// withInitializer(integerLiteral(equals(1)))))))
4662/// matches Foo
4663/// with withInitializer matching (1)
4665 internal::Matcher<Expr>, InnerMatcher) {
4666 const Expr* NodeAsExpr = Node.getInit();
4667 return (NodeAsExpr != nullptr &&
4668 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4669}
4670
4671/// Matches a constructor initializer if it is explicitly written in
4672/// code (as opposed to implicitly added by the compiler).
4673///
4674/// Given
4675/// \code
4676/// struct Foo {
4677/// Foo() { }
4678/// Foo(int) : foo_("A") { }
4679/// string foo_;
4680/// };
4681/// \endcode
4682/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4683/// will match Foo(int), but not Foo()
4685 return Node.isWritten();
4686}
4687
4688/// Matches a constructor initializer if it is initializing a base, as
4689/// opposed to a member.
4690///
4691/// Given
4692/// \code
4693/// struct B {};
4694/// struct D : B {
4695/// int I;
4696/// D(int i) : I(i) {}
4697/// };
4698/// struct E : B {
4699/// E() : B() {}
4700/// };
4701/// \endcode
4702/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4703/// will match E(), but not match D(int).
4704AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4705 return Node.isBaseInitializer();
4706}
4707
4708/// Matches a constructor initializer if it is initializing a member, as
4709/// opposed to a base.
4710///
4711/// Given
4712/// \code
4713/// struct B {};
4714/// struct D : B {
4715/// int I;
4716/// D(int i) : I(i) {}
4717/// };
4718/// struct E : B {
4719/// E() : B() {}
4720/// };
4721/// \endcode
4722/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4723/// will match D(int), but not match E().
4724AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4725 return Node.isMemberInitializer();
4726}
4727
4728/// Matches any argument of a call expression or a constructor call
4729/// expression, or an ObjC-message-send expression.
4730///
4731/// Given
4732/// \code
4733/// void x(int, int, int) { int y; x(1, y, 42); }
4734/// \endcode
4735/// callExpr(hasAnyArgument(declRefExpr()))
4736/// matches x(1, y, 42)
4737/// with hasAnyArgument(...)
4738/// matching y
4739///
4740/// For ObjectiveC, given
4741/// \code
4742/// @interface I - (void) f:(int) y; @end
4743/// void foo(I *i) { [i f:12]; }
4744/// \endcode
4745/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4746/// matches [i f:12]
4751 internal::Matcher<Expr>, InnerMatcher) {
4752 for (const Expr *Arg : Node.arguments()) {
4753 if (Finder->isTraversalIgnoringImplicitNodes() &&
4754 isa<CXXDefaultArgExpr>(Arg))
4755 break;
4756 BoundNodesTreeBuilder Result(*Builder);
4757 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4758 *Builder = std::move(Result);
4759 return true;
4760 }
4761 }
4762 return false;
4763}
4764
4765/// Matches lambda captures.
4766///
4767/// Given
4768/// \code
4769/// int main() {
4770/// int x;
4771/// auto f = [x](){};
4772/// auto g = [x = 1](){};
4773/// }
4774/// \endcode
4775/// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4776/// `lambdaCapture()` matches `x` and `x=1`.
4777extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4778
4779/// Matches any capture in a lambda expression.
4780///
4781/// Given
4782/// \code
4783/// void foo() {
4784/// int t = 5;
4785/// auto f = [=](){ return t; };
4786/// }
4787/// \endcode
4788/// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4789/// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4790/// both match `[=](){ return t; }`.
4791AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4792 InnerMatcher) {
4793 for (const LambdaCapture &Capture : Node.captures()) {
4794 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4795 if (InnerMatcher.matches(Capture, Finder, &Result)) {
4796 *Builder = std::move(Result);
4797 return true;
4798 }
4799 }
4800 return false;
4801}
4802
4803/// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4804/// `VarDecl` can be a separate variable that is captured by value or
4805/// reference, or a synthesized variable if the capture has an initializer.
4806///
4807/// Given
4808/// \code
4809/// void foo() {
4810/// int x;
4811/// auto f = [x](){};
4812/// auto g = [x = 1](){};
4813/// }
4814/// \endcode
4815/// In the matcher
4816/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4817/// capturesVar(hasName("x")) matches `x` and `x = 1`.
4818AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
4819 InnerMatcher) {
4820 auto *capturedVar = Node.getCapturedVar();
4821 return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
4822}
4823
4824/// Matches a `LambdaCapture` that refers to 'this'.
4825///
4826/// Given
4827/// \code
4828/// class C {
4829/// int cc;
4830/// int f() {
4831/// auto l = [this]() { return cc; };
4832/// return l();
4833/// }
4834/// };
4835/// \endcode
4836/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
4837/// matches `[this]() { return cc; }`.
4838AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
4839
4840/// Matches a constructor call expression which uses list initialization.
4841AST_MATCHER(CXXConstructExpr, isListInitialization) {
4842 return Node.isListInitialization();
4843}
4844
4845/// Matches a constructor call expression which requires
4846/// zero initialization.
4847///
4848/// Given
4849/// \code
4850/// void foo() {
4851/// struct point { double x; double y; };
4852/// point pt[2] = { { 1.0, 2.0 } };
4853/// }
4854/// \endcode
4855/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
4856/// will match the implicit array filler for pt[1].
4857AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
4858 return Node.requiresZeroInitialization();
4859}
4860
4861/// Matches the n'th parameter of a function or an ObjC method
4862/// declaration or a block.
4863///
4864/// Given
4865/// \code
4866/// class X { void f(int x) {} };
4867/// \endcode
4868/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
4869/// matches f(int x) {}
4870/// with hasParameter(...)
4871/// matching int x
4872///
4873/// For ObjectiveC, given
4874/// \code
4875/// @interface I - (void) f:(int) y; @end
4876/// \endcode
4877//
4878/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
4879/// matches the declaration of method f with hasParameter
4880/// matching y.
4884 BlockDecl),
4885 unsigned, N, internal::Matcher<ParmVarDecl>,
4886 InnerMatcher) {
4887 return (N < Node.parameters().size()
4888 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4889}
4890
4891/// Matches all arguments and their respective ParmVarDecl.
4892///
4893/// Given
4894/// \code
4895/// void f(int i);
4896/// int y;
4897/// f(y);
4898/// \endcode
4899/// callExpr(
4900/// forEachArgumentWithParam(
4901/// declRefExpr(to(varDecl(hasName("y")))),
4902/// parmVarDecl(hasType(isInteger()))
4903/// ))
4904/// matches f(y);
4905/// with declRefExpr(...)
4906/// matching int y
4907/// and parmVarDecl(...)
4908/// matching int i
4909AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4912 internal::Matcher<Expr>, ArgMatcher,
4913 internal::Matcher<ParmVarDecl>, ParamMatcher) {
4914 BoundNodesTreeBuilder Result;
4915 // The first argument of an overloaded member operator is the implicit object
4916 // argument of the method which should not be matched against a parameter, so
4917 // we skip over it here.
4918 BoundNodesTreeBuilder Matches;
4919 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4920 .matches(Node, Finder, &Matches)
4921 ? 1
4922 : 0;
4923 int ParamIndex = 0;
4924 bool Matched = false;
4925 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
4926 BoundNodesTreeBuilder ArgMatches(*Builder);
4927 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4928 Finder, &ArgMatches)) {
4929 BoundNodesTreeBuilder ParamMatches(ArgMatches);
4931 hasParameter(ParamIndex, ParamMatcher)))),
4932 callExpr(callee(functionDecl(
4933 hasParameter(ParamIndex, ParamMatcher))))))
4934 .matches(Node, Finder, &ParamMatches)) {
4935 Result.addMatch(ParamMatches);
4936 Matched = true;
4937 }
4938 }
4939 ++ParamIndex;
4940 }
4941 *Builder = std::move(Result);
4942 return Matched;
4943}
4944
4945/// Matches all arguments and their respective types for a \c CallExpr or
4946/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
4947/// it works on calls through function pointers as well.
4948///
4949/// The difference is, that function pointers do not provide access to a
4950/// \c ParmVarDecl, but only the \c QualType for each argument.
4951///
4952/// Given
4953/// \code
4954/// void f(int i);
4955/// int y;
4956/// f(y);
4957/// void (*f_ptr)(int) = f;
4958/// f_ptr(y);
4959/// \endcode
4960/// callExpr(
4961/// forEachArgumentWithParamType(
4962/// declRefExpr(to(varDecl(hasName("y")))),
4963/// qualType(isInteger()).bind("type)
4964/// ))
4965/// matches f(y) and f_ptr(y)
4966/// with declRefExpr(...)
4967/// matching int y
4968/// and qualType(...)
4969/// matching int
4970AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
4973 internal::Matcher<Expr>, ArgMatcher,
4974 internal::Matcher<QualType>, ParamMatcher) {
4975 BoundNodesTreeBuilder Result;
4976 // The first argument of an overloaded member operator is the implicit object
4977 // argument of the method which should not be matched against a parameter, so
4978 // we skip over it here.
4979 BoundNodesTreeBuilder Matches;
4980 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4981 .matches(Node, Finder, &Matches)
4982 ? 1
4983 : 0;
4984
4985 const FunctionProtoType *FProto = nullptr;
4986
4987 if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4988 if (const auto *Value =
4989 dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4991
4992 // This does not necessarily lead to a `FunctionProtoType`,
4993 // e.g. K&R functions do not have a function prototype.
4994 if (QT->isFunctionPointerType())
4995 FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4996
4997 if (QT->isMemberFunctionPointerType()) {
4998 const auto *MP = QT->getAs<MemberPointerType>();
4999 assert(MP && "Must be member-pointer if its a memberfunctionpointer");
5000 FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
5001 assert(FProto &&
5002 "The call must have happened through a member function "
5003 "pointer");
5004 }
5005 }
5006 }
5007
5008 unsigned ParamIndex = 0;
5009 bool Matched = false;
5010 unsigned NumArgs = Node.getNumArgs();
5011 if (FProto && FProto->isVariadic())
5012 NumArgs = std::min(NumArgs, FProto->getNumParams());
5013
5014 for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
5015 BoundNodesTreeBuilder ArgMatches(*Builder);
5016 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
5017 &ArgMatches)) {
5018 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5019
5020 // This test is cheaper compared to the big matcher in the next if.
5021 // Therefore, please keep this order.
5022 if (FProto && FProto->getNumParams() > ParamIndex) {
5023 QualType ParamType = FProto->getParamType(ParamIndex);
5024 if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
5025 Result.addMatch(ParamMatches);
5026 Matched = true;
5027 continue;
5028 }
5029 }
5031 hasParameter(ParamIndex, hasType(ParamMatcher))))),
5032 callExpr(callee(functionDecl(
5033 hasParameter(ParamIndex, hasType(ParamMatcher)))))))
5034 .matches(Node, Finder, &ParamMatches)) {
5035 Result.addMatch(ParamMatches);
5036 Matched = true;
5037 continue;
5038 }
5039 }
5040 }
5041 *Builder = std::move(Result);
5042 return Matched;
5043}
5044
5045/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
5046/// list. The parameter list could be that of either a block, function, or
5047/// objc-method.
5048///
5049///
5050/// Given
5051///
5052/// \code
5053/// void f(int a, int b, int c) {
5054/// }
5055/// \endcode
5056///
5057/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
5058///
5059/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
5060AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
5061 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
5062
5063 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
5064 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5065 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
5066 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5067 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
5068 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5069
5070 return false;
5071}
5072
5073/// Matches any parameter of a function or an ObjC method declaration or a
5074/// block.
5075///
5076/// Does not match the 'this' parameter of a method.
5077///
5078/// Given
5079/// \code
5080/// class X { void f(int x, int y, int z) {} };
5081/// \endcode
5082/// cxxMethodDecl(hasAnyParameter(hasName("y")))
5083/// matches f(int x, int y, int z) {}
5084/// with hasAnyParameter(...)
5085/// matching int y
5086///
5087/// For ObjectiveC, given
5088/// \code
5089/// @interface I - (void) f:(int) y; @end
5090/// \endcode
5091//
5092/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5093/// matches the declaration of method f with hasParameter
5094/// matching y.
5095///
5096/// For blocks, given
5097/// \code
5098/// b = ^(int y) { printf("%d", y) };
5099/// \endcode
5100///
5101/// the matcher blockDecl(hasAnyParameter(hasName("y")))
5102/// matches the declaration of the block b with hasParameter
5103/// matching y.
5107 BlockDecl),
5108 internal::Matcher<ParmVarDecl>,
5109 InnerMatcher) {
5110 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5111 Node.param_end(), Finder,
5112 Builder) != Node.param_end();
5113}
5114
5115/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5116/// specific parameter count.
5117///
5118/// Given
5119/// \code
5120/// void f(int i) {}
5121/// void g(int i, int j) {}
5122/// void h(int i, int j);
5123/// void j(int i);
5124/// void k(int x, int y, int z, ...);
5125/// \endcode
5126/// functionDecl(parameterCountIs(2))
5127/// matches \c g and \c h
5128/// functionProtoType(parameterCountIs(2))
5129/// matches \c g and \c h
5130/// functionProtoType(parameterCountIs(3))
5131/// matches \c k
5135 unsigned, N) {
5136 return Node.getNumParams() == N;
5137}
5138
5139/// Matches classTemplateSpecialization, templateSpecializationType and
5140/// functionDecl nodes where the template argument matches the inner matcher.
5141/// This matcher may produce multiple matches.
5142///
5143/// Given
5144/// \code
5145/// template <typename T, unsigned N, unsigned M>
5146/// struct Matrix {};
5147///
5148/// constexpr unsigned R = 2;
5149/// Matrix<int, R * 2, R * 4> M;
5150///
5151/// template <typename T, typename U>
5152/// void f(T&& t, U&& u) {}
5153///
5154/// bool B = false;
5155/// f(R, B);
5156/// \endcode
5157/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5158/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5159/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5160/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5161/// and 'bool'
5163 forEachTemplateArgument,
5166 clang::ast_matchers::internal::Matcher<TemplateArgument>, InnerMatcher) {
5167 ArrayRef<TemplateArgument> TemplateArgs =
5168 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5169 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5170 bool Matched = false;
5171 for (const auto &Arg : TemplateArgs) {
5172 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5173 if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5174 Matched = true;
5175 Result.addMatch(ArgBuilder);
5176 }
5177 }
5178 *Builder = std::move(Result);
5179 return Matched;
5180}
5181
5182/// Matches \c FunctionDecls that have a noreturn attribute.
5183///
5184/// Given
5185/// \code
5186/// void nope();
5187/// [[noreturn]] void a();
5188/// __attribute__((noreturn)) void b();
5189/// struct c { [[noreturn]] c(); };
5190/// \endcode
5191/// functionDecl(isNoReturn())
5192/// matches all of those except
5193/// \code
5194/// void nope();
5195/// \endcode
5196AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5197
5198/// Matches the return type of a function declaration.
5199///
5200/// Given:
5201/// \code
5202/// class X { int f() { return 1; } };
5203/// \endcode
5204/// cxxMethodDecl(returns(asString("int")))
5205/// matches int f() { return 1; }
5207 internal::Matcher<QualType>, InnerMatcher) {
5208 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5209}
5210
5211/// Matches extern "C" function or variable declarations.
5212///
5213/// Given:
5214/// \code
5215/// extern "C" void f() {}
5216/// extern "C" { void g() {} }
5217/// void h() {}
5218/// extern "C" int x = 1;
5219/// extern "C" int y = 2;
5220/// int z = 3;
5221/// \endcode
5222/// functionDecl(isExternC())
5223/// matches the declaration of f and g, but not the declaration of h.
5224/// varDecl(isExternC())
5225/// matches the declaration of x and y, but not the declaration of z.
5227 VarDecl)) {
5228 return Node.isExternC();
5229}
5230
5231/// Matches variable/function declarations that have "static" storage
5232/// class specifier ("static" keyword) written in the source.
5233///
5234/// Given:
5235/// \code
5236/// static void f() {}
5237/// static int i = 0;
5238/// extern int j;
5239/// int k;
5240/// \endcode
5241/// functionDecl(isStaticStorageClass())
5242/// matches the function declaration f.
5243/// varDecl(isStaticStorageClass())
5244/// matches the variable declaration i.
5245AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5247 VarDecl)) {
5248 return Node.getStorageClass() == SC_Static;
5249}
5250
5251/// Matches deleted function declarations.
5252///
5253/// Given:
5254/// \code
5255/// void Func();
5256/// void DeletedFunc() = delete;
5257/// \endcode
5258/// functionDecl(isDeleted())
5259/// matches the declaration of DeletedFunc, but not Func.
5261 return Node.isDeleted();
5262}
5263
5264/// Matches defaulted function declarations.
5265///
5266/// Given:
5267/// \code
5268/// class A { ~A(); };
5269/// class B { ~B() = default; };
5270/// \endcode
5271/// functionDecl(isDefaulted())
5272/// matches the declaration of ~B, but not ~A.
5274 return Node.isDefaulted();
5275}
5276
5277/// Matches weak function declarations.
5278///
5279/// Given:
5280/// \code
5281/// void foo() __attribute__((__weakref__("__foo")));
5282/// void bar();
5283/// \endcode
5284/// functionDecl(isWeak())
5285/// matches the weak declaration "foo", but not "bar".
5286AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5287
5288/// Matches functions that have a dynamic exception specification.
5289///
5290/// Given:
5291/// \code
5292/// void f();
5293/// void g() noexcept;
5294/// void h() noexcept(true);
5295/// void i() noexcept(false);
5296/// void j() throw();
5297/// void k() throw(int);
5298/// void l() throw(...);
5299/// \endcode
5300/// functionDecl(hasDynamicExceptionSpec()) and
5301/// functionProtoType(hasDynamicExceptionSpec())
5302/// match the declarations of j, k, and l, but not f, g, h, or i.
5303AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5306 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5307 return FnTy->hasDynamicExceptionSpec();
5308 return false;
5309}
5310
5311/// Matches functions that have a non-throwing exception specification.
5312///
5313/// Given:
5314/// \code
5315/// void f();
5316/// void g() noexcept;
5317/// void h() throw();
5318/// void i() throw(int);
5319/// void j() noexcept(false);
5320/// \endcode
5321/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5322/// match the declarations of g, and h, but not f, i or j.
5326 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5327
5328 // If the function does not have a prototype, then it is assumed to be a
5329 // throwing function (as it would if the function did not have any exception
5330 // specification).
5331 if (!FnTy)
5332 return false;
5333
5334 // Assume the best for any unresolved exception specification.
5336 return true;
5337
5338 return FnTy->isNothrow();
5339}
5340
5341/// Matches consteval function declarations and if consteval/if ! consteval
5342/// statements.
5343///
5344/// Given:
5345/// \code
5346/// consteval int a();
5347/// void b() { if consteval {} }
5348/// void c() { if ! consteval {} }
5349/// void d() { if ! consteval {} else {} }
5350/// \endcode
5351/// functionDecl(isConsteval())
5352/// matches the declaration of "int a()".
5353/// ifStmt(isConsteval())
5354/// matches the if statement in "void b()", "void c()", "void d()".
5357 return Node.isConsteval();
5358}
5359
5360/// Matches constexpr variable and function declarations,
5361/// and if constexpr.
5362///
5363/// Given:
5364/// \code
5365/// constexpr int foo = 42;
5366/// constexpr int bar();
5367/// void baz() { if constexpr(1 > 0) {} }
5368/// \endcode
5369/// varDecl(isConstexpr())
5370/// matches the declaration of foo.
5371/// functionDecl(isConstexpr())
5372/// matches the declaration of bar.
5373/// ifStmt(isConstexpr())
5374/// matches the if statement in baz.
5378 IfStmt)) {
5379 return Node.isConstexpr();
5380}
5381
5382/// Matches constinit variable declarations.
5383///
5384/// Given:
5385/// \code
5386/// constinit int foo = 42;
5387/// constinit const char* bar = "bar";
5388/// int baz = 42;
5389/// [[clang::require_constant_initialization]] int xyz = 42;
5390/// \endcode
5391/// varDecl(isConstinit())
5392/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5393AST_MATCHER(VarDecl, isConstinit) {
5394 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5395 return CIA->isConstinit();
5396 return false;
5397}
5398
5399/// Matches selection statements with initializer.
5400///
5401/// Given:
5402/// \code
5403/// void foo() {
5404/// if (int i = foobar(); i > 0) {}
5405/// switch (int i = foobar(); i) {}
5406/// for (auto& a = get_range(); auto& x : a) {}
5407/// }
5408/// void bar() {
5409/// if (foobar() > 0) {}
5410/// switch (foobar()) {}
5411/// for (auto& x : get_range()) {}
5412/// }
5413/// \endcode
5414/// ifStmt(hasInitStatement(anything()))
5415/// matches the if statement in foo but not in bar.
5416/// switchStmt(hasInitStatement(anything()))
5417/// matches the switch statement in foo but not in bar.
5418/// cxxForRangeStmt(hasInitStatement(anything()))
5419/// matches the range for statement in foo but not in bar.
5423 internal::Matcher<Stmt>, InnerMatcher) {
5424 const Stmt *Init = Node.getInit();
5425 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5426}
5427
5428/// Matches the condition expression of an if statement, for loop,
5429/// switch statement or conditional operator.
5430///
5431/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5432/// \code
5433/// if (true) {}
5434/// \endcode
5436 hasCondition,
5439 internal::Matcher<Expr>, InnerMatcher) {
5440 const Expr *const Condition = Node.getCond();
5441 return (Condition != nullptr &&
5442 InnerMatcher.matches(*Condition, Finder, Builder));
5443}
5444
5445/// Matches the then-statement of an if statement.
5446///
5447/// Examples matches the if statement
5448/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5449/// \code
5450/// if (false) true; else false;
5451/// \endcode
5452AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5453 const Stmt *const Then = Node.getThen();
5454 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5455}
5456
5457/// Matches the else-statement of an if statement.
5458///
5459/// Examples matches the if statement
5460/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5461/// \code
5462/// if (false) false; else true;
5463/// \endcode
5464AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5465 const Stmt *const Else = Node.getElse();
5466 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5467}
5468
5469/// Matches if a node equals a previously bound node.
5470///
5471/// Matches a node if it equals the node previously bound to \p ID.
5472///
5473/// Given
5474/// \code
5475/// class X { int a; int b; };
5476/// \endcode
5477/// cxxRecordDecl(
5478/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5479/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5480/// matches the class \c X, as \c a and \c b have the same type.
5481///
5482/// Note that when multiple matches are involved via \c forEach* matchers,
5483/// \c equalsBoundNodes acts as a filter.
5484/// For example:
5485/// compoundStmt(
5486/// forEachDescendant(varDecl().bind("d")),
5487/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5488/// will trigger a match for each combination of variable declaration
5489/// and reference to that variable declaration within a compound statement.
5492 QualType),
5493 std::string, ID) {
5494 // FIXME: Figure out whether it makes sense to allow this
5495 // on any other node types.
5496 // For *Loc it probably does not make sense, as those seem
5497 // unique. For NestedNameSepcifier it might make sense, as
5498 // those also have pointer identity, but I'm not sure whether
5499 // they're ever reused.
5500 internal::NotEqualsBoundNodePredicate Predicate;
5501 Predicate.ID = ID;
5502 Predicate.Node = DynTypedNode::create(Node);
5503 return Builder->removeBindings(Predicate);
5504}
5505
5506/// Matches the condition variable statement in an if statement.
5507///
5508/// Given
5509/// \code
5510/// if (A* a = GetAPointer()) {}
5511/// \endcode
5512/// hasConditionVariableStatement(...)
5513/// matches 'A* a = GetAPointer()'.
5514AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5515 internal::Matcher<DeclStmt>, InnerMatcher) {
5516 const DeclStmt* const DeclarationStatement =
5517 Node.getConditionVariableDeclStmt();
5518 return DeclarationStatement != nullptr &&
5519 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5520}
5521
5522/// Matches the index expression of an array subscript expression.
5523///
5524/// Given
5525/// \code
5526/// int i[5];
5527/// void f() { i[1] = 42; }
5528/// \endcode
5529/// arraySubscriptExpression(hasIndex(integerLiteral()))
5530/// matches \c i[1] with the \c integerLiteral() matching \c 1
5532 internal::Matcher<Expr>, InnerMatcher) {
5533 if (const Expr* Expression = Node.getIdx())
5534 return InnerMatcher.matches(*Expression, Finder, Builder);
5535 return false;
5536}
5537
5538/// Matches the base expression of an array subscript expression.
5539///
5540/// Given
5541/// \code
5542/// int i[5];
5543/// void f() { i[1] = 42; }
5544/// \endcode
5545/// arraySubscriptExpression(hasBase(implicitCastExpr(
5546/// hasSourceExpression(declRefExpr()))))
5547/// matches \c i[1] with the \c declRefExpr() matching \c i
5549 internal::Matcher<Expr>, InnerMatcher) {
5550 if (const Expr* Expression = Node.getBase())
5551 return InnerMatcher.matches(*Expression, Finder, Builder);
5552 return false;
5553}
5554
5555/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5556/// definition that has a given body. Note that in case of functions or
5557/// coroutines this matcher only matches the definition itself and not the
5558/// other declarations of the same function or coroutine.
5559///
5560/// Given
5561/// \code
5562/// for (;;) {}
5563/// \endcode
5564/// forStmt(hasBody(compoundStmt()))
5565/// matches 'for (;;) {}'
5566/// with compoundStmt()
5567/// matching '{}'
5568///
5569/// Given
5570/// \code
5571/// void f();
5572/// void f() {}
5573/// \endcode
5574/// functionDecl(hasBody(compoundStmt()))
5575/// matches 'void f() {}'
5576/// with compoundStmt()
5577/// matching '{}'
5578/// but does not match 'void f();'
5580 hasBody,
5583 internal::Matcher<Stmt>, InnerMatcher) {
5584 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5585 return false;
5586 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5587 return (Statement != nullptr &&
5588 InnerMatcher.matches(*Statement, Finder, Builder));
5589}
5590
5591/// Matches a function declaration that has a given body present in the AST.
5592/// Note that this matcher matches all the declarations of a function whose
5593/// body is present in the AST.
5594///
5595/// Given
5596/// \code
5597/// void f();
5598/// void f() {}
5599/// void g();
5600/// \endcode
5601/// functionDecl(hasAnyBody(compoundStmt()))
5602/// matches both 'void f();'
5603/// and 'void f() {}'
5604/// with compoundStmt()
5605/// matching '{}'
5606/// but does not match 'void g();'
5608 internal::Matcher<Stmt>, InnerMatcher) {
5609 const Stmt *const Statement = Node.getBody();
5610 return (Statement != nullptr &&
5611 InnerMatcher.matches(*Statement, Finder, Builder));
5612}
5613
5614
5615/// Matches compound statements where at least one substatement matches
5616/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5617///
5618/// Given
5619/// \code
5620/// { {}; 1+2; }
5621/// \endcode
5622/// hasAnySubstatement(compoundStmt())
5623/// matches '{ {}; 1+2; }'
5624/// with compoundStmt()
5625/// matching '{}'
5626AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5628 StmtExpr),
5629 internal::Matcher<Stmt>, InnerMatcher) {
5630 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5631 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5632 CS->body_end(), Finder,
5633 Builder) != CS->body_end();
5634}
5635
5636/// Checks that a compound statement contains a specific number of
5637/// child statements.
5638///
5639/// Example: Given
5640/// \code
5641/// { for (;;) {} }
5642/// \endcode
5643/// compoundStmt(statementCountIs(0)))
5644/// matches '{}'
5645/// but does not match the outer compound statement.
5646AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5647 return Node.size() == N;
5648}
5649
5650/// Matches literals that are equal to the given value of type ValueT.
5651///
5652/// Given
5653/// \code
5654/// f('\0', false, 3.14, 42);
5655/// \endcode
5656/// characterLiteral(equals(0))
5657/// matches '\0'
5658/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5659/// match false
5660/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5661/// match 3.14
5662/// integerLiteral(equals(42))
5663/// matches 42
5664///
5665/// Note that you cannot directly match a negative numeric literal because the
5666/// minus sign is not part of the literal: It is a unary operator whose operand
5667/// is the positive numeric literal. Instead, you must use a unaryOperator()
5668/// matcher to match the minus sign:
5669///
5670/// unaryOperator(hasOperatorName("-"),
5671/// hasUnaryOperand(integerLiteral(equals(13))))
5672///
5673/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5674/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5675template <typename ValueT>
5676internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5677 void(internal::AllNodeBaseTypes), ValueT>
5678equals(const ValueT &Value) {
5679 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5680 void(internal::AllNodeBaseTypes), ValueT>(
5681 Value);
5682}
5683
5688 bool, Value, 0) {
5689 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5690 .matchesNode(Node);
5691}
5692
5697 unsigned, Value, 1) {
5698 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5699 .matchesNode(Node);
5700}
5701
5707 double, Value, 2) {
5708 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5709 .matchesNode(Node);
5710}
5711
5712/// Matches the operator Name of operator expressions (binary or
5713/// unary).
5714///
5715/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5716/// \code
5717/// !(a || b)
5718/// \endcode
5720 hasOperatorName,
5723 std::string, Name) {
5724 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5725 return *OpName == Name;
5726 return false;
5727}
5728
5729/// Matches operator expressions (binary or unary) that have any of the
5730/// specified names.
5731///
5732/// hasAnyOperatorName("+", "-")
5733/// Is equivalent to
5734/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5735extern const internal::VariadicFunction<
5736 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5740 std::vector<std::string>>,
5743
5744/// Matches all kinds of assignment operators.
5745///
5746/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5747/// \code
5748/// if (a == b)
5749/// a += b;
5750/// \endcode
5751///
5752/// Example 2: matches s1 = s2
5753/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5754/// \code
5755/// struct S { S& operator=(const S&); };
5756/// void x() { S s1, s2; s1 = s2; }
5757/// \endcode
5759 isAssignmentOperator,
5762 return Node.isAssignmentOp();
5763}
5764
5765/// Matches comparison operators.
5766///
5767/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5768/// \code
5769/// if (a == b)
5770/// a += b;
5771/// \endcode
5772///
5773/// Example 2: matches s1 < s2
5774/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5775/// \code
5776/// struct S { bool operator<(const S& other); };
5777/// void x(S s1, S s2) { bool b1 = s1 < s2; }
5778/// \endcode
5780 isComparisonOperator,
5783 return Node.isComparisonOp();
5784}
5785
5786/// Matches the left hand side of binary operator expressions.
5787///
5788/// Example matches a (matcher = binaryOperator(hasLHS()))
5789/// \code
5790/// a || b
5791/// \endcode
5796 internal::Matcher<Expr>, InnerMatcher) {
5797 const Expr *LeftHandSide = internal::getLHS(Node);
5798 return (LeftHandSide != nullptr &&
5799 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
5800}
5801
5802/// Matches the right hand side of binary operator expressions.
5803///
5804/// Example matches b (matcher = binaryOperator(hasRHS()))
5805/// \code
5806/// a || b
5807/// \endcode
5812 internal::Matcher<Expr>, InnerMatcher) {
5813 const Expr *RightHandSide = internal::getRHS(Node);
5814 return (RightHandSide != nullptr &&
5815 InnerMatcher.matches(*RightHandSide, Finder, Builder));
5816}
5817
5818/// Matches if either the left hand side or the right hand side of a
5819/// binary operator matches.
5821 hasEitherOperand,
5824 internal::Matcher<Expr>, InnerMatcher) {
5825 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5826 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
5827 .matches(Node, Finder, Builder);
5828}
5829
5830/// Matches if both matchers match with opposite sides of the binary operator.
5831///
5832/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
5833/// integerLiteral(equals(2)))
5834/// \code
5835/// 1 + 2 // Match
5836/// 2 + 1 // Match
5837/// 1 + 1 // No match
5838/// 2 + 2 // No match
5839/// \endcode
5841 hasOperands,
5844 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
5845 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
5846 anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
5847 allOf(hasLHS(Matcher2), hasRHS(Matcher1))))
5848 .matches(Node, Finder, Builder);
5849}
5850
5851/// Matches if the operand of a unary operator matches.
5852///
5853/// Example matches true (matcher = hasUnaryOperand(
5854/// cxxBoolLiteral(equals(true))))
5855/// \code
5856/// !true
5857/// \endcode
5861 internal::Matcher<Expr>, InnerMatcher) {
5862 const Expr *const Operand = internal::getSubExpr(Node);
5863 return (Operand != nullptr &&
5864 InnerMatcher.matches(*Operand, Finder, Builder));
5865}
5866
5867/// Matches if the cast's source expression
5868/// or opaque value's source expression matches the given matcher.
5869///
5870/// Example 1: matches "a string"
5871/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
5872/// \code
5873/// class URL { URL(string); };
5874/// URL url = "a string";
5875/// \endcode
5876///
5877/// Example 2: matches 'b' (matcher =
5878/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
5879/// \code
5880/// int a = b ?: 1;
5881/// \endcode
5882AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
5885 internal::Matcher<Expr>, InnerMatcher) {
5886 const Expr *const SubExpression =
5887 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
5888 return (SubExpression != nullptr &&
5889 InnerMatcher.matches(*SubExpression, Finder, Builder));
5890}
5891
5892/// Matches casts that has a given cast kind.
5893///
5894/// Example: matches the implicit cast around \c 0
5895/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
5896/// \code
5897/// int *p = 0;
5898/// \endcode
5899///
5900/// If the matcher is use from clang-query, CastKind parameter
5901/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
5902AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
5903 return Node.getCastKind() == Kind;
5904}
5905
5906/// Matches casts whose destination type matches a given matcher.
5907///
5908/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
5909/// actual casts "explicit" casts.)
5911 internal::Matcher<QualType>, InnerMatcher) {
5912 const QualType NodeType = Node.getTypeAsWritten();
5913 return InnerMatcher.matches(NodeType, Finder, Builder);
5914}
5915
5916/// Matches implicit casts whose destination type matches a given
5917/// matcher.
5918AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
5919 internal::Matcher<QualType>, InnerMatcher) {
5920 return InnerMatcher.matches(Node.getType(), Finder, Builder);
5921}
5922
5923/// Matches TagDecl object that are spelled with "struct."
5924///
5925/// Example matches S, but not C, U or E.
5926/// \code
5927/// struct S {};
5928/// class C {};
5929/// union U {};
5930/// enum E {};
5931/// \endcode
5933 return Node.isStruct();
5934}
5935
5936/// Matches TagDecl object that are spelled with "union."
5937///
5938/// Example matches U, but not C, S or E.
5939/// \code
5940/// struct S {};
5941/// class C {};
5942/// union U {};
5943/// enum E {};
5944/// \endcode
5946 return Node.isUnion();
5947}
5948
5949/// Matches TagDecl object that are spelled with "class."
5950///
5951/// Example matches C, but not S, U or E.
5952/// \code
5953/// struct S {};
5954/// class C {};
5955/// union U {};
5956/// enum E {};
5957/// \endcode
5959 return Node.isClass();
5960}
5961
5962/// Matches TagDecl object that are spelled with "enum."
5963///
5964/// Example matches E, but not C, S or U.
5965/// \code
5966/// struct S {};
5967/// class C {};
5968/// union U {};
5969/// enum E {};
5970/// \endcode
5972 return Node.isEnum();
5973}
5974
5975/// Matches the true branch expression of a conditional operator.
5976///
5977/// Example 1 (conditional ternary operator): matches a
5978/// \code
5979/// condition ? a : b
5980/// \endcode
5981///
5982/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
5983/// \code
5984/// condition ?: b
5985/// \endcode
5987 internal::Matcher<Expr>, InnerMatcher) {
5988 const Expr *Expression = Node.getTrueExpr();
5989 return (Expression != nullptr &&
5990 InnerMatcher.matches(*Expression, Finder, Builder));
5991}
5992
5993/// Matches the false branch expression of a conditional operator
5994/// (binary or ternary).
5995///
5996/// Example matches b
5997/// \code
5998/// condition ? a : b
5999/// condition ?: b
6000/// \endcode
6002 internal::Matcher<Expr>, InnerMatcher) {
6003 const Expr *Expression = Node.getFalseExpr();
6004 return (Expression != nullptr &&
6005 InnerMatcher.matches(*Expression, Finder, Builder));
6006}
6007
6008/// Matches if a declaration has a body attached.
6009///
6010/// Example matches A, va, fa
6011/// \code
6012/// class A {};
6013/// class B; // Doesn't match, as it has no body.
6014/// int va;
6015/// extern int vb; // Doesn't match, as it doesn't define the variable.
6016/// void fa() {}
6017/// void fb(); // Doesn't match, as it has no body.
6018/// @interface X
6019/// - (void)ma; // Doesn't match, interface is declaration.
6020/// @end
6021/// @implementation X
6022/// - (void)ma {}
6023/// @end
6024/// \endcode
6025///
6026/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
6027/// Matcher<ObjCMethodDecl>