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