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