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