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 expressions that refer to dependent scope declarations.
2129///
2130/// example matches T::v;
2131/// \code
2132/// template <class T> class X : T { void f() { T::v; } };
2133/// \endcode
2134extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2137
2138/// Matches a reference to an ObjCIvar.
2139///
2140/// Example: matches "a" in "init" method:
2141/// \code
2142/// @implementation A {
2143/// NSString *a;
2144/// }
2145/// - (void) init {
2146/// a = @"hello";
2147/// }
2148/// \endcode
2149extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2151
2152/// Matches a reference to a block.
2153///
2154/// Example: matches "^{}":
2155/// \code
2156/// void f() { ^{}(); }
2157/// \endcode
2158extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2159
2160/// Matches if statements.
2161///
2162/// Example matches 'if (x) {}'
2163/// \code
2164/// if (x) {}
2165/// \endcode
2166extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2167
2168/// Matches for statements.
2169///
2170/// Example matches 'for (;;) {}'
2171/// \code
2172/// for (;;) {}
2173/// int i[] = {1, 2, 3}; for (auto a : i);
2174/// \endcode
2175extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2176
2177/// Matches the increment statement of a for loop.
2178///
2179/// Example:
2180/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2181/// matches '++x' in
2182/// \code
2183/// for (x; x < N; ++x) { }
2184/// \endcode
2185AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2186 InnerMatcher) {
2187 const Stmt *const Increment = Node.getInc();
2188 return (Increment != nullptr &&
2189 InnerMatcher.matches(*Increment, Finder, Builder));
2190}
2191
2192/// Matches the initialization statement of a for loop.
2193///
2194/// Example:
2195/// forStmt(hasLoopInit(declStmt()))
2196/// matches 'int x = 0' in
2197/// \code
2198/// for (int x = 0; x < N; ++x) { }
2199/// \endcode
2200AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2201 InnerMatcher) {
2202 const Stmt *const Init = Node.getInit();
2203 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2204}
2205
2206/// Matches range-based for statements.
2207///
2208/// cxxForRangeStmt() matches 'for (auto a : i)'
2209/// \code
2210/// int i[] = {1, 2, 3}; for (auto a : i);
2211/// for(int j = 0; j < 5; ++j);
2212/// \endcode
2213extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2215
2216/// Matches the initialization statement of a for loop.
2217///
2218/// Example:
2219/// forStmt(hasLoopVariable(anything()))
2220/// matches 'int x' in
2221/// \code
2222/// for (int x : a) { }
2223/// \endcode
2224AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2225 InnerMatcher) {
2226 const VarDecl *const Var = Node.getLoopVariable();
2227 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2228}
2229
2230/// Matches the range initialization statement of a for loop.
2231///
2232/// Example:
2233/// forStmt(hasRangeInit(anything()))
2234/// matches 'a' in
2235/// \code
2236/// for (int x : a) { }
2237/// \endcode
2238AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2239 InnerMatcher) {
2240 const Expr *const Init = Node.getRangeInit();
2241 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2242}
2243
2244/// Matches while statements.
2245///
2246/// Given
2247/// \code
2248/// while (true) {}
2249/// \endcode
2250/// whileStmt()
2251/// matches 'while (true) {}'.
2252extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2253
2254/// Matches do statements.
2255///
2256/// Given
2257/// \code
2258/// do {} while (true);
2259/// \endcode
2260/// doStmt()
2261/// matches 'do {} while(true)'
2262extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2263
2264/// Matches break statements.
2265///
2266/// Given
2267/// \code
2268/// while (true) { break; }
2269/// \endcode
2270/// breakStmt()
2271/// matches 'break'
2272extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2273
2274/// Matches continue statements.
2275///
2276/// Given
2277/// \code
2278/// while (true) { continue; }
2279/// \endcode
2280/// continueStmt()
2281/// matches 'continue'
2282extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2284
2285/// Matches co_return statements.
2286///
2287/// Given
2288/// \code
2289/// while (true) { co_return; }
2290/// \endcode
2291/// coreturnStmt()
2292/// matches 'co_return'
2293extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoreturnStmt>
2295
2296/// Matches return statements.
2297///
2298/// Given
2299/// \code
2300/// return 1;
2301/// \endcode
2302/// returnStmt()
2303/// matches 'return 1'
2304extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2305
2306/// Matches goto statements.
2307///
2308/// Given
2309/// \code
2310/// goto FOO;
2311/// FOO: bar();
2312/// \endcode
2313/// gotoStmt()
2314/// matches 'goto FOO'
2315extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2316
2317/// Matches label statements.
2318///
2319/// Given
2320/// \code
2321/// goto FOO;
2322/// FOO: bar();
2323/// \endcode
2324/// labelStmt()
2325/// matches 'FOO:'
2326extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2327
2328/// Matches address of label statements (GNU extension).
2329///
2330/// Given
2331/// \code
2332/// FOO: bar();
2333/// void *ptr = &&FOO;
2334/// goto *bar;
2335/// \endcode
2336/// addrLabelExpr()
2337/// matches '&&FOO'
2338extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2340
2341/// Matches switch statements.
2342///
2343/// Given
2344/// \code
2345/// switch(a) { case 42: break; default: break; }
2346/// \endcode
2347/// switchStmt()
2348/// matches 'switch(a)'.
2349extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2350
2351/// Matches case and default statements inside switch statements.
2352///
2353/// Given
2354/// \code
2355/// switch(a) { case 42: break; default: break; }
2356/// \endcode
2357/// switchCase()
2358/// matches 'case 42:' and 'default:'.
2359extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2360
2361/// Matches case statements inside switch statements.
2362///
2363/// Given
2364/// \code
2365/// switch(a) { case 42: break; default: break; }
2366/// \endcode
2367/// caseStmt()
2368/// matches 'case 42:'.
2369extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2370
2371/// Matches default statements inside switch statements.
2372///
2373/// Given
2374/// \code
2375/// switch(a) { case 42: break; default: break; }
2376/// \endcode
2377/// defaultStmt()
2378/// matches 'default:'.
2379extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2381
2382/// Matches compound statements.
2383///
2384/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2385/// \code
2386/// for (;;) {{}}
2387/// \endcode
2388extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2390
2391/// Matches catch statements.
2392///
2393/// \code
2394/// try {} catch(int i) {}
2395/// \endcode
2396/// cxxCatchStmt()
2397/// matches 'catch(int i)'
2398extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2400
2401/// Matches try statements.
2402///
2403/// \code
2404/// try {} catch(int i) {}
2405/// \endcode
2406/// cxxTryStmt()
2407/// matches 'try {}'
2408extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2409
2410/// Matches throw expressions.
2411///
2412/// \code
2413/// try { throw 5; } catch(int i) {}
2414/// \endcode
2415/// cxxThrowExpr()
2416/// matches 'throw 5'
2417extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2419
2420/// Matches null statements.
2421///
2422/// \code
2423/// foo();;
2424/// \endcode
2425/// nullStmt()
2426/// matches the second ';'
2427extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2428
2429/// Matches asm statements.
2430///
2431/// \code
2432/// int i = 100;
2433/// __asm("mov al, 2");
2434/// \endcode
2435/// asmStmt()
2436/// matches '__asm("mov al, 2")'
2437extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2438
2439/// Matches bool literals.
2440///
2441/// Example matches true
2442/// \code
2443/// true
2444/// \endcode
2445extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2447
2448/// Matches string literals (also matches wide string literals).
2449///
2450/// Example matches "abcd", L"abcd"
2451/// \code
2452/// char *s = "abcd";
2453/// wchar_t *ws = L"abcd";
2454/// \endcode
2455extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2457
2458/// Matches character literals (also matches wchar_t).
2459///
2460/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2461/// though.
2462///
2463/// Example matches 'a', L'a'
2464/// \code
2465/// char ch = 'a';
2466/// wchar_t chw = L'a';
2467/// \endcode
2468extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2470
2471/// Matches integer literals of all sizes / encodings, e.g.
2472/// 1, 1L, 0x1 and 1U.
2473///
2474/// Does not match character-encoded integers such as L'a'.
2475extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2477
2478/// Matches float literals of all sizes / encodings, e.g.
2479/// 1.0, 1.0f, 1.0L and 1e10.
2480///
2481/// Does not match implicit conversions such as
2482/// \code
2483/// float a = 10;
2484/// \endcode
2485extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2487
2488/// Matches imaginary literals, which are based on integer and floating
2489/// point literals e.g.: 1i, 1.0i
2490extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2492
2493/// Matches fixed point literals
2494extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2496
2497/// Matches user defined literal operator call.
2498///
2499/// Example match: "foo"_suffix
2500extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2502
2503/// Matches compound (i.e. non-scalar) literals
2504///
2505/// Example match: {1}, (1, 2)
2506/// \code
2507/// int array[4] = {1};
2508/// vector int myvec = (vector int)(1, 2);
2509/// \endcode
2510extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2512
2513/// Matches co_await expressions.
2514///
2515/// Given
2516/// \code
2517/// co_await 1;
2518/// \endcode
2519/// coawaitExpr()
2520/// matches 'co_await 1'
2521extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoawaitExpr>
2523/// Matches co_await expressions where the type of the promise is dependent
2524extern const internal::VariadicDynCastAllOfMatcher<Stmt, DependentCoawaitExpr>
2526/// Matches co_yield expressions.
2527///
2528/// Given
2529/// \code
2530/// co_yield 1;
2531/// \endcode
2532/// coyieldExpr()
2533/// matches 'co_yield 1'
2534extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoyieldExpr>
2536
2537/// Matches coroutine body statements.
2538///
2539/// coroutineBodyStmt() matches the coroutine below
2540/// \code
2541/// generator<int> gen() {
2542/// co_return;
2543/// }
2544/// \endcode
2545extern const internal::VariadicDynCastAllOfMatcher<Stmt, CoroutineBodyStmt>
2547
2548/// Matches nullptr literal.
2549extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2551
2552/// Matches GNU __builtin_choose_expr.
2553extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2554 chooseExpr;
2555
2556/// Matches builtin function __builtin_convertvector.
2557extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConvertVectorExpr>
2559
2560/// Matches GNU __null expression.
2561extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2563
2564/// Matches C11 _Generic expression.
2565extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2567
2568/// Matches atomic builtins.
2569/// Example matches __atomic_load_n(ptr, 1)
2570/// \code
2571/// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2572/// \endcode
2573extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2574
2575/// Matches statement expression (GNU extension).
2576///
2577/// Example match: ({ int X = 4; X; })
2578/// \code
2579/// int C = ({ int X = 4; X; });
2580/// \endcode
2581extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2582
2583/// Matches binary operator expressions.
2584///
2585/// Example matches a || b
2586/// \code
2587/// !(a || b)
2588/// \endcode
2589/// See also the binaryOperation() matcher for more-general matching.
2590extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2592
2593/// Matches unary operator expressions.
2594///
2595/// Example matches !a
2596/// \code
2597/// !a || b
2598/// \endcode
2599extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2601
2602/// Matches conditional operator expressions.
2603///
2604/// Example matches a ? b : c
2605/// \code
2606/// (a ? b : c) + 42
2607/// \endcode
2608extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2610
2611/// Matches binary conditional operator expressions (GNU extension).
2612///
2613/// Example matches a ?: b
2614/// \code
2615/// (a ?: b) + 42;
2616/// \endcode
2617extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2620
2621/// Matches opaque value expressions. They are used as helpers
2622/// to reference another expressions and can be met
2623/// in BinaryConditionalOperators, for example.
2624///
2625/// Example matches 'a'
2626/// \code
2627/// (a ?: c) + 42;
2628/// \endcode
2629extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2631
2632/// Matches a C++ static_assert declaration.
2633///
2634/// Example:
2635/// staticAssertDecl()
2636/// matches
2637/// static_assert(sizeof(S) == sizeof(int))
2638/// in
2639/// \code
2640/// struct S {
2641/// int x;
2642/// };
2643/// static_assert(sizeof(S) == sizeof(int));
2644/// \endcode
2645extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2647
2648/// Matches a reinterpret_cast expression.
2649///
2650/// Either the source expression or the destination type can be matched
2651/// using has(), but hasDestinationType() is more specific and can be
2652/// more readable.
2653///
2654/// Example matches reinterpret_cast<char*>(&p) in
2655/// \code
2656/// void* p = reinterpret_cast<char*>(&p);
2657/// \endcode
2658extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2660
2661/// Matches a C++ static_cast expression.
2662///
2663/// \see hasDestinationType
2664/// \see reinterpretCast
2665///
2666/// Example:
2667/// cxxStaticCastExpr()
2668/// matches
2669/// static_cast<long>(8)
2670/// in
2671/// \code
2672/// long eight(static_cast<long>(8));
2673/// \endcode
2674extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2676
2677/// Matches a dynamic_cast expression.
2678///
2679/// Example:
2680/// cxxDynamicCastExpr()
2681/// matches
2682/// dynamic_cast<D*>(&b);
2683/// in
2684/// \code
2685/// struct B { virtual ~B() {} }; struct D : B {};
2686/// B b;
2687/// D* p = dynamic_cast<D*>(&b);
2688/// \endcode
2689extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2691
2692/// Matches a const_cast expression.
2693///
2694/// Example: Matches const_cast<int*>(&r) in
2695/// \code
2696/// int n = 42;
2697/// const int &r(n);
2698/// int* p = const_cast<int*>(&r);
2699/// \endcode
2700extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2702
2703/// Matches a C-style cast expression.
2704///
2705/// Example: Matches (int) 2.2f in
2706/// \code
2707/// int i = (int) 2.2f;
2708/// \endcode
2709extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2711
2712/// Matches explicit cast expressions.
2713///
2714/// Matches any cast expression written in user code, whether it be a
2715/// C-style cast, a functional-style cast, or a keyword cast.
2716///
2717/// Does not match implicit conversions.
2718///
2719/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2720/// Clang uses the term "cast" to apply to implicit conversions as well as to
2721/// actual cast expressions.
2722///
2723/// \see hasDestinationType.
2724///
2725/// Example: matches all five of the casts in
2726/// \code
2727/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2728/// \endcode
2729/// but does not match the implicit conversion in
2730/// \code
2731/// long ell = 42;
2732/// \endcode
2733extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2735
2736/// Matches the implicit cast nodes of Clang's AST.
2737///
2738/// This matches many different places, including function call return value
2739/// eliding, as well as any type conversions.
2740extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2742
2743/// Matches any cast nodes of Clang's AST.
2744///
2745/// Example: castExpr() matches each of the following:
2746/// \code
2747/// (int) 3;
2748/// const_cast<Expr *>(SubExpr);
2749/// char c = 0;
2750/// \endcode
2751/// but does not match
2752/// \code
2753/// int i = (0);
2754/// int k = 0;
2755/// \endcode
2756extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2757
2758/// Matches functional cast expressions
2759///
2760/// Example: Matches Foo(bar);
2761/// \code
2762/// Foo f = bar;
2763/// Foo g = (Foo) bar;
2764/// Foo h = Foo(bar);
2765/// \endcode
2766extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2768
2769/// Matches functional cast expressions having N != 1 arguments
2770///
2771/// Example: Matches Foo(bar, bar)
2772/// \code
2773/// Foo h = Foo(bar, bar);
2774/// \endcode
2775extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2777
2778/// Matches predefined identifier expressions [C99 6.4.2.2].
2779///
2780/// Example: Matches __func__
2781/// \code
2782/// printf("%s", __func__);
2783/// \endcode
2784extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2786
2787/// Matches C99 designated initializer expressions [C99 6.7.8].
2788///
2789/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2790/// \code
2791/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2792/// \endcode
2793extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2795
2796/// Matches designated initializer expressions that contain
2797/// a specific number of designators.
2798///
2799/// Example: Given
2800/// \code
2801/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2802/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2803/// \endcode
2804/// designatorCountIs(2)
2805/// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2806/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2807AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2808 return Node.size() == N;
2809}
2810
2811/// Matches \c QualTypes in the clang AST.
2812extern const internal::VariadicAllOfMatcher<QualType> qualType;
2813
2814/// Matches \c Types in the clang AST.
2815extern const internal::VariadicAllOfMatcher<Type> type;
2816
2817/// Matches \c TypeLocs in the clang AST.
2818extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2819
2820/// Matches if any of the given matchers matches.
2821///
2822/// Unlike \c anyOf, \c eachOf will generate a match result for each
2823/// matching submatcher.
2824///
2825/// For example, in:
2826/// \code
2827/// class A { int a; int b; };
2828/// \endcode
2829/// The matcher:
2830/// \code
2831/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2832/// has(fieldDecl(hasName("b")).bind("v"))))
2833/// \endcode
2834/// will generate two results binding "v", the first of which binds
2835/// the field declaration of \c a, the second the field declaration of
2836/// \c b.
2837///
2838/// Usable as: Any Matcher
2839extern const internal::VariadicOperatorMatcherFunc<
2840 2, std::numeric_limits<unsigned>::max()>
2841 eachOf;
2842
2843/// Matches if any of the given matchers matches.
2844///
2845/// Usable as: Any Matcher
2846extern const internal::VariadicOperatorMatcherFunc<
2847 2, std::numeric_limits<unsigned>::max()>
2848 anyOf;
2849
2850/// Matches if all given matchers match.
2851///
2852/// Usable as: Any Matcher
2853extern const internal::VariadicOperatorMatcherFunc<
2854 2, std::numeric_limits<unsigned>::max()>
2855 allOf;
2856
2857/// Matches any node regardless of the submatcher.
2858///
2859/// However, \c optionally will retain any bindings generated by the submatcher.
2860/// Useful when additional information which may or may not present about a main
2861/// matching node is desired.
2862///
2863/// For example, in:
2864/// \code
2865/// class Foo {
2866/// int bar;
2867/// }
2868/// \endcode
2869/// The matcher:
2870/// \code
2871/// cxxRecordDecl(
2872/// optionally(has(
2873/// fieldDecl(hasName("bar")).bind("var")
2874/// ))).bind("record")
2875/// \endcode
2876/// will produce a result binding for both "record" and "var".
2877/// The matcher will produce a "record" binding for even if there is no data
2878/// member named "bar" in that class.
2879///
2880/// Usable as: Any Matcher
2881extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2882
2883/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2884///
2885/// Given
2886/// \code
2887/// Foo x = bar;
2888/// int y = sizeof(x) + alignof(x);
2889/// \endcode
2890/// unaryExprOrTypeTraitExpr()
2891/// matches \c sizeof(x) and \c alignof(x)
2892extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2895
2896/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2897///
2898/// Given
2899/// \code
2900/// if (true);
2901/// for (; true; );
2902/// \endcode
2903/// with the matcher
2904/// \code
2905/// mapAnyOf(ifStmt, forStmt).with(
2906/// hasCondition(cxxBoolLiteralExpr(equals(true)))
2907/// ).bind("trueCond")
2908/// \endcode
2909/// matches the \c if and the \c for. It is equivalent to:
2910/// \code
2911/// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2912/// anyOf(
2913/// ifStmt(trueCond).bind("trueCond"),
2914/// forStmt(trueCond).bind("trueCond")
2915/// );
2916/// \endcode
2917///
2918/// The with() chain-call accepts zero or more matchers which are combined
2919/// as-if with allOf() in each of the node matchers.
2920/// Usable as: Any Matcher
2921template <typename T, typename... U>
2922auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2923 return internal::MapAnyOfHelper<U...>();
2924}
2925
2926/// Matches nodes which can be used with binary operators.
2927///
2928/// The code
2929/// \code
2930/// var1 != var2;
2931/// \endcode
2932/// might be represented in the clang AST as a binaryOperator, a
2933/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2934///
2935/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2936/// least one is a class type (cxxOperatorCallExpr)
2937/// * whether the code appears in a template declaration, if at least one of the
2938/// vars is a dependent-type (binaryOperator)
2939/// * whether the code relies on a rewritten binary operator, such as a
2940/// spaceship operator or an inverted equality operator
2941/// (cxxRewrittenBinaryOperator)
2942///
2943/// This matcher elides details in places where the matchers for the nodes are
2944/// compatible.
2945///
2946/// Given
2947/// \code
2948/// binaryOperation(
2949/// hasOperatorName("!="),
2950/// hasLHS(expr().bind("lhs")),
2951/// hasRHS(expr().bind("rhs"))
2952/// )
2953/// \endcode
2954/// matches each use of "!=" in:
2955/// \code
2956/// struct S{
2957/// bool operator!=(const S&) const;
2958/// };
2959///
2960/// void foo()
2961/// {
2962/// 1 != 2;
2963/// S() != S();
2964/// }
2965///
2966/// template<typename T>
2967/// void templ()
2968/// {
2969/// 1 != 2;
2970/// T() != S();
2971/// }
2972/// struct HasOpEq
2973/// {
2974/// bool operator==(const HasOpEq &) const;
2975/// };
2976///
2977/// void inverse()
2978/// {
2979/// HasOpEq s1;
2980/// HasOpEq s2;
2981/// if (s1 != s2)
2982/// return;
2983/// }
2984///
2985/// struct HasSpaceship
2986/// {
2987/// bool operator<=>(const HasOpEq &) const;
2988/// };
2989///
2990/// void use_spaceship()
2991/// {
2992/// HasSpaceship s1;
2993/// HasSpaceship s2;
2994/// if (s1 != s2)
2995/// return;
2996/// }
2997/// \endcode
2998extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
3001
3002/// Matches function calls and constructor calls
3003///
3004/// Because CallExpr and CXXConstructExpr do not share a common
3005/// base class with API accessing arguments etc, AST Matchers for code
3006/// which should match both are typically duplicated. This matcher
3007/// removes the need for duplication.
3008///
3009/// Given code
3010/// \code
3011/// struct ConstructorTakesInt
3012/// {
3013/// ConstructorTakesInt(int i) {}
3014/// };
3015///
3016/// void callTakesInt(int i)
3017/// {
3018/// }
3019///
3020/// void doCall()
3021/// {
3022/// callTakesInt(42);
3023/// }
3024///
3025/// void doConstruct()
3026/// {
3027/// ConstructorTakesInt cti(42);
3028/// }
3029/// \endcode
3030///
3031/// The matcher
3032/// \code
3033/// invocation(hasArgument(0, integerLiteral(equals(42))))
3034/// \endcode
3035/// matches the expression in both doCall and doConstruct
3036extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation;
3037
3038/// Matches unary expressions that have a specific type of argument.
3039///
3040/// Given
3041/// \code
3042/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
3043/// \endcode
3044/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
3045/// matches \c sizeof(a) and \c alignof(c)
3047 internal::Matcher<QualType>, InnerMatcher) {
3048 const QualType ArgumentType = Node.getTypeOfArgument();
3049 return InnerMatcher.matches(ArgumentType, Finder, Builder);
3050}
3051
3052/// Matches unary expressions of a certain kind.
3053///
3054/// Given
3055/// \code
3056/// int x;
3057/// int s = sizeof(x) + alignof(x)
3058/// \endcode
3059/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
3060/// matches \c sizeof(x)
3061///
3062/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
3063/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
3065 return Node.getKind() == Kind;
3066}
3067
3068/// Same as unaryExprOrTypeTraitExpr, but only matching
3069/// alignof.
3070inline internal::BindableMatcher<Stmt> alignOfExpr(
3071 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3073 allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
3074 InnerMatcher)));
3075}
3076
3077/// Same as unaryExprOrTypeTraitExpr, but only matching
3078/// sizeof.
3079inline internal::BindableMatcher<Stmt> sizeOfExpr(
3080 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
3082 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
3083}
3084
3085/// Matches NamedDecl nodes that have the specified name.
3086///
3087/// Supports specifying enclosing namespaces or classes by prefixing the name
3088/// with '<enclosing>::'.
3089/// Does not match typedefs of an underlying type with the given name.
3090///
3091/// Example matches X (Name == "X")
3092/// \code
3093/// class X;
3094/// \endcode
3095///
3096/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
3097/// \code
3098/// namespace a { namespace b { class X; } }
3099/// \endcode
3100inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
3101 return internal::Matcher<NamedDecl>(
3102 new internal::HasNameMatcher({std::string(Name)}));
3103}
3104
3105/// Matches NamedDecl nodes that have any of the specified names.
3106///
3107/// This matcher is only provided as a performance optimization of hasName.
3108/// \code
3109/// hasAnyName(a, b, c)
3110/// \endcode
3111/// is equivalent to, but faster than
3112/// \code
3113/// anyOf(hasName(a), hasName(b), hasName(c))
3114/// \endcode
3115extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
3117 hasAnyName;
3118
3119/// Matches NamedDecl nodes whose fully qualified names contain
3120/// a substring matched by the given RegExp.
3121///
3122/// Supports specifying enclosing namespaces or classes by
3123/// prefixing the name with '<enclosing>::'. Does not match typedefs
3124/// of an underlying type with the given name.
3125///
3126/// Example matches X (regexp == "::X")
3127/// \code
3128/// class X;
3129/// \endcode
3130///
3131/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
3132/// \code
3133/// namespace foo { namespace bar { class X; } }
3134/// \endcode
3135AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
3136 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
3137 return RegExp->match(FullNameString);
3138}
3139
3140/// Matches overloaded operator names.
3141///
3142/// Matches overloaded operator names specified in strings without the
3143/// "operator" prefix: e.g. "<<".
3144///
3145/// Given:
3146/// \code
3147/// class A { int operator*(); };
3148/// const A &operator<<(const A &a, const A &b);
3149/// A a;
3150/// a << a; // <-- This matches
3151/// \endcode
3152///
3153/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
3154/// specified line and
3155/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
3156/// matches the declaration of \c A.
3157///
3158/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
3159inline internal::PolymorphicMatcher<
3160 internal::HasOverloadedOperatorNameMatcher,
3162 std::vector<std::string>>
3164 return internal::PolymorphicMatcher<
3165 internal::HasOverloadedOperatorNameMatcher,
3167 std::vector<std::string>>({std::string(Name)});
3168}
3169
3170/// Matches overloaded operator names.
3171///
3172/// Matches overloaded operator names specified in strings without the
3173/// "operator" prefix: e.g. "<<".
3174///
3175/// hasAnyOverloadedOperatorName("+", "-")
3176/// Is equivalent to
3177/// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
3178extern const internal::VariadicFunction<
3179 internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher,
3182 std::vector<std::string>>,
3185
3186/// Matches template-dependent, but known, member names.
3187///
3188/// In template declarations, dependent members are not resolved and so can
3189/// not be matched to particular named declarations.
3190///
3191/// This matcher allows to match on the known name of members.
3192///
3193/// Given
3194/// \code
3195/// template <typename T>
3196/// struct S {
3197/// void mem();
3198/// };
3199/// template <typename T>
3200/// void x() {
3201/// S<T> s;
3202/// s.mem();
3203/// }
3204/// \endcode
3205/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
3206AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
3207 return Node.getMember().getAsString() == N;
3208}
3209
3210/// Matches template-dependent, but known, member names against an already-bound
3211/// node
3212///
3213/// In template declarations, dependent members are not resolved and so can
3214/// not be matched to particular named declarations.
3215///
3216/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3217/// and CXXMethodDecl nodes.
3218///
3219/// Given
3220/// \code
3221/// template <typename T>
3222/// struct S {
3223/// void mem();
3224/// };
3225/// template <typename T>
3226/// void x() {
3227/// S<T> s;
3228/// s.mem();
3229/// }
3230/// \endcode
3231/// The matcher
3232/// @code
3233/// \c cxxDependentScopeMemberExpr(
3234/// hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3235/// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3236/// cxxMethodDecl(hasName("mem")).bind("templMem")
3237/// )))))
3238/// )))),
3239/// memberHasSameNameAsBoundNode("templMem")
3240/// )
3241/// @endcode
3242/// first matches and binds the @c mem member of the @c S template, then
3243/// compares its name to the usage in @c s.mem() in the @c x function template
3244AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3245 std::string, BindingID) {
3246 auto MemberName = Node.getMember().getAsString();
3247
3248 return Builder->removeBindings(
3249 [this, MemberName](const BoundNodesMap &Nodes) {
3250 const DynTypedNode &BN = Nodes.getNode(this->BindingID);
3251 if (const auto *ND = BN.get<NamedDecl>()) {
3252 if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3253 return true;
3254 return ND->getName() != MemberName;
3255 }
3256 return true;
3257 });
3258}
3259
3260/// Matches the dependent name of a DependentScopeDeclRefExpr
3261///
3262/// Given:
3263/// \code
3264/// template <class T> class X : T { void f() { T::v; } };
3265/// \endcode
3266/// \c dependentScopeDeclRefExpr(hasDependentName("v")) matches `T::v`
3267AST_MATCHER_P(DependentScopeDeclRefExpr, hasDependentName, std::string, N) {
3268 return Node.getDeclName().getAsString() == N;
3269}
3270
3271/// Matches C++ classes that are directly or indirectly derived from a class
3272/// matching \c Base, or Objective-C classes that directly or indirectly
3273/// subclass a class matching \c Base.
3274///
3275/// Note that a class is not considered to be derived from itself.
3276///
3277/// Example matches Y, Z, C (Base == hasName("X"))
3278/// \code
3279/// class X;
3280/// class Y : public X {}; // directly derived
3281/// class Z : public Y {}; // indirectly derived
3282/// typedef X A;
3283/// typedef A B;
3284/// class C : public B {}; // derived from a typedef of X
3285/// \endcode
3286///
3287/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3288/// \code
3289/// class Foo;
3290/// typedef Foo X;
3291/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3292/// \endcode
3293///
3294/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3295/// \code
3296/// @interface NSObject @end
3297/// @interface Bar : NSObject @end
3298/// \endcode
3299///
3300/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3302 isDerivedFrom,
3304 internal::Matcher<NamedDecl>, Base) {
3305 // Check if the node is a C++ struct/union/class.
3306 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3307 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3308
3309 // The node must be an Objective-C class.
3310 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3311 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3312 /*Directly=*/false);
3313}
3314
3315/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3317 isDerivedFrom,
3319 std::string, BaseName, 1) {
3320 if (BaseName.empty())
3321 return false;
3322
3323 const auto M = isDerivedFrom(hasName(BaseName));
3324
3325 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3326 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3327
3328 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3329 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3330}
3331
3332/// Matches C++ classes that have a direct or indirect base matching \p
3333/// BaseSpecMatcher.
3334///
3335/// Example:
3336/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3337/// \code
3338/// class Foo;
3339/// class Bar : Foo {};
3340/// class Baz : Bar {};
3341/// class SpecialBase;
3342/// class Proxy : SpecialBase {}; // matches Proxy
3343/// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived
3344/// \endcode
3345///
3346// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3347AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3348 BaseSpecMatcher) {
3349 return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3350}
3351
3352/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3353///
3354/// Example:
3355/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3356/// \code
3357/// class Foo;
3358/// class Bar : Foo {};
3359/// class Baz : Bar {};
3360/// class SpecialBase;
3361/// class Proxy : SpecialBase {}; // matches Proxy
3362/// class IndirectlyDerived : Proxy {}; // doesn't match
3363/// \endcode
3364AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3365 BaseSpecMatcher) {
3366 return Node.hasDefinition() &&
3367 llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) {
3368 return BaseSpecMatcher.matches(Base, Finder, Builder);
3369 });
3370}
3371
3372/// Similar to \c isDerivedFrom(), but also matches classes that directly
3373/// match \c Base.
3375 isSameOrDerivedFrom,
3377 internal::Matcher<NamedDecl>, Base, 0) {
3378 const auto M = anyOf(Base, isDerivedFrom(Base));
3379
3380 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3381 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3382
3383 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3384 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3385}
3386
3387/// Overloaded method as shortcut for
3388/// \c isSameOrDerivedFrom(hasName(...)).
3390 isSameOrDerivedFrom,
3392 std::string, BaseName, 1) {
3393 if (BaseName.empty())
3394 return false;
3395
3396 const auto M = isSameOrDerivedFrom(hasName(BaseName));
3397
3398 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3399 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3400
3401 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3402 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3403}
3404
3405/// Matches C++ or Objective-C classes that are directly derived from a class
3406/// matching \c Base.
3407///
3408/// Note that a class is not considered to be derived from itself.
3409///
3410/// Example matches Y, C (Base == hasName("X"))
3411/// \code
3412/// class X;
3413/// class Y : public X {}; // directly derived
3414/// class Z : public Y {}; // indirectly derived
3415/// typedef X A;
3416/// typedef A B;
3417/// class C : public B {}; // derived from a typedef of X
3418/// \endcode
3419///
3420/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3421/// \code
3422/// class Foo;
3423/// typedef Foo X;
3424/// class Bar : public Foo {}; // derived from a type that X is a typedef of
3425/// \endcode
3427 isDirectlyDerivedFrom,
3429 internal::Matcher<NamedDecl>, Base, 0) {
3430 // Check if the node is a C++ struct/union/class.
3431 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3432 return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3433
3434 // The node must be an Objective-C class.
3435 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3436 return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3437 /*Directly=*/true);
3438}
3439
3440/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3442 isDirectlyDerivedFrom,
3444 std::string, BaseName, 1) {
3445 if (BaseName.empty())
3446 return false;
3447 const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3448
3449 if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3450 return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3451
3452 const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3453 return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3454}
3455/// Matches the first method of a class or struct that satisfies \c
3456/// InnerMatcher.
3457///
3458/// Given:
3459/// \code
3460/// class A { void func(); };
3461/// class B { void member(); };
3462/// \endcode
3463///
3464/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3465/// \c A but not \c B.
3466AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3467 InnerMatcher) {
3468 BoundNodesTreeBuilder Result(*Builder);
3469 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3470 Node.method_end(), Finder, &Result);
3471 if (MatchIt == Node.method_end())
3472 return false;
3473
3474 if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit())
3475 return false;
3476 *Builder = std::move(Result);
3477 return true;
3478}
3479
3480/// Matches the generated class of lambda expressions.
3481///
3482/// Given:
3483/// \code
3484/// auto x = []{};
3485/// \endcode
3486///
3487/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3488/// \c decltype(x)
3490 return Node.isLambda();
3491}
3492
3493/// Matches AST nodes that have child AST nodes that match the
3494/// provided matcher.
3495///
3496/// Example matches X, Y
3497/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3498/// \code
3499/// class X {}; // Matches X, because X::X is a class of name X inside X.
3500/// class Y { class X {}; };
3501/// class Z { class Y { class X {}; }; }; // Does not match Z.
3502/// \endcode
3503///
3504/// ChildT must be an AST base type.
3505///
3506/// Usable as: Any Matcher
3507/// Note that has is direct matcher, so it also matches things like implicit
3508/// casts and paren casts. If you are matching with expr then you should
3509/// probably consider using ignoringParenImpCasts like:
3510/// has(ignoringParenImpCasts(expr())).
3511extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3512
3513/// Matches AST nodes that have descendant AST nodes that match the
3514/// provided matcher.
3515///
3516/// Example matches X, Y, Z
3517/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3518/// \code
3519/// class X {}; // Matches X, because X::X is a class of name X inside X.
3520/// class Y { class X {}; };
3521/// class Z { class Y { class X {}; }; };
3522/// \endcode
3523///
3524/// DescendantT must be an AST base type.
3525///
3526/// Usable as: Any Matcher
3527extern const internal::ArgumentAdaptingMatcherFunc<
3528 internal::HasDescendantMatcher>
3530
3531/// Matches AST nodes that have child AST nodes that match the
3532/// provided matcher.
3533///
3534/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3535/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3536/// \code
3537/// class X {};
3538/// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
3539/// // inside Y.
3540/// class Z { class Y { class X {}; }; }; // Does not match Z.
3541/// \endcode
3542///
3543/// ChildT must be an AST base type.
3544///
3545/// As opposed to 'has', 'forEach' will cause a match for each result that
3546/// matches instead of only on the first one.
3547///
3548/// Usable as: Any Matcher
3549extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3550 forEach;
3551
3552/// Matches AST nodes that have descendant AST nodes that match the
3553/// provided matcher.
3554///
3555/// Example matches X, A, A::X, B, B::C, B::C::X
3556/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3557/// \code
3558/// class X {};
3559/// class A { class X {}; }; // Matches A, because A::X is a class of name
3560/// // X inside A.
3561/// class B { class C { class X {}; }; };
3562/// \endcode
3563///
3564/// DescendantT must be an AST base type.
3565///
3566/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3567/// each result that matches instead of only on the first one.
3568///
3569/// Note: Recursively combined ForEachDescendant can cause many matches:
3570/// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3571/// forEachDescendant(cxxRecordDecl())
3572/// )))
3573/// will match 10 times (plus injected class name matches) on:
3574/// \code
3575/// class A { class B { class C { class D { class E {}; }; }; }; };
3576/// \endcode
3577///
3578/// Usable as: Any Matcher
3579extern const internal::ArgumentAdaptingMatcherFunc<
3580 internal::ForEachDescendantMatcher>
3582
3583/// Matches if the node or any descendant matches.
3584///
3585/// Generates results for each match.
3586///
3587/// For example, in:
3588/// \code
3589/// class A { class B {}; class C {}; };
3590/// \endcode
3591/// The matcher:
3592/// \code
3593/// cxxRecordDecl(hasName("::A"),
3594/// findAll(cxxRecordDecl(isDefinition()).bind("m")))
3595/// \endcode
3596/// will generate results for \c A, \c B and \c C.
3597///
3598/// Usable as: Any Matcher
3599template <typename T>
3600internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3601 return eachOf(Matcher, forEachDescendant(Matcher));
3602}
3603
3604/// Matches AST nodes that have a parent that matches the provided
3605/// matcher.
3606///
3607/// Given
3608/// \code
3609/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3610/// \endcode
3611/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3612///
3613/// Usable as: Any Matcher
3614extern const internal::ArgumentAdaptingMatcherFunc<
3615 internal::HasParentMatcher,
3616 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3617 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3618 hasParent;
3619
3620/// Matches AST nodes that have an ancestor that matches the provided
3621/// matcher.
3622///
3623/// Given
3624/// \code
3625/// void f() { if (true) { int x = 42; } }
3626/// void g() { for (;;) { int x = 43; } }
3627/// \endcode
3628/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3629///
3630/// Usable as: Any Matcher
3631extern const internal::ArgumentAdaptingMatcherFunc<
3632 internal::HasAncestorMatcher,
3633 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>,
3634 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc, Attr>>
3636
3637/// Matches if the provided matcher does not match.
3638///
3639/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3640/// \code
3641/// class X {};
3642/// class Y {};
3643/// \endcode
3644///
3645/// Usable as: Any Matcher
3646extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3647
3648/// Matches a node if the declaration associated with that node
3649/// matches the given matcher.
3650///
3651/// The associated declaration is:
3652/// - for type nodes, the declaration of the underlying type
3653/// - for CallExpr, the declaration of the callee
3654/// - for MemberExpr, the declaration of the referenced member
3655/// - for CXXConstructExpr, the declaration of the constructor
3656/// - for CXXNewExpr, the declaration of the operator new
3657/// - for ObjCIvarExpr, the declaration of the ivar
3658///
3659/// For type nodes, hasDeclaration will generally match the declaration of the
3660/// sugared type. Given
3661/// \code
3662/// class X {};
3663/// typedef X Y;
3664/// Y y;
3665/// \endcode
3666/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3667/// typedefDecl. A common use case is to match the underlying, desugared type.
3668/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3669/// \code
3670/// varDecl(hasType(hasUnqualifiedDesugaredType(
3671/// recordType(hasDeclaration(decl())))))
3672/// \endcode
3673/// In this matcher, the decl will match the CXXRecordDecl of class X.
3674///
3675/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3676/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3677/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3678/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3679/// Matcher<TagType>, Matcher<TemplateSpecializationType>,
3680/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3681/// Matcher<UnresolvedUsingType>
3682inline internal::PolymorphicMatcher<
3683 internal::HasDeclarationMatcher,
3684 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>
3685hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3686 return internal::PolymorphicMatcher<
3687 internal::HasDeclarationMatcher,
3688 void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>(
3689 InnerMatcher);
3690}
3691
3692/// Matches a \c NamedDecl whose underlying declaration matches the given
3693/// matcher.
3694///
3695/// Given
3696/// \code
3697/// namespace N { template<class T> void f(T t); }
3698/// template <class T> void g() { using N::f; f(T()); }
3699/// \endcode
3700/// \c unresolvedLookupExpr(hasAnyDeclaration(
3701/// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3702/// matches the use of \c f in \c g() .
3703AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3704 InnerMatcher) {
3705 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3706
3707 return UnderlyingDecl != nullptr &&
3708 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3709}
3710
3711/// Matches on the implicit object argument of a member call expression, after
3712/// stripping off any parentheses or implicit casts.
3713///
3714/// Given
3715/// \code
3716/// class Y { public: void m(); };
3717/// Y g();
3718/// class X : public Y {};
3719/// void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3720/// \endcode
3721/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3722/// matches `y.m()` and `(g()).m()`.
3723/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3724/// matches `x.m()`.
3725/// cxxMemberCallExpr(on(callExpr()))
3726/// matches `(g()).m()`.
3727///
3728/// FIXME: Overload to allow directly matching types?
3729AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3730 InnerMatcher) {
3731 const Expr *ExprNode = Node.getImplicitObjectArgument()
3732 ->IgnoreParenImpCasts();
3733 return (ExprNode != nullptr &&
3734 InnerMatcher.matches(*ExprNode, Finder, Builder));
3735}
3736
3737
3738/// Matches on the receiver of an ObjectiveC Message expression.
3739///
3740/// Example
3741/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3742/// matches the [webView ...] message invocation.
3743/// \code
3744/// NSString *webViewJavaScript = ...
3745/// UIWebView *webView = ...
3746/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3747/// \endcode
3748AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3749 InnerMatcher) {
3750 const QualType TypeDecl = Node.getReceiverType();
3751 return InnerMatcher.matches(TypeDecl, Finder, Builder);
3752}
3753
3754/// Returns true when the Objective-C method declaration is a class method.
3755///
3756/// Example
3757/// matcher = objcMethodDecl(isClassMethod())
3758/// matches
3759/// \code
3760/// @interface I + (void)foo; @end
3761/// \endcode
3762/// but not
3763/// \code
3764/// @interface I - (void)bar; @end
3765/// \endcode
3767 return Node.isClassMethod();
3768}
3769
3770/// Returns true when the Objective-C method declaration is an instance method.
3771///
3772/// Example
3773/// matcher = objcMethodDecl(isInstanceMethod())
3774/// matches
3775/// \code
3776/// @interface I - (void)bar; @end
3777/// \endcode
3778/// but not
3779/// \code
3780/// @interface I + (void)foo; @end
3781/// \endcode
3783 return Node.isInstanceMethod();
3784}
3785
3786/// Returns true when the Objective-C message is sent to a class.
3787///
3788/// Example
3789/// matcher = objcMessageExpr(isClassMessage())
3790/// matches
3791/// \code
3792/// [NSString stringWithFormat:@"format"];
3793/// \endcode
3794/// but not
3795/// \code
3796/// NSString *x = @"hello";
3797/// [x containsString:@"h"];
3798/// \endcode
3800 return Node.isClassMessage();
3801}
3802
3803/// Returns true when the Objective-C message is sent to an instance.
3804///
3805/// Example
3806/// matcher = objcMessageExpr(isInstanceMessage())
3807/// matches
3808/// \code
3809/// NSString *x = @"hello";
3810/// [x containsString:@"h"];
3811/// \endcode
3812/// but not
3813/// \code
3814/// [NSString stringWithFormat:@"format"];
3815/// \endcode
3816AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3817 return Node.isInstanceMessage();
3818}
3819
3820/// Matches if the Objective-C message is sent to an instance,
3821/// and the inner matcher matches on that instance.
3822///
3823/// For example the method call in
3824/// \code
3825/// NSString *x = @"hello";
3826/// [x containsString:@"h"];
3827/// \endcode
3828/// is matched by
3829/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3830AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3831 InnerMatcher) {
3832 const Expr *ReceiverNode = Node.getInstanceReceiver();
3833 return (ReceiverNode != nullptr &&
3834 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3835 Builder));
3836}
3837
3838/// Matches when BaseName == Selector.getAsString()
3839///
3840/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3841/// matches the outer message expr in the code below, but NOT the message
3842/// invocation for self.bodyView.
3843/// \code
3844/// [self.bodyView loadHTMLString:html baseURL:NULL];
3845/// \endcode
3846AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3847 Selector Sel = Node.getSelector();
3848 return BaseName == Sel.getAsString();
3849}
3850
3851/// Matches when at least one of the supplied string equals to the
3852/// Selector.getAsString()
3853///
3854/// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3855/// matches both of the expressions below:
3856/// \code
3857/// [myObj methodA:argA];
3858/// [myObj methodB:argB];
3859/// \endcode
3860extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3861 StringRef,
3864
3865/// Matches ObjC selectors whose name contains
3866/// a substring matched by the given RegExp.
3867/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3868/// matches the outer message expr in the code below, but NOT the message
3869/// invocation for self.bodyView.
3870/// \code
3871/// [self.bodyView loadHTMLString:html baseURL:NULL];
3872/// \endcode
3873AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3874 std::string SelectorString = Node.getSelector().getAsString();
3875 return RegExp->match(SelectorString);
3876}
3877
3878/// Matches when the selector is the empty selector
3879///
3880/// Matches only when the selector of the objCMessageExpr is NULL. This may
3881/// represent an error condition in the tree!
3882AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3883 return Node.getSelector().isNull();
3884}
3885
3886/// Matches when the selector is a Unary Selector
3887///
3888/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3889/// matches self.bodyView in the code below, but NOT the outer message
3890/// invocation of "loadHTMLString:baseURL:".
3891/// \code
3892/// [self.bodyView loadHTMLString:html baseURL:NULL];
3893/// \endcode
3894AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3895 return Node.getSelector().isUnarySelector();
3896}
3897
3898/// Matches when the selector is a keyword selector
3899///
3900/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3901/// message expression in
3902///
3903/// \code
3904/// UIWebView *webView = ...;
3905/// CGRect bodyFrame = webView.frame;
3906/// bodyFrame.size.height = self.bodyContentHeight;
3907/// webView.frame = bodyFrame;
3908/// // ^---- matches here
3909/// \endcode
3910AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3911 return Node.getSelector().isKeywordSelector();
3912}
3913
3914/// Matches when the selector has the specified number of arguments
3915///
3916/// matcher = objCMessageExpr(numSelectorArgs(0));
3917/// matches self.bodyView in the code below
3918///
3919/// matcher = objCMessageExpr(numSelectorArgs(2));
3920/// matches the invocation of "loadHTMLString:baseURL:" but not that
3921/// of self.bodyView
3922/// \code
3923/// [self.bodyView loadHTMLString:html baseURL:NULL];
3924/// \endcode
3925AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3926 return Node.getSelector().getNumArgs() == N;
3927}
3928
3929/// Matches if the call or fold expression's callee expression matches.
3930///
3931/// Given
3932/// \code
3933/// class Y { void x() { this->x(); x(); Y y; y.x(); } };
3934/// void f() { f(); }
3935/// \endcode
3936/// callExpr(callee(expr()))
3937/// matches this->x(), x(), y.x(), f()
3938/// with callee(...)
3939/// matching this->x, x, y.x, f respectively
3940///
3941/// Given
3942/// \code
3943/// template <typename... Args>
3944/// auto sum(Args... args) {
3945/// return (0 + ... + args);
3946/// }
3947///
3948/// template <typename... Args>
3949/// auto multiply(Args... args) {
3950/// return (args * ... * 1);
3951/// }
3952/// \endcode
3953/// cxxFoldExpr(callee(expr()))
3954/// matches (args * ... * 1)
3955/// with callee(...)
3956/// matching *
3957///
3958/// Note: Callee cannot take the more general internal::Matcher<Expr>
3959/// because this introduces ambiguous overloads with calls to Callee taking a
3960/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3961/// implemented in terms of implicit casts.
3964 CXXFoldExpr),
3965 internal::Matcher<Stmt>, InnerMatcher, 0) {
3966 const auto *ExprNode = Node.getCallee();
3967 return (ExprNode != nullptr &&
3968 InnerMatcher.matches(*ExprNode, Finder, Builder));
3969}
3970
3971/// Matches 1) if the call expression's callee's declaration matches the
3972/// given matcher; or 2) if the Obj-C message expression's callee's method
3973/// declaration matches the given matcher.
3974///
3975/// Example matches y.x() (matcher = callExpr(callee(
3976/// cxxMethodDecl(hasName("x")))))
3977/// \code
3978/// class Y { public: void x(); };
3979/// void z() { Y y; y.x(); }
3980/// \endcode
3981///
3982/// Example 2. Matches [I foo] with
3983/// objcMessageExpr(callee(objcMethodDecl(hasName("foo"))))
3984///
3985/// \code
3986/// @interface I: NSObject
3987/// +(void)foo;
3988/// @end
3989/// ...
3990/// [I foo]
3991/// \endcode
3994 internal::Matcher<Decl>, InnerMatcher, 1) {
3995 if (isa<CallExpr>(&Node))
3996 return callExpr(hasDeclaration(InnerMatcher))
3997 .matches(Node, Finder, Builder);
3998 else {
3999 // The dynamic cast below is guaranteed to succeed as there are only 2
4000 // supported return types.
4001 const auto *MsgNode = cast<ObjCMessageExpr>(&Node);
4002 const Decl *DeclNode = MsgNode->getMethodDecl();
4003 return (DeclNode != nullptr &&
4004 InnerMatcher.matches(*DeclNode, Finder, Builder));
4005 }
4006}
4007
4008/// Matches if the expression's or declaration's type matches a type
4009/// matcher.
4010///
4011/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4012/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4013/// and U (matcher = typedefDecl(hasType(asString("int")))
4014/// and friend class X (matcher = friendDecl(hasType("X"))
4015/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4016/// asString("class X")))
4017/// \code
4018/// class X {};
4019/// void y(X &x) { x; X z; }
4020/// typedef int U;
4021/// class Y { friend class X; };
4022/// class Z : public virtual X {};
4023/// \endcode
4025 hasType,
4028 internal::Matcher<QualType>, InnerMatcher, 0) {
4029 QualType QT = internal::getUnderlyingType(Node);
4030 if (!QT.isNull())
4031 return InnerMatcher.matches(QT, Finder, Builder);
4032 return false;
4033}
4034
4035/// Overloaded to match the declaration of the expression's or value
4036/// declaration's type.
4037///
4038/// In case of a value declaration (for example a variable declaration),
4039/// this resolves one layer of indirection. For example, in the value
4040/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
4041/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
4042/// declaration of x.
4043///
4044/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
4045/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
4046/// and friend class X (matcher = friendDecl(hasType("X"))
4047/// and public virtual X (matcher = cxxBaseSpecifier(hasType(
4048/// cxxRecordDecl(hasName("X"))))
4049/// \code
4050/// class X {};
4051/// void y(X &x) { x; X z; }
4052/// class Y { friend class X; };
4053/// class Z : public virtual X {};
4054/// \endcode
4055///
4056/// Example matches class Derived
4057/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
4058/// \code
4059/// class Base {};
4060/// class Derived : Base {};
4061/// \endcode
4062///
4063/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
4064/// Matcher<CXXBaseSpecifier>
4066 hasType,
4069 internal::Matcher<Decl>, InnerMatcher, 1) {
4070 QualType QT = internal::getUnderlyingType(Node);
4071 if (!QT.isNull())
4072 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
4073 return false;
4074}
4075
4076/// Matches if the type location of a node matches the inner matcher.
4077///
4078/// Examples:
4079/// \code
4080/// int x;
4081/// \endcode
4082/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
4083/// matches int x
4084///
4085/// \code
4086/// auto x = int(3);
4087/// \endcode
4088/// cxxTemporaryObjectExpr(hasTypeLoc(loc(asString("int"))))
4089/// matches int(3)
4090///
4091/// \code
4092/// struct Foo { Foo(int, int); };
4093/// auto x = Foo(1, 2);
4094/// \endcode
4095/// cxxFunctionalCastExpr(hasTypeLoc(loc(asString("struct Foo"))))
4096/// matches Foo(1, 2)
4097///
4098/// Usable as: Matcher<BlockDecl>, Matcher<CXXBaseSpecifier>,
4099/// Matcher<CXXCtorInitializer>, Matcher<CXXFunctionalCastExpr>,
4100/// Matcher<CXXNewExpr>, Matcher<CXXTemporaryObjectExpr>,
4101/// Matcher<CXXUnresolvedConstructExpr>,
4102/// Matcher<CompoundLiteralExpr>,
4103/// Matcher<DeclaratorDecl>, Matcher<ExplicitCastExpr>,
4104/// Matcher<ObjCPropertyDecl>, Matcher<TemplateArgumentLoc>,
4105/// Matcher<TypedefNameDecl>
4107 hasTypeLoc,
4113 internal::Matcher<TypeLoc>, Inner) {
4114 TypeSourceInfo *source = internal::GetTypeSourceInfo(Node);
4115 if (source == nullptr) {
4116 // This happens for example for implicit destructors.
4117 return false;
4118 }
4119 return Inner.matches(source->getTypeLoc(), Finder, Builder);
4120}
4121
4122/// Matches if the matched type is represented by the given string.
4123///
4124/// Given
4125/// \code
4126/// class Y { public: void x(); };
4127/// void z() { Y* y; y->x(); }
4128/// \endcode
4129/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
4130/// matches y->x()
4131AST_MATCHER_P(QualType, asString, std::string, Name) {
4132 return Name == Node.getAsString();
4133}
4134
4135/// Matches if the matched type is a pointer type and the pointee type
4136/// matches the specified matcher.
4137///
4138/// Example matches y->x()
4139/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
4140/// cxxRecordDecl(hasName("Y")))))))
4141/// \code
4142/// class Y { public: void x(); };
4143/// void z() { Y *y; y->x(); }
4144/// \endcode
4146 QualType, pointsTo, internal::Matcher<QualType>,
4147 InnerMatcher) {
4148 return (!Node.isNull() && Node->isAnyPointerType() &&
4149 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4150}
4151
4152/// Overloaded to match the pointee type's declaration.
4153AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
4154 InnerMatcher, 1) {
4155 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
4156 .matches(Node, Finder, Builder);
4157}
4158
4159/// Matches if the matched type matches the unqualified desugared
4160/// type of the matched node.
4161///
4162/// For example, in:
4163/// \code
4164/// class A {};
4165/// using B = A;
4166/// \endcode
4167/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
4168/// both B and A.
4169AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
4170 InnerMatcher) {
4171 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
4172 Builder);
4173}
4174
4175/// Matches if the matched type is a reference type and the referenced
4176/// type matches the specified matcher.
4177///
4178/// Example matches X &x and const X &y
4179/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
4180/// \code
4181/// class X {
4182/// void a(X b) {
4183/// X &x = b;
4184/// const X &y = b;
4185/// }
4186/// };
4187/// \endcode
4188AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
4189 InnerMatcher) {
4190 return (!Node.isNull() && Node->isReferenceType() &&
4191 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
4192}
4193
4194/// Matches QualTypes whose canonical type matches InnerMatcher.
4195///
4196/// Given:
4197/// \code
4198/// typedef int &int_ref;
4199/// int a;
4200/// int_ref b = a;
4201/// \endcode
4202///
4203/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
4204/// declaration of b but \c
4205/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
4206AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
4207 InnerMatcher) {
4208 if (Node.isNull())
4209 return false;
4210 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
4211}
4212
4213/// Overloaded to match the referenced type's declaration.
4214AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
4215 InnerMatcher, 1) {
4216 return references(qualType(hasDeclaration(InnerMatcher)))
4217 .matches(Node, Finder, Builder);
4218}
4219
4220/// Matches on the implicit object argument of a member call expression. Unlike
4221/// `on`, matches the argument directly without stripping away anything.
4222///
4223/// Given
4224/// \code
4225/// class Y { public: void m(); };
4226/// Y g();
4227/// class X : public Y { void g(); };
4228/// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
4229/// \endcode
4230/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
4231/// cxxRecordDecl(hasName("Y")))))
4232/// matches `y.m()`, `x.m()` and (`g()).m()`, but not `x.g()`).
4233/// cxxMemberCallExpr(on(callExpr()))
4234/// only matches `(g()).m()` (the parens are ignored).
4235///
4236/// FIXME: Overload to allow directly matching types?
4237AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
4238 internal::Matcher<Expr>, InnerMatcher) {
4239 const Expr *ExprNode = Node.getImplicitObjectArgument();
4240 return (ExprNode != nullptr &&
4241 InnerMatcher.matches(*ExprNode, Finder, Builder));
4242}
4243
4244/// Matches if the type of the expression's implicit object argument either
4245/// matches the InnerMatcher, or is a pointer to a type that matches the
4246/// InnerMatcher.
4247///
4248/// Given
4249/// \code
4250/// class Y { public: void m(); };
4251/// class X : public Y { void g(); };
4252/// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
4253/// \endcode
4254/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4255/// cxxRecordDecl(hasName("Y")))))
4256/// matches `y.m()`, `p->m()` and `x.m()`.
4257/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
4258/// cxxRecordDecl(hasName("X")))))
4259/// matches `x.g()`.
4261 internal::Matcher<QualType>, InnerMatcher, 0) {
4262 return onImplicitObjectArgument(
4263 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4264 .matches(Node, Finder, Builder);
4265}
4266
4267/// Overloaded to match the type's declaration.
4269 internal::Matcher<Decl>, InnerMatcher, 1) {
4270 return onImplicitObjectArgument(
4271 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
4272 .matches(Node, Finder, Builder);
4273}
4274
4275/// Matches a DeclRefExpr that refers to a declaration that matches the
4276/// specified matcher.
4277///
4278/// Example matches x in if(x)
4279/// (matcher = declRefExpr(to(varDecl(hasName("x")))))
4280/// \code
4281/// bool x;
4282/// if (x) {}
4283/// \endcode
4284AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
4285 InnerMatcher) {
4286 const Decl *DeclNode = Node.getDecl();
4287 return (DeclNode != nullptr &&
4288 InnerMatcher.matches(*DeclNode, Finder, Builder));
4289}
4290
4291/// Matches if a node refers to a declaration through a specific
4292/// using shadow declaration.
4293///
4294/// Examples:
4295/// \code
4296/// namespace a { int f(); }
4297/// using a::f;
4298/// int x = f();
4299/// \endcode
4300/// declRefExpr(throughUsingDecl(anything()))
4301/// matches \c f
4302///
4303/// \code
4304/// namespace a { class X{}; }
4305/// using a::X;
4306/// X x;
4307/// \endcode
4308/// typeLoc(loc(usingType(throughUsingDecl(anything()))))
4309/// matches \c X
4310///
4311/// Usable as: Matcher<DeclRefExpr>, Matcher<UsingType>
4314 UsingType),
4315 internal::Matcher<UsingShadowDecl>, Inner) {
4316 const NamedDecl *FoundDecl = Node.getFoundDecl();
4317 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4318 return Inner.matches(*UsingDecl, Finder, Builder);
4319 return false;
4320}
4321
4322/// Matches an \c OverloadExpr if any of the declarations in the set of
4323/// overloads matches the given matcher.
4324///
4325/// Given
4326/// \code
4327/// template <typename T> void foo(T);
4328/// template <typename T> void bar(T);
4329/// template <typename T> void baz(T t) {
4330/// foo(t);
4331/// bar(t);
4332/// }
4333/// \endcode
4334/// unresolvedLookupExpr(hasAnyDeclaration(
4335/// functionTemplateDecl(hasName("foo"))))
4336/// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4337AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4338 InnerMatcher) {
4339 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4340 Node.decls_end(), Finder,
4341 Builder) != Node.decls_end();
4342}
4343
4344/// Matches the Decl of a DeclStmt which has a single declaration.
4345///
4346/// Given
4347/// \code
4348/// int a, b;
4349/// int c;
4350/// \endcode
4351/// declStmt(hasSingleDecl(anything()))
4352/// matches 'int c;' but not 'int a, b;'.
4353AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4354 if (Node.isSingleDecl()) {
4355 const Decl *FoundDecl = Node.getSingleDecl();
4356 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4357 }
4358 return false;
4359}
4360
4361/// Matches a variable declaration that has an initializer expression
4362/// that matches the given matcher.
4363///
4364/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4365/// \code
4366/// bool y() { return true; }
4367/// bool x = y();
4368/// \endcode
4370 VarDecl, hasInitializer, internal::Matcher<Expr>,
4371 InnerMatcher) {
4372 const Expr *Initializer = Node.getAnyInitializer();
4373 return (Initializer != nullptr &&
4374 InnerMatcher.matches(*Initializer, Finder, Builder));
4375}
4376
4377/// Matches a variable serving as the implicit variable for a lambda init-
4378/// capture.
4379///
4380/// Example matches x (matcher = varDecl(isInitCapture()))
4381/// \code
4382/// auto f = [x=3]() { return x; };
4383/// \endcode
4384AST_MATCHER(VarDecl, isInitCapture) { return Node.isInitCapture(); }
4385
4386/// Matches each lambda capture in a lambda expression.
4387///
4388/// Given
4389/// \code
4390/// int main() {
4391/// int x, y;
4392/// float z;
4393/// auto f = [=]() { return x + y + z; };
4394/// }
4395/// \endcode
4396/// lambdaExpr(forEachLambdaCapture(
4397/// lambdaCapture(capturesVar(varDecl(hasType(isInteger()))))))
4398/// will trigger two matches, binding for 'x' and 'y' respectively.
4399AST_MATCHER_P(LambdaExpr, forEachLambdaCapture,
4400 internal::Matcher<LambdaCapture>, InnerMatcher) {
4401 BoundNodesTreeBuilder Result;
4402 bool Matched = false;
4403 for (const auto &Capture : Node.captures()) {
4404 if (Finder->isTraversalIgnoringImplicitNodes() && Capture.isImplicit())
4405 continue;
4406 BoundNodesTreeBuilder CaptureBuilder(*Builder);
4407 if (InnerMatcher.matches(Capture, Finder, &CaptureBuilder)) {
4408 Matched = true;
4409 Result.addMatch(CaptureBuilder);
4410 }
4411 }
4412 *Builder = std::move(Result);
4413 return Matched;
4414}
4415
4416/// \brief Matches a static variable with local scope.
4417///
4418/// Example matches y (matcher = varDecl(isStaticLocal()))
4419/// \code
4420/// void f() {
4421/// int x;
4422/// static int y;
4423/// }
4424/// static int z;
4425/// \endcode
4426AST_MATCHER(VarDecl, isStaticLocal) {
4427 return Node.isStaticLocal();
4428}
4429
4430/// Matches a variable declaration that has function scope and is a
4431/// non-static local variable.
4432///
4433/// Example matches x (matcher = varDecl(hasLocalStorage())
4434/// \code
4435/// void f() {
4436/// int x;
4437/// static int y;
4438/// }
4439/// int z;
4440/// \endcode
4441AST_MATCHER(VarDecl, hasLocalStorage) {
4442 return Node.hasLocalStorage();
4443}
4444
4445/// Matches a variable declaration that does not have local storage.
4446///
4447/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4448/// \code
4449/// void f() {
4450/// int x;
4451/// static int y;
4452/// }
4453/// int z;
4454/// \endcode
4455AST_MATCHER(VarDecl, hasGlobalStorage) {
4456 return Node.hasGlobalStorage();
4457}
4458
4459/// Matches a variable declaration that has automatic storage duration.
4460///
4461/// Example matches x, but not y, z, or a.
4462/// (matcher = varDecl(hasAutomaticStorageDuration())
4463/// \code
4464/// void f() {
4465/// int x;
4466/// static int y;
4467/// thread_local int z;
4468/// }
4469/// int a;
4470/// \endcode
4471AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4472 return Node.getStorageDuration() == SD_Automatic;
4473}
4474
4475/// Matches a variable declaration that has static storage duration.
4476/// It includes the variable declared at namespace scope and those declared
4477/// with "static" and "extern" storage class specifiers.
4478///
4479/// \code
4480/// void f() {
4481/// int x;
4482/// static int y;
4483/// thread_local int z;
4484/// }
4485/// int a;
4486/// static int b;
4487/// extern int c;
4488/// varDecl(hasStaticStorageDuration())
4489/// matches the function declaration y, a, b and c.
4490/// \endcode
4491AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4492 return Node.getStorageDuration() == SD_Static;
4493}
4494
4495/// Matches a variable declaration that has thread storage duration.
4496///
4497/// Example matches z, but not x, z, or a.
4498/// (matcher = varDecl(hasThreadStorageDuration())
4499/// \code
4500/// void f() {
4501/// int x;
4502/// static int y;
4503/// thread_local int z;
4504/// }
4505/// int a;
4506/// \endcode
4507AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4508 return Node.getStorageDuration() == SD_Thread;
4509}
4510
4511/// Matches a variable declaration that is an exception variable from
4512/// a C++ catch block, or an Objective-C \@catch statement.
4513///
4514/// Example matches x (matcher = varDecl(isExceptionVariable())
4515/// \code
4516/// void f(int y) {
4517/// try {
4518/// } catch (int x) {
4519/// }
4520/// }
4521/// \endcode
4522AST_MATCHER(VarDecl, isExceptionVariable) {
4523 return Node.isExceptionVariable();
4524}
4525
4526/// Checks that a call expression or a constructor call expression has
4527/// a specific number of arguments (including absent default arguments).
4528///
4529/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4530/// \code
4531/// void f(int x, int y);
4532/// f(0, 0);
4533/// \endcode
4538 unsigned, N) {
4539 unsigned NumArgs = Node.getNumArgs();
4540 if (!Finder->isTraversalIgnoringImplicitNodes())
4541 return NumArgs == N;
4542 while (NumArgs) {
4543 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4544 break;
4545 --NumArgs;
4546 }
4547 return NumArgs == N;
4548}
4549
4550/// Checks that a call expression or a constructor call expression has at least
4551/// the specified number of arguments (including absent default arguments).
4552///
4553/// Example matches f(0, 0) and g(0, 0, 0)
4554/// (matcher = callExpr(argumentCountAtLeast(2)))
4555/// \code
4556/// void f(int x, int y);
4557/// void g(int x, int y, int z);
4558/// f(0, 0);
4559/// g(0, 0, 0);
4560/// \endcode
4561AST_POLYMORPHIC_MATCHER_P(argumentCountAtLeast,
4565 unsigned, N) {
4566 unsigned NumArgs = Node.getNumArgs();
4567 if (!Finder->isTraversalIgnoringImplicitNodes())
4568 return NumArgs >= N;
4569 while (NumArgs) {
4570 if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4571 break;
4572 --NumArgs;
4573 }
4574 return NumArgs >= N;
4575}
4576
4577/// Matches the n'th argument of a call expression or a constructor
4578/// call expression.
4579///
4580/// Example matches y in x(y)
4581/// (matcher = callExpr(hasArgument(0, declRefExpr())))
4582/// \code
4583/// void x(int) { int y; x(y); }
4584/// \endcode
4589 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4590 if (N >= Node.getNumArgs())
4591 return false;
4592 const Expr *Arg = Node.getArg(N);
4593 if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg))
4594 return false;
4595 return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4596}
4597
4598/// Matches the operand that does not contain the parameter pack.
4599///
4600/// Example matches `(0 + ... + args)` and `(args * ... * 1)`
4601/// (matcher = cxxFoldExpr(hasFoldInit(expr())))
4602/// with hasFoldInit(...)
4603/// matching `0` and `1` respectively
4604/// \code
4605/// template <typename... Args>
4606/// auto sum(Args... args) {
4607/// return (0 + ... + args);
4608/// }
4609///
4610/// template <typename... Args>
4611/// auto multiply(Args... args) {
4612/// return (args * ... * 1);
4613/// }
4614/// \endcode
4615AST_MATCHER_P(CXXFoldExpr, hasFoldInit, internal::Matcher<Expr>, InnerMacher) {
4616 const auto *const Init = Node.getInit();
4617 return Init && InnerMacher.matches(*Init, Finder, Builder);
4618}
4619
4620/// Matches the operand that contains the parameter pack.
4621///
4622/// Example matches `(0 + ... + args)`
4623/// (matcher = cxxFoldExpr(hasPattern(expr())))
4624/// with hasPattern(...)
4625/// matching `args`
4626/// \code
4627/// template <typename... Args>
4628/// auto sum(Args... args) {
4629/// return (0 + ... + args);
4630/// }
4631///
4632/// template <typename... Args>
4633/// auto multiply(Args... args) {
4634/// return (args * ... * 1);
4635/// }
4636/// \endcode
4637AST_MATCHER_P(CXXFoldExpr, hasPattern, internal::Matcher<Expr>, InnerMacher) {
4638 const Expr *const Pattern = Node.getPattern();
4639 return Pattern && InnerMacher.matches(*Pattern, Finder, Builder);
4640}
4641
4642/// Matches right-folding fold expressions.
4643///
4644/// Example matches `(args * ... * 1)`
4645/// (matcher = cxxFoldExpr(isRightFold()))
4646/// \code
4647/// template <typename... Args>
4648/// auto sum(Args... args) {
4649/// return (0 + ... + args);
4650/// }
4651///
4652/// template <typename... Args>
4653/// auto multiply(Args... args) {
4654/// return (args * ... * 1);
4655/// }
4656/// \endcode
4657AST_MATCHER(CXXFoldExpr, isRightFold) { return Node.isRightFold(); }
4658
4659/// Matches left-folding fold expressions.
4660///
4661/// Example matches `(0 + ... + args)`
4662/// (matcher = cxxFoldExpr(isLeftFold()))
4663/// \code
4664/// template <typename... Args>
4665/// auto sum(Args... args) {
4666/// return (0 + ... + args);
4667/// }
4668///
4669/// template <typename... Args>
4670/// auto multiply(Args... args) {
4671/// return (args * ... * 1);
4672/// }
4673/// \endcode
4674AST_MATCHER(CXXFoldExpr, isLeftFold) { return Node.isLeftFold(); }
4675
4676/// Matches unary fold expressions, i.e. fold expressions without an
4677/// initializer.
4678///
4679/// Example matches `(args * ...)`
4680/// (matcher = cxxFoldExpr(isUnaryFold()))
4681/// \code
4682/// template <typename... Args>
4683/// auto sum(Args... args) {
4684/// return (0 + ... + args);
4685/// }
4686///
4687/// template <typename... Args>
4688/// auto multiply(Args... args) {
4689/// return (args * ...);
4690/// }
4691/// \endcode
4692AST_MATCHER(CXXFoldExpr, isUnaryFold) { return Node.getInit() == nullptr; }
4693
4694/// Matches binary fold expressions, i.e. fold expressions with an initializer.
4695///
4696/// Example matches `(0 + ... + args)`
4697/// (matcher = cxxFoldExpr(isBinaryFold()))
4698/// \code
4699/// template <typename... Args>
4700/// auto sum(Args... args) {
4701/// return (0 + ... + args);
4702/// }
4703///
4704/// template <typename... Args>
4705/// auto multiply(Args... args) {
4706/// return (args * ...);
4707/// }
4708/// \endcode
4709AST_MATCHER(CXXFoldExpr, isBinaryFold) { return Node.getInit() != nullptr; }
4710
4711/// Matches the n'th item of an initializer list expression.
4712///
4713/// Example matches y.
4714/// (matcher = initListExpr(hasInit(0, expr())))
4715/// \code
4716/// int x{y}.
4717/// \endcode
4718AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N, internal::Matcher<Expr>,
4719 InnerMatcher) {
4720 return N < Node.getNumInits() &&
4721 InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4722}
4723
4724/// Matches declaration statements that contain a specific number of
4725/// declarations.
4726///
4727/// Example: Given
4728/// \code
4729/// int a, b;
4730/// int c;
4731/// int d = 2, e;
4732/// \endcode
4733/// declCountIs(2)
4734/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4735AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4736 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4737}
4738
4739/// Matches the n'th declaration of a declaration statement.
4740///
4741/// Note that this does not work for global declarations because the AST
4742/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4743/// DeclStmt's.
4744/// Example: Given non-global declarations
4745/// \code
4746/// int a, b = 0;
4747/// int c;
4748/// int d = 2, e;
4749/// \endcode
4750/// declStmt(containsDeclaration(
4751/// 0, varDecl(hasInitializer(anything()))))
4752/// matches only 'int d = 2, e;', and
4753/// declStmt(containsDeclaration(1, varDecl()))
4754/// \code
4755/// matches 'int a, b = 0' as well as 'int d = 2, e;'
4756/// but 'int c;' is not matched.
4757/// \endcode
4758AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4759 internal::Matcher<Decl>, InnerMatcher) {
4760 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4761 if (N >= NumDecls)
4762 return false;
4763 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4764 std::advance(Iterator, N);
4765 return InnerMatcher.matches(**Iterator, Finder, Builder);
4766}
4767
4768/// Matches a C++ catch statement that has a catch-all handler.
4769///
4770/// Given
4771/// \code
4772/// try {
4773/// // ...
4774/// } catch (int) {
4775/// // ...
4776/// } catch (...) {
4777/// // ...
4778/// }
4779/// \endcode
4780/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4782 return Node.getExceptionDecl() == nullptr;
4783}
4784
4785/// Matches a constructor initializer.
4786///
4787/// Given
4788/// \code
4789/// struct Foo {
4790/// Foo() : foo_(1) { }
4791/// int foo_;
4792/// };
4793/// \endcode
4794/// cxxRecordDecl(has(cxxConstructorDecl(
4795/// hasAnyConstructorInitializer(anything())
4796/// )))
4797/// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4798AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4799 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4800 auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4801 Node.init_end(), Finder, Builder);
4802 if (MatchIt == Node.init_end())
4803 return false;
4804 return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes();
4805}
4806
4807/// Matches the field declaration of a constructor initializer.
4808///
4809/// Given
4810/// \code
4811/// struct Foo {
4812/// Foo() : foo_(1) { }
4813/// int foo_;
4814/// };
4815/// \endcode
4816/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4817/// forField(hasName("foo_"))))))
4818/// matches Foo
4819/// with forField matching foo_
4821 internal::Matcher<FieldDecl>, InnerMatcher) {
4822 const FieldDecl *NodeAsDecl = Node.getAnyMember();
4823 return (NodeAsDecl != nullptr &&
4824 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4825}
4826
4827/// Matches the initializer expression of a constructor initializer.
4828///
4829/// Given
4830/// \code
4831/// struct Foo {
4832/// Foo() : foo_(1) { }
4833/// int foo_;
4834/// };
4835/// \endcode
4836/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4837/// withInitializer(integerLiteral(equals(1)))))))
4838/// matches Foo
4839/// with withInitializer matching (1)
4841 internal::Matcher<Expr>, InnerMatcher) {
4842 const Expr* NodeAsExpr = Node.getInit();
4843 return (NodeAsExpr != nullptr &&
4844 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4845}
4846
4847/// Matches a constructor initializer if it is explicitly written in
4848/// code (as opposed to implicitly added by the compiler).
4849///
4850/// Given
4851/// \code
4852/// struct Foo {
4853/// Foo() { }
4854/// Foo(int) : foo_("A") { }
4855/// string foo_;
4856/// };
4857/// \endcode
4858/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4859/// will match Foo(int), but not Foo()
4861 return Node.isWritten();
4862}
4863
4864/// Matches a constructor initializer if it is initializing a base, as
4865/// opposed to a member.
4866///
4867/// Given
4868/// \code
4869/// struct B {};
4870/// struct D : B {
4871/// int I;
4872/// D(int i) : I(i) {}
4873/// };
4874/// struct E : B {
4875/// E() : B() {}
4876/// };
4877/// \endcode
4878/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4879/// will match E(), but not match D(int).
4880AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4881 return Node.isBaseInitializer();
4882}
4883
4884/// Matches a constructor initializer if it is initializing a member, as
4885/// opposed to a base.
4886///
4887/// Given
4888/// \code
4889/// struct B {};
4890/// struct D : B {
4891/// int I;
4892/// D(int i) : I(i) {}
4893/// };
4894/// struct E : B {
4895/// E() : B() {}
4896/// };
4897/// \endcode
4898/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4899/// will match D(int), but not match E().
4900AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4901 return Node.isMemberInitializer();
4902}
4903
4904/// Matches any argument of a call expression or a constructor call
4905/// expression, or an ObjC-message-send expression.
4906///
4907/// Given
4908/// \code
4909/// void x(int, int, int) { int y; x(1, y, 42); }
4910/// \endcode
4911/// callExpr(hasAnyArgument(declRefExpr()))
4912/// matches x(1, y, 42)
4913/// with hasAnyArgument(...)
4914/// matching y
4915///
4916/// For ObjectiveC, given
4917/// \code
4918/// @interface I - (void) f:(int) y; @end
4919/// void foo(I *i) { [i f:12]; }
4920/// \endcode
4921/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4922/// matches [i f:12]
4927 internal::Matcher<Expr>, InnerMatcher) {
4928 for (const Expr *Arg : Node.arguments()) {
4929 if (Finder->isTraversalIgnoringImplicitNodes() &&
4930 isa<CXXDefaultArgExpr>(Arg))
4931 break;
4932 BoundNodesTreeBuilder Result(*Builder);
4933 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4934 *Builder = std::move(Result);
4935 return true;
4936 }
4937 }
4938 return false;
4939}
4940
4941/// Matches lambda captures.
4942///
4943/// Given
4944/// \code
4945/// int main() {
4946/// int x;
4947/// auto f = [x](){};
4948/// auto g = [x = 1](){};
4949/// }
4950/// \endcode
4951/// In the matcher `lambdaExpr(hasAnyCapture(lambdaCapture()))`,
4952/// `lambdaCapture()` matches `x` and `x=1`.
4953extern const internal::VariadicAllOfMatcher<LambdaCapture> lambdaCapture;
4954
4955/// Matches any capture in a lambda expression.
4956///
4957/// Given
4958/// \code
4959/// void foo() {
4960/// int t = 5;
4961/// auto f = [=](){ return t; };
4962/// }
4963/// \endcode
4964/// lambdaExpr(hasAnyCapture(lambdaCapture())) and
4965/// lambdaExpr(hasAnyCapture(lambdaCapture(refersToVarDecl(hasName("t")))))
4966/// both match `[=](){ return t; }`.
4967AST_MATCHER_P(LambdaExpr, hasAnyCapture, internal::Matcher<LambdaCapture>,
4968 InnerMatcher) {
4969 for (const LambdaCapture &Capture : Node.captures()) {
4970 clang::ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
4971 if (InnerMatcher.matches(Capture, Finder, &Result)) {
4972 *Builder = std::move(Result);
4973 return true;
4974 }
4975 }
4976 return false;
4977}
4978
4979/// Matches a `LambdaCapture` that refers to the specified `VarDecl`. The
4980/// `VarDecl` can be a separate variable that is captured by value or
4981/// reference, or a synthesized variable if the capture has an initializer.
4982///
4983/// Given
4984/// \code
4985/// void foo() {
4986/// int x;
4987/// auto f = [x](){};
4988/// auto g = [x = 1](){};
4989/// }
4990/// \endcode
4991/// In the matcher
4992/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesVar(hasName("x")))),
4993/// capturesVar(hasName("x")) matches `x` and `x = 1`.
4994AST_MATCHER_P(LambdaCapture, capturesVar, internal::Matcher<ValueDecl>,
4995 InnerMatcher) {
4996 if (!Node.capturesVariable())
4997 return false;
4998 auto *capturedVar = Node.getCapturedVar();
4999 return capturedVar && InnerMatcher.matches(*capturedVar, Finder, Builder);
5000}
5001
5002/// Matches a `LambdaCapture` that refers to 'this'.
5003///
5004/// Given
5005/// \code
5006/// class C {
5007/// int cc;
5008/// int f() {
5009/// auto l = [this]() { return cc; };
5010/// return l();
5011/// }
5012/// };
5013/// \endcode
5014/// lambdaExpr(hasAnyCapture(lambdaCapture(capturesThis())))
5015/// matches `[this]() { return cc; }`.
5016AST_MATCHER(LambdaCapture, capturesThis) { return Node.capturesThis(); }
5017
5018/// Matches a constructor call expression which uses list initialization.
5019AST_MATCHER(CXXConstructExpr, isListInitialization) {
5020 return Node.isListInitialization();
5021}
5022
5023/// Matches a constructor call expression which requires
5024/// zero initialization.
5025///
5026/// Given
5027/// \code
5028/// void foo() {
5029/// struct point { double x; double y; };
5030/// point pt[2] = { { 1.0, 2.0 } };
5031/// }
5032/// \endcode
5033/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
5034/// will match the implicit array filler for pt[1].
5035AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
5036 return Node.requiresZeroInitialization();
5037}
5038
5039/// Matches the n'th parameter of a function or an ObjC method
5040/// declaration or a block.
5041///
5042/// Given
5043/// \code
5044/// class X { void f(int x) {} };
5045/// \endcode
5046/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
5047/// matches f(int x) {}
5048/// with hasParameter(...)
5049/// matching int x
5050///
5051/// For ObjectiveC, given
5052/// \code
5053/// @interface I - (void) f:(int) y; @end
5054/// \endcode
5055//
5056/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
5057/// matches the declaration of method f with hasParameter
5058/// matching y.
5062 BlockDecl),
5063 unsigned, N, internal::Matcher<ParmVarDecl>,
5064 InnerMatcher) {
5065 return (N < Node.parameters().size()
5066 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
5067}
5068
5069/// Matches if the given method declaration declares a member function with an
5070/// explicit object parameter.
5071///
5072/// Given
5073/// \code
5074/// struct A {
5075/// int operator-(this A, int);
5076/// void fun(this A &&self);
5077/// static int operator()(int);
5078/// int operator+(int);
5079/// };
5080/// \endcode
5081///
5082/// cxxMethodDecl(isExplicitObjectMemberFunction()) matches the first two
5083/// methods but not the last two.
5084AST_MATCHER(CXXMethodDecl, isExplicitObjectMemberFunction) {
5085 return Node.isExplicitObjectMemberFunction();
5086}
5087
5088/// Matches all arguments and their respective ParmVarDecl.
5089///
5090/// Given
5091/// \code
5092/// void f(int i);
5093/// int y;
5094/// f(y);
5095/// \endcode
5096/// callExpr(
5097/// forEachArgumentWithParam(
5098/// declRefExpr(to(varDecl(hasName("y")))),
5099/// parmVarDecl(hasType(isInteger()))
5100/// ))
5101/// matches f(y);
5102/// with declRefExpr(...)
5103/// matching int y
5104/// and parmVarDecl(...)
5105/// matching int i
5106AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
5109 internal::Matcher<Expr>, ArgMatcher,
5110 internal::Matcher<ParmVarDecl>, ParamMatcher) {
5111 BoundNodesTreeBuilder Result;
5112 // The first argument of an overloaded member operator is the implicit object
5113 // argument of the method which should not be matched against a parameter, so
5114 // we skip over it here.
5115 BoundNodesTreeBuilder Matches;
5116 unsigned ArgIndex =
5118 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5119 .matches(Node, Finder, &Matches)
5120 ? 1
5121 : 0;
5122 int ParamIndex = 0;
5123 bool Matched = false;
5124 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
5125 BoundNodesTreeBuilder ArgMatches(*Builder);
5126 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
5127 Finder, &ArgMatches)) {
5128 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5130 hasParameter(ParamIndex, ParamMatcher)))),
5131 callExpr(callee(functionDecl(
5132 hasParameter(ParamIndex, ParamMatcher))))))
5133 .matches(Node, Finder, &ParamMatches)) {
5134 Result.addMatch(ParamMatches);
5135 Matched = true;
5136 }
5137 }
5138 ++ParamIndex;
5139 }
5140 *Builder = std::move(Result);
5141 return Matched;
5142}
5143
5144/// Matches all arguments and their respective types for a \c CallExpr or
5145/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
5146/// it works on calls through function pointers as well.
5147///
5148/// The difference is, that function pointers do not provide access to a
5149/// \c ParmVarDecl, but only the \c QualType for each argument.
5150///
5151/// Given
5152/// \code
5153/// void f(int i);
5154/// int y;
5155/// f(y);
5156/// void (*f_ptr)(int) = f;
5157/// f_ptr(y);
5158/// \endcode
5159/// callExpr(
5160/// forEachArgumentWithParamType(
5161/// declRefExpr(to(varDecl(hasName("y")))),
5162/// qualType(isInteger()).bind("type)
5163/// ))
5164/// matches f(y) and f_ptr(y)
5165/// with declRefExpr(...)
5166/// matching int y
5167/// and qualType(...)
5168/// matching int
5169AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
5172 internal::Matcher<Expr>, ArgMatcher,
5173 internal::Matcher<QualType>, ParamMatcher) {
5174 BoundNodesTreeBuilder Result;
5175 // The first argument of an overloaded member operator is the implicit object
5176 // argument of the method which should not be matched against a parameter, so
5177 // we skip over it here.
5178 BoundNodesTreeBuilder Matches;
5179 unsigned ArgIndex =
5181 callee(cxxMethodDecl(unless(isExplicitObjectMemberFunction()))))
5182 .matches(Node, Finder, &Matches)
5183 ? 1
5184 : 0;
5185 const FunctionProtoType *FProto = nullptr;
5186
5187 if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
5188 if (const auto *Value =
5189 dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
5191
5192 // This does not necessarily lead to a `FunctionProtoType`,
5193 // e.g. K&R functions do not have a function prototype.
5194 if (QT->isFunctionPointerType())
5195 FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
5196
5197 if (QT->isMemberFunctionPointerType()) {
5198 const auto *MP = QT->getAs<MemberPointerType>();
5199 assert(MP && "Must be member-pointer if its a memberfunctionpointer");
5200 FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
5201 assert(FProto &&
5202 "The call must have happened through a member function "
5203 "pointer");
5204 }
5205 }
5206 }
5207
5208 unsigned ParamIndex = 0;
5209 bool Matched = false;
5210 unsigned NumArgs = Node.getNumArgs();
5211 if (FProto && FProto->isVariadic())
5212 NumArgs = std::min(NumArgs, FProto->getNumParams());
5213
5214 for (; ArgIndex < NumArgs; ++ArgIndex, ++ParamIndex) {
5215 BoundNodesTreeBuilder ArgMatches(*Builder);
5216 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
5217 &ArgMatches)) {
5218 BoundNodesTreeBuilder ParamMatches(ArgMatches);
5219
5220 // This test is cheaper compared to the big matcher in the next if.
5221 // Therefore, please keep this order.
5222 if (FProto && FProto->getNumParams() > ParamIndex) {
5223 QualType ParamType = FProto->getParamType(ParamIndex);
5224 if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
5225 Result.addMatch(ParamMatches);
5226 Matched = true;
5227 continue;
5228 }
5229 }
5231 hasParameter(ParamIndex, hasType(ParamMatcher))))),
5232 callExpr(callee(functionDecl(
5233 hasParameter(ParamIndex, hasType(ParamMatcher)))))))
5234 .matches(Node, Finder, &ParamMatches)) {
5235 Result.addMatch(ParamMatches);
5236 Matched = true;
5237 continue;
5238 }
5239 }
5240 }
5241 *Builder = std::move(Result);
5242 return Matched;
5243}
5244
5245/// Matches the ParmVarDecl nodes that are at the N'th position in the parameter
5246/// list. The parameter list could be that of either a block, function, or
5247/// objc-method.
5248///
5249///
5250/// Given
5251///
5252/// \code
5253/// void f(int a, int b, int c) {
5254/// }
5255/// \endcode
5256///
5257/// ``parmVarDecl(isAtPosition(0))`` matches ``int a``.
5258///
5259/// ``parmVarDecl(isAtPosition(1))`` matches ``int b``.
5260AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) {
5261 const clang::DeclContext *Context = Node.getParentFunctionOrMethod();
5262
5263 if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context))
5264 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5265 if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context))
5266 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5267 if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context))
5268 return N < Decl->param_size() && Decl->getParamDecl(N) == &Node;
5269
5270 return false;
5271}
5272
5273/// Matches any parameter of a function or an ObjC method declaration or a
5274/// block.
5275///
5276/// Does not match the 'this' parameter of a method.
5277///
5278/// Given
5279/// \code
5280/// class X { void f(int x, int y, int z) {} };
5281/// \endcode
5282/// cxxMethodDecl(hasAnyParameter(hasName("y")))
5283/// matches f(int x, int y, int z) {}
5284/// with hasAnyParameter(...)
5285/// matching int y
5286///
5287/// For ObjectiveC, given
5288/// \code
5289/// @interface I - (void) f:(int) y; @end
5290/// \endcode
5291//
5292/// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
5293/// matches the declaration of method f with hasParameter
5294/// matching y.
5295///
5296/// For blocks, given
5297/// \code
5298/// b = ^(int y) { printf("%d", y) };
5299/// \endcode
5300///
5301/// the matcher blockDecl(hasAnyParameter(hasName("y")))
5302/// matches the declaration of the block b with hasParameter
5303/// matching y.
5307 BlockDecl),
5308 internal::Matcher<ParmVarDecl>,
5309 InnerMatcher) {
5310 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
5311 Node.param_end(), Finder,
5312 Builder) != Node.param_end();
5313}
5314
5315/// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
5316/// specific parameter count.
5317///
5318/// Given
5319/// \code
5320/// void f(int i) {}
5321/// void g(int i, int j) {}
5322/// void h(int i, int j);
5323/// void j(int i);
5324/// void k(int x, int y, int z, ...);
5325/// \endcode
5326/// functionDecl(parameterCountIs(2))
5327/// matches \c g and \c h
5328/// functionProtoType(parameterCountIs(2))
5329/// matches \c g and \c h
5330/// functionProtoType(parameterCountIs(3))
5331/// matches \c k
5335 unsigned, N) {
5336 return Node.getNumParams() == N;
5337}
5338
5339/// Matches templateSpecializationType, class template specialization,
5340/// variable template specialization, and function template specialization
5341/// nodes where the template argument matches the inner matcher. This matcher
5342/// may produce multiple matches.
5343///
5344/// Given
5345/// \code
5346/// template <typename T, unsigned N, unsigned M>
5347/// struct Matrix {};
5348///
5349/// constexpr unsigned R = 2;
5350/// Matrix<int, R * 2, R * 4> M;
5351///
5352/// template <typename T, typename U>
5353/// void f(T&& t, U&& u) {}
5354///
5355/// bool B = false;
5356/// f(R, B);
5357/// \endcode
5358/// templateSpecializationType(forEachTemplateArgument(isExpr(expr())))
5359/// matches twice, with expr() matching 'R * 2' and 'R * 4'
5360/// functionDecl(forEachTemplateArgument(refersToType(builtinType())))
5361/// matches the specialization f<unsigned, bool> twice, for 'unsigned'
5362/// and 'bool'
5364 forEachTemplateArgument,
5368 internal::Matcher<TemplateArgument>, InnerMatcher) {
5369 ArrayRef<TemplateArgument> TemplateArgs =
5370 clang::ast_matchers::internal::getTemplateSpecializationArgs(Node);
5371 clang::ast_matchers::internal::BoundNodesTreeBuilder Result;
5372 bool Matched = false;
5373 for (const auto &Arg : TemplateArgs) {
5374 clang::ast_matchers::internal::BoundNodesTreeBuilder ArgBuilder(*Builder);
5375 if (InnerMatcher.matches(Arg, Finder, &ArgBuilder)) {
5376 Matched = true;
5377 Result.addMatch(ArgBuilder);
5378 }
5379 }
5380 *Builder = std::move(Result);
5381 return Matched;
5382}
5383
5384/// Matches \c FunctionDecls that have a noreturn attribute.
5385///
5386/// Given
5387/// \code
5388/// void nope();
5389/// [[noreturn]] void a();
5390/// __attribute__((noreturn)) void b();
5391/// struct c { [[noreturn]] c(); };
5392/// \endcode
5393/// functionDecl(isNoReturn())
5394/// matches all of those except
5395/// \code
5396/// void nope();
5397/// \endcode
5398AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
5399
5400/// Matches the return type of a function declaration.
5401///
5402/// Given:
5403/// \code
5404/// class X { int f() { return 1; } };
5405/// \endcode
5406/// cxxMethodDecl(returns(asString("int")))
5407/// matches int f() { return 1; }
5409 internal::Matcher<QualType>, InnerMatcher) {
5410 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
5411}
5412
5413/// Matches extern "C" function or variable declarations.
5414///
5415/// Given:
5416/// \code
5417/// extern "C" void f() {}
5418/// extern "C" { void g() {} }
5419/// void h() {}
5420/// extern "C" int x = 1;
5421/// extern "C" int y = 2;
5422/// int z = 3;
5423/// \endcode
5424/// functionDecl(isExternC())
5425/// matches the declaration of f and g, but not the declaration of h.
5426/// varDecl(isExternC())
5427/// matches the declaration of x and y, but not the declaration of z.
5429 VarDecl)) {
5430 return Node.isExternC();
5431}
5432
5433/// Matches variable/function declarations that have "static" storage
5434/// class specifier ("static" keyword) written in the source.
5435///
5436/// Given:
5437/// \code
5438/// static void f() {}
5439/// static int i = 0;
5440/// extern int j;
5441/// int k;
5442/// \endcode
5443/// functionDecl(isStaticStorageClass())
5444/// matches the function declaration f.
5445/// varDecl(isStaticStorageClass())
5446/// matches the variable declaration i.
5447AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
5449 VarDecl)) {
5450 return Node.getStorageClass() == SC_Static;
5451}
5452
5453/// Matches deleted function declarations.
5454///
5455/// Given:
5456/// \code
5457/// void Func();
5458/// void DeletedFunc() = delete;
5459/// \endcode
5460/// functionDecl(isDeleted())
5461/// matches the declaration of DeletedFunc, but not Func.
5463 return Node.isDeleted();
5464}
5465
5466/// Matches defaulted function declarations.
5467///
5468/// Given:
5469/// \code
5470/// class A { ~A(); };
5471/// class B { ~B() = default; };
5472/// \endcode
5473/// functionDecl(isDefaulted())
5474/// matches the declaration of ~B, but not ~A.
5476 return Node.isDefaulted();
5477}
5478
5479/// Matches weak function declarations.
5480///
5481/// Given:
5482/// \code
5483/// void foo() __attribute__((__weakref__("__foo")));
5484/// void bar();
5485/// \endcode
5486/// functionDecl(isWeak())
5487/// matches the weak declaration "foo", but not "bar".
5488AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); }
5489
5490/// Matches functions that have a dynamic exception specification.
5491///
5492/// Given:
5493/// \code
5494/// void f();
5495/// void g() noexcept;
5496/// void h() noexcept(true);
5497/// void i() noexcept(false);
5498/// void j() throw();
5499/// void k() throw(int);
5500/// void l() throw(...);
5501/// \endcode
5502/// functionDecl(hasDynamicExceptionSpec()) and
5503/// functionProtoType(hasDynamicExceptionSpec())
5504/// match the declarations of j, k, and l, but not f, g, h, or i.
5505AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
5508 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
5509 return FnTy->hasDynamicExceptionSpec();
5510 return false;
5511}
5512
5513/// Matches functions that have a non-throwing exception specification.
5514///
5515/// Given:
5516/// \code
5517/// void f();
5518/// void g() noexcept;
5519/// void h() throw();
5520/// void i() throw(int);
5521/// void j() noexcept(false);
5522/// \endcode
5523/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
5524/// match the declarations of g, and h, but not f, i or j.
5528 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
5529
5530 // If the function does not have a prototype, then it is assumed to be a
5531 // throwing function (as it would if the function did not have any exception
5532 // specification).
5533 if (!FnTy)
5534 return false;
5535
5536 // Assume the best for any unresolved exception specification.
5538 return true;
5539
5540 return FnTy->isNothrow();
5541}
5542
5543/// Matches consteval function declarations and if consteval/if ! consteval
5544/// statements.
5545///
5546/// Given:
5547/// \code
5548/// consteval int a();
5549/// void b() { if consteval {} }
5550/// void c() { if ! consteval {} }
5551/// void d() { if ! consteval {} else {} }
5552/// \endcode
5553/// functionDecl(isConsteval())
5554/// matches the declaration of "int a()".
5555/// ifStmt(isConsteval())
5556/// matches the if statement in "void b()", "void c()", "void d()".
5559 return Node.isConsteval();
5560}
5561
5562/// Matches constexpr variable and function declarations,
5563/// and if constexpr.
5564///
5565/// Given:
5566/// \code
5567/// constexpr int foo = 42;
5568/// constexpr int bar();
5569/// void baz() { if constexpr(1 > 0) {} }
5570/// \endcode
5571/// varDecl(isConstexpr())
5572/// matches the declaration of foo.
5573/// functionDecl(isConstexpr())
5574/// matches the declaration of bar.
5575/// ifStmt(isConstexpr())
5576/// matches the if statement in baz.
5580 IfStmt)) {
5581 return Node.isConstexpr();
5582}
5583
5584/// Matches constinit variable declarations.
5585///
5586/// Given:
5587/// \code
5588/// constinit int foo = 42;
5589/// constinit const char* bar = "bar";
5590/// int baz = 42;
5591/// [[clang::require_constant_initialization]] int xyz = 42;
5592/// \endcode
5593/// varDecl(isConstinit())
5594/// matches the declaration of `foo` and `bar`, but not `baz` and `xyz`.
5595AST_MATCHER(VarDecl, isConstinit) {
5596 if (const auto *CIA = Node.getAttr<ConstInitAttr>())
5597 return CIA->isConstinit();
5598 return false;
5599}
5600
5601/// Matches selection statements with initializer.
5602///
5603/// Given:
5604/// \code
5605/// void foo() {
5606/// if (int i = foobar(); i > 0) {}
5607/// switch (int i = foobar(); i) {}
5608/// for (auto& a = get_range(); auto& x : a) {}
5609/// }
5610/// void bar() {
5611/// if (foobar() > 0) {}
5612/// switch (foobar()) {}
5613/// for (auto& x : get_range()) {}
5614/// }
5615/// \endcode
5616/// ifStmt(hasInitStatement(anything()))
5617/// matches the if statement in foo but not in bar.
5618/// switchStmt(hasInitStatement(anything()))
5619/// matches the switch statement in foo but not in bar.
5620/// cxxForRangeStmt(hasInitStatement(anything()))
5621/// matches the range for statement in foo but not in bar.
5625 internal::Matcher<Stmt>, InnerMatcher) {
5626 const Stmt *Init = Node.getInit();
5627 return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder);
5628}
5629
5630/// Matches the condition expression of an if statement, for loop,
5631/// switch statement or conditional operator.
5632///
5633/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
5634/// \code
5635/// if (true) {}
5636/// \endcode
5638 hasCondition,
5641 internal::Matcher<Expr>, InnerMatcher) {
5642 const Expr *const Condition = Node.getCond();
5643 return (Condition != nullptr &&
5644 InnerMatcher.matches(*Condition, Finder, Builder));
5645}
5646
5647/// Matches the then-statement of an if statement.
5648///
5649/// Examples matches the if statement
5650/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
5651/// \code
5652/// if (false) true; else false;
5653/// \endcode
5654AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
5655 const Stmt *const Then = Node.getThen();
5656 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
5657}
5658
5659/// Matches the else-statement of an if statement.
5660///
5661/// Examples matches the if statement
5662/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
5663/// \code
5664/// if (false) false; else true;
5665/// \endcode
5666AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
5667 const Stmt *const Else = Node.getElse();
5668 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
5669}
5670
5671/// Matches if a node equals a previously bound node.
5672///
5673/// Matches a node if it equals the node previously bound to \p ID.
5674///
5675/// Given
5676/// \code
5677/// class X { int a; int b; };
5678/// \endcode
5679/// cxxRecordDecl(
5680/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
5681/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
5682/// matches the class \c X, as \c a and \c b have the same type.
5683///
5684/// Note that when multiple matches are involved via \c forEach* matchers,
5685/// \c equalsBoundNodes acts as a filter.
5686/// For example:
5687/// compoundStmt(
5688/// forEachDescendant(varDecl().bind("d")),
5689/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
5690/// will trigger a match for each combination of variable declaration
5691/// and reference to that variable declaration within a compound statement.
5694 QualType),
5695 std::string, ID) {
5696 // FIXME: Figure out whether it makes sense to allow this
5697 // on any other node types.
5698 // For *Loc it probably does not make sense, as those seem
5699 // unique. For NestedNameSepcifier it might make sense, as
5700 // those also have pointer identity, but I'm not sure whether
5701 // they're ever reused.
5702 internal::NotEqualsBoundNodePredicate Predicate;
5703 Predicate.ID = ID;
5704 Predicate.Node = DynTypedNode::create(Node);
5705 return Builder->removeBindings(Predicate);
5706}
5707
5708/// Matches the condition variable statement in an if statement.
5709///
5710/// Given
5711/// \code
5712/// if (A* a = GetAPointer()) {}
5713/// \endcode
5714/// hasConditionVariableStatement(...)
5715/// matches 'A* a = GetAPointer()'.
5716AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
5717 internal::Matcher<DeclStmt>, InnerMatcher) {
5718 const DeclStmt* const DeclarationStatement =
5719 Node.getConditionVariableDeclStmt();
5720 return DeclarationStatement != nullptr &&
5721 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
5722}
5723
5724/// Matches the index expression of an array subscript expression.
5725///
5726/// Given
5727/// \code
5728/// int i[5];
5729/// void f() { i[1] = 42; }
5730/// \endcode
5731/// arraySubscriptExpression(hasIndex(integerLiteral()))
5732/// matches \c i[1] with the \c integerLiteral() matching \c 1
5734 internal::Matcher<Expr>, InnerMatcher) {
5735 if (const Expr* Expression = Node.getIdx())
5736 return InnerMatcher.matches(*Expression, Finder, Builder);
5737 return false;
5738}
5739
5740/// Matches the base expression of an array subscript expression.
5741///
5742/// Given
5743/// \code
5744/// int i[5];
5745/// void f() { i[1] = 42; }
5746/// \endcode
5747/// arraySubscriptExpression(hasBase(implicitCastExpr(
5748/// hasSourceExpression(declRefExpr()))))
5749/// matches \c i[1] with the \c declRefExpr() matching \c i
5751 internal::Matcher<Expr>, InnerMatcher) {
5752 if (const Expr* Expression = Node.getBase())
5753 return InnerMatcher.matches(*Expression, Finder, Builder);
5754 return false;
5755}
5756
5757/// Matches a 'for', 'while', 'while' statement or a function or coroutine
5758/// definition that has a given body. Note that in case of functions or
5759/// coroutines this matcher only matches the definition itself and not the
5760/// other declarations of the same function or coroutine.
5761///
5762/// Given
5763/// \code
5764/// for (;;) {}
5765/// \endcode
5766/// forStmt(hasBody(compoundStmt()))
5767/// matches 'for (;;) {}'
5768/// with compoundStmt()
5769/// matching '{}'
5770///
5771/// Given
5772/// \code
5773/// void f();
5774/// void f() {}
5775/// \endcode
5776/// functionDecl(hasBody(compoundStmt()))
5777/// matches 'void f() {}'
5778/// with compoundStmt()
5779/// matching '{}'
5780/// but does not match 'void f();'
5782 hasBody,
5785 internal::Matcher<Stmt>, InnerMatcher) {
5786 if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node))
5787 return false;
5788 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
5789 return (Statement != nullptr &&
5790 InnerMatcher.matches(*Statement, Finder, Builder));
5791}
5792
5793/// Matches a function declaration that has a given body present in the AST.
5794/// Note that this matcher matches all the declarations of a function whose
5795/// body is present in the AST.
5796///
5797/// Given
5798/// \code
5799/// void f();
5800/// void f() {}
5801/// void g();
5802/// \endcode
5803/// functionDecl(hasAnyBody(compoundStmt()))
5804/// matches both 'void f();'
5805/// and 'void f() {}'
5806/// with compoundStmt()
5807/// matching '{}'
5808/// but does not match 'void g();'
5810 internal::Matcher<Stmt>, InnerMatcher) {
5811 const Stmt *const Statement = Node.getBody();
5812 return (Statement != nullptr &&
5813 InnerMatcher.matches(*Statement, Finder, Builder));
5814}
5815
5816
5817/// Matches compound statements where at least one substatement matches
5818/// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
5819///
5820/// Given
5821/// \code
5822/// { {}; 1+2; }
5823/// \endcode
5824/// hasAnySubstatement(compoundStmt())
5825/// matches '{ {}; 1+2; }'
5826/// with compoundStmt()
5827/// matching '{}'
5828AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
5830 StmtExpr),
5831 internal::Matcher<Stmt>, InnerMatcher) {
5832 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
5833 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
5834 CS->body_end(), Finder,
5835 Builder) != CS->body_end();
5836}
5837
5838/// Checks that a compound statement contains a specific number of
5839/// child statements.
5840///
5841/// Example: Given
5842/// \code
5843/// { for (;;) {} }
5844/// \endcode
5845/// compoundStmt(statementCountIs(0)))
5846/// matches '{}'
5847/// but does not match the outer compound statement.
5848AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
5849 return Node.size() == N;
5850}
5851
5852/// Matches literals that are equal to the given value of type ValueT.
5853///
5854/// Given
5855/// \code
5856/// f('\0', false, 3.14, 42);
5857/// \endcode
5858/// characterLiteral(equals(0))
5859/// matches '\0'
5860/// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
5861/// match false
5862/// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
5863/// match 3.14
5864/// integerLiteral(equals(42))
5865/// matches 42
5866///
5867/// Note that you cannot directly match a negative numeric literal because the
5868/// minus sign is not part of the literal: It is a unary operator whose operand
5869/// is the positive numeric literal. Instead, you must use a unaryOperator()
5870/// matcher to match the minus sign:
5871///
5872/// unaryOperator(hasOperatorName("-"),
5873/// hasUnaryOperand(integerLiteral(equals(13))))
5874///
5875/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
5876/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
5877template <typename ValueT>
5878internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5879 void(internal::AllNodeBaseTypes), ValueT>
5880equals(const ValueT &Value) {
5881 return internal::PolymorphicMatcher<internal::ValueEqualsMatcher,
5882 void(internal::AllNodeBaseTypes), ValueT>(
5883 Value);
5884}
5885
5890 bool, Value, 0) {
5891 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5892 .matchesNode(Node);
5893}
5894
5899 unsigned, Value, 1) {
5900 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5901 .matchesNode(Node);
5902}
5903
5909 double, Value, 2) {
5910 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
5911 .matchesNode(Node);
5912}
5913
5914/// Matches the operator Name of operator expressions and fold expressions
5915/// (binary or unary).
5916///
5917/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
5918/// \code
5919/// !(a || b)
5920/// \endcode
5921///
5922/// Example matches `(0 + ... + args)`
5923/// (matcher = cxxFoldExpr(hasOperatorName("+")))
5924/// \code
5925/// template <typename... Args>
5926/// auto sum(Args... args) {
5927/// return (0 + ... + args);
5928/// }
5929/// \endcode
5931 hasOperatorName,
5935 std::string, Name) {
5936 if (std::optional<StringRef> OpName = internal::getOpName(Node))
5937 return *OpName == Name;
5938 return false;
5939}
5940
5941/// Matches operator expressions (binary or unary) that have any of the
5942/// specified names.
5943///
5944/// hasAnyOperatorName("+", "-")
5945/// Is equivalent to
5946/// anyOf(hasOperatorName("+"), hasOperatorName("-"))
5947extern const internal::VariadicFunction<
5948 internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher,
5952 std::vector<std::string>>,
5955
5956/// Matches all kinds of assignment operators.
5957///
5958/// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
5959/// \code
5960/// if (a == b)
5961/// a += b;
5962/// \endcode
5963///
5964/// Example 2: matches s1 = s2
5965/// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
5966/// \code
5967/// struct S { S& operator=(const S&); };
5968/// void x() { S s1, s2; s1 = s2; }
5969/// \endcode
5971 isAssignmentOperator,
5974 return Node.isAssignmentOp();
5975}
5976
5977/// Matches comparison operators.
5978///
5979/// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator()))
5980/// \code
5981/// if (a == b)
5982/// a += b;
5983/// \endcode
5984///
5985/// Example 2: matches s1 < s2
5986/// (matcher = cxxOperatorCallExpr(isComparisonOperator()))
5987/// \code
5988/// struct S { bool operator<(const S& other); };
5989/// void x(S s1, S s2) { bool b1 = s1 < s2; }
5990/// \endcode
5992 isComparisonOperator,
5995 return Node.isComparisonOp();
5996}
5997
5998/// Matches the left hand side of binary operator expressions.
5999///
6000/// Example matches a (matcher = binaryOperator(hasLHS()))
6001/// \code
6002/// a || b
6003/// \endcode
6005 hasLHS,
6009 internal::Matcher<Expr>, InnerMatcher) {
6010 const Expr *LeftHandSide = internal::getLHS(Node);
6011 return (LeftHandSide != nullptr &&
6012 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
6013}
6014
6015/// Matches the right hand side of binary operator expressions.
6016///
6017/// Example matches b (matcher = binaryOperator(hasRHS()))
6018/// \code
6019/// a || b
6020/// \endcode
6022 hasRHS,
6026 internal::Matcher<Expr>, InnerMatcher) {
6027 const Expr *RightHandSide = internal::getRHS(Node);
6028 return (RightHandSide != nullptr &&
6029 InnerMatcher.matches(*RightHandSide, Finder, Builder));
6030}
6031
6032/// Matches if either the left hand side or the right hand side of a
6033/// binary operator or fold expression matches.
6035 hasEitherOperand,
6038 internal::Matcher<Expr>, InnerMatcher) {
6039 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6040 anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)))
6041 .matches(Node, Finder, Builder);
6042}
6043
6044/// Matches if both matchers match with opposite sides of the binary operator
6045/// or fold expression.
6046///
6047/// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1),
6048/// integerLiteral(equals(2)))
6049/// \code
6050/// 1 + 2 // Match
6051/// 2 + 1 // Match
6052/// 1 + 1 // No match
6053/// 2 + 2 // No match
6054/// \endcode
6056 hasOperands,
6059 internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) {
6060 return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()(
6061 anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)),
6062 allOf(hasRHS(Matcher1), hasLHS(Matcher2))))
6063 .matches(Node, Finder, Builder);
6064}
6065
6066/// Matches if the operand of a unary operator matches.
6067///
6068/// Example matches true (matcher = hasUnaryOperand(
6069/// cxxBoolLiteral(equals(true))))
6070/// \code
6071/// !true
6072/// \endcode
6076 internal::Matcher<Expr>, InnerMatcher) {
6077 const Expr *const Operand = internal::getSubExpr(Node);
6078 return (Operand != nullptr &&
6079 InnerMatcher.matches(*Operand, Finder, Builder));
6080}
6081
6082/// Matches if the cast's source expression
6083/// or opaque value's source expression matches the given matcher.
6084///
6085/// Example 1: matches "a string"
6086/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
6087/// \code
6088/// class URL { URL(string); };
6089/// URL url = "a string";
6090/// \endcode
6091///
6092/// Example 2: matches 'b' (matcher =
6093/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
6094/// \code
6095/// int a = b ?: 1;
6096/// \endcode
6097AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
6100 internal::Matcher<Expr>, InnerMatcher) {
6101 const Expr *const SubExpression =
6102 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
6103 return (SubExpression != nullptr &&
6104 InnerMatcher.matches(*SubExpression, Finder, Builder));
6105}
6106
6107/// Matches casts that has a given cast kind.
6108///
6109/// Example: matches the implicit cast around \c 0
6110/// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
6111/// \code
6112/// int *p = 0;
6113/// \endcode
6114///
6115/// If the matcher is use from clang-query, CastKind parameter
6116/// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer").
6118 return Node.getCastKind() == Kind;
6119}
6120
6121/// Matches casts whose destination type matches a given matcher.
6122///
6123/// (Note: Clang's AST refers to other conversions as "casts" too, and calls
6124/// actual casts "explicit" casts.)
6126 internal::Matcher<QualType>, InnerMatcher) {
6127 const QualType NodeType = Node.getTypeAsWritten();
6128 return InnerMatcher.matches(NodeType, Finder, Builder);
6129}
6130
6131/// Matches implicit casts whose destination type matches a given
6132/// matcher.
6133AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
6134 internal::Matcher<QualType>, InnerMatcher) {
6135 return InnerMatcher.matches(Node.getType(), Finder, Builder);
6136}
6137
6138/// Matches TagDecl object that are spelled with "struct."
6139///
6140/// Example matches S, but not C, U or E.
6141/// \code
6142/// struct S {};
6143/// class C {};
6144/// union U {};
6145/// enum E {};
6146/// \endcode
6148 return Node.isStruct();
6149}
6150
6151/// Matches TagDecl object that are spelled with "union."
6152///
6153/// Example matches U, but not C, S or E.
6154/// \code
6155/// struct S {};
6156/// class C {};
6157/// union U {};
6158/// enum E {};
6159/// \endcode
6161 return Node.isUnion();
6162}
6163
6164/// Matches TagDecl object that are spelled with "class."
6165///
6166/// Example matches C, but not S, U or E.
6167/// \code
6168/// struct S {};
6169/// class C {};
6170/// union U {};
6171/// enum E {};
6172/// \endcode
6174 return Node.isClass();
6175}
6176
6177/// Matches TagDecl object that are spelled with "enum."
6178///
6179/// Example matches E, but not C, S or U.
6180/// \code
6181/// struct S {};
6182/// class C {};
6183/// union U {};
6184/// enum E {};
6185/// \endcode
6187 return Node.isEnum();
6188}
6189
6190/// Matches the true branch expression of a conditional operator.
6191///
6192/// Example 1 (conditional ternary operator): matches a
6193/// \code
6194/// condition ? a : b
6195/// \endcode
6196///
6197/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
6198/// \code
6199/// condition ?: b
6200/// \endcode
6202 internal::Matcher<Expr>, InnerMatcher) {
6203 const Expr *Expression = Node.getTrueExpr();
6204 return (Expression != nullptr &&
6205 InnerMatcher.matches(*Expression, Finder, Builder));
6206}
6207
6208/// Matches the false branch expression of a conditional operator
6209/// (binary or ternary).
6210///
6211/// Example matches b
6212/// \code
6213/// condition ? a : b
6214/// condition ?: b
6215/// \endcode
6217 internal::Matcher<Expr>, InnerMatcher) {
6218 const Expr *Expression = Node.getFalseExpr();
6219 return (Expression != nullptr &&
6220 InnerMatcher.matches(*Expression, Finder, Builder));
6221}
6222
6223/// Matches if a declaration has a body attached.
6224///
6225/// Example matches A, va, fa
6226/// \code
6227/// class A {};
6228/// class B; // Doesn't match, as it has no body.
6229/// int va;
6230/// extern int vb; // Doesn't match, as it doesn't define the variable.
6231/// void fa() {}
6232/// void fb(); // Doesn't match, as it has no body.
6233/// @interface X
6234/// - (void)ma; // Doesn't match, interface is declaration.
6235/// @end
6236/// @implementation X
6237/// - (void)ma {}
6238/// @end
6239/// \endcode
6240///
6241/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
6242/// Matcher<ObjCMethodDecl>
6246 FunctionDecl)) {
6247 return Node.isThisDeclarationADefinition();
6248}
6249
6250/// Matches if a function declaration is variadic.
6251///
6252/// Example matches f, but not g or h. The function i will not match, even when
6253/// compiled in C mode.
6254/// \code
6255/// void f(...);
6256/// void g(int);
6257/// template <typename... Ts> void h(Ts...);
6258/// void i();
6259/// \endcode
6261 return Node.isVariadic();
6262}
6263
6264/// Matches the class declaration that the given method declaration
6265/// belongs to.
6266///
6267/// FIXME: Generalize this for other kinds of declarations.
6268/// FIXME: What other kind of declarations would we need to generalize
6269/// this to?
6270///
6271/// Example matches A() in the last line
6272/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
6273/// ofClass(hasName("A"))))))
6274/// \code
6275/// class A {
6276/// public:
6277/// A();
6278/// };
6279/// A a = A();
6280/// \endcode
6282 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
6283
6284 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
6285
6286 const CXXRecordDecl *Parent = Node.getParent();
6287 return (Parent != nullptr &&
6288 InnerMatcher.matches(*Parent, Finder, Builder));
6289}
6290
6291/// Matches each method overridden by the given method. This matcher may
6292/// produce multiple matches.
6293///
6294/// Given
6295/// \code
6296/// class A { virtual void f(); };
6297/// class B : public A { void f(); };
6298/// class C : public B { void f(); };
6299/// \endcode
6300/// cxxMethodDecl(ofClass(hasName("C")),
6301/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6302/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
6303/// that B::f is not overridden by C::f).
6304///
6305/// The check can produce multiple matches in case of multiple inheritance, e.g.
6306/// \code
6307/// class A1 { virtual void f(); };
6308/// class A2 { virtual void f(); };
6309/// class C : public A1, public A2 { void f(); };
6310/// \endcode
6311/// cxxMethodDecl(ofClass(hasName("C")),
6312/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
6313/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
6314/// once with "b" binding "A2::f" and "d" binding "C::f".
6315AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
6316 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
6317 BoundNodesTreeBuilder Result;
6318 bool Matched = false;
6319 for (const auto *Overridden : Node.overridden_methods()) {
6320 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
6321 const bool OverriddenMatched =
6322 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
6323 if (OverriddenMatched) {
6324 Matched = true;
6325 Result.addMatch(OverriddenBuilder);
6326 }
6327 }
6328 *Builder = std::move(Result);
6329 return Matched;
6330}
6331
6332/// Matches declarations of virtual methods and C++ base specifers that specify
6333/// virtual inheritance.
6334///
6335/// Example:
6336/// \code
6337/// class A {
6338/// public:
6339/// virtual void x(); // matches x
6340/// };
6341/// \endcode
6342///
6343/// Example:
6344/// \code
6345/// class Base {};
6346/// class DirectlyDerived : virtual Base {}; // matches Base
6347/// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base
6348/// \endcode
6349///
6350/// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier>
6354 return Node.isVirtual();
6355}
6356
6357/// Matches if the given method declaration has an explicit "virtual".
6358///
6359/// Given
6360/// \code
6361/// class A {
6362/// public:
6363/// virtual void x();
6364/// };
6365/// class B : public A {
6366/// public:
6367/// void x();
6368/// };
6369/// \endcode
6370/// matches A::x but not B::x
6371AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
6372 return Node.isVirtualAsWritten();
6373}
6374
6375AST_MATCHER(CXXConstructorDecl, isInheritingConstructor) {
6376 return Node.isInheritingConstructor();
6377}
6378
6379/// Matches if the given method or class declaration is final.
6380///
6381/// Given:
6382/// \code
6383/// class A final {};
6384///
6385/// struct B {
6386/// virtual void f();
6387/// };
6388///
6389/// struct C : B {
6390/// void f() final;
6391/// };
6392/// \endcode
6393/// matches A and C::f, but not B, C, or B::f
6396 CXXMethodDecl)) {
6397 return Node.template hasAttr<FinalAttr>();
6398}
6399
6400/// Matches if the given method declaration is pure.
6401///
6402/// Given
6403/// \code
6404/// class A {
6405/// public:
6406/// virtual void x() = 0;
6407/// };
6408/// \endcode
6409/// matches A::x
6410AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPureVirtual(); }
6411
6412/// Matches if the given method declaration is const.
6413///
6414/// Given
6415/// \code
6416/// struct A {
6417/// void foo() const;
6418/// void bar();
6419/// };
6420/// \endcode
6421///
6422/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
6424 return Node.isConst();
6425}
6426
6427/// Matches if the given method declaration declares a copy assignment
6428/// operator.
6429///
6430/// Given
6431/// \code
6432/// struct A {
6433/// A &operator=(const A &);
6434/// A &operator=(A &&);
6435/// };
6436/// \endcode
6437///
6438/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
6439/// the second one.
6440AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
6441 return Node.isCopyAssignmentOperator();
6442}
6443
6444/// Matches if the given method declaration declares a move assignment
6445/// operator.
6446///
6447/// Given
6448/// \code
6449/// struct A {
6450/// A &operator=(const A &);
6451/// A &operator=(A &&);
6452/// };
6453/// \endcode
6454///
6455/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
6456/// the first one.
6457AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
6458 return Node.isMoveAssignmentOperator();
6459}
6460
6461/// Matches if the given method declaration overrides another method.
6462///
6463/// Given
6464/// \code
6465/// class A {
6466/// public:
6467/// virtual void x();
6468/// };
6469/// class B : public A {
6470/// public:
6471/// virtual void x();
6472/// };
6473/// \endcode
6474/// matches B::x
6476 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
6477}
6478
6479/// Matches method declarations that are user-provided.
6480///
6481/// Given
6482/// \code
6483/// struct S {
6484/// S(); // #1
6485/// S(const S &) = default; // #2
6486/// S(S &&) = delete; // #3
6487/// };
6488/// \endcode
6489/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
6490AST_MATCHER(CXXMethodDecl, isUserProvided) {
6491 return Node.isUserProvided();
6492}
6493
6494/// Matches member expressions that are called with '->' as opposed
6495/// to '.'.
6496///
6497/// Member calls on the implicit this pointer match as called with '->'.
6498///
6499/// Given
6500/// \code
6501/// class Y {
6502/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
6503/// template <class T> void f() { this->f<T>(); f<T>(); }
6504/// int a;
6505/// static int b;
6506/// };
6507/// template <class T>
6508/// class Z {
6509/// void x() { this->m; }
6510/// };
6511/// \endcode
6512/// memberExpr(isArrow())
6513/// matches this->x, x, y.x, a, this->b
6514/// cxxDependentScopeMemberExpr(isArrow())
6515/// matches this->m
6516/// unresolvedMemberExpr(isArrow())
6517/// matches this->f<T>, f<T>
6521 return Node.isArrow();
6522}
6523
6524/// Matches QualType nodes that are of integer type.
6525///
6526/// Given
6527/// \code
6528/// void a(int);
6529/// void b(long);
6530/// void c(double);
6531/// \endcode
6532/// functionDecl(hasAnyParameter(hasType(isInteger())))
6533/// matches "a(int)", "b(long)", but not "c(double)".
6535 return Node->isIntegerType();
6536}
6537
6538/// Matches QualType nodes that are of unsigned integer type.
6539///
6540/// Given
6541/// \code
6542/// void a(int);
6543/// void b(unsigned long);
6544/// void c(double);
6545/// \endcode
6546/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
6547/// matches "b(unsigned long)", but not "a(int)" and "c(double)".
6548AST_MATCHER(QualType, isUnsignedInteger) {
6549 return Node->isUnsignedIntegerType();
6550}
6551
6552/// Matches QualType nodes that are of signed integer type.
6553///
6554/// Given
6555/// \code
6556/// void a(int);
6557/// void b(unsigned long);
6558/// void c(double);
6559/// \endcode
6560/// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
6561/// matches "a(int)", but not "b(unsigned long)" and "c(double)".
6562AST_MATCHER(QualType, isSignedInteger) {
6563 return Node->isSignedIntegerType();
6564}
6565
6566/// Matches QualType nodes that are of character type.
6567///
6568/// Given
6569/// \code
6570/// void a(char);
6571/// void b(wchar_t);
6572/// void c(double);
6573/// \endcode
6574/// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
6575/// matches "a(char)", "b(wchar_t)", but not "c(double)".
6576AST_MATCHER(QualType, isAnyCharacter) {
6577 return Node->isAnyCharacterType();
6578}
6579
6580/// Matches QualType nodes that are of any pointer type; this includes
6581/// the Objective-C object pointer type, which is different despite being
6582/// syntactically similar.
6583///
6584/// Given
6585/// \code
6586/// int *i = nullptr;
6587///
6588/// @interface Foo
6589/// @end
6590/// Foo *f;
6591///
6592/// int j;
6593/// \endcode
6594/// varDecl(hasType(isAnyPointer()))
6595/// matches "int *i" and "Foo *f", but not "int j".
6596AST_MATCHER(QualType, isAnyPointer) {
6597 return Node->isAnyPointerType();
6598}
6599
6600/// Matches QualType nodes that are const-qualified, i.e., that
6601/// include "top-level" const.
6602///
6603/// Given
6604/// \code
6605/// void a(int);
6606/// void b(int const);
6607/// void c(const int);
6608/// void d(const int*);
6609/// void e(int const) {};
6610/// \endcode
6611/// functionDecl(hasAnyParameter(hasType(isConstQualified())))
6612/// matches "void b(int const)", "void c(const int)" and
6613/// "void e(int const) {}". It does not match d as there
6614/// is no top-level const on the parameter type "const int *".
6615AST_MATCHER(QualType, isConstQualified) {
6616 return Node.isConstQualified();
6617}
6618
6619/// Matches QualType nodes that are volatile-qualified, i.e., that
6620/// include "top-level" volatile.
6621///
6622/// Given
6623/// \code
6624/// void a(int);
6625/// void b(int volatile);
6626/// void c(volatile int);
6627/// void d(volatile int*);
6628/// void e(int volatile) {};
6629/// \endcode
6630/// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
6631/// matches "void b(int volatile)", "void c(volatile int)" and
6632/// "void e(int volatile) {}". It does not match d as there
6633/// is no top-level volatile on the parameter type "volatile int *".
6634AST_MATCHER(QualType, isVolatileQualified) {
6635 return Node.isVolatileQualified();
6636}
6637
6638/// Matches QualType nodes that have local CV-qualifiers attached to
6639/// the node, not hidden within a typedef.
6640///
6641/// Given
6642/// \code
6643/// typedef const int const_int;
6644/// const_int i;
6645/// int *const j;
6646/// int *volatile k;
6647/// int m;
6648/// \endcode
6649/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
6650/// \c i is const-qualified but the qualifier is not local.
6651AST_MATCHER(QualType, hasLocalQualifiers) {
6652 return Node.hasLocalQualifiers();
6653}
6654
6655/// Matches a member expression where the member is matched by a
6656/// given matcher.
6657///
6658/// Given
6659/// \code
6660/// struct { int first, second; } first, second;
6661/// int i(second.first);
6662/// int j(first.second);
6663/// \endcode
6664/// memberExpr(member(hasName("first")))
6665/// matches second.first
6666/// but not first.second (because the member name there is "second").
6668 internal::Matcher<ValueDecl>, InnerMatcher) {
6669 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
6670}
6671
6672/// Matches a member expression where the object expression is matched by a
6673/// given matcher. Implicit object expressions are included; that is, it matches
6674/// use of implicit `this`.
6675///
6676/// Given
6677/// \code
6678/// struct X {
6679/// int m;
6680/// int f(X x) { x.m; return m; }
6681/// };
6682/// \endcode
6683/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
6684/// matches `x.m`, but not `m`; however,
6685/// memberExpr(hasObjectExpression(hasType(pointsTo(
6686// cxxRecordDecl(hasName("X"))))))
6687/// matches `m` (aka. `this->m`), but not `x.m`.
6689 hasObjectExpression,
6692 internal::Matcher<Expr>, InnerMatcher) {
6693 if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
6694 if (E->isImplicitAccess())
6695 return false;
6696 if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
6697 if (E->isImplicitAccess())
6698 return false;
6699 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
6700}
6701
6702/// Matches any using shadow declaration.
6703///
6704/// Given
6705/// \code
6706/// namespace X { void b(); }
6707/// using X::b;
6708/// \endcode
6709/// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
6710/// matches \code using X::b \endcode
6711AST_MATCHER_P(BaseUsingDecl, hasAnyUsingShadowDecl,
6712 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
6713 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
6714 Node.shadow_end(), Finder,
6715 Builder) != Node.shadow_end();
6716}
6717
6718/// Matches a using shadow declaration where the target declaration is
6719/// matched by the given matcher.
6720///
6721/// Given
6722/// \code
6723/// namespace X { int a; void b(); }
6724/// using X::a;
6725/// using X::b;
6726/// \endcode
6727/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
6728/// matches \code using X::b \endcode
6729/// but not \code using X::a \endcode
6731 internal::Matcher<NamedDecl>, InnerMatcher) {
6732 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
6733}
6734
6735/// Matches template instantiations of function, class, or static
6736/// member variable template instantiations.
6737///
6738/// Given
6739/// \code
6740/// template <typename T> class X {}; class A {}; X<A> x;
6741/// \endcode
6742/// or
6743/// \code
6744/// template <typename T> class X {}; class A {}; template class X<A>;
6745/// \endcode
6746/// or
6747/// \code
6748/// template <typename T> class X {}; class A {}; extern template class X<A>;
6749/// \endcode
6750/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6751/// matches the template instantiation of X<A>.
6752///
6753/// But given
6754/// \code
6755/// template <typename T> class X {}; class A {};
6756/// template <> class X<A> {}; X<A> x;
6757/// \endcode
6758/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
6759/// does not match, as X<A> is an explicit template specialization.
6760///
6761/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6764 CXXRecordDecl)) {
6765 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
6766 Node.getTemplateSpecializationKind() ==
6768 Node.getTemplateSpecializationKind() ==
6770}
6771
6772/// Matches declarations that are template instantiations or are inside
6773/// template instantiations.
6774///
6775/// Given
6776/// \code
6777/// template<typename T> void A(T t) { T i; }
6778/// A(0);
6779/// A(0U);
6780/// \endcode
6781/// functionDecl(isInstantiated())
6782/// matches 'A(int) {...};' and 'A(unsigned) {...}'.
6783AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
6784 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
6787 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
6788}
6789
6790/// Matches statements inside of a template instantiation.
6791///
6792/// Given
6793/// \code
6794/// int j;
6795/// template<typename T> void A(T t) { T i; j += 42;}
6796/// A(0);
6797/// A(0U);
6798/// \endcode
6799/// declStmt(isInTemplateInstantiation())
6800/// matches 'int i;' and 'unsigned i'.
6801/// unless(stmt(isInTemplateInstantiation()))
6802/// will NOT match j += 42; as it's shared between the template definition and
6803/// instantiation.
6804AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
6808}
6809
6810/// Matches explicit template specializations of function, class, or
6811/// static member variable template instantiations.
6812///
6813/// Given
6814/// \code
6815/// template<typename T> void A(T t) { }
6816/// template<> void A(int N) { }
6817/// \endcode
6818/// functionDecl(isExplicitTemplateSpecialization())
6819/// matches the specialization A<int>().
6820///
6821/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
6822AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
6824 CXXRecordDecl)) {
6825 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
6826}
6827
6828/// Matches \c TypeLocs for which the given inner
6829/// QualType-matcher matches.
6830AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
6831 internal::Matcher<QualType>, InnerMatcher, 0) {
6832 return internal::BindableMatcher<TypeLoc>(
6833 new internal::TypeLocTypeMatcher(InnerMatcher));
6834}
6835
6836/// Matches `QualifiedTypeLoc`s in the clang AST.
6837///
6838/// Given
6839/// \code
6840/// const int x = 0;
6841/// \endcode
6842/// qualifiedTypeLoc()
6843/// matches `const int`.
6844extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, QualifiedTypeLoc>
6846
6847/// Matches `QualifiedTypeLoc`s that have an unqualified `TypeLoc` matching
6848/// `InnerMatcher`.
6849///
6850/// Given
6851/// \code
6852/// int* const x;
6853/// const int y;
6854/// \endcode
6855/// qualifiedTypeLoc(hasUnqualifiedLoc(pointerTypeLoc()))
6856/// matches the `TypeLoc` of the variable declaration of `x`, but not `y`.
6857AST_MATCHER_P(QualifiedTypeLoc, hasUnqualifiedLoc, internal::Matcher<TypeLoc>,
6858 InnerMatcher) {
6859 return InnerMatcher.matches(Node.getUnqualifiedLoc(), Finder, Builder);
6860}
6861
6862/// Matches a function declared with the specified return `TypeLoc`.
6863///
6864/// Given
6865/// \code
6866/// int f() { return 5; }
6867/// void g() {}
6868/// \endcode
6869/// functionDecl(hasReturnTypeLoc(loc(asString("int"))))
6870/// matches the declaration of `f`, but not `g`.
6871AST_MATCHER_P(FunctionDecl, hasReturnTypeLoc, internal::Matcher<TypeLoc>,
6872 ReturnMatcher) {
6873 auto Loc = Node.getFunctionTypeLoc();
6874 return Loc && ReturnMatcher.matches(Loc.getReturnLoc(), Finder, Builder);
6875}
6876
6877/// Matches pointer `TypeLoc`s.
6878///
6879/// Given
6880/// \code
6881/// int* x;
6882/// \endcode
6883/// pointerTypeLoc()
6884/// matches `int*`.
6885extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, PointerTypeLoc>
6887
6888/// Matches pointer `TypeLoc`s that have a pointee `TypeLoc` matching
6889/// `PointeeMatcher`.
6890///
6891/// Given
6892/// \code
6893/// int* x;
6894/// \endcode
6895/// pointerTypeLoc(hasPointeeLoc(loc(asString("int"))))
6896/// matches `int*`.
6897AST_MATCHER_P(PointerTypeLoc, hasPointeeLoc, internal::Matcher<TypeLoc>,
6898 PointeeMatcher) {
6899 return PointeeMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
6900}
6901
6902/// Matches reference `TypeLoc`s.
6903///
6904/// Given
6905/// \code
6906/// int x = 3;
6907/// int& l = x;
6908/// int&& r = 3;
6909/// \endcode
6910/// referenceTypeLoc()
6911/// matches `int&` and `int&&`.
6912extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ReferenceTypeLoc>
6914
6915/// Matches reference `TypeLoc`s that have a referent `TypeLoc` matching
6916/// `ReferentMatcher`.
6917///
6918/// Given
6919/// \code
6920/// int x = 3;
6921/// int& xx = x;
6922/// \endcode
6923/// referenceTypeLoc(hasReferentLoc(loc(asString("int"))))
6924/// matches `int&`.
6925AST_MATCHER_P(ReferenceTypeLoc, hasReferentLoc, internal::Matcher<TypeLoc>,
6926 ReferentMatcher) {
6927 return ReferentMatcher.matches(Node.getPointeeLoc(), Finder, Builder);
6928}
6929
6930/// Matches template specialization `TypeLoc`s.
6931///
6932/// Given
6933/// \code
6934/// template <typename T> class C {};
6935/// C<char> var;
6936/// \endcode
6937/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(typeLoc())))
6938/// matches `C<char> var`.
6939extern const internal::VariadicDynCastAllOfMatcher<
6942
6943/// Matches template specialization `TypeLoc`s, class template specializations,
6944/// variable template specializations, and function template specializations
6945/// that have at least one `TemplateArgumentLoc` matching the given
6946/// `InnerMatcher`.
6947///
6948/// Given
6949/// \code
6950/// template<typename T> class A {};
6951/// A<int> a;
6952/// \endcode
6953/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasAnyTemplateArgumentLoc(
6954/// hasTypeLoc(loc(asString("int")))))))
6955/// matches `A<int> a`.
6957 hasAnyTemplateArgumentLoc,
6961 internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
6962 auto Args = internal::getTemplateArgsWritten(Node);
6963 return matchesFirstInRange(InnerMatcher, Args.begin(), Args.end(), Finder,
6964 Builder) != Args.end();
6965 return false;
6966}
6967
6968/// Matches template specialization `TypeLoc`s, class template specializations,
6969/// variable template specializations, and function template specializations
6970/// where the n'th `TemplateArgumentLoc` matches the given `InnerMatcher`.
6971///
6972/// Given
6973/// \code
6974/// template<typename T, typename U> class A {};
6975/// A<double, int> b;
6976/// A<int, double> c;
6977/// \endcode
6978/// varDecl(hasTypeLoc(templateSpecializationTypeLoc(hasTemplateArgumentLoc(0,
6979/// hasTypeLoc(loc(asString("double")))))))
6980/// matches `A<double, int> b`, but not `A<int, double> c`.
6982 hasTemplateArgumentLoc,
6986 unsigned, Index, internal::Matcher<TemplateArgumentLoc>, InnerMatcher) {
6987 auto Args = internal::getTemplateArgsWritten(Node);
6988 return Index < Args.size() &&
6989 InnerMatcher.matches(Args[Index], Finder, Builder);
6990}
6991
6992/// Matches C or C++ elaborated `TypeLoc`s.
6993///
6994/// Given
6995/// \code
6996/// struct s {};
6997/// struct s ss;
6998/// \endcode
6999/// elaboratedTypeLoc()
7000/// matches the `TypeLoc` of the variable declaration of `ss`.
7001extern const internal::VariadicDynCastAllOfMatcher<TypeLoc, ElaboratedTypeLoc>
7003
7004/// Matches elaborated `TypeLoc`s that have a named `TypeLoc` matching
7005/// `InnerMatcher`.
7006///
7007/// Given
7008/// \code
7009/// template <typename T>
7010/// class C {};
7011/// class C<int> c;
7012///
7013/// class D {};
7014/// class D d;
7015/// \endcode
7016/// elaboratedTypeLoc(hasNamedTypeLoc(templateSpecializationTypeLoc()));
7017/// matches the `TypeLoc` of the variable declaration of `c`, but not `d`.
7018AST_MATCHER_P(ElaboratedTypeLoc, hasNamedTypeLoc, internal::Matcher<TypeLoc>,
7019 InnerMatcher) {
7020 return InnerMatcher.matches(Node.getNamedTypeLoc(), Finder, Builder);
7021}
7022
7023/// Matches type \c bool.
7024///
7025/// Given
7026/// \code
7027/// struct S { bool func(); };
7028/// \endcode
7029/// functionDecl(returns(booleanType()))
7030/// matches "bool func();"
7031AST_MATCHER(Type, booleanType) {
7032 return Node.isBooleanType();
7033}
7034
7035/// Matches type \c void.
7036///
7037/// Given
7038/// \code
7039/// struct S { void func(); };
7040/// \endcode
7041/// functionDecl(returns(voidType()))
7042/// matches "void func();"
7043AST_MATCHER(Type, voidType) {
7044 return Node.isVoidType();
7045}
7046
7047template <typename NodeType>
7048using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
7049
7050/// Matches builtin Types.
7051///
7052/// Given
7053/// \code
7054/// struct A {};
7055/// A a;
7056/// int b;
7057/// float c;
7058/// bool d;
7059/// \endcode
7060/// builtinType()
7061/// matches "int b", "float c" and "bool d"
7063
7064/// Matches all kinds of arrays.
7065///
7066/// Given
7067/// \code
7068/// int a[] = { 2, 3 };
7069/// int b[4];
7070/// void f() { int c[a[0]]; }
7071/// \endcode
7072/// arrayType()
7073/// matches "int a[]", "int b[4]" and "int c[a[0]]";
7075
7076/// Matches C99 complex types.
7077///
7078/// Given
7079/// \code
7080/// _Complex float f;
7081/// \endcode
7082/// complexType()
7083/// matches "_Complex float f"
7085
7086/// Matches any real floating-point type (float, double, long double).
7087///
7088/// Given
7089/// \code
7090/// int i;
7091/// float f;
7092/// \endcode
7093/// realFloatingPointType()
7094/// matches "float f" but not "int i"
7095AST_MATCHER(Type, realFloatingPointType) {
7096 return Node.isRealFloatingType();
7097}
7098
7099/// Matches arrays and C99 complex types that have a specific element
7100/// type.
7101///
7102/// Given
7103/// \code
7104/// struct A {};
7105/// A a[7];
7106/// int b[7];
7107/// \endcode
7108/// arrayType(hasElementType(builtinType()))
7109/// matches "int b[7]"
7110///
7111/// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
7112AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
7114 ComplexType));
7115
7116/// Matches C arrays with a specified constant size.
7117///
7118/// Given
7119/// \code
7120/// void() {
7121/// int a[2];
7122/// int b[] = { 2, 3 };
7123/// int c[b[0]];
7124/// }
7125/// \endcode
7126/// constantArrayType()
7127/// matches "int a[2]"
7129
7130/// Matches nodes that have the specified size.
7131///
7132/// Given
7133/// \code
7134/// int a[42];
7135/// int b[2 * 21];
7136/// int c[41], d[43];
7137/// char *s = "abcd";
7138/// wchar_t *ws = L"abcd";
7139/// char *w = "a";
7140/// \endcode
7141/// constantArrayType(hasSize(42))
7142/// matches "int a[42]" and "int b[2 * 21]"
7143/// stringLiteral(hasSize(4))
7144/// matches "abcd", L"abcd"
7148 unsigned, N) {
7149 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
7150}
7151
7152/// Matches C++ arrays whose size is a value-dependent expression.
7153///
7154/// Given
7155/// \code
7156/// template<typename T, int Size>
7157/// class array {
7158/// T data[Size];
7159/// };
7160/// \endcode
7161/// dependentSizedArrayType()
7162/// matches "T data[Size]"
7164
7165/// Matches C++ extended vector type where either the type or size is
7166/// dependent.
7167///
7168/// Given
7169/// \code
7170/// template<typename T, int Size>
7171/// class vector {
7172/// typedef T __attribute__((ext_vector_type(Size))) type;
7173/// };
7174/// \endcode
7175/// dependentSizedExtVectorType()
7176/// matches "T __attribute__((ext_vector_type(Size)))"
7179
7180/// Matches C arrays with unspecified size.
7181///
7182/// Given
7183/// \code
7184/// int a[] = { 2, 3 };
7185/// int b[42];
7186/// void f(int c[]) { int d[a[0]]; };
7187/// \endcode
7188/// incompleteArrayType()
7189/// matches "int a[]" and "int c[]"
7191
7192/// Matches C arrays with a specified size that is not an
7193/// integer-constant-expression.
7194///
7195/// Given
7196/// \code
7197/// void f() {
7198/// int a[] = { 2, 3 }
7199/// int b[42];
7200/// int c[a[0]];
7201/// }
7202/// \endcode
7203/// variableArrayType()
7204/// matches "int c[a[0]]"
7206
7207/// Matches \c VariableArrayType nodes that have a specific size
7208/// expression.
7209///
7210/// Given
7211/// \code
7212/// void f(int b) {
7213/// int a[b];
7214/// }
7215/// \endcode
7216/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
7217/// varDecl(hasName("b")))))))
7218/// matches "int a[b]"
7220 internal::Matcher<Expr>, InnerMatcher) {
7221 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
7222}
7223
7224/// Matches atomic types.
7225///
7226/// Given
7227/// \code
7228/// _Atomic(int) i;
7229/// \endcode
7230/// atomicType()
7231/// matches "_Atomic(int) i"
7233
7234/// Matches atomic types with a specific value type.
7235///
7236/// Given
7237/// \code
7238/// _Atomic(int) i;
7239/// _Atomic(float) f;
7240/// \endcode
7241/// atomicType(hasValueType(isInteger()))
7242/// matches "_Atomic(int) i"
7243///
7244/// Usable as: Matcher<AtomicType>
7247
7248/// Matches types nodes representing C++11 auto types.
7249///
7250/// Given:
7251/// \code
7252/// auto n = 4;
7253/// int v[] = { 2, 3 }
7254/// for (auto i : v) { }
7255/// \endcode
7256/// autoType()
7257/// matches "auto n" and "auto i"
7259
7260/// Matches types nodes representing C++11 decltype(<expr>) types.
7261///
7262/// Given:
7263/// \code
7264/// short i = 1;
7265/// int j = 42;
7266/// decltype(i + j) result = i + j;
7267/// \endcode
7268/// decltypeType()
7269/// matches "decltype(i + j)"
7271
7272/// Matches \c AutoType nodes where the deduced type is a specific type.
7273///
7274/// Note: There is no \c TypeLoc for the deduced type and thus no
7275/// \c getDeducedLoc() matcher.
7276///
7277/// Given
7278/// \code
7279/// auto a = 1;
7280/// auto b = 2.0;
7281/// \endcode
7282/// autoType(hasDeducedType(isInteger()))
7283/// matches "auto a"
7284///
7285/// Usable as: Matcher<AutoType>
7286AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
7288
7289/// Matches \c DecltypeType or \c UsingType nodes to find the underlying type.
7290///
7291/// Given
7292/// \code
7293/// decltype(1) a = 1;
7294/// decltype(2.0) b = 2.0;
7295/// \endcode
7296/// decltypeType(hasUnderlyingType(isInteger()))
7297/// matches the type of "a"
7298///
7299/// Usable as: Matcher<DecltypeType>, Matcher<UsingType>
7302 UsingType));
7303
7304/// Matches \c FunctionType nodes.
7305///
7306/// Given
7307/// \code
7308/// int (*f)(int);
7309/// void g();
7310/// \endcode
7311/// functionType()
7312/// matches "int (*f)(int)" and the type of "g".
7314
7315/// Matches \c FunctionProtoType nodes.
7316///
7317/// Given
7318/// \code
7319/// int (*f)(int);
7320/// void g();
7321/// \endcode
7322/// functionProtoType()
7323/// matches "int (*f)(int)" and the type of "g" in C++ mode.
7324/// In C mode, "g" is not matched because it does not contain a prototype.
7326
7327/// Matches \c ParenType nodes.
7328///
7329/// Given
7330/// \code
7331/// int (*ptr_to_array)[4];
7332/// int *array_of_ptrs[4];
7333/// \endcode
7334///
7335/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
7336/// \c array_of_ptrs.
7338
7339/// Matches \c ParenType nodes where the inner type is a specific type.
7340///
7341/// Given
7342/// \code
7343/// int (*ptr_to_array)[4];
7344/// int (*ptr_to_func)(int);
7345/// \endcode
7346///
7347/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
7348/// \c ptr_to_func but not \c ptr_to_array.
7349///
7350/// Usable as: Matcher<ParenType>
7351AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
7353
7354/// Matches block pointer types, i.e. types syntactically represented as
7355/// "void (^)(int)".
7356///
7357/// The \c pointee is always required to be a \c FunctionType.
7359
7360/// Matches member pointer types.
7361/// Given
7362/// \code
7363/// struct A { int i; }
7364/// A::* ptr = A::i;
7365/// \endcode
7366/// memberPointerType()
7367/// matches "A::* ptr"
7369
7370/// Matches pointer types, but does not match Objective-C object pointer
7371/// types.
7372///
7373/// Given
7374/// \code
7375/// int *a;
7376/// int &b = *a;
7377/// int c = 5;
7378///
7379/// @interface Foo
7380/// @end
7381/// Foo *f;
7382/// \endcode
7383/// pointerType()
7384/// matches "int *a", but does not match "Foo *f".
7386
7387/// Matches an Objective-C object pointer type, which is different from
7388/// a pointer type, despite being syntactically similar.
7389///
7390/// Given
7391/// \code
7392/// int *a;
7393///
7394/// @interface Foo
7395/// @end
7396/// Foo *f;
7397/// \endcode
7398/// pointerType()
7399/// matches "Foo *f", but does not match "int *a".
7401
7402/// Matches both lvalue and rvalue reference types.
7403///
7404/// Given
7405/// \code
7406/// int *a;
7407/// int &b = *a;
7408/// int &&c = 1;
7409/// auto &d = b;
7410/// auto &&e = c;
7411/// auto &&f = 2;
7412/// int g = 5;
7413/// \endcode
7414///
7415/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
7417
7418/// Matches lvalue reference types.
7419///
7420/// Given:
7421/// \code
7422/// int *a;
7423/// int &b = *a;
7424/// int &&c = 1;
7425/// auto &d = b;
7426/// auto &&e = c;
7427/// auto &&f = 2;
7428/// int g = 5;
7429/// \endcode
7430///
7431/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
7432/// matched since the type is deduced as int& by reference collapsing rules.
7434
7435/// Matches rvalue reference types.
7436///
7437/// Given:
7438/// \code
7439/// int *a;
7440/// int &b = *a;
7441/// int &&c = 1;
7442/// auto &d = b;
7443/// auto &&e = c;
7444/// auto &&f = 2;
7445/// int g = 5;
7446/// \endcode
7447///
7448/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
7449/// matched as it is deduced to int& by reference collapsing rules.
7451
7452/// Narrows PointerType (and similar) matchers to those where the
7453/// \c pointee matches a given matcher.
7454///
7455/// Given
7456/// \code
7457/// int *a;
7458/// int const *b;
7459/// float const *f;
7460/// \endcode
7461/// pointerType(pointee(isConstQualified(), isInteger()))
7462/// matches "int const *b"
7463///
7464/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
7465/// Matcher<PointerType>, Matcher<ReferenceType>
7467 pointee, getPointee,
7471
7472/// Matches typedef types.
7473///
7474/// Given
7475/// \code
7476/// typedef int X;
7477/// \endcode
7478/// typedefType()
7479/// matches "typedef int X"
7481
7482/// Matches qualified types when the qualifier is applied via a macro.
7483///
7484/// Given
7485/// \code
7486/// #define CDECL __attribute__((cdecl))
7487/// typedef void (CDECL *X)();
7488/// typedef void (__attribute__((cdecl)) *Y)();
7489/// \endcode
7490/// macroQualifiedType()
7491/// matches the type of the typedef declaration of \c X but not \c Y.
7493
7494/// Matches enum types.
7495///
7496/// Given
7497/// \code
7498/// enum C { Green };
7499/// enum class S { Red };
7500///
7501/// C c;
7502/// S s;
7503/// \endcode
7504//
7505/// \c enumType() matches the type of the variable declarations of both \c c and
7506/// \c s.
7508
7509/// Matches template specialization types.
7510///
7511/// Given
7512/// \code
7513/// template <typename T>
7514/// class C { };
7515///
7516/// template class C<int>; // A
7517/// C<char> var; // B
7518/// \endcode
7519///
7520/// \c templateSpecializationType() matches the type of the explicit
7521/// instantiation in \c A and the type of the variable declaration in \c B.
7524
7525/// Matches C++17 deduced template specialization types, e.g. deduced class
7526/// template types.
7527///
7528/// Given
7529/// \code
7530/// template <typename T>
7531/// class C { public: C(T); };
7532///
7533/// C c(123);
7534/// \endcode
7535/// \c deducedTemplateSpecializationType() matches the type in the declaration
7536/// of the variable \c c.
7539
7540/// Matches types nodes representing unary type transformations.
7541///
7542/// Given:
7543/// \code
7544/// typedef __underlying_type(T) type;
7545/// \endcode
7546/// unaryTransformType()
7547/// matches "__underlying_type(T)"
7549
7550/// Matches record types (e.g. structs, classes).
7551///
7552/// Given
7553/// \code
7554/// class C {};
7555/// struct S {};
7556///
7557/// C c;
7558/// S s;
7559/// \endcode
7560///
7561/// \c recordType() matches the type of the variable declarations of both \c c
7562/// and \c s.
7564
7565/// Matches tag types (record and enum types).
7566///
7567/// Given
7568/// \code
7569/// enum E {};
7570/// class C {};
7571///
7572/// E e;
7573/// C c;
7574/// \endcode
7575///
7576/// \c tagType() matches the type of the variable declarations of both \c e
7577/// and \c c.
7578extern const AstTypeMatcher<TagType> tagType;
7579
7580/// Matches types specified with an elaborated type keyword or with a
7581/// qualified name.
7582///
7583/// Given
7584/// \code
7585/// namespace N {
7586/// namespace M {
7587/// class D {};
7588/// }
7589/// }
7590/// class C {};
7591///
7592/// class C c;
7593/// N::M::D d;
7594/// \endcode
7595///
7596/// \c elaboratedType() matches the type of the variable declarations of both
7597/// \c c and \c d.
7599
7600/// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
7601/// matches \c InnerMatcher if the qualifier exists.
7602///
7603/// Given
7604/// \code
7605/// namespace N {
7606/// namespace M {
7607/// class D {};
7608/// }
7609/// }
7610/// N::M::D d;
7611/// \endcode
7612///
7613/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
7614/// matches the type of the variable declaration of \c d.
7616 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
7617 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
7618 return InnerMatcher.matches(*Qualifier, Finder, Builder);
7619
7620 return false;
7621}
7622
7623/// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
7624///
7625/// Given
7626/// \code
7627/// namespace N {
7628/// namespace M {
7629/// class D {};
7630/// }
7631/// }
7632/// N::M::D d;
7633/// \endcode
7634///
7635/// \c elaboratedType(namesType(recordType(
7636/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
7637/// declaration of \c d.
7638AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
7639 InnerMatcher) {
7640 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
7641}
7642
7643/// Matches types specified through a using declaration.
7644///
7645/// Given
7646/// \code
7647/// namespace a { struct S {}; }
7648/// using a::S;
7649/// S s;
7650/// \endcode
7651///
7652/// \c usingType() matches the type of the variable declaration of \c s.
7654
7655/// Matches types that represent the result of substituting a type for a
7656/// template type parameter.
7657///
7658/// Given
7659/// \code
7660/// template <typename T>
7661/// void F(T t) {
7662/// int i = 1 + t;
7663/// }
7664/// \endcode
7665///
7666/// \c substTemplateTypeParmType() matches the type of 't' but not '1'
7669
7670/// Matches template type parameter substitutions that have a replacement
7671/// type that matches the provided matcher.
7672///
7673/// Given
7674/// \code
7675/// template <typename T>
7676/// double F(T t);
7677/// int i;
7678/// double j = F(i);
7679/// \endcode
7680///
7681/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
7683 hasReplacementType, getReplacementType,
7685
7686/// Matches template type parameter types.
7687///
7688/// Example matches T, but not int.
7689/// (matcher = templateTypeParmType())
7690/// \code
7691/// template <typename T> void f(int i);
7692/// \endcode
7694
7695/// Matches injected class name types.
7696///
7697/// Example matches S s, but not S<T> s.
7698/// (matcher = parmVarDecl(hasType(injectedClassNameType())))
7699/// \code
7700/// template <typename T> struct S {
7701/// void f(S s);
7702/// void g(S<T> s);
7703/// };
7704/// \endcode
7706
7707/// Matches decayed type
7708/// Example matches i[] in declaration of f.
7709/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
7710/// Example matches i[1].
7711/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
7712/// \code
7713/// void f(int i[]) {
7714/// i[1] = 0;
7715/// }
7716/// \endcode
7718
7719/// Matches the decayed type, whoes decayed type matches \c InnerMatcher
7720AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
7721 InnerType) {
7722 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
7723}
7724
7725/// Matches a dependent name type
7726///
7727/// Example matches T::type
7728/// \code
7729/// template <typename T> struct declToImport {
7730/// typedef typename T::type dependent_name;
7731/// };
7732/// \endcode
7734
7735/// Matches a dependent template specialization type
7736///
7737/// Example matches A<T>::template B<T>
7738/// \code
7739/// template<typename T> struct A;
7740/// template<typename T> struct declToImport {
7741/// typename A<T>::template B<T> a;
7742/// };
7743/// \endcode
7746
7747/// Matches declarations whose declaration context, interpreted as a
7748/// Decl, matches \c InnerMatcher.
7749///
7750/// Given
7751/// \code
7752/// namespace N {
7753/// namespace M {
7754/// class D {};
7755/// }
7756/// }
7757/// \endcode
7758///
7759/// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
7760/// declaration of \c class \c D.
7761AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
7762 const DeclContext *DC = Node.getDeclContext();
7763 if (!DC) return false;
7764 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
7765}
7766
7767/// Matches nested name specifiers.
7768///
7769/// Given
7770/// \code
7771/// namespace ns {
7772/// struct A { static void f(); };
7773/// void A::f() {}
7774/// void g() { A::f(); }
7775/// }
7776/// ns::A a;
7777/// \endcode
7778/// nestedNameSpecifier()
7779/// matches "ns::" and both "A::"
7780extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
7782
7783/// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
7784extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
7786
7787/// Matches \c NestedNameSpecifierLocs for which the given inner
7788/// NestedNameSpecifier-matcher matches.
7790 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
7791 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
7792 return internal::BindableMatcher<NestedNameSpecifierLoc>(
7793 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
7794 InnerMatcher));
7795}
7796
7797/// Matches nested name specifiers that specify a type matching the
7798/// given \c QualType matcher without qualifiers.
7799///
7800/// Given
7801/// \code
7802/// struct A { struct B { struct C {}; }; };
7803/// A::B::C c;
7804/// \endcode
7805/// nestedNameSpecifier(specifiesType(
7806/// hasDeclaration(cxxRecordDecl(hasName("A")))
7807/// ))
7808/// matches "A::"
7810 internal::Matcher<QualType>, InnerMatcher) {
7811 if (!Node.getAsType())
7812 return false;
7813 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
7814}
7815
7816/// Matches nested name specifier locs that specify a type matching the
7817/// given \c TypeLoc.
7818///
7819/// Given
7820/// \code
7821/// struct A { struct B { struct C {}; }; };
7822/// A::B::C c;
7823/// \endcode
7824/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
7825/// hasDeclaration(cxxRecordDecl(hasName("A")))))))
7826/// matches "A::"
7828 internal::Matcher<TypeLoc>, InnerMatcher) {
7829 return Node && Node.getNestedNameSpecifier()->getAsType() &&
7830 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
7831}
7832
7833/// Matches on the prefix of a \c NestedNameSpecifier.
7834///
7835/// Given
7836/// \code
7837/// struct A { struct B { struct C {}; }; };
7838/// A::B::C c;
7839/// \endcode
7840/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
7841/// matches "A::"
7843 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
7844 0) {
7845 const NestedNameSpecifier *NextNode = Node.getPrefix();
7846 if (!NextNode)
7847 return false;
7848 return InnerMatcher.matches(*NextNode, Finder, Builder);
7849}
7850
7851/// Matches on the prefix of a \c NestedNameSpecifierLoc.
7852///
7853/// Given
7854/// \code
7855/// struct A { struct B { struct C {}; }; };
7856/// A::B::C c;
7857/// \endcode
7858/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
7859/// matches "A::"
7861 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
7862 1) {
7863 NestedNameSpecifierLoc NextNode = Node.getPrefix();
7864 if (!NextNode)
7865 return false;
7866 return InnerMatcher.matches(NextNode, Finder, Builder);
7867}
7868
7869/// Matches nested name specifiers that specify a namespace matching the
7870/// given namespace matcher.
7871///
7872/// Given
7873/// \code
7874/// namespace ns { struct A {}; }
7875/// ns::A a;
7876/// \endcode
7877/// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
7878/// matches "ns::"
7880 internal::Matcher<NamespaceDecl>, InnerMatcher) {
7881 if (!Node.getAsNamespace())
7882 return false;
7883 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
7884}
7885
7886/// Matches attributes.
7887/// Attributes may be attached with a variety of different syntaxes (including
7888/// keywords, C++11 attributes, GNU ``__attribute``` and MSVC `__declspec``,
7889/// and ``#pragma``s). They may also be implicit.
7890///
7891/// Given
7892/// \code
7893/// struct [[nodiscard]] Foo{};
7894/// void bar(int * __attribute__((nonnull)) );
7895/// __declspec(noinline) void baz();
7896///
7897/// #pragma omp declare simd
7898/// int min();
7899/// \endcode
7900/// attr()
7901/// matches "nodiscard", "nonnull", "noinline", and the whole "#pragma" line.
7902extern const internal::VariadicAllOfMatcher<Attr> attr;
7903
7904/// Overloads for the \c equalsNode matcher.
7905/// FIXME: Implement for other node types.
7906/// @{
7907
7908/// Matches if a node equals another node.
7909///
7910/// \c Decl has pointer identity in the AST.
7911AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
7912 return &Node == Other;
7913}
7914/// Matches if a node equals another node.
7915///
7916/// \c Stmt has pointer identity in the AST.
7917AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
7918 return &Node == Other;
7919}
7920/// Matches if a node equals another node.
7921///
7922/// \c Type has pointer identity in the AST.
7923AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
7924 return &Node == Other;
7925}
7926
7927/// @}
7928
7929/// Matches each case or default statement belonging to the given switch
7930/// statement. This matcher may produce multiple matches.
7931///
7932/// Given
7933/// \code
7934/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
7935/// \endcode
7936/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
7937/// matches four times, with "c" binding each of "case 1:", "case 2:",
7938/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
7939/// "switch (1)", "switch (2)" and "switch (2)".
7940AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
7941 InnerMatcher) {
7942 BoundNodesTreeBuilder Result;
7943 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
7944 // iteration order. We should use the more general iterating matchers once
7945 // they are capable of expressing this matcher (for example, it should ignore
7946 // case statements belonging to nested switch statements).
7947 bool Matched = false;
7948 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
7949 SC = SC->getNextSwitchCase()) {
7950 BoundNodesTreeBuilder CaseBuilder(*Builder);
7951 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
7952 if (CaseMatched) {
7953 Matched = true;
7954 Result.addMatch(CaseBuilder);
7955 }
7956 }
7957 *Builder = std::move(Result);
7958 return Matched;
7959}
7960
7961/// Matches each constructor initializer in a constructor definition.
7962///
7963/// Given
7964/// \code
7965/// class A { A() : i(42), j(42) {} int i; int j; };
7966/// \endcode
7967/// cxxConstructorDecl(forEachConstructorInitializer(
7968/// forField(decl().bind("x"))
7969/// ))
7970/// will trigger two matches, binding for 'i' and 'j' respectively.
7971AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
7972 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
7973 BoundNodesTreeBuilder Result;
7974 bool Matched = false;
7975 for (const auto *I : Node.inits()) {
7976 if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten())
7977 continue;
7978 BoundNodesTreeBuilder InitBuilder(*Builder);
7979 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
7980 Matched = true;
7981 Result.addMatch(InitBuilder);
7982 }
7983 }
7984 *Builder = std::move(Result);
7985 return Matched;
7986}
7987
7988/// Matches constructor declarations that are copy constructors.
7989///
7990/// Given
7991/// \code
7992/// struct S {
7993/// S(); // #1
7994/// S(const S &); // #2
7995/// S(S &&); // #3
7996/// };
7997/// \endcode
7998/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
7999AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
8000 return Node.isCopyConstructor();
8001}
8002
8003/// Matches constructor declarations that are move constructors.
8004///
8005/// Given
8006/// \code
8007/// struct S {
8008/// S(); // #1
8009/// S(const S &); // #2
8010/// S(S &&); // #3
8011/// };
8012/// \endcode
8013/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
8014AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
8015 return Node.isMoveConstructor();
8016}
8017
8018/// Matches constructor declarations that are default constructors.
8019///
8020/// Given
8021/// \code
8022/// struct S {
8023/// S(); // #1
8024/// S(const S &); // #2
8025/// S(S &&); // #3
8026/// };
8027/// \endcode
8028/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
8029AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
8030 return Node.isDefaultConstructor();
8031}
8032
8033/// Matches constructors that delegate to another constructor.
8034///
8035/// Given
8036/// \code
8037/// struct S {
8038/// S(); // #1
8039/// S(int) {} // #2
8040/// S(S &&) : S() {} // #3
8041/// };
8042/// S::S() : S(0) {} // #4
8043/// \endcode
8044/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
8045/// #1 or #2.
8046AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
8047 return Node.isDelegatingConstructor();
8048}
8049
8050/// Matches constructor, conversion function, and deduction guide declarations
8051/// that have an explicit specifier if this explicit specifier is resolved to
8052/// true.
8053///
8054/// Given
8055/// \code
8056/// template<bool b>
8057/// struct S {
8058/// S(int); // #1
8059/// explicit S(double); // #2
8060/// operator int(); // #3
8061/// explicit operator bool(); // #4
8062/// explicit(false) S(bool) // # 7
8063/// explicit(true) S(char) // # 8
8064/// explicit(b) S(S) // # 9
8065/// };
8066/// S(int) -> S<true> // #5
8067/// explicit S(double) -> S<false> // #6
8068/// \endcode
8069/// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
8070/// cxxConversionDecl(isExplicit()) will match #4, but not #3.
8071/// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
8075 return Node.isExplicit();
8076}
8077
8078/// Matches the expression in an explicit specifier if present in the given
8079/// declaration.
8080///
8081/// Given
8082/// \code
8083/// template<bool b>
8084/// struct S {
8085/// S(int); // #1
8086/// explicit S(double); // #2
8087/// operator int(); // #3
8088/// explicit operator bool(); // #4
8089/// explicit(false) S(bool) // # 7
8090/// explicit(true) S(char) // # 8
8091/// explicit(b) S(S) // # 9
8092/// };
8093/// S(int) -> S<true> // #5
8094/// explicit S(double) -> S<false> // #6
8095/// \endcode
8096/// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
8097/// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
8098/// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
8099AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
8100 InnerMatcher) {
8102 if (!ES.getExpr())
8103 return false;
8104
8105 ASTChildrenNotSpelledInSourceScope RAII(Finder, false);
8106
8107 return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
8108}
8109
8110/// Matches functions, variables and namespace declarations that are marked with
8111/// the inline keyword.
8112///
8113/// Given
8114/// \code
8115/// inline void f();
8116/// void g();
8117/// namespace n {
8118/// inline namespace m {}
8119/// }
8120/// inline int Foo = 5;
8121/// \endcode
8122/// functionDecl(isInline()) will match ::f().
8123/// namespaceDecl(isInline()) will match n::m.
8124/// varDecl(isInline()) will match Foo;
8127 VarDecl)) {
8128 // This is required because the spelling of the function used to determine
8129 // whether inline is specified or not differs between the polymorphic types.
8130 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
8131 return FD->isInlineSpecified();
8132 if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
8133 return NSD->isInline();
8134 if (const auto *VD = dyn_cast<VarDecl>(&Node))
8135 return VD->isInline();
8136 llvm_unreachable("Not a valid polymorphic type");
8137}
8138
8139/// Matches anonymous namespace declarations.
8140///
8141/// Given
8142/// \code
8143/// namespace n {
8144/// namespace {} // #1
8145/// }
8146/// \endcode
8147/// namespaceDecl(isAnonymous()) will match #1 but not ::n.
8149 return Node.isAnonymousNamespace();
8150}
8151
8152/// Matches declarations in the namespace `std`, but not in nested namespaces.
8153///
8154/// Given
8155/// \code
8156/// class vector {};
8157/// namespace foo {
8158/// class vector {};
8159/// namespace std {
8160/// class vector {};
8161/// }
8162/// }
8163/// namespace std {
8164/// inline namespace __1 {
8165/// class vector {}; // #1
8166/// namespace experimental {
8167/// class vector {};
8168/// }
8169/// }
8170/// }
8171/// \endcode
8172/// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
8173AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
8174
8175/// Matches declarations in an anonymous namespace.
8176///
8177/// Given
8178/// \code
8179/// class vector {};
8180/// namespace foo {
8181/// class vector {};
8182/// namespace {
8183/// class vector {}; // #1
8184/// }
8185/// }
8186/// namespace {
8187/// class vector {}; // #2
8188/// namespace foo {
8189/// class vector{}; // #3
8190/// }
8191/// }
8192/// \endcode
8193/// cxxRecordDecl(hasName("vector"), isInAnonymousNamespace()) will match
8194/// #1, #2 and #3.
8195AST_MATCHER(Decl, isInAnonymousNamespace) {
8196 return Node.isInAnonymousNamespace();
8197}
8198
8199/// If the given case statement does not use the GNU case range
8200/// extension, matches the constant given in the statement.
8201///
8202/// Given
8203/// \code
8204/// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
8205/// \endcode
8206/// caseStmt(hasCaseConstant(integerLiteral()))
8207/// matches "case 1:"
8208AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
8209 InnerMatcher) {
8210 if (Node.getRHS())
8211 return false;
8212
8213 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
8214}
8215
8216/// Matches declaration that has a given attribute.
8217///
8218/// Given
8219/// \code
8220/// __attribute__((device)) void f() { ... }
8221/// \endcode
8222/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
8223/// f. If the matcher is used from clang-query, attr::Kind parameter should be
8224/// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
8226 for (const auto *Attr : Node.attrs()) {
8227 if (Attr->getKind() == AttrKind)
8228 return true;
8229 }
8230 return false;
8231}
8232
8233/// Matches the return value expression of a return statement
8234///
8235/// Given
8236/// \code
8237/// return a + b;
8238/// \endcode
8239/// hasReturnValue(binaryOperator())
8240/// matches 'return a + b'
8241/// with binaryOperator()
8242/// matching 'a + b'
8243AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
8244 InnerMatcher) {
8245 if (const auto *RetValue = Node.getRetValue())
8246 return InnerMatcher.matches(*RetValue, Finder, Builder);
8247 return false;
8248}
8249
8250/// Matches CUDA kernel call expression.
8251///
8252/// Example matches,
8253/// \code
8254/// kernel<<<i,j>>>();
8255/// \endcode
8256extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
8258
8259/// Matches expressions that resolve to a null pointer constant, such as
8260/// GNU's __null, C++11's nullptr, or C's NULL macro.
8261///
8262/// Given:
8263/// \code
8264/// void *v1 = NULL;
8265/// void *v2 = nullptr;
8266/// void *v3 = __null; // GNU extension
8267/// char *cp = (char *)0;
8268/// int *ip = 0;
8269/// int i = 0;
8270/// \endcode
8271/// expr(nullPointerConstant())
8272/// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
8273/// initializer for i.
8274AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
8275 return anyOf(
8277 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
8278}
8279
8280/// Matches the DecompositionDecl the binding belongs to.
8281///
8282/// For example, in:
8283/// \code
8284/// void foo()
8285/// {
8286/// int arr[3];
8287/// auto &[f, s, t] = arr;
8288///
8289/// f = 42;
8290/// }
8291/// \endcode
8292/// The matcher:
8293/// \code
8294/// bindingDecl(hasName("f"),
8295/// forDecomposition(decompositionDecl())
8296/// \endcode
8297/// matches 'f' in 'auto &[f, s, t]'.
8298AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>,
8299 InnerMatcher) {
8300 if (const ValueDecl *VD = Node.getDecomposedDecl())
8301 return InnerMatcher.matches(*VD, Finder, Builder);
8302 return false;
8303}
8304
8305/// Matches the Nth binding of a DecompositionDecl.
8306///
8307/// For example, in:
8308/// \code
8309/// void foo()
8310/// {
8311/// int arr[3];
8312/// auto &[f, s, t] = arr;
8313///
8314/// f = 42;
8315/// }
8316/// \endcode
8317/// The matcher:
8318/// \code
8319/// decompositionDecl(hasBinding(0,
8320/// bindingDecl(hasName("f").bind("fBinding"))))
8321/// \endcode
8322/// matches the decomposition decl with 'f' bound to "fBinding".
8323AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N,
8324 internal::Matcher<BindingDecl>, InnerMatcher) {
8325 if (Node.bindings().size() <= N)
8326 return false;
8327 return InnerMatcher.matches(*Node.bindings()[N], Finder, Builder);
8328}
8329
8330/// Matches any binding of a DecompositionDecl.
8331///
8332/// For example, in:
8333/// \code
8334/// void foo()
8335/// {
8336/// int arr[3];
8337/// auto &[f, s, t] = arr;
8338///
8339/// f = 42;
8340/// }
8341/// \endcode
8342/// The matcher:
8343/// \code
8344/// decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding"))))
8345/// \endcode
8346/// matches the decomposition decl with 'f' bound to "fBinding".
8347AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>,
8348 InnerMatcher) {
8349 return llvm::any_of(Node.bindings(), [&](const auto *Binding) {
8350 return InnerMatcher.matches(*Binding, Finder, Builder);
8351 });
8352}
8353
8354/// Matches declaration of the function the statement belongs to.
8355///
8356/// Deprecated. Use forCallable() to correctly handle the situation when
8357/// the declaration is not a function (but a block or an Objective-C method).
8358/// forFunction() not only fails to take non-functions into account but also
8359/// may match the wrong declaration in their presence.
8360///
8361/// Given:
8362/// \code
8363/// F& operator=(const F& o) {
8364/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
8365/// return *this;
8366/// }
8367/// \endcode
8368/// returnStmt(forFunction(hasName("operator=")))
8369/// matches 'return *this'
8370/// but does not match 'return v > 0'
8371AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
8372 InnerMatcher) {
8373 const auto &Parents = Finder->getASTContext().getParents(Node);
8374
8375 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
8376 while (!Stack.empty()) {
8377 const auto &CurNode = Stack.back();
8378 Stack.pop_back();
8379 if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
8380 if (InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
8381 return true;
8382 }
8383 } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
8384 if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
8385 Builder)) {
8386 return true;
8387 }
8388 } else {
8389 llvm::append_range(Stack, Finder->getASTContext().getParents(CurNode));
8390 }
8391 }
8392 return false;
8393}
8394
8395/// Matches declaration of the function, method, or block the statement
8396/// belongs to.
8397///
8398/// Given:
8399/// \code
8400/// F& operator=(const F& o) {
8401/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
8402/// return *this;
8403/// }
8404/// \endcode
8405/// returnStmt(forCallable(functionDecl(hasName("operator="))))
8406/// matches 'return *this'
8407/// but does not match 'return v > 0'
8408///
8409/// Given:
8410/// \code
8411/// -(void) foo {
8412/// int x = 1;
8413/// dispatch_sync(queue, ^{ int y = 2; });
8414/// }
8415/// \endcode
8416/// declStmt(forCallable(objcMethodDecl()))
8417/// matches 'int x = 1'
8418/// but does not match 'int y = 2'.
8419/// whereas declStmt(forCallable(blockDecl()))
8420/// matches 'int y = 2'
8421/// but does not match 'int x = 1'.
8422AST_MATCHER_P(Stmt, forCallable, internal::Matcher<Decl>, InnerMatcher) {
8423 const auto &Parents = Finder->getASTContext().getParents(Node);
8424
8425 llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end());
8426 while (!Stack.empty()) {
8427 const auto &CurNode = Stack.back();
8428 Stack.pop_back();
8429 if (const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
8430 BoundNodesTreeBuilder B = *Builder;
8431 if (InnerMatcher.matches(*FuncDeclNode, Finder, &B)) {
8432 *Builder = std::move(B);
8433 return true;
8434 }
8435 } else if (const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
8436 BoundNodesTreeBuilder B = *Builder;
8437 if (InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder,
8438 &B)) {
8439 *Builder = std::move(B);
8440 return true;
8441 }
8442 } else if (const auto *ObjCMethodDeclNode = CurNode.get<ObjCMethodDecl>()) {
8443 BoundNodesTreeBuilder B = *Builder;
8444 if (InnerMatcher.matches(*ObjCMethodDeclNode, Finder, &B)) {
8445 *Builder = std::move(B);
8446 return true;
8447 }
8448 } else if (const auto *BlockDeclNode = CurNode.get<BlockDecl>()) {
8449 BoundNodesTreeBuilder B = *Builder;
8450 if (InnerMatcher.matches(*BlockDeclNode, Finder, &B)) {
8451 *Builder = std::move(B);
8452 return true;
8453 }
8454 } else {
8455 llvm::append_range(Stack, Finder->getASTContext().getParents(CurNode));
8456 }
8457 }
8458 return false;
8459}
8460
8461/// Matches a declaration that has external formal linkage.
8462///
8463/// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
8464/// \code
8465/// void f() {
8466/// int x;
8467/// static int y;
8468/// }
8469/// int z;
8470/// \endcode
8471///
8472/// Example matches f() because it has external formal linkage despite being
8473/// unique to the translation unit as though it has internal likage
8474/// (matcher = functionDecl(hasExternalFormalLinkage()))
8475///
8476/// \code
8477/// namespace {
8478/// void f() {}
8479/// }
8480/// \endcode
8481AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
8482 return Node.hasExternalFormalLinkage();
8483}
8484
8485/// Matches a declaration that has default arguments.
8486///
8487/// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
8488/// \code
8489/// void x(int val) {}
8490/// void y(int val = 0) {}
8491/// \endcode
8492///
8493/// Deprecated. Use hasInitializer() instead to be able to
8494/// match on the contents of the default argument. For example:
8495///
8496/// \code
8497/// void x(int val = 7) {}
8498/// void y(int val = 42) {}
8499/// \endcode
8500/// parmVarDecl(hasInitializer(integerLiteral(equals(42))))
8501/// matches the parameter of y
8502///
8503/// A matcher such as
8504/// parmVarDecl(hasInitializer(anything()))
8505/// is equivalent to parmVarDecl(hasDefaultArgument()).
8506AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
8507 return Node.hasDefaultArg();
8508}
8509
8510/// Matches array new expressions.
8511///
8512/// Given:
8513/// \code
8514/// MyClass *p1 = new MyClass[10];
8515/// \endcode
8516/// cxxNewExpr(isArray())
8517/// matches the expression 'new MyClass[10]'.
8519 return Node.isArray();
8520}
8521
8522/// Matches placement new expression arguments.
8523///
8524/// Given:
8525/// \code
8526/// MyClass *p1 = new (Storage, 16) MyClass();
8527/// \endcode
8528/// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16))))
8529/// matches the expression 'new (Storage, 16) MyClass()'.
8530AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index,
8531 internal::Matcher<Expr>, InnerMatcher) {
8532 return Node.getNumPlacementArgs() > Index &&
8533 InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder);
8534}
8535
8536/// Matches any placement new expression arguments.
8537///
8538/// Given:
8539/// \code
8540/// MyClass *p1 = new (Storage) MyClass();
8541/// \endcode
8542/// cxxNewExpr(hasAnyPlacementArg(anything()))
8543/// matches the expression 'new (Storage, 16) MyClass()'.
8544AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>,
8545 InnerMatcher) {
8546 return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) {
8547 return InnerMatcher.matches(*Arg, Finder, Builder);
8548 });
8549}
8550
8551/// Matches array new expressions with a given array size.
8552///
8553/// Given:
8554/// \code
8555/// MyClass *p1 = new MyClass[10];
8556/// \endcode
8557/// cxxNewExpr(hasArraySize(integerLiteral(equals(10))))
8558/// matches the expression 'new MyClass[10]'.
8559AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
8560 return Node.isArray() && *Node.getArraySize() &&
8561 InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
8562}
8563
8564/// Matches a class declaration that is defined.
8565///
8566/// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
8567/// \code
8568/// class x {};
8569/// class y;
8570/// \endcode
8572 return Node.hasDefinition();
8573}
8574
8575/// Matches C++11 scoped enum declaration.
8576///
8577/// Example matches Y (matcher = enumDecl(isScoped()))
8578/// \code
8579/// enum X {};
8580/// enum class Y {};
8581/// \endcode
8583 return Node.isScoped();
8584}
8585
8586/// Matches a function declared with a trailing return type.
8587///
8588/// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
8589/// \code
8590/// int X() {}
8591/// auto Y() -> int {}
8592/// \endcode
8593AST_MATCHER(FunctionDecl, hasTrailingReturn) {
8594 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
8595 return F->hasTrailingReturn();
8596 return false;
8597}
8598
8599/// Matches expressions that match InnerMatcher that are possibly wrapped in an
8600/// elidable constructor and other corresponding bookkeeping nodes.
8601///
8602/// In C++17, elidable copy constructors are no longer being generated in the
8603/// AST as it is not permitted by the standard. They are, however, part of the
8604/// AST in C++14 and earlier. So, a matcher must abstract over these differences
8605/// to work in all language modes. This matcher skips elidable constructor-call
8606/// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and
8607/// various implicit nodes inside the constructor calls, all of which will not
8608/// appear in the C++17 AST.
8609///
8610/// Given
8611///
8612/// \code
8613/// struct H {};
8614/// H G();
8615/// void f() {
8616/// H D = G();
8617/// }
8618/// \endcode
8619///
8620/// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))``
8621/// matches ``H D = G()`` in C++11 through C++17 (and beyond).
8622AST_MATCHER_P(Expr, ignoringElidableConstructorCall, internal::Matcher<Expr>,
8623 InnerMatcher) {
8624 // E tracks the node that we are examining.
8625 const Expr *E = &Node;
8626 // If present, remove an outer `ExprWithCleanups` corresponding to the
8627 // underlying `CXXConstructExpr`. This check won't cover all cases of added
8628 // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the
8629 // EWC is placed on the outermost node of the expression, which this may not
8630 // be), but, it still improves the coverage of this matcher.
8631 if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node))
8632 E = CleanupsExpr->getSubExpr();
8633 if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) {
8634 if (CtorExpr->isElidable()) {
8635 if (const auto *MaterializeTemp =
8636 dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
8637 return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder,
8638 Builder);
8639 }
8640 }
8641 }
8642 return InnerMatcher.matches(Node, Finder, Builder);
8643}
8644
8645//----------------------------------------------------------------------------//
8646// OpenMP handling.
8647//----------------------------------------------------------------------------//
8648
8649/// Matches any ``#pragma omp`` executable directive.
8650///
8651/// Given
8652///
8653/// \code
8654/// #pragma omp parallel
8655/// #pragma omp parallel default(none)
8656/// #pragma omp taskyield
8657/// \endcode
8658///
8659/// ``ompExecutableDirective()`` matches ``omp parallel``,
8660/// ``omp parallel default(none)`` and ``omp taskyield``.
8661extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
8663
8664/// Matches standalone OpenMP directives,
8665/// i.e., directives that can't have a structured block.
8666///
8667/// Given
8668///
8669/// \code
8670/// #pragma omp parallel
8671/// {}
8672/// #pragma omp taskyield
8673/// \endcode
8674///
8675/// ``ompExecutableDirective(isStandaloneDirective()))`` matches
8676/// ``omp taskyield``.
8677AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
8678 return Node.isStandaloneDirective();
8679}
8680
8681/// Matches the structured-block of the OpenMP executable directive
8682///
8683/// Prerequisite: the executable directive must not be standalone directive.
8684/// If it is, it will never match.
8685///
8686/// Given
8687///
8688/// \code
8689/// #pragma omp parallel
8690/// ;
8691/// #pragma omp parallel
8692/// {}
8693/// \endcode
8694///
8695/// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
8697 internal::Matcher<Stmt>, InnerMatcher) {
8698 if (Node.isStandaloneDirective())
8699 return false; // Standalone directives have no structured blocks.
8700 return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
8701}
8702
8703/// Matches any clause in an OpenMP directive.
8704///
8705/// Given
8706///
8707/// \code
8708/// #pragma omp parallel
8709/// #pragma omp parallel default(none)
8710/// \endcode
8711///
8712/// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
8713/// ``omp parallel default(none)``.
8715 internal::Matcher<OMPClause>, InnerMatcher) {
8716 ArrayRef<OMPClause *> Clauses = Node.clauses();
8717 return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
8718 Clauses.end(), Finder,
8719 Builder) != Clauses.end();
8720}
8721
8722/// Matches OpenMP ``default`` clause.
8723///
8724/// Given
8725///
8726/// \code
8727/// #pragma omp parallel default(none)
8728/// #pragma omp parallel default(shared)
8729/// #pragma omp parallel default(private)
8730/// #pragma omp parallel default(firstprivate)
8731/// #pragma omp parallel
8732/// \endcode
8733///
8734/// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``,
8735/// `` default(private)`` and ``default(firstprivate)``
8736extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
8738
8739/// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
8740///
8741/// Given
8742///
8743/// \code
8744/// #pragma omp parallel
8745/// #pragma omp parallel default(none)
8746/// #pragma omp parallel default(shared)
8747/// #pragma omp parallel default(private)
8748/// #pragma omp parallel default(firstprivate)
8749/// \endcode
8750///
8751/// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
8753 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none;
8754}
8755
8756/// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
8757///
8758/// Given
8759///
8760/// \code
8761/// #pragma omp parallel
8762/// #pragma omp parallel default(none)
8763/// #pragma omp parallel default(shared)
8764/// #pragma omp parallel default(private)
8765/// #pragma omp parallel default(firstprivate)
8766/// \endcode
8767///
8768/// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
8770 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared;
8771}
8772
8773/// Matches if the OpenMP ``default`` clause has ``private`` kind
8774/// specified.
8775///
8776/// Given
8777///
8778/// \code
8779/// #pragma omp parallel
8780/// #pragma omp parallel default(none)
8781/// #pragma omp parallel default(shared)
8782/// #pragma omp parallel default(private)
8783/// #pragma omp parallel default(firstprivate)
8784/// \endcode
8785///
8786/// ``ompDefaultClause(isPrivateKind())`` matches only
8787/// ``default(private)``.
8789 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_private;
8790}
8791
8792/// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind
8793/// specified.
8794///
8795/// Given
8796///
8797/// \code
8798/// #pragma omp parallel
8799/// #pragma omp parallel default(none)
8800/// #pragma omp parallel default(shared)
8801/// #pragma omp parallel default(private)
8802/// #pragma omp parallel default(firstprivate)
8803/// \endcode
8804///
8805/// ``ompDefaultClause(isFirstPrivateKind())`` matches only
8806/// ``default(firstprivate)``.
8807AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) {
8808 return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate;
8809}
8810
8811/// Matches if the OpenMP directive is allowed to contain the specified OpenMP
8812/// clause kind.
8813///
8814/// Given
8815///
8816/// \code
8817/// #pragma omp parallel
8818/// #pragma omp parallel for
8819/// #pragma omp for
8820/// \endcode
8821///
8822/// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
8823/// ``omp parallel`` and ``omp parallel for``.
8824///
8825/// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
8826/// should be passed as a quoted string. e.g.,
8827/// ``isAllowedToContainClauseKind("OMPC_default").``
8828AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
8829 OpenMPClauseKind, CKind) {
8830 return llvm::omp::isAllowedClauseForDirective(
8831 Node.getDirectiveKind(), CKind,
8832 Finder->getASTContext().getLangOpts().OpenMP);
8833}
8834
8835//----------------------------------------------------------------------------//
8836// End OpenMP handling.
8837//----------------------------------------------------------------------------//
8838
8839} // namespace ast_matchers
8840} // namespace clang
8841
8842#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.
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
Expr * E
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:3051
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:1828
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:1628
body_iterator body_end()
Definition: Stmt.h:1693
body_iterator body_begin()
Definition: Stmt.h:1692
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:1519
DeclGroupRef::const_iterator const_decl_iterator
Definition: Stmt.h:1563
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
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3323
Represents a C99 designated initializer expression.
Definition: Expr.h:5333
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2752
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:2808
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:2165
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:3046
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:2415
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:2611
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 AstTypeMatcher< DependentTemplateSpecializationType > dependentTemplateSpecializationType
Matches a dependent template specialization type.
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 AstTypeMatcher< DependentNameType > dependentNameType
Matches a dependent name type.
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:3100
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 internal::VariadicDynCastAllOfMatcher< Stmt, DependentScopeDeclRefExpr > dependentScopeDeclRefExpr
Matches expressions that refer to dependent scope 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:3079
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:7048
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:2922
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:5880
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:3163
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:3070
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:3600
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:3685
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