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