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 if a node equals a previously bound node.
5757///
5758/// Matches a node if it equals the node previously bound to \p ID.
5759///
5760/// Given
5761/// \code
5762/// class X { int a; int b; };
5763/// \endcode
5764/// cxxRecordDecl(
5765/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5766/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5767/// matches the class \c X, as \c a and \c b have the same type.
5768///
5769/// Note that when multiple matches are involved via \c forEach* matchers,
5770/// \c equalsBoundNodes acts as a filter.
5771/// For example:
5772/// compoundStmt(
5773/// forEachDescendant(varDecl().bind("d")),
5774/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5775/// will trigger a match for each combination of variable declaration
5776/// and reference to that variable declaration within a compound statement.
5777AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
5779 QualType),
5780 std::string, ID) {
5781 // FIXME: Figure out whether it makes sense to allow this
5782 // on any other node types.
5783 // For *Loc it probably does not make sense, as those seem
5784 // unique. For NestedNameSpecifier it might make sense, as
5785 // those also have pointer identity, but I'm not sure whether
5786 // they're ever reused.
5787 internal::NotEqualsBoundNodePredicate Predicate;
5788 Predicate.ID = ID;
5789 Predicate.Node = DynTypedNode::create(Node);
5790 return Builder->removeBindings(Predicate);
5791}
5792
5793/// Matches a declaration if it declares the same entity as the node previously
5794/// bound to \p ID.
5795AST_MATCHER_P(Decl, declaresSameEntityAsBoundNode, std::string, ID) {
5796 return Builder->removeBindings([&](const internal::BoundNodesMap &Nodes) {
5797 return !clang::declaresSameEntity(&Node, Nodes.getNodeAs<Decl>(ID));
5798 });
5799}
5800
5801/// Matches the condition variable statement in an if statement, for loop,
5802/// while loop or switch statement.
5803///
5804/// Given
5805/// \code
5806/// if (A* a = GetAPointer()) {}
5807/// for (; A* a = GetAPointer(); ) {}
5808/// \endcode
5809/// hasConditionVariableStatement(...)
5810/// matches both 'A* a = GetAPointer()'.
5811AST_POLYMORPHIC_MATCHER_P(hasConditionVariableStatement,
5812 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt,
5813 WhileStmt,
5814 SwitchStmt),
5815 internal::Matcher<DeclStmt>, InnerMatcher) {
5816 const DeclStmt* const DeclarationStatement =
5817 Node.getConditionVariableDeclStmt();
5818 return DeclarationStatement != nullptr &&
5819 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5820}
5821
5822/// Matches the index expression of an array subscript expression.
5823///
5824/// Given
5825/// \code
5826/// int i[5];
5827/// void f() { i[1] = 42; }
5828/// \endcode
5829/// arraySubscriptExpression(hasIndex(integerLiteral()))
5830/// matches \c i[1] with the \c integerLiteral() matching \c 1
5831AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
5832 internal::Matcher<Expr>, InnerMatcher) {
5833 if (const Expr* Expression = Node.getIdx())
5834 return InnerMatcher.matches(*Expression, Finder, Builder);
5835 return false;
5836}
5837
5838/// Matches the base expression of an array subscript expression.
5839///
5840/// Given
5841/// \code
5842/// int i[5];
5843/// void f() { i[1] = 42; }
5844/// \endcode
5845/// arraySubscriptExpression(hasBase(implicitCastExpr(
5846/// hasSourceExpression(declRefExpr()))))
5847/// matches \c i[1] with the \c declRefExpr() matching \c i
5848AST_MATCHER_P(ArraySubscriptExpr, hasBase,
5849 internal::Matcher<Expr>, InnerMatcher) {
5850 if (const Expr* Expression = Node.getBase())
5851 return InnerMatcher.matches(*Expression, Finder, Builder);
5852 return false;
5853}
5854
5855/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5856/// definition that has a given body. Note that in case of functions or
5857/// coroutines this matcher only matches the definition itself and not the
5858/// other declarations of the same function or coroutine.
5859///
5860/// Given
5861/// \code
5862/// for (;;) {}
5863/// \endcode
5864/// forStmt(hasBody(compoundStmt()))
5865/// matches 'for (;;) {}'
5866/// with compoundStmt()
5867/// matching '{}'
5868///
5869/// Given
5870/// \code
5871/// void f();
5872/// void f() {}
5873/// \endcode
5874/// functionDecl(hasBody(compoundStmt()))
5875/// matches 'void f() {}'
5876/// with compoundStmt()
5877/// matching '{}'
5878/// but does not match 'void f();'
5880 hasBody,
5881 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt, WhileStmt, CXXForRangeStmt,
5882 FunctionDecl, CoroutineBodyStmt),
5883 internal::Matcher<Stmt>, InnerMatcher) {
5884 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5885 return false;
5886 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5887 return (Statement != nullptr &&
5888 InnerMatcher.matches(*Statement, Finder, Builder));
5889}
5890
5891/// Matches a function declaration that has a given body present in the AST.
5892/// Note that this matcher matches all the declarations of a function whose
5893/// body is present in the AST.
5894///
5895/// Given
5896/// \code
5897/// void f();
5898/// void f() {}
5899/// void g();
5900/// \endcode
5901/// functionDecl(hasAnyBody(compoundStmt()))
5902/// matches both 'void f();'
5903/// and 'void f() {}'
5904/// with compoundStmt()
5905/// matching '{}'
5906/// but does not match 'void g();'
5907AST_MATCHER_P(FunctionDecl, hasAnyBody,
5908 internal::Matcher<Stmt>, InnerMatcher) {
5909 const Stmt *const Statement = Node.getBody();
5910 return (Statement != nullptr &&
5911 InnerMatcher.matches(*Statement, Finder, Builder));
5912}
5913
5914
5915/// Matches compound statements where at least one substatement matches
5916/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5917///
5918/// Given
5919/// \code
5920/// { {}; 1+2; }
5921/// \endcode
5922/// hasAnySubstatement(compoundStmt())
5923/// matches '{ {}; 1+2; }'
5924/// with compoundStmt()
5925/// matching '{}'
5926AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5928 StmtExpr),
5929 internal::Matcher<Stmt>, InnerMatcher) {
5930 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5931 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5932 CS->body_end(), Finder,
5933 Builder) != CS->body_end();
5934}
5935
5936/// Checks that a compound statement contains a specific number of
5937/// child statements.
5938///
5939/// Example: Given
5940/// \code
5941/// { for (;;) {} }
5942/// \endcode
5943/// compoundStmt(statementCountIs(0)))
5944/// matches '{}'
5945/// but does not match the outer compound statement.
5946AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5947 return Node.size() == N;
5948}
5949
5950/// Matches literals that are equal to the given value of type ValueT.
5951///
5952/// Given
5953/// \code
5954/// f('\0', false, 3.14, 42);
5955/// \endcode
5956/// characterLiteral(equals(0))
5957/// matches '\0'
5958/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5959/// match false
5960/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5961/// match 3.14
5962/// integerLiteral(equals(42))
5963/// matches 42
5964///
5965/// Note that you cannot directly match a negative numeric literal because the
5966/// minus sign is not part of the literal: It is a unary operator whose operand
5967/// is the positive numeric literal. Instead, you must use a unaryOperator()
5968/// matcher to match the minus sign:
5969///
5970/// unaryOperator(hasOperatorName("-"),
5971/// hasUnaryOperand(integerLiteral(equals(13))))
5972///
5973/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5974/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5975template <typename ValueT>
5976internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5977 void(internal::AllNodeBaseTypes), ValueT>
5978equals(const ValueT &Value) {
5979 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5980 void(internal::AllNodeBaseTypes), ValueT>(
5981 Value);
5982}
5983
5985 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5986 CXXBoolLiteralExpr,
5987 IntegerLiteral),
5988 bool, Value, 0) {
5989 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5990 .matchesNode(Node);
5991}
5992
5994 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
5995 CXXBoolLiteralExpr,
5996 IntegerLiteral),
5997 unsigned, Value, 1) {
5998 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5999 .matchesNode(Node);
6000}
6001
6003 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
6004 CXXBoolLiteralExpr,
6005 FloatingLiteral,
6006 IntegerLiteral),
6007 double, Value, 2) {
6008 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
6009 .matchesNode(Node);
6010}
6011
6012/// Matches the operator Name of operator expressions and fold expressions
6013/// (binary or unary).
6014///
6015/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
6016/// \code
6017/// !(a || b)
6018/// \endcode
6019///
6020/// Example matches `(0 + ... + args)`
6021/// (matcher = cxxFoldExpr(hasOperatorName("+")))
6022/// \code
6023/// template <typename... Args>
6024/// auto sum(Args... args) {
6025/// return (0 + ... + args);
6026/// }
6027/// \endcode
6029 hasOperatorName,
6030 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6031 CXXRewrittenBinaryOperator, CXXFoldExpr,
6032 UnaryOperator),
6033 std::string, Name) {
6034 if (std::optional<StringRef> OpName = internal::getOpName(Node))
6035 return *OpName == Name;
6036 return false;
6037}
6038
6039/// Matches operator expressions (binary or unary) that have any of the
6040/// specified names.
6041///
6042/// hasAnyOperatorName("+", "-")
6043/// Is equivalent to
6044/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
6045extern const internal::VariadicFunction<
6046 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
6048 BinaryOperator, CXXOperatorCallExpr,
6049 CXXRewrittenBinaryOperator, UnaryOperator),
6050 std::vector<std::string>>,
6053
6054/// Matches all kinds of assignment operators.
6055///
6056/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
6057/// \code
6058/// if (a == b)
6059/// a += b;
6060/// \endcode
6061///
6062/// Example 2: matches s1 = s2
6063/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
6064/// \code
6065/// struct S { S& operator=(const S&); };
6066/// void x() { S s1, s2; s1 = s2; }
6067/// \endcode
6069 isAssignmentOperator,
6070 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6071 CXXRewrittenBinaryOperator)) {
6072 return Node.isAssignmentOp();
6073}
6074
6075/// Matches comparison operators.
6076///
6077/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
6078/// \code
6079/// if (a == b)
6080/// a += b;
6081/// \endcode
6082///
6083/// Example 2: matches s1 < s2
6084/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
6085/// \code
6086/// struct S { bool operator<(const S& other); };
6087/// void x(S s1, S s2) { bool b1 = s1 < s2; }
6088/// \endcode
6090 isComparisonOperator,
6091 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6092 CXXRewrittenBinaryOperator)) {
6093 return Node.isComparisonOp();
6094}
6095
6096/// Matches the left hand side of binary operator expressions.
6097///
6098/// Example matches a (matcher = binaryOperator(hasLHS()))
6099/// \code
6100/// a || b
6101/// \endcode
6103 hasLHS,
6104 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6105 CXXRewrittenBinaryOperator,
6106 ArraySubscriptExpr, CXXFoldExpr),
6107 internal::Matcher<Expr>, InnerMatcher) {
6108 const Expr *LeftHandSide = internal::getLHS(Node);
6109 return (LeftHandSide != nullptr &&
6110 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
6111}
6112
6113/// Matches the right hand side of binary operator expressions.
6114///
6115/// Example matches b (matcher = binaryOperator(hasRHS()))
6116/// \code
6117/// a || b
6118/// \endcode
6120 hasRHS,
6121 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6122 CXXRewrittenBinaryOperator,
6123 ArraySubscriptExpr, CXXFoldExpr),
6124 internal::Matcher<Expr>, InnerMatcher) {
6125 const Expr *RightHandSide = internal::getRHS(Node);
6126 return (RightHandSide != nullptr &&
6127 InnerMatcher.matches(*RightHandSide, Finder, Builder));
6128}
6129
6130/// Matches if either the left hand side or the right hand side of a
6131/// binary operator or fold expression matches.
6133 hasEitherOperand,
6134 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6135 CXXFoldExpr, CXXRewrittenBinaryOperator),
6136 internal::Matcher<Expr>, InnerMatcher) {
6137 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6138 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
6139 .matches(Node, Finder, Builder);
6140}
6141
6142/// Matches if both matchers match with opposite sides of the binary operator
6143/// or fold expression.
6144///
6145/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
6146/// integerLiteral(equals(2)))
6147/// \code
6148/// 1 + 2 // Match
6149/// 2 + 1 // Match
6150/// 1 + 1 // No match
6151/// 2 + 2 // No match
6152/// \endcode
6154 hasOperands,
6155 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr,
6156 CXXFoldExpr, CXXRewrittenBinaryOperator),
6157 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
6158 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6159 anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
6160 allOf(hasRHS(Matcher1), hasLHS(Matcher2))))
6161 .matches(Node, Finder, Builder);
6162}
6163
6164/// Matches if the operand of a unary operator matches.
6165///
6166/// Example matches true (matcher = hasUnaryOperand(
6167/// cxxBoolLiteral(equals(true))))
6168/// \code
6169/// !true
6170/// \endcode
6171AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand,
6172 AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator,
6173 CXXOperatorCallExpr),
6174 internal::Matcher<Expr>, InnerMatcher) {
6175 const Expr *const Operand = internal::getSubExpr(Node);
6176 return (Operand != nullptr &&
6177 InnerMatcher.matches(*Operand, Finder, Builder));
6178}
6179
6180/// Matches if the cast's source expression
6181/// or opaque value's source expression matches the given matcher.
6182///
6183/// Example 1: matches "a string"
6184/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
6185/// \code
6186/// class URL { URL(string); };
6187/// URL url = "a string";
6188/// \endcode
6189///
6190/// Example 2: matches 'b' (matcher =
6191/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
6192/// \code
6193/// int a = b ?: 1;
6194/// \endcode
6195AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
6197 OpaqueValueExpr),
6198 internal::Matcher<Expr>, InnerMatcher) {
6199 const Expr *const SubExpression =
6200 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
6201 return (SubExpression != nullptr &&
6202 InnerMatcher.matches(*SubExpression, Finder, Builder));
6203}
6204
6205/// Matches casts that has a given cast kind.
6206///
6207/// Example: matches the implicit cast around \c 0
6208/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
6209/// \code
6210/// int *p = 0;
6211/// \endcode
6212///
6213/// If the matcher is use from clang-query, CastKind parameter
6214/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
6215AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
6216 return Node.getCastKind() == Kind;
6217}
6218
6219/// Matches casts whose destination type matches a given matcher.
6220///
6221/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
6222/// actual casts "explicit" casts.)
6223AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
6224 internal::Matcher<QualType>, InnerMatcher) {
6225 const QualType NodeType = Node.getTypeAsWritten();
6226 return InnerMatcher.matches(NodeType, Finder, Builder);
6227}
6228
6229/// Matches implicit casts whose destination type matches a given
6230/// matcher.
6231AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
6232 internal::Matcher<QualType>, InnerMatcher) {
6233 return InnerMatcher.matches(Node.getType(), Finder, Builder);
6234}
6235
6236/// Matches TagDecl object that are spelled with "struct."
6237///
6238/// Example matches S, but not C, U or E.
6239/// \code
6240/// struct S {};
6241/// class C {};
6242/// union U {};
6243/// enum E {};
6244/// \endcode
6245AST_MATCHER(TagDecl, isStruct) {
6246 return Node.isStruct();
6247}
6248
6249/// Matches TagDecl object that are spelled with "union."
6250///
6251/// Example matches U, but not C, S or E.
6252/// \code
6253/// struct S {};
6254/// class C {};
6255/// union U {};
6256/// enum E {};
6257/// \endcode
6258AST_MATCHER(TagDecl, isUnion) {
6259 return Node.isUnion();
6260}
6261
6262/// Matches TagDecl object that are spelled with "class."
6263///
6264/// Example matches C, but not S, U or E.
6265/// \code
6266/// struct S {};
6267/// class C {};
6268/// union U {};
6269/// enum E {};
6270/// \endcode
6271AST_MATCHER(TagDecl, isClass) {
6272 return Node.isClass();
6273}
6274
6275/// Matches TagDecl object that are spelled with "enum."
6276///
6277/// Example matches E, but not C, S or U.
6278/// \code
6279/// struct S {};
6280/// class C {};
6281/// union U {};
6282/// enum E {};
6283/// \endcode
6284AST_MATCHER(TagDecl, isEnum) {
6285 return Node.isEnum();
6286}
6287
6288/// Matches the true branch expression of a conditional operator.
6289///
6290/// Example 1 (conditional ternary operator): matches a
6291/// \code
6292/// condition ? a : b
6293/// \endcode
6294///
6295/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
6296/// \code
6297/// condition ?: b
6298/// \endcode
6299AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
6300 internal::Matcher<Expr>, InnerMatcher) {
6301 const Expr *Expression = Node.getTrueExpr();
6302 return (Expression != nullptr &&
6303 InnerMatcher.matches(*Expression, Finder, Builder));
6304}
6305
6306/// Matches the false branch expression of a conditional operator
6307/// (binary or ternary).
6308///
6309/// Example matches b
6310/// \code
6311/// condition ? a : b
6312/// condition ?: b
6313/// \endcode
6314AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
6315 internal::Matcher<Expr>, InnerMatcher) {
6316 const Expr *Expression = Node.getFalseExpr();
6317 return (Expression != nullptr &&
6318 InnerMatcher.matches(*Expression, Finder, Builder));
6319}
6320
6321/// Matches if a declaration has a body attached.
6322///
6323/// Example matches A, va, fa
6324/// \code
6325/// class A {};
6326/// class B; // Doesn't match, as it has no body.
6327/// int va;
6328/// extern int vb; // Doesn't match, as it doesn't define the variable.
6329/// void fa() {}
6330/// void fb(); // Doesn't match, as it has no body.
6331/// @interface X
6332/// - (void)ma; // Doesn't match, interface is declaration.
6333/// @end
6334/// @implementation X
6335/// - (void)ma {}
6336/// @end
6337/// \endcode
6338///
6339/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
6340/// Matcher<ObjCMethodDecl>
6341AST_POLYMORPHIC_MATCHER(isDefinition,
6342 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
6343 ObjCMethodDecl,
6344 FunctionDecl)) {
6345 return Node.isThisDeclarationADefinition();
6346}
6347
6348/// Matches if a function declaration is variadic.
6349///
6350/// Example matches f, but not g or h. The function i will not match, even when
6351/// compiled in C mode.
6352/// \code
6353/// void f(...);
6354/// void g(int);
6355/// template <typename... Ts> void h(Ts...);
6356/// void i();
6357/// \endcode
6358AST_MATCHER(FunctionDecl, isVariadic) {
6359 return Node.isVariadic();
6360}
6361
6362/// Matches the class declaration that the given method declaration
6363/// belongs to.
6364///
6365/// FIXME: Generalize this for other kinds of declarations.
6366/// FIXME: What other kind of declarations would we need to generalize
6367/// this to?
6368///
6369/// Example matches A() in the last line
6370/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
6371/// ofClass(hasName("A"))))))
6372/// \code
6373/// class A {
6374/// public:
6375/// A();
6376/// };
6377/// A a = A();
6378/// \endcode
6379AST_MATCHER_P(CXXMethodDecl, ofClass,
6380 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
6381
6382 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
6383
6384 const CXXRecordDecl *Parent = Node.getParent();
6385 return (Parent != nullptr &&
6386 InnerMatcher.matches(*Parent, Finder, Builder));
6387}
6388
6389/// Matches each method overridden by the given method. This matcher may
6390/// produce multiple matches.
6391///
6392/// Given
6393/// \code
6394/// class A { virtual void f(); };
6395/// class B : public A { void f(); };
6396/// class C : public B { void f(); };
6397/// \endcode
6398/// cxxMethodDecl(ofClass(hasName("C")),
6399/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6400/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
6401/// that B::f is not overridden by C::f).
6402///
6403/// The check can produce multiple matches in case of multiple inheritance, e.g.
6404/// \code
6405/// class A1 { virtual void f(); };
6406/// class A2 { virtual void f(); };
6407/// class C : public A1, public A2 { void f(); };
6408/// \endcode
6409/// cxxMethodDecl(ofClass(hasName("C")),
6410/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6411/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
6412/// once with "b" binding "A2::f" and "d" binding "C::f".
6413AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
6414 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
6415 BoundNodesTreeBuilder Result;
6416 bool Matched = false;
6417 for (const auto *Overridden : Node.overridden_methods()) {
6418 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
6419 const bool OverriddenMatched =
6420 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
6421 if (OverriddenMatched) {
6422 Matched = true;
6423 Result.addMatch(OverriddenBuilder);
6424 }
6425 }
6426 *Builder = std::move(Result);
6427 return Matched;
6428}
6429
6430/// Matches declarations of virtual methods and C++ base specifiers that specify
6431/// virtual inheritance.
6432///
6433/// Example:
6434/// \code
6435/// class A {
6436/// public:
6437/// virtual void x(); // matches x
6438/// };
6439/// \endcode
6440///
6441/// Example:
6442/// \code
6443/// class Base {};
6444/// class DirectlyDerived : virtual Base {}; // matches Base
6445/// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
6446/// \endcode
6447///
6448/// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
6449AST_POLYMORPHIC_MATCHER(isVirtual,
6450 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl,
6451 CXXBaseSpecifier)) {
6452 return Node.isVirtual();
6453}
6454
6455/// Matches if the given method declaration has an explicit "virtual".
6456///
6457/// Given
6458/// \code
6459/// class A {
6460/// public:
6461/// virtual void x();
6462/// };
6463/// class B : public A {
6464/// public:
6465/// void x();
6466/// };
6467/// \endcode
6468/// matches A::x but not B::x
6469AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
6470 return Node.isVirtualAsWritten();
6471}
6472
6473AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
6474 return Node.isInheritingConstructor();
6475}
6476
6477/// Matches if the given method or class declaration is final.
6478///
6479/// Given:
6480/// \code
6481/// class A final {};
6482///
6483/// struct B {
6484/// virtual void f();
6485/// };
6486///
6487/// struct C : B {
6488/// void f() final;
6489/// };
6490/// \endcode
6491/// matches A and C::f, but not B, C, or B::f
6493 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
6494 CXXMethodDecl)) {
6495 return Node.template hasAttr<FinalAttr>();
6496}
6497
6498/// Matches if the given method declaration is pure.
6499///
6500/// Given
6501/// \code
6502/// class A {
6503/// public:
6504/// virtual void x() = 0;
6505/// };
6506/// \endcode
6507/// matches A::x
6508AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPureVirtual(); }
6509
6510/// Matches if the given method declaration is const.
6511///
6512/// Given
6513/// \code
6514/// struct A {
6515/// void foo() const;
6516/// void bar();
6517/// };
6518/// \endcode
6519///
6520/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
6521AST_MATCHER(CXXMethodDecl, isConst) {
6522 return Node.isConst();
6523}
6524
6525/// Matches if the given method declaration declares a copy assignment
6526/// operator.
6527///
6528/// Given
6529/// \code
6530/// struct A {
6531/// A &operator=(const A &);
6532/// A &operator=(A &&);
6533/// };
6534/// \endcode
6535///
6536/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
6537/// the second one.
6538AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
6539 return Node.isCopyAssignmentOperator();
6540}
6541
6542/// Matches if the given method declaration declares a move assignment
6543/// operator.
6544///
6545/// Given
6546/// \code
6547/// struct A {
6548/// A &operator=(const A &);
6549/// A &operator=(A &&);
6550/// };
6551/// \endcode
6552///
6553/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
6554/// the first one.
6555AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
6556 return Node.isMoveAssignmentOperator();
6557}
6558
6559/// Matches if the given method declaration overrides another method.
6560///
6561/// Given
6562/// \code
6563/// class A {
6564/// public:
6565/// virtual void x();
6566/// };
6567/// class B : public A {
6568/// public:
6569/// virtual void x();
6570/// };
6571/// \endcode
6572/// matches B::x
6573AST_MATCHER(CXXMethodDecl, isOverride) {
6574 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
6575}
6576
6577/// Matches method declarations that are user-provided.
6578///
6579/// Given
6580/// \code
6581/// struct S {
6582/// S(); // #1
6583/// S(const S &) = default; // #2
6584/// S(S &&) = delete; // #3
6585/// };
6586/// \endcode
6587/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
6588AST_MATCHER(CXXMethodDecl, isUserProvided) {
6589 return Node.isUserProvided();
6590}
6591
6592/// Matches member expressions that are called with '->' as opposed
6593/// to '.'.
6594///
6595/// Member calls on the implicit this pointer match as called with '->'.
6596///
6597/// Given
6598/// \code
6599/// class Y {
6600/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
6601/// template <class T> void f() { this->f<T>(); f<T>(); }
6602/// int a;
6603/// static int b;
6604/// };
6605/// template <class T>
6606/// class Z {
6607/// void x() { this->m; }
6608/// };
6609/// \endcode
6610/// memberExpr(isArrow())
6611/// matches this->x, x, y.x, a, this->b
6612/// cxxDependentScopeMemberExpr(isArrow())
6613/// matches this->m
6614/// unresolvedMemberExpr(isArrow())
6615/// matches this->f<T>, f<T>
6617 isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
6618 CXXDependentScopeMemberExpr)) {
6619 return Node.isArrow();
6620}
6621
6622/// Matches QualType nodes that are of integer type.
6623///
6624/// Given
6625/// \code
6626/// void a(int);
6627/// void b(unsigned long);
6628/// void c(double);
6629/// \endcode
6630/// functionDecl(hasAnyParameter(hasType(isInteger())))
6631/// matches "a(int)", "b(unsigned long)", but not "c(double)".
6632AST_MATCHER(QualType, isInteger) {
6633 return Node->isIntegerType();
6634}
6635
6636/// Matches QualType nodes that are of unsigned integer type.
6637///
6638/// Given
6639/// \code
6640/// void a(int);
6641/// void b(unsigned long);
6642/// void c(double);
6643/// \endcode
6644/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6645/// matches "b(unsigned long)", but not "a(int)" and "c(double)".
6646AST_MATCHER(QualType, isUnsignedInteger) {
6647 return Node->isUnsignedIntegerType();
6648}
6649
6650/// Matches QualType nodes that are of signed integer type.
6651///
6652/// Given
6653/// \code
6654/// void a(int);
6655/// void b(unsigned long);
6656/// void c(double);
6657/// \endcode
6658/// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6659/// matches "a(int)", but not "b(unsigned long)" and "c(double)".
6660AST_MATCHER(QualType, isSignedInteger) {
6661 return Node->isSignedIntegerType();
6662}
6663
6664/// Matches QualType nodes that are of character type.
6665///
6666/// Given
6667/// \code
6668/// void a(char);
6669/// void b(wchar_t);
6670/// void c(double);
6671/// \endcode
6672/// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6673/// matches "a(char)", "b(wchar_t)", but not "c(double)".
6674AST_MATCHER(QualType, isAnyCharacter) {
6675 return Node->isAnyCharacterType();
6676}
6677
6678/// Matches QualType nodes that are of any pointer type; this includes
6679/// the Objective-C object pointer type, which is different despite being
6680/// syntactically similar.
6681///
6682/// Given
6683/// \code
6684/// int *i = nullptr;
6685///
6686/// @interface Foo
6687/// @end
6688/// Foo *f;
6689///
6690/// int j;
6691/// \endcode
6692/// varDecl(hasType(isAnyPointer()))
6693/// matches "int *i" and "Foo *f", but not "int j".
6694AST_MATCHER(QualType, isAnyPointer) {
6695 return Node->isAnyPointerType();
6696}
6697
6698/// Matches QualType nodes that are const-qualified, i.e., that
6699/// include "top-level" const.
6700///
6701/// Given
6702/// \code
6703/// void a(int);
6704/// void b(int const);
6705/// void c(const int);
6706/// void d(const int*);
6707/// void e(int const) {};
6708/// \endcode
6709/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6710/// matches "void b(int const)", "void c(const int)" and
6711/// "void e(int const) {}". It does not match d as there
6712/// is no top-level const on the parameter type "const int *".
6713AST_MATCHER(QualType, isConstQualified) {
6714 return Node.isConstQualified();
6715}
6716
6717/// Matches QualType nodes that are volatile-qualified, i.e., that
6718/// include "top-level" volatile.
6719///
6720/// Given
6721/// \code
6722/// void a(int);
6723/// void b(int volatile);
6724/// void c(volatile int);
6725/// void d(volatile int*);
6726/// void e(int volatile) {};
6727/// \endcode
6728/// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6729/// matches "void b(int volatile)", "void c(volatile int)" and
6730/// "void e(int volatile) {}". It does not match d as there
6731/// is no top-level volatile on the parameter type "volatile int *".
6732AST_MATCHER(QualType, isVolatileQualified) {
6733 return Node.isVolatileQualified();
6734}
6735
6736/// Matches QualType nodes that have local CV-qualifiers attached to
6737/// the node, not hidden within a typedef.
6738///
6739/// Given
6740/// \code
6741/// typedef const int const_int;
6742/// const_int i;
6743/// int *const j;
6744/// int *volatile k;
6745/// int m;
6746/// \endcode
6747/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
6748/// \c i is const-qualified but the qualifier is not local.
6749AST_MATCHER(QualType, hasLocalQualifiers) {
6750 return Node.hasLocalQualifiers();
6751}
6752
6753/// Matches a member expression where the member is matched by a
6754/// given matcher.
6755///
6756/// Given
6757/// \code
6758/// struct { int first, second; } first, second;
6759/// int i(second.first);
6760/// int j(first.second);
6761/// \endcode
6762/// memberExpr(member(hasName("first")))
6763/// matches second.first
6764/// but not first.second (because the member name there is "second").
6765AST_MATCHER_P(MemberExpr, member,
6766 internal::Matcher<ValueDecl>, InnerMatcher) {
6767 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
6768}
6769
6770/// Matches a member expression where the object expression is matched by a
6771/// given matcher. Implicit object expressions are included; that is, it matches
6772/// use of implicit `this`.
6773///
6774/// Given
6775/// \code
6776/// struct X {
6777/// int m;
6778/// int f(X x) { x.m; return m; }
6779/// };
6780/// \endcode
6781/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
6782/// matches `x.m`, but not `m`; however,
6783/// memberExpr(hasObjectExpression(hasType(pointsTo(
6784// cxxRecordDecl(hasName("X"))))))
6785/// matches `m` (aka. `this->m`), but not `x.m`.
6787 hasObjectExpression,
6788 AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
6789 CXXDependentScopeMemberExpr),
6790 internal::Matcher<Expr>, InnerMatcher) {
6791 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
6792 if (E->isImplicitAccess())
6793 return false;
6794 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
6795 if (E->isImplicitAccess())
6796 return false;
6797 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
6798}
6799
6800/// Matches any using shadow declaration.
6801///
6802/// Given
6803/// \code
6804/// namespace X { void b(); }
6805/// using X::b;
6806/// \endcode
6807/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
6808/// matches \code using X::b \endcode
6809AST_MATCHER_P(BaseUsingDecl, hasAnyUsingShadowDecl,
6810 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
6811 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
6812 Node.shadow_end(), Finder,
6813 Builder) != Node.shadow_end();
6814}
6815
6816/// Matches a using shadow declaration where the target declaration is
6817/// matched by the given matcher.
6818///
6819/// Given
6820/// \code
6821/// namespace X { int a; void b(); }
6822/// using X::a;
6823/// using X::b;
6824/// \endcode
6825/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
6826/// matches \code using X::b \endcode
6827/// but not \code using X::a \endcode
6828AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
6829 internal::Matcher<NamedDecl>, InnerMatcher) {
6830 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
6831}
6832
6833/// Matches template instantiations of function, class, or static
6834/// member variable template instantiations.
6835///
6836/// Given
6837/// \code
6838/// template <typename T> class X {}; class A {}; X<A> x;
6839/// \endcode
6840/// or
6841/// \code
6842/// template <typename T> class X {}; class A {}; template class X<A>;
6843/// \endcode
6844/// or
6845/// \code
6846/// template <typename T> class X {}; class A {}; extern template class X<A>;
6847/// \endcode
6848/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6849/// matches the template instantiation of X<A>.
6850///
6851/// But given
6852/// \code
6853/// template <typename T> class X {}; class A {};
6854/// template <> class X<A> {}; X<A> x;
6855/// \endcode
6856/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6857/// does not match, as X<A> is an explicit template specialization.
6858///
6859/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6861 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
6862 CXXRecordDecl)) {
6863 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
6864 Node.getTemplateSpecializationKind() ==
6866 Node.getTemplateSpecializationKind() ==
6868}
6869
6870/// Matches declarations that are template instantiations or are inside
6871/// template instantiations.
6872///
6873/// Given
6874/// \code
6875/// template<typename T> void A(T t) { T i; }
6876/// A(0);
6877/// A(0U);
6878/// \endcode
6879/// functionDecl(isInstantiated())
6880/// matches 'A(int) {...};' and 'A(unsigned) {...}'.
6881AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
6882 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6885 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
6886}
6887
6888/// Matches statements inside of a template instantiation.
6889///
6890/// Given
6891/// \code
6892/// int j;
6893/// template<typename T> void A(T t) { T i; j += 42;}
6894/// A(0);
6895/// A(0U);
6896/// \endcode
6897/// declStmt(isInTemplateInstantiation())
6898/// matches 'int i;' and 'unsigned i'.
6899/// unless(stmt(isInTemplateInstantiation()))
6900/// will NOT match j += 42; as it's shared between the template definition and
6901/// instantiation.
6902AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
6906}
6907
6908/// Matches explicit template specializations of function, class, or
6909/// static member variable template instantiations.
6910///
6911/// Given
6912/// \code
6913/// template<typename T> void A(T t) { }
6914/// template<> void A(int N) { }
6915/// \endcode
6916/// functionDecl(isExplicitTemplateSpecialization())
6917/// matches the specialization A<int>().
6918///
6919/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6920AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
6921 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
6922 CXXRecordDecl)) {
6923 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
6924}
6925
6926/// Matches \c TypeLocs for which the given inner
6927/// QualType-matcher matches.
6928AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
6929 internal::Matcher<QualType>, InnerMatcher, 0) {
6930 return internal::BindableMatcher<TypeLoc>(
6931 new internal::TypeLocTypeMatcher(InnerMatcher));
6932}
6933
6934/// Matches `QualifiedTypeLoc`s in the clang AST.
6935///
6936/// Given
6937/// \code
6938/// const int x = 0;
6939/// \endcode
6940/// qualifiedTypeLoc()
6941/// matches `const int`.
6942extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, QualifiedTypeLoc>
6944
6945/// Matches `QualifiedTypeLoc`s that have an unqualified `TypeLoc` matching
6946/// `InnerMatcher`.
6947///
6948/// Given
6949/// \code
6950/// int* const x;
6951/// const int y;
6952/// \endcode
6953/// qualifiedTypeLoc(hasUnqualifiedLoc(pointerTypeLoc()))
6954/// matches the `TypeLoc` of the variable declaration of `x`, but not `y`.
6955AST_MATCHER_P(QualifiedTypeLoc, hasUnqualifiedLoc, internal::Matcher<TypeLoc>,
6956 InnerMatcher) {
6957 return InnerMatcher.matches(Node.getUnqualifiedLoc(), Finder, Builder);
6958}
6959
6960/// Matches a function declared with the specified return `TypeLoc`.
6961///
6962/// Given
6963/// \code
6964/// int f() { return 5; }
6965/// void g() {}
6966/// \endcode
6967/// functionDecl(hasReturnTypeLoc(loc(asString("int"))))
6968/// matches the declaration of `f`, but not `g`.
6969AST_MATCHER_P(FunctionDecl, hasReturnTypeLoc, internal::Matcher<TypeLoc>,
6970 ReturnMatcher) {
6971 auto Loc = Node.getFunctionTypeLoc();
6972 return Loc && ReturnMatcher.matches(Loc.getReturnLoc(), Finder, Builder);
6973}
6974
6975/// Matches pointer `TypeLoc`s.
6976///
6977/// Given
6978/// \code
6979/// int* x;
6980/// \endcode
6981/// pointerTypeLoc()
6982/// matches `int*`.
6983extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, PointerTypeLoc>
6985
6986/// Matches pointer `TypeLoc`s that have a pointee `TypeLoc` matching
6987/// `PointeeMatcher`.
6988///
6989/// Given
6990/// \code
6991/// int* x;
6992/// \endcode
6993/// pointerTypeLoc(hasPointeeLoc(loc(asString("int"))))
6994/// matches `int*`.
6995AST_MATCHER_P(PointerTypeLoc, hasPointeeLoc, internal::Matcher<TypeLoc>,
6996 PointeeMatcher) {
6997 return PointeeMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
6998}
6999
7000/// Matches reference `TypeLoc`s.
7001///
7002/// Given
7003/// \code
7004/// int x = 3;
7005/// int& l = x;
7006/// int&& r = 3;
7007/// \endcode
7008/// referenceTypeLoc()
7009/// matches `int&` and `int&&`.
7010extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ReferenceTypeLoc>
7012
7013/// Matches reference `TypeLoc`s that have a referent `TypeLoc` matching
7014/// `ReferentMatcher`.
7015///
7016/// Given
7017/// \code
7018/// int x = 3;
7019/// int& xx = x;
7020/// \endcode
7021/// referenceTypeLoc(hasReferentLoc(loc(asString("int"))))
7022/// matches `int&`.
7023AST_MATCHER_P(ReferenceTypeLoc, hasReferentLoc, internal::Matcher<TypeLoc>,
7024 ReferentMatcher) {
7025 return ReferentMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
7026}
7027
7028/// Matches `ArrayTypeLoc`s.
7029///
7030/// Given
7031/// \code
7032/// int a[] = {1, 2};
7033/// int b[3];
7034/// void f() { int c[a[0]]; }
7035/// \endcode
7036/// arrayTypeLoc()
7037/// matches "int a[]", "int b[3]" and "int c[a[0]]".
7038extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ArrayTypeLoc>
7040
7041/// Matches `FunctionTypeLoc`s.
7042///
7043/// Given
7044/// \code
7045/// void f(int);
7046/// using g = double (char, float);
7047/// char (*fn_ptr)();
7048/// \endcode
7049/// functionTypeLoc()
7050/// matches "void (int)", "double (char, float)", and "char ()".
7051extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, FunctionTypeLoc>
7053
7054/// Matches template specialization `TypeLoc`s.
7055///
7056/// Given
7057/// \code
7058/// template <typename T> class C {};
7059/// C<char> var;
7060/// \endcode
7061/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(typeLoc())))
7062/// matches `C<char> var`.
7063extern const internal::VariadicDynCastAllOfMatcher<
7064 TypeLoc, TemplateSpecializationTypeLoc>
7066
7067/// Matches template specialization `TypeLoc`s, class template specializations,
7068/// variable template specializations, unresolved overloads, and function
7069/// template specializations that have at least one `TemplateArgumentLoc`
7070/// matching the given `InnerMatcher`.
7071///
7072/// Given
7073/// \code
7074/// template<typename T> class A {};
7075/// A<int> a;
7076/// \endcode
7077/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasAnyTemplateArgumentLoc(
7078/// hasTypeLoc(loc(asString("int")))))))
7079/// matches `A<int> a`.
7081 hasAnyTemplateArgumentLoc,
7082 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
7083 VarTemplateSpecializationDecl, FunctionDecl,
7084 DeclRefExpr, TemplateSpecializationTypeLoc,
7085 OverloadExpr),
7086 internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
7087 auto Args = internal::getTemplateArgsWritten(Node);
7088 return matchesFirstInRange(InnerMatcher, Args.begin(), Args.end(), Finder,
7089 Builder) != Args.end();
7090 return false;
7091}
7092
7093/// Matches template specialization `TypeLoc`s, class template specializations,
7094/// variable template specializations, unresolved overloads, and function
7095/// template specializations where the n'th `TemplateArgumentLoc` matches the
7096/// given `InnerMatcher`.
7097///
7098/// Given
7099/// \code
7100/// template<typename T, typename U> class A {};
7101/// A<double, int> b;
7102/// A<int, double> c;
7103/// \endcode
7104/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasTemplateArgumentLoc(0,
7105/// hasTypeLoc(loc(asString("double")))))))
7106/// matches `A<double, int> b`, but not `A<int, double> c`.
7108 hasTemplateArgumentLoc,
7109 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
7110 VarTemplateSpecializationDecl, FunctionDecl,
7111 DeclRefExpr, TemplateSpecializationTypeLoc,
7112 OverloadExpr),
7113 unsigned, Index, internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
7114 auto Args = internal::getTemplateArgsWritten(Node);
7115 return Index < Args.size() &&
7116 InnerMatcher.matches(Args[Index], Finder, Builder);
7117}
7118
7119/// Matches template specialization `TypeLoc`s, class template specializations,
7120/// variable template specializations, unresolved overloads, and function
7121/// template specializations that have exactly `MatchCount` number of
7122/// `TemplateArgumentLoc`s.
7123///
7124/// Given
7125/// \code
7126/// template<typename T> class A {};
7127/// A<int> a;
7128/// \endcode
7129/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(templateArgumentLocCountIs(1))))
7130/// matches `A<int> a`.
7132 templateArgumentLocCountIs,
7133 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
7134 VarTemplateSpecializationDecl, FunctionDecl,
7135 DeclRefExpr, TemplateSpecializationTypeLoc,
7136 OverloadExpr),
7137 unsigned, MatchCount) {
7138 unsigned Count = internal::getNumTemplateArgsWritten(Node);
7139 return Count == MatchCount;
7140}
7141
7142/// Matches type \c bool.
7143///
7144/// Given
7145/// \code
7146/// struct S { bool func(); };
7147/// \endcode
7148/// functionDecl(returns(booleanType()))
7149/// matches "bool func();"
7150AST_MATCHER(Type, booleanType) {
7151 return Node.isBooleanType();
7152}
7153
7154/// Matches type \c void.
7155///
7156/// Given
7157/// \code
7158/// struct S { void func(); };
7159/// \endcode
7160/// functionDecl(returns(voidType()))
7161/// matches "void func();"
7162AST_MATCHER(Type, voidType) {
7163 return Node.isVoidType();
7164}
7165
7166template <typename NodeType>
7167using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
7168
7169/// Matches builtin Types.
7170///
7171/// Given
7172/// \code
7173/// struct A {};
7174/// A a;
7175/// int b;
7176/// float c;
7177/// bool d;
7178/// \endcode
7179/// builtinType()
7180/// matches "int b", "float c" and "bool d"
7181extern const AstTypeMatcher<BuiltinType> builtinType;
7182
7183/// Matches all kinds of arrays.
7184///
7185/// Given
7186/// \code
7187/// int a[] = { 2, 3 };
7188/// int b[4];
7189/// void f() { int c[a[0]]; }
7190/// \endcode
7191/// arrayType()
7192/// matches "int a[]", "int b[4]" and "int c[a[0]]";
7193extern const AstTypeMatcher<ArrayType> arrayType;
7194
7195/// Matches C99 complex types.
7196///
7197/// Given
7198/// \code
7199/// _Complex float f;
7200/// \endcode
7201/// complexType()
7202/// matches "_Complex float f"
7203extern const AstTypeMatcher<ComplexType> complexType;
7204
7205/// Matches any real floating-point type (float, double, long double).
7206///
7207/// Given
7208/// \code
7209/// int i;
7210/// float f;
7211/// \endcode
7212/// realFloatingPointType()
7213/// matches "float f" but not "int i"
7214AST_MATCHER(Type, realFloatingPointType) {
7215 return Node.isRealFloatingType();
7216}
7217
7218/// Matches arrays and C99 complex types that have a specific element
7219/// type.
7220///
7221/// Given
7222/// \code
7223/// struct A {};
7224/// A a[7];
7225/// int b[7];
7226/// \endcode
7227/// arrayType(hasElementType(builtinType()))
7228/// matches "int b[7]"
7229///
7230/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
7231AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
7233 ComplexType));
7234
7235/// Matches C arrays with a specified constant size.
7236///
7237/// Given
7238/// \code
7239/// void() {
7240/// int a[2];
7241/// int b[] = { 2, 3 };
7242/// int c[b[0]];
7243/// }
7244/// \endcode
7245/// constantArrayType()
7246/// matches "int a[2]"
7247extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
7248
7249/// Matches nodes that have the specified size.
7250///
7251/// Given
7252/// \code
7253/// int a[42];
7254/// int b[2 * 21];
7255/// int c[41], d[43];
7256/// char *s = "abcd";
7257/// wchar_t *ws = L"abcd";
7258/// char *w = "a";
7259/// \endcode
7260/// constantArrayType(hasSize(42))
7261/// matches "int a[42]" and "int b[2 * 21]"
7262/// stringLiteral(hasSize(4))
7263/// matches "abcd", L"abcd"
7265 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
7266 StringLiteral),
7267 unsigned, N) {
7268 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
7269}
7270
7271/// Matches C++ arrays whose size is a value-dependent expression.
7272///
7273/// Given
7274/// \code
7275/// template<typename T, int Size>
7276/// class array {
7277/// T data[Size];
7278/// };
7279/// \endcode
7280/// dependentSizedArrayType()
7281/// matches "T data[Size]"
7282extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
7283
7284/// Matches C++ extended vector type where either the type or size is
7285/// dependent.
7286///
7287/// Given
7288/// \code
7289/// template<typename T, int Size>
7290/// class vector {
7291/// typedef T __attribute__((ext_vector_type(Size))) type;
7292/// };
7293/// \endcode
7294/// dependentSizedExtVectorType()
7295/// matches "T __attribute__((ext_vector_type(Size)))"
7296extern const AstTypeMatcher<DependentSizedExtVectorType>
7298
7299/// Matches C arrays with unspecified size.
7300///
7301/// Given
7302/// \code
7303/// int a[] = { 2, 3 };
7304/// int b[42];
7305/// void f(int c[]) { int d[a[0]]; };
7306/// \endcode
7307/// incompleteArrayType()
7308/// matches "int a[]" and "int c[]"
7309extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
7310
7311/// Matches C arrays with a specified size that is not an
7312/// integer-constant-expression.
7313///
7314/// Given
7315/// \code
7316/// void f() {
7317/// int a[] = { 2, 3 }
7318/// int b[42];
7319/// int c[a[0]];
7320/// }
7321/// \endcode
7322/// variableArrayType()
7323/// matches "int c[a[0]]"
7324extern const AstTypeMatcher<VariableArrayType> variableArrayType;
7325
7326/// Matches \c VariableArrayType nodes that have a specific size
7327/// expression.
7328///
7329/// Given
7330/// \code
7331/// void f(int b) {
7332/// int a[b];
7333/// }
7334/// \endcode
7335/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
7336/// varDecl(hasName("b")))))))
7337/// matches "int a[b]"
7338AST_MATCHER_P(VariableArrayType, hasSizeExpr,
7339 internal::Matcher<Expr>, InnerMatcher) {
7340 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
7341}
7342
7343/// Matches atomic types.
7344///
7345/// Given
7346/// \code
7347/// _Atomic(int) i;
7348/// \endcode
7349/// atomicType()
7350/// matches "_Atomic(int) i"
7351extern const AstTypeMatcher<AtomicType> atomicType;
7352
7353/// Matches atomic types with a specific value type.
7354///
7355/// Given
7356/// \code
7357/// _Atomic(int) i;
7358/// _Atomic(float) f;
7359/// \endcode
7360/// atomicType(hasValueType(isInteger()))
7361/// matches "_Atomic(int) i"
7362///
7363/// Usable as: Matcher<AtomicType>
7364AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
7366
7367/// Matches types nodes representing C++11 auto types.
7368///
7369/// Given:
7370/// \code
7371/// auto n = 4;
7372/// int v[] = { 2, 3 }
7373/// for (auto i : v) { }
7374/// \endcode
7375/// autoType()
7376/// matches "auto n" and "auto i"
7377extern const AstTypeMatcher<AutoType> autoType;
7378
7379/// Matches types nodes representing C++11 decltype(<expr>) types.
7380///
7381/// Given:
7382/// \code
7383/// short i = 1;
7384/// int j = 42;
7385/// decltype(i + j) result = i + j;
7386/// \endcode
7387/// decltypeType()
7388/// matches "decltype(i + j)"
7389extern const AstTypeMatcher<DecltypeType> decltypeType;
7390
7391/// Matches \c AutoType nodes where the deduced type is a specific type.
7392///
7393/// Note: There is no \c TypeLoc for the deduced type and thus no
7394/// \c getDeducedLoc() matcher.
7395///
7396/// Given
7397/// \code
7398/// auto a = 1;
7399/// auto b = 2.0;
7400/// \endcode
7401/// autoType(hasDeducedType(isInteger()))
7402/// matches "auto a"
7403///
7404/// Usable as: Matcher<AutoType>
7405AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
7407
7408/// Matches \c QualType nodes to find the underlying type.
7409///
7410/// Given
7411/// \code
7412/// decltype(1) a = 1;
7413/// decltype(2.0) b = 2.0;
7414/// \endcode
7415/// decltypeType(hasUnderlyingType(isInteger()))
7416/// matches the type of "a"
7417///
7418/// Usable as: Matcher<QualType>
7419AST_MATCHER_P(Type, hasUnderlyingType, internal::Matcher<QualType>, Inner) {
7420 QualType QT = Node.getLocallyUnqualifiedSingleStepDesugaredType();
7421 if (QT == QualType(&Node, 0))
7422 return false;
7423 return Inner.matches(QT, Finder, Builder);
7424}
7425
7426/// Matches \c FunctionType nodes.
7427///
7428/// Given
7429/// \code
7430/// int (*f)(int);
7431/// void g();
7432/// \endcode
7433/// functionType()
7434/// matches "int (*f)(int)" and the type of "g".
7435extern const AstTypeMatcher<FunctionType> functionType;
7436
7437/// Matches \c FunctionProtoType nodes.
7438///
7439/// Given
7440/// \code
7441/// int (*f)(int);
7442/// void g();
7443/// \endcode
7444/// functionProtoType()
7445/// matches "int (*f)(int)" and the type of "g" in C++ mode.
7446/// In C mode, "g" is not matched because it does not contain a prototype.
7447extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
7448
7449/// Matches \c ParenType nodes.
7450///
7451/// Given
7452/// \code
7453/// int (*ptr_to_array)[4];
7454/// int *array_of_ptrs[4];
7455/// \endcode
7456///
7457/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
7458/// \c array_of_ptrs.
7459extern const AstTypeMatcher<ParenType> parenType;
7460
7461/// Matches \c ParenType nodes where the inner type is a specific type.
7462///
7463/// Given
7464/// \code
7465/// int (*ptr_to_array)[4];
7466/// int (*ptr_to_func)(int);
7467/// \endcode
7468///
7469/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
7470/// \c ptr_to_func but not \c ptr_to_array.
7471///
7472/// Usable as: Matcher<ParenType>
7473AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
7475
7476/// Matches block pointer types, i.e. types syntactically represented as
7477/// "void (^)(int)".
7478///
7479/// The \c pointee is always required to be a \c FunctionType.
7480extern const AstTypeMatcher<BlockPointerType> blockPointerType;
7481
7482/// Matches member pointer types.
7483/// Given
7484/// \code
7485/// struct A { int i; }
7486/// A::* ptr = A::i;
7487/// \endcode
7488/// memberPointerType()
7489/// matches "A::* ptr"
7490extern const AstTypeMatcher<MemberPointerType> memberPointerType;
7491
7492/// Matches pointer types, but does not match Objective-C object pointer
7493/// types.
7494///
7495/// Given
7496/// \code
7497/// int *a;
7498/// int &b = *a;
7499/// int c = 5;
7500///
7501/// @interface Foo
7502/// @end
7503/// Foo *f;
7504/// \endcode
7505/// pointerType()
7506/// matches "int *a", but does not match "Foo *f".
7507extern const AstTypeMatcher<PointerType> pointerType;
7508
7509/// Matches an Objective-C object pointer type, which is different from
7510/// a pointer type, despite being syntactically similar.
7511///
7512/// Given
7513/// \code
7514/// int *a;
7515///
7516/// @interface Foo
7517/// @end
7518/// Foo *f;
7519/// \endcode
7520/// pointerType()
7521/// matches "Foo *f", but does not match "int *a".
7522extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
7523
7524/// Matches both lvalue and rvalue reference types.
7525///
7526/// Given
7527/// \code
7528/// int *a;
7529/// int &b = *a;
7530/// int &&c = 1;
7531/// auto &d = b;
7532/// auto &&e = c;
7533/// auto &&f = 2;
7534/// int g = 5;
7535/// \endcode
7536///
7537/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
7538extern const AstTypeMatcher<ReferenceType> referenceType;
7539
7540/// Matches lvalue reference types.
7541///
7542/// Given:
7543/// \code
7544/// int *a;
7545/// int &b = *a;
7546/// int &&c = 1;
7547/// auto &d = b;
7548/// auto &&e = c;
7549/// auto &&f = 2;
7550/// int g = 5;
7551/// \endcode
7552///
7553/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
7554/// matched since the type is deduced as int& by reference collapsing rules.
7555extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
7556
7557/// Matches rvalue reference types.
7558///
7559/// Given:
7560/// \code
7561/// int *a;
7562/// int &b = *a;
7563/// int &&c = 1;
7564/// auto &d = b;
7565/// auto &&e = c;
7566/// auto &&f = 2;
7567/// int g = 5;
7568/// \endcode
7569///
7570/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
7571/// matched as it is deduced to int& by reference collapsing rules.
7572extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
7573
7574/// Narrows PointerType (and similar) matchers to those where the
7575/// \c pointee matches a given matcher.
7576///
7577/// Given
7578/// \code
7579/// int *a;
7580/// int const *b;
7581/// float const *f;
7582/// \endcode
7583/// pointerType(pointee(isConstQualified(), isInteger()))
7584/// matches "int const *b"
7585///
7586/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
7587/// Matcher<PointerType>, Matcher<ReferenceType>,
7588/// Matcher<ObjCObjectPointerType>
7590 pointee, getPointee,
7591 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
7592 PointerType, ReferenceType,
7593 ObjCObjectPointerType));
7594
7595/// Matches typedef types.
7596///
7597/// Given
7598/// \code
7599/// typedef int X;
7600/// \endcode
7601/// typedefType()
7602/// matches "typedef int X"
7603extern const AstTypeMatcher<TypedefType> typedefType;
7604
7605/// Matches qualified types when the qualifier is applied via a macro.
7606///
7607/// Given
7608/// \code
7609/// #define CDECL __attribute__((cdecl))
7610/// typedef void (CDECL *X)();
7611/// typedef void (__attribute__((cdecl)) *Y)();
7612/// \endcode
7613/// macroQualifiedType()
7614/// matches the type of the typedef declaration of \c X but not \c Y.
7615extern const AstTypeMatcher<MacroQualifiedType> macroQualifiedType;
7616
7617/// Matches enum types.
7618///
7619/// Given
7620/// \code
7621/// enum C { Green };
7622/// enum class S { Red };
7623///
7624/// C c;
7625/// S s;
7626/// \endcode
7627//
7628/// \c enumType() matches the type of the variable declarations of both \c c and
7629/// \c s.
7630extern const AstTypeMatcher<EnumType> enumType;
7631
7632/// Matches template specialization types.
7633///
7634/// Given
7635/// \code
7636/// template <typename T>
7637/// class C { };
7638///
7639/// template class C<int>; // A
7640/// C<char> var; // B
7641/// \endcode
7642///
7643/// \c templateSpecializationType() matches the type of the explicit
7644/// instantiation in \c A and the type of the variable declaration in \c B.
7645extern const AstTypeMatcher<TemplateSpecializationType>
7647
7648/// Matches C++17 deduced template specialization types, e.g. deduced class
7649/// template types.
7650///
7651/// Given
7652/// \code
7653/// template <typename T>
7654/// class C { public: C(T); };
7655///
7656/// C c(123);
7657/// \endcode
7658/// \c deducedTemplateSpecializationType() matches the type in the declaration
7659/// of the variable \c c.
7660extern const AstTypeMatcher<DeducedTemplateSpecializationType>
7662
7663/// Matches types nodes representing unary type transformations.
7664///
7665/// Given:
7666/// \code
7667/// typedef __underlying_type(T) type;
7668/// \endcode
7669/// unaryTransformType()
7670/// matches "__underlying_type(T)"
7671extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
7672
7673/// Matches record types (e.g. structs, classes).
7674///
7675/// Given
7676/// \code
7677/// class C {};
7678/// struct S {};
7679///
7680/// C c;
7681/// S s;
7682/// \endcode
7683///
7684/// \c recordType() matches the type of the variable declarations of both \c c
7685/// and \c s.
7686extern const AstTypeMatcher<RecordType> recordType;
7687
7688/// Matches tag types (record and enum types).
7689///
7690/// Given
7691/// \code
7692/// enum E {};
7693/// class C {};
7694///
7695/// E e;
7696/// C c;
7697/// \endcode
7698///
7699/// \c tagType() matches the type of the variable declarations of both \c e
7700/// and \c c.
7701extern const AstTypeMatcher<TagType> tagType;
7702
7703/// Matches Types whose qualifier, a NestedNameSpecifier,
7704/// matches \c InnerMatcher if the qualifier exists.
7705///
7706/// Given
7707/// \code
7708/// namespace N {
7709/// namespace M {
7710/// class D {};
7711/// }
7712/// }
7713/// N::M::D d;
7714/// \endcode
7715///
7716/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
7717/// matches the type of the variable declaration of \c d.
7718AST_MATCHER_P(Type, hasQualifier, internal::Matcher<NestedNameSpecifier>,
7719 InnerMatcher) {
7720 if (NestedNameSpecifier Qualifier = Node.getPrefix())
7721 return InnerMatcher.matches(Qualifier, Finder, Builder);
7722
7723 return false;
7724}
7725
7726/// Matches types specified through a using declaration.
7727///
7728/// Given
7729/// \code
7730/// namespace a { struct S {}; }
7731/// using a::S;
7732/// S s;
7733/// \endcode
7734///
7735/// \c usingType() matches the type of the variable declaration of \c s.
7736extern const AstTypeMatcher<UsingType> usingType;
7737
7738/// Matches types that represent the result of substituting a type for a
7739/// template type parameter.
7740///
7741/// Given
7742/// \code
7743/// template <typename T>
7744/// void F(T t) {
7745/// int i = 1 + t;
7746/// }
7747/// \endcode
7748///
7749/// \c substTemplateTypeParmType() matches the type of 't' but not '1'
7750extern const AstTypeMatcher<SubstTemplateTypeParmType>
7752
7753/// Matches template type parameter substitutions that have a replacement
7754/// type that matches the provided matcher.
7755///
7756/// Given
7757/// \code
7758/// template <typename T>
7759/// double F(T t);
7760/// int i;
7761/// double j = F(i);
7762/// \endcode
7763///
7764/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
7766 hasReplacementType, getReplacementType,
7767 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
7768
7769/// Matches template type parameter types.
7770///
7771/// Example matches T, but not int.
7772/// (matcher = templateTypeParmType())
7773/// \code
7774/// template <typename T> void f(int i);
7775/// \endcode
7776extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
7777
7778/// Matches injected class name types.
7779///
7780/// Example matches S s, but not S<T> s.
7781/// (matcher = parmVarDecl(hasType(injectedClassNameType())))
7782/// \code
7783/// template <typename T> struct S {
7784/// void f(S s);
7785/// void g(S<T> s);
7786/// };
7787/// \endcode
7788extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
7789
7790/// Matches decayed type
7791/// Example matches i[] in declaration of f.
7792/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
7793/// Example matches i[1].
7794/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
7795/// \code
7796/// void f(int i[]) {
7797/// i[1] = 0;
7798/// }
7799/// \endcode
7800extern const AstTypeMatcher<DecayedType> decayedType;
7801
7802/// Matches the decayed type, whose decayed type matches \c InnerMatcher
7803AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
7804 InnerType) {
7805 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
7806}
7807
7808/// Matches a dependent name type
7809///
7810/// Example matches T::type
7811/// \code
7812/// template <typename T> struct declToImport {
7813/// typedef typename T::type dependent_name;
7814/// };
7815/// \endcode
7816extern const AstTypeMatcher<DependentNameType> dependentNameType;
7817
7818/// Matches declarations whose declaration context, interpreted as a
7819/// Decl, matches \c InnerMatcher.
7820///
7821/// Given
7822/// \code
7823/// namespace N {
7824/// namespace M {
7825/// class D {};
7826/// }
7827/// }
7828/// \endcode
7829///
7830/// \c cxxRecordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
7831/// declaration of \c class \c D.
7832AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
7833 const DeclContext *DC = Node.getDeclContext();
7834 if (!DC) return false;
7835 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
7836}
7837
7838/// Matches nested name specifiers.
7839///
7840/// Given
7841/// \code
7842/// namespace ns {
7843/// struct A { static void f(); };
7844/// void A::f() {}
7845/// void g() { A::f(); }
7846/// }
7847/// ns::A a;
7848/// \endcode
7849/// nestedNameSpecifier()
7850/// matches "ns::" and both "A::"
7851extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
7853
7854/// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
7855extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
7857
7858/// Matches \c NestedNameSpecifierLocs for which the given inner
7859/// NestedNameSpecifier-matcher matches.
7861 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
7862 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
7863 return internal::BindableMatcher<NestedNameSpecifierLoc>(
7864 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
7865 InnerMatcher));
7866}
7867
7868/// Matches nested name specifiers that specify a type matching the
7869/// given \c QualType matcher without qualifiers.
7870///
7871/// Given
7872/// \code
7873/// struct A { struct B { struct C {}; }; };
7874/// A::B::C c;
7875/// \endcode
7876/// nestedNameSpecifier(specifiesType(
7877/// hasDeclaration(cxxRecordDecl(hasName("A")))
7878/// ))
7879/// matches "A::"
7880AST_MATCHER_P(NestedNameSpecifier, specifiesType,
7881 internal::Matcher<QualType>, InnerMatcher) {
7882 if (Node.getKind() != NestedNameSpecifier::Kind::Type)
7883 return false;
7884 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
7885}
7886
7887/// Matches nested name specifier locs that specify a type matching the
7888/// given \c TypeLoc.
7889///
7890/// Given
7891/// \code
7892/// struct A { struct B { struct C {}; }; };
7893/// A::B::C c;
7894/// \endcode
7895/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
7896/// hasDeclaration(cxxRecordDecl(hasName("A")))))))
7897/// matches "A::"
7898AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
7899 internal::Matcher<TypeLoc>, InnerMatcher) {
7900 if (!Node)
7901 return false;
7902 TypeLoc TL = Node.getAsTypeLoc();
7903 if (!TL)
7904 return false;
7905 return InnerMatcher.matches(TL, Finder, Builder);
7906}
7907
7908/// Matches on the prefix of a \c NestedNameSpecifier.
7909///
7910/// Given
7911/// \code
7912/// struct A { struct B { struct C {}; }; };
7913/// A::B::C c;
7914/// \endcode
7915/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
7916/// matches "A::"
7917AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
7918 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
7919 0) {
7920 NestedNameSpecifier NextNode = std::nullopt;
7921 switch (Node.getKind()) {
7923 NextNode = Node.getAsNamespaceAndPrefix().Prefix;
7924 break;
7926 NextNode = Node.getAsType()->getPrefix();
7927 break;
7928 default:
7929 break;
7930 }
7931
7932 if (!NextNode)
7933 return false;
7934 return InnerMatcher.matches(NextNode, Finder, Builder);
7935}
7936
7937/// Matches on the prefix of a \c NestedNameSpecifierLoc.
7938///
7939/// Given
7940/// \code
7941/// struct A { struct B { struct C {}; }; };
7942/// A::B::C c;
7943/// \endcode
7944/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
7945/// matches "A::"
7946AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
7947 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
7948 1) {
7949 NestedNameSpecifierLoc NextNode;
7950 if (TypeLoc TL = Node.getAsTypeLoc())
7951 NextNode = TL.getPrefix();
7952 else
7953 NextNode = Node.getAsNamespaceAndPrefix().Prefix;
7954
7955 if (!NextNode)
7956 return false;
7957 return InnerMatcher.matches(NextNode, Finder, Builder);
7958}
7959
7960/// Matches nested name specifiers that specify a namespace matching the
7961/// given namespace matcher.
7962///
7963/// Given
7964/// \code
7965/// namespace ns { struct A {}; }
7966/// ns::A a;
7967/// \endcode
7968/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
7969/// matches "ns::"
7970AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
7971 internal::Matcher<NamespaceDecl>, InnerMatcher) {
7972 if (Node.getKind() != NestedNameSpecifier::Kind::Namespace)
7973 return false;
7974 const auto *Namespace =
7975 dyn_cast<NamespaceDecl>(Node.getAsNamespaceAndPrefix().Namespace);
7976 if (!Namespace)
7977 return false;
7978 return InnerMatcher.matches(*Namespace, Finder, Builder);
7979}
7980
7981/// Matches attributes.
7982/// Attributes may be attached with a variety of different syntaxes (including
7983/// keywords, C++11 attributes, GNU ``__attribute``` and MSVC `__declspec``,
7984/// and ``#pragma``s). They may also be implicit.
7985///
7986/// Given
7987/// \code
7988/// struct [[nodiscard]] Foo{};
7989/// void bar(int * __attribute__((nonnull)) );
7990/// __declspec(noinline) void baz();
7991///
7992/// #pragma omp declare simd
7993/// int min();
7994/// \endcode
7995/// attr()
7996/// matches "nodiscard", "nonnull", "noinline", and the whole "#pragma" line.
7997extern const internal::VariadicAllOfMatcher<Attr> attr;
7998
7999/// Overloads for the \c equalsNode matcher.
8000/// FIXME: Implement for other node types.
8001/// @{
8002
8003/// Matches if a node equals another node.
8004///
8005/// \c Decl has pointer identity in the AST.
8006AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
8007 return &Node == Other;
8008}
8009/// Matches if a node equals another node.
8010///
8011/// \c Stmt has pointer identity in the AST.
8012AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
8013 return &Node == Other;
8014}
8015/// Matches if a node equals another node.
8016///
8017/// \c Type has pointer identity in the AST.
8018AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
8019 return &Node == Other;
8020}
8021
8022/// @}
8023
8024/// Matches each case or default statement belonging to the given switch
8025/// statement. This matcher may produce multiple matches.
8026///
8027/// Given
8028/// \code
8029/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
8030/// \endcode
8031/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
8032/// matches four times, with "c" binding each of "case 1:", "case 2:",
8033/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
8034/// "switch (1)", "switch (2)" and "switch (2)".
8035AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
8036 InnerMatcher) {
8037 BoundNodesTreeBuilder Result;
8038 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
8039 // iteration order. We should use the more general iterating matchers once
8040 // they are capable of expressing this matcher (for example, it should ignore
8041 // case statements belonging to nested switch statements).
8042 bool Matched = false;
8043 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
8044 SC = SC->getNextSwitchCase()) {
8045 BoundNodesTreeBuilder CaseBuilder(*Builder);
8046 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
8047 if (CaseMatched) {
8048 Matched = true;
8049 Result.addMatch(CaseBuilder);
8050 }
8051 }
8052 *Builder = std::move(Result);
8053 return Matched;
8054}
8055
8056/// Matches each constructor initializer in a constructor definition.
8057///
8058/// Given
8059/// \code
8060/// class A { A() : i(42), j(42) {} int i; int j; };
8061/// \endcode
8062/// cxxConstructorDecl(forEachConstructorInitializer(
8063/// forField(decl().bind("x"))
8064/// ))
8065/// will trigger two matches, binding for 'i' and 'j' respectively.
8066AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
8067 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
8068 BoundNodesTreeBuilder Result;
8069 bool Matched = false;
8070 for (const auto *I : Node.inits()) {
8071 if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
8072 continue;
8073 BoundNodesTreeBuilder InitBuilder(*Builder);
8074 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
8075 Matched = true;
8076 Result.addMatch(InitBuilder);
8077 }
8078 }
8079 *Builder = std::move(Result);
8080 return Matched;
8081}
8082
8083/// Matches constructor declarations that are copy constructors.
8084///
8085/// Given
8086/// \code
8087/// struct S {
8088/// S(); // #1
8089/// S(const S &); // #2
8090/// S(S &&); // #3
8091/// };
8092/// \endcode
8093/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
8094AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
8095 return Node.isCopyConstructor();
8096}
8097
8098/// Matches constructor declarations that are move constructors.
8099///
8100/// Given
8101/// \code
8102/// struct S {
8103/// S(); // #1
8104/// S(const S &); // #2
8105/// S(S &&); // #3
8106/// };
8107/// \endcode
8108/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
8109AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
8110 return Node.isMoveConstructor();
8111}
8112
8113/// Matches constructor declarations that are default constructors.
8114///
8115/// Given
8116/// \code
8117/// struct S {
8118/// S(); // #1
8119/// S(const S &); // #2
8120/// S(S &&); // #3
8121/// };
8122/// \endcode
8123/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
8124AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
8125 return Node.isDefaultConstructor();
8126}
8127
8128/// Matches constructors that delegate to another constructor.
8129///
8130/// Given
8131/// \code
8132/// struct S {
8133/// S(); // #1
8134/// S(int) {} // #2
8135/// S(S &&) : S() {} // #3
8136/// };
8137/// S::S() : S(0) {} // #4
8138/// \endcode
8139/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
8140/// #1 or #2.
8141AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
8142 return Node.isDelegatingConstructor();
8143}
8144
8145/// Matches constructor, conversion function, and deduction guide declarations
8146/// that have an explicit specifier if this explicit specifier is resolved to
8147/// true.
8148///
8149/// Given
8150/// \code
8151/// template<bool b>
8152/// struct S {
8153/// S(int); // #1
8154/// explicit S(double); // #2
8155/// operator int(); // #3
8156/// explicit operator bool(); // #4
8157/// explicit(false) S(bool) // # 7
8158/// explicit(true) S(char) // # 8
8159/// explicit(b) S(S) // # 9
8160/// };
8161/// S(int) -> S<true> // #5
8162/// explicit S(double) -> S<false> // #6
8163/// \endcode
8164/// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
8165/// cxxConversionDecl(isExplicit()) will match #4, but not #3.
8166/// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
8168 CXXConstructorDecl, CXXConversionDecl,
8169 CXXDeductionGuideDecl)) {
8170 return Node.isExplicit();
8171}
8172
8173/// Matches the expression in an explicit specifier if present in the given
8174/// declaration.
8175///
8176/// Given
8177/// \code
8178/// template<bool b>
8179/// struct S {
8180/// S(int); // #1
8181/// explicit S(double); // #2
8182/// operator int(); // #3
8183/// explicit operator bool(); // #4
8184/// explicit(false) S(bool) // # 7
8185/// explicit(true) S(char) // # 8
8186/// explicit(b) S(S) // # 9
8187/// };
8188/// S(int) -> S<true> // #5
8189/// explicit S(double) -> S<false> // #6
8190/// \endcode
8191/// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
8192/// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
8193/// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
8194AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
8195 InnerMatcher) {
8196 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
8197 if (!ES.getExpr())
8198 return false;
8199
8200 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
8201
8202 return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
8203}
8204
8205/// Matches functions, variables and namespace declarations that are marked with
8206/// the inline keyword.
8207///
8208/// Given
8209/// \code
8210/// inline void f();
8211/// void g();
8212/// namespace n {
8213/// inline namespace m {}
8214/// }
8215/// inline int Foo = 5;
8216/// \endcode
8217/// functionDecl(isInline()) will match ::f().
8218/// namespaceDecl(isInline()) will match n::m.
8219/// varDecl(isInline()) will match Foo;
8221 FunctionDecl,
8222 VarDecl)) {
8223 // This is required because the spelling of the function used to determine
8224 // whether inline is specified or not differs between the polymorphic types.
8225 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
8226 return FD->isInlineSpecified();
8227 if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
8228 return NSD->isInline();
8229 if (const auto *VD = dyn_cast<VarDecl>(&Node))
8230 return VD->isInline();
8231 llvm_unreachable("Not a valid polymorphic type");
8232}
8233
8234/// Matches anonymous namespace declarations.
8235///
8236/// Given
8237/// \code
8238/// namespace n {
8239/// namespace {} // #1
8240/// }
8241/// \endcode
8242/// namespaceDecl(isAnonymous()) will match #1 but not ::n.
8243AST_MATCHER(NamespaceDecl, isAnonymous) {
8244 return Node.isAnonymousNamespace();
8245}
8246
8247/// Matches declarations in the namespace `std`, but not in nested namespaces.
8248///
8249/// Given
8250/// \code
8251/// class vector {};
8252/// namespace foo {
8253/// class vector {};
8254/// namespace std {
8255/// class vector {};
8256/// }
8257/// }
8258/// namespace std {
8259/// inline namespace __1 {
8260/// class vector {}; // #1
8261/// namespace experimental {
8262/// class vector {};
8263/// }
8264/// }
8265/// }
8266/// \endcode
8267/// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
8268AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
8269
8270/// Matches declarations in an anonymous namespace.
8271///
8272/// Given
8273/// \code
8274/// class vector {};
8275/// namespace foo {
8276/// class vector {};
8277/// namespace {
8278/// class vector {}; // #1
8279/// }
8280/// }
8281/// namespace {
8282/// class vector {}; // #2
8283/// namespace foo {
8284/// class vector{}; // #3
8285/// }
8286/// }
8287/// \endcode
8288/// cxxRecordDecl(hasName("vector"), isInAnonymousNamespace()) will match
8289/// #1, #2 and #3.
8290AST_MATCHER(Decl, isInAnonymousNamespace) {
8291 return Node.isInAnonymousNamespace();
8292}
8293
8294/// If the given case statement does not use the GNU case range
8295/// extension, matches the constant given in the statement.
8296///
8297/// Given
8298/// \code
8299/// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
8300/// \endcode
8301/// caseStmt(hasCaseConstant(integerLiteral()))
8302/// matches "case 1:"
8303AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
8304 InnerMatcher) {
8305 if (Node.getRHS())
8306 return false;
8307
8308 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
8309}
8310
8311/// Matches declaration that has a given attribute.
8312///
8313/// Given
8314/// \code
8315/// __attribute__((device)) void f() { ... }
8316/// \endcode
8317/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
8318/// f. If the matcher is used from clang-query, attr::Kind parameter should be
8319/// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
8320AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
8321 for (const auto *Attr : Node.attrs()) {
8322 if (Attr->getKind() == AttrKind)
8323 return true;
8324 }
8325 return false;
8326}
8327
8328/// Matches the return value expression of a return statement
8329///
8330/// Given
8331/// \code
8332/// return a + b;
8333/// \endcode
8334/// hasReturnValue(binaryOperator())
8335/// matches 'return a + b'
8336/// with binaryOperator()
8337/// matching 'a + b'
8338AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
8339 InnerMatcher) {
8340 if (const auto *RetValue = Node.getRetValue())
8341 return InnerMatcher.matches(*RetValue, Finder, Builder);
8342 return false;
8343}
8344
8345/// Matches CUDA kernel call expression.
8346///
8347/// Example matches,
8348/// \code
8349/// kernel<<<i,j>>>();
8350/// \endcode
8351extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
8353
8354/// Matches expressions that resolve to a null pointer constant, such as
8355/// GNU's __null, C++11's nullptr, or C's NULL macro.
8356///
8357/// Given:
8358/// \code
8359/// void *v1 = NULL;
8360/// void *v2 = nullptr;
8361/// void *v3 = __null; // GNU extension
8362/// char *cp = (char *)0;
8363/// int *ip = 0;
8364/// int i = 0;
8365/// \endcode
8366/// expr(nullPointerConstant())
8367/// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
8368/// initializer for i.
8369AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
8370 return anyOf(
8372 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
8373}
8374
8375/// Matches the DecompositionDecl the binding belongs to.
8376///
8377/// For example, in:
8378/// \code
8379/// void foo()
8380/// {
8381/// int arr[3];
8382/// auto &[f, s, t] = arr;
8383///
8384/// f = 42;
8385/// }
8386/// \endcode
8387/// The matcher:
8388/// \code
8389/// bindingDecl(hasName("f"),
8390/// forDecomposition(decompositionDecl())
8391/// \endcode
8392/// matches 'f' in 'auto &[f, s, t]'.
8393AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>,
8394 InnerMatcher) {
8395 if (const ValueDecl *VD = Node.getDecomposedDecl())
8396 return InnerMatcher.matches(*VD, Finder, Builder);
8397 return false;
8398}
8399
8400/// Matches the Nth binding of a DecompositionDecl.
8401///
8402/// For example, in:
8403/// \code
8404/// void foo()
8405/// {
8406/// int arr[3];
8407/// auto &[f, s, t] = arr;
8408///
8409/// f = 42;
8410/// }
8411/// \endcode
8412/// The matcher:
8413/// \code
8414/// decompositionDecl(hasBinding(0,
8415/// bindingDecl(hasName("f").bind("fBinding"))))
8416/// \endcode
8417/// matches the decomposition decl with 'f' bound to "fBinding".
8418AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N,
8419 internal::Matcher<BindingDecl>, InnerMatcher) {
8420 if (Node.bindings().size() <= N)
8421 return false;
8422 return InnerMatcher.matches(*Node.bindings()[N], Finder, Builder);
8423}
8424
8425/// Matches any binding of a DecompositionDecl.
8426///
8427/// For example, in:
8428/// \code
8429/// void foo()
8430/// {
8431/// int arr[3];
8432/// auto &[f, s, t] = arr;
8433///
8434/// f = 42;
8435/// }
8436/// \endcode
8437/// The matcher:
8438/// \code
8439/// decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding"))))
8440/// \endcode
8441/// matches the decomposition decl with 'f' bound to "fBinding".
8442AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>,
8443 InnerMatcher) {
8444 return llvm::any_of(Node.bindings(), [&](const auto *Binding) {
8445 return InnerMatcher.matches(*Binding, Finder, Builder);
8446 });
8447}
8448
8449/// Matches declaration of the function the statement belongs to.
8450///
8451/// Deprecated. Use forCallable() to correctly handle the situation when
8452/// the declaration is not a function (but a block or an Objective-C method).
8453/// forFunction() not only fails to take non-functions into account but also
8454/// may match the wrong declaration in their presence.
8455///
8456/// Given:
8457/// \code
8458/// F& operator=(const F& o) {
8459/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
8460/// return *this;
8461/// }
8462/// \endcode
8463/// returnStmt(forFunction(hasName("operator=")))
8464/// matches 'return *this'
8465/// but does not match 'return v > 0'
8466AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
8467 InnerMatcher) {
8468 const auto &Parents = Finder->getASTContext().getParents(Node);
8469
8470 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
8471 while (!Stack.empty()) {
8472 const auto &CurNode = Stack.back();
8473 Stack.pop_back();
8474 if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
8475 if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
8476 return true;
8477 }
8478 } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
8479 if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
8480 Builder)) {
8481 return true;
8482 }
8483 } else {
8484 llvm::append_range(Stack, Finder->getASTContext().getParents(CurNode));
8485 }
8486 }
8487 return false;
8488}
8489
8490/// Matches declaration of the function, method, or block the statement
8491/// belongs to.
8492///
8493/// Given:
8494/// \code
8495/// F& operator=(const F& o) {
8496/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
8497/// return *this;
8498/// }
8499/// \endcode
8500/// returnStmt(forCallable(functionDecl(hasName("operator="))))
8501/// matches 'return *this'
8502/// but does not match 'return v > 0'
8503///
8504/// Given:
8505/// \code
8506/// -(void) foo {
8507/// int x = 1;
8508/// dispatch_sync(queue, ^{ int y = 2; });
8509/// }
8510/// \endcode
8511/// declStmt(forCallable(objcMethodDecl()))
8512/// matches 'int x = 1'
8513/// but does not match 'int y = 2'.
8514/// whereas declStmt(forCallable(blockDecl()))
8515/// matches 'int y = 2'
8516/// but does not match 'int x = 1'.
8517AST_MATCHER_P(Stmt, forCallable, internal::Matcher<Decl>, InnerMatcher) {
8518 const auto &Parents = Finder->getASTContext().getParents(Node);
8519
8520 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
8521 while (!Stack.empty()) {
8522 const auto &CurNode = Stack.back();
8523 Stack.pop_back();
8524 if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
8525 BoundNodesTreeBuilder B = *Builder;
8526 if (InnerMatcher.matches(*FuncDeclNode, Finder, &B)) {
8527 *Builder = std::move(B);
8528 return true;
8529 }
8530 } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
8531 BoundNodesTreeBuilder B = *Builder;
8532 if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
8533 &B)) {
8534 *Builder = std::move(B);
8535 return true;
8536 }
8537 } else if (const auto *ObjCMethodDeclNode = CurNode.get<ObjCMethodDecl>()) {
8538 BoundNodesTreeBuilder B = *Builder;
8539 if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, &B)) {
8540 *Builder = std::move(B);
8541 return true;
8542 }
8543 } else if (const auto *BlockDeclNode = CurNode.get<BlockDecl>()) {
8544 BoundNodesTreeBuilder B = *Builder;
8545 if (InnerMatcher.matches(*BlockDeclNode, Finder, &B)) {
8546 *Builder = std::move(B);
8547 return true;
8548 }
8549 } else {
8550 llvm::append_range(Stack, Finder->getASTContext().getParents(CurNode));
8551 }
8552 }
8553 return false;
8554}
8555
8556/// Matches a declaration that has external formal linkage.
8557///
8558/// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
8559/// \code
8560/// void f() {
8561/// int x;
8562/// static int y;
8563/// }
8564/// int z;
8565/// \endcode
8566///
8567/// Example matches f() because it has external formal linkage despite being
8568/// unique to the translation unit as though it has internal linkage
8569/// (matcher = functionDecl(hasExternalFormalLinkage()))
8570///
8571/// \code
8572/// namespace {
8573/// void f() {}
8574/// }
8575/// \endcode
8576AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
8577 return Node.hasExternalFormalLinkage();
8578}
8579
8580/// Matches a declaration that has default arguments.
8581///
8582/// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
8583/// \code
8584/// void x(int val) {}
8585/// void y(int val = 0) {}
8586/// \endcode
8587///
8588/// Deprecated. Use hasInitializer() instead to be able to
8589/// match on the contents of the default argument. For example:
8590///
8591/// \code
8592/// void x(int val = 7) {}
8593/// void y(int val = 42) {}
8594/// \endcode
8595/// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
8596/// matches the parameter of y
8597///
8598/// A matcher such as
8599/// parmVarDecl(hasInitializer(anything()))
8600/// is equivalent to parmVarDecl(hasDefaultArgument()).
8601AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
8602 return Node.hasDefaultArg();
8603}
8604
8605/// Matches array new expressions.
8606///
8607/// Given:
8608/// \code
8609/// MyClass *p1 = new MyClass[10];
8610/// \endcode
8611/// cxxNewExpr(isArray())
8612/// matches the expression 'new MyClass[10]'.
8613AST_MATCHER(CXXNewExpr, isArray) {
8614 return Node.isArray();
8615}
8616
8617/// Matches placement new expression arguments.
8618///
8619/// Given:
8620/// \code
8621/// MyClass *p1 = new (Storage, 16) MyClass();
8622/// \endcode
8623/// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
8624/// matches the expression 'new (Storage, 16) MyClass()'.
8625AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
8626 internal::Matcher<Expr>, InnerMatcher) {
8627 return Node.getNumPlacementArgs() > Index &&
8628 InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
8629}
8630
8631/// Matches any placement new expression arguments.
8632///
8633/// Given:
8634/// \code
8635/// MyClass *p1 = new (Storage) MyClass();
8636/// \endcode
8637/// cxxNewExpr(hasAnyPlacementArg(anything()))
8638/// matches the expression 'new (Storage, 16) MyClass()'.
8639AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
8640 InnerMatcher) {
8641 return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
8642 return InnerMatcher.matches(*Arg, Finder, Builder);
8643 });
8644}
8645
8646/// Matches array new expressions with a given array size.
8647///
8648/// Given:
8649/// \code
8650/// MyClass *p1 = new MyClass[10];
8651/// \endcode
8652/// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
8653/// matches the expression 'new MyClass[10]'.
8654AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
8655 return Node.isArray() && *Node.getArraySize() &&
8656 InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
8657}
8658
8659/// Matches a class declaration that is defined.
8660///
8661/// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
8662/// \code
8663/// class x {};
8664/// class y;
8665/// \endcode
8666AST_MATCHER(CXXRecordDecl, hasDefinition) {
8667 return Node.hasDefinition();
8668}
8669
8670/// Matches C++11 scoped enum declaration.
8671///
8672/// Example matches Y (matcher = enumDecl(isScoped()))
8673/// \code
8674/// enum X {};
8675/// enum class Y {};
8676/// \endcode
8677AST_MATCHER(EnumDecl, isScoped) {
8678 return Node.isScoped();
8679}
8680
8681/// Matches a function declared with a trailing return type.
8682///
8683/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
8684/// \code
8685/// int X() {}
8686/// auto Y() -> int {}
8687/// \endcode
8688AST_MATCHER(FunctionDecl, hasTrailingReturn) {
8689 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
8690 return F->hasTrailingReturn();
8691 return false;
8692}
8693
8694/// Matches expressions that match InnerMatcher that are possibly wrapped in an
8695/// elidable constructor and other corresponding bookkeeping nodes.
8696///
8697/// In C++17, elidable copy constructors are no longer being generated in the
8698/// AST as it is not permitted by the standard. They are, however, part of the
8699/// AST in C++14 and earlier. So, a matcher must abstract over these differences
8700/// to work in all language modes. This matcher skips elidable constructor-call
8701/// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
8702/// various implicit nodes inside the constructor calls, all of which will not
8703/// appear in the C++17 AST.
8704///
8705/// Given
8706///
8707/// \code
8708/// struct H {};
8709/// H G();
8710/// void f() {
8711/// H D = G();
8712/// }
8713/// \endcode
8714///
8715/// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
8716/// matches ``H D = G()`` in C++11 through C++17 (and beyond).
8717AST_MATCHER_P(Expr, ignoringElidableConstructorCall, internal::Matcher<Expr>,
8718 InnerMatcher) {
8719 // E tracks the node that we are examining.
8720 const Expr *E = &Node;
8721 // If present, remove an outer `ExprWithCleanups` corresponding to the
8722 // underlying `CXXConstructExpr`. This check won't cover all cases of added
8723 // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
8724 // EWC is placed on the outermost node of the expression, which this may not
8725 // be), but, it still improves the coverage of this matcher.
8726 if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
8727 E = CleanupsExpr->getSubExpr();
8728 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
8729 if (CtorExpr->isElidable()) {
8730 if (const auto *MaterializeTemp =
8731 dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
8732 return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
8733 Builder);
8734 }
8735 }
8736 }
8737 return InnerMatcher.matches(Node, Finder, Builder);
8738}
8739
8740//----------------------------------------------------------------------------//
8741// OpenMP handling.
8742//----------------------------------------------------------------------------//
8743
8744/// Matches any ``#pragma omp`` executable directive.
8745///
8746/// Given
8747///
8748/// \code
8749/// #pragma omp parallel
8750/// #pragma omp parallel default(none)
8751/// #pragma omp taskyield
8752/// \endcode
8753///
8754/// ``ompExecutableDirective()`` matches ``omp parallel``,
8755/// ``omp parallel default(none)`` and ``omp taskyield``.
8756extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
8758
8759/// Matches standalone OpenMP directives,
8760/// i.e., directives that can't have a structured block.
8761///
8762/// Given
8763///
8764/// \code
8765/// #pragma omp parallel
8766/// {}
8767/// #pragma omp taskyield
8768/// \endcode
8769///
8770/// ``ompExecutableDirective(isStandaloneDirective()))`` matches
8771/// ``omp taskyield``.
8772AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
8773 return Node.isStandaloneDirective();
8774}
8775
8776/// Matches the structured-block of the OpenMP executable directive
8777///
8778/// Prerequisite: the executable directive must not be standalone directive.
8779/// If it is, it will never match.
8780///
8781/// Given
8782///
8783/// \code
8784/// #pragma omp parallel
8785/// ;
8786/// #pragma omp parallel
8787/// {}
8788/// \endcode
8789///
8790/// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
8791AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
8792 internal::Matcher<Stmt>, InnerMatcher) {
8793 if (Node.isStandaloneDirective())
8794 return false; // Standalone directives have no structured blocks.
8795 return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
8796}
8797
8798/// Matches any clause in an OpenMP directive.
8799///
8800/// Given
8801///
8802/// \code
8803/// #pragma omp parallel
8804/// #pragma omp parallel default(none)
8805/// \endcode
8806///
8807/// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
8808/// ``omp parallel default(none)``.
8809AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
8810 internal::Matcher<OMPClause>, InnerMatcher) {
8811 ArrayRef<OMPClause *> Clauses = Node.clauses();
8812 return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
8813 Clauses.end(), Finder,
8814 Builder) != Clauses.end();
8815}
8816
8817/// Matches any ``#pragma omp target update`` executable directive.
8818///
8819/// Given
8820///
8821/// \code
8822/// #pragma omp target update from(a)
8823/// #pragma omp target update to(b)
8824/// \endcode
8825///
8826/// ``ompTargetUpdateDirective()`` matches both ``omp target update from(a)``
8827/// and ``omp target update to(b)``.
8828extern const internal::VariadicDynCastAllOfMatcher<Stmt,
8829 OMPTargetUpdateDirective>
8831
8832/// Matches any ``#pragma omp split`` executable directive.
8833///
8834/// Given
8835///
8836/// \code
8837/// #pragma omp split counts(2, omp_fill)
8838/// for (int i = 0; i < n; ++i) {}
8839/// \endcode
8840///
8841/// ``ompSplitDirective()`` matches the split directive.
8842extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPSplitDirective>
8844
8845/// Matches OpenMP ``counts`` clause used by ``#pragma omp split``.
8846///
8847/// Given ``#pragma omp split counts(1, 2, omp_fill)``, ``ompCountsClause()``
8848/// matches the ``counts`` clause node.
8849extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPCountsClause>
8851
8852/// Matches OpenMP ``default`` clause.
8853///
8854/// Given
8855///
8856/// \code
8857/// #pragma omp parallel default(none)
8858/// #pragma omp parallel default(shared)
8859/// #pragma omp parallel default(private)
8860/// #pragma omp parallel default(firstprivate)
8861/// #pragma omp parallel
8862/// \endcode
8863///
8864/// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``,
8865/// `` default(private)`` and ``default(firstprivate)``
8866extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
8868
8869/// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
8870///
8871/// Given
8872///
8873/// \code
8874/// #pragma omp parallel
8875/// #pragma omp parallel default(none)
8876/// #pragma omp parallel default(shared)
8877/// #pragma omp parallel default(private)
8878/// #pragma omp parallel default(firstprivate)
8879/// \endcode
8880///
8881/// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
8882AST_MATCHER(OMPDefaultClause, isNoneKind) {
8883 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
8884}
8885
8886/// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
8887///
8888/// Given
8889///
8890/// \code
8891/// #pragma omp parallel
8892/// #pragma omp parallel default(none)
8893/// #pragma omp parallel default(shared)
8894/// #pragma omp parallel default(private)
8895/// #pragma omp parallel default(firstprivate)
8896/// \endcode
8897///
8898/// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
8899AST_MATCHER(OMPDefaultClause, isSharedKind) {
8900 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
8901}
8902
8903/// Matches if the OpenMP ``default`` clause has ``private`` kind
8904/// specified.
8905///
8906/// Given
8907///
8908/// \code
8909/// #pragma omp parallel
8910/// #pragma omp parallel default(none)
8911/// #pragma omp parallel default(shared)
8912/// #pragma omp parallel default(private)
8913/// #pragma omp parallel default(firstprivate)
8914/// \endcode
8915///
8916/// ``ompDefaultClause(isPrivateKind())`` matches only
8917/// ``default(private)``.
8918AST_MATCHER(OMPDefaultClause, isPrivateKind) {
8919 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_private;
8920}
8921
8922/// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
8923/// specified.
8924///
8925/// Given
8926///
8927/// \code
8928/// #pragma omp parallel
8929/// #pragma omp parallel default(none)
8930/// #pragma omp parallel default(shared)
8931/// #pragma omp parallel default(private)
8932/// #pragma omp parallel default(firstprivate)
8933/// \endcode
8934///
8935/// ``ompDefaultClause(isFirstPrivateKind())`` matches only
8936/// ``default(firstprivate)``.
8937AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
8938 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
8939}
8940
8941/// Matches if the OpenMP directive is allowed to contain the specified OpenMP
8942/// clause kind.
8943///
8944/// Given
8945///
8946/// \code
8947/// #pragma omp parallel
8948/// #pragma omp parallel for
8949/// #pragma omp for
8950/// \endcode
8951///
8952/// ``ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
8953/// ``omp parallel`` and ``omp parallel for``.
8954///
8955/// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
8956/// should be passed as a quoted string. e.g.,
8957/// ``isAllowedToContainClauseKind("OMPC_default").``
8958AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
8959 OpenMPClauseKind, CKind) {
8960 return llvm::omp::isAllowedClauseForDirective(
8961 Node.getDirectiveKind(), CKind,
8962 Finder->getASTContext().getLangOpts().OpenMP);
8963}
8964
8965/// Matches OpenMP ``from`` clause.
8966///
8967/// Given
8968///
8969/// \code
8970/// #pragma omp target update from(a)
8971/// \endcode
8972///
8973/// ``ompFromClause()`` matches ``from(a)``.
8974extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPFromClause>
8976
8977/// Matches OpenMP ``to`` clause.
8978///
8979/// Given
8980///
8981/// \code
8982/// #pragma omp target update to(a)
8983/// \endcode
8984///
8985/// ``ompToClause()`` matches ``to(a)``.
8986extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPToClause>
8988
8989//----------------------------------------------------------------------------//
8990// End OpenMP handling.
8991//----------------------------------------------------------------------------//
8992
8993} // namespace ast_matchers
8994} // namespace clang
8995
8996#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:4690
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:2372
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:3178
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
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:3531
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
A container of type source information.
Definition TypeBase.h:8416
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:3580
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:213
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:253
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:343
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:342
@ 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:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ 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