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