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