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