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