1 //===--- ASTMatchers.h - Structural query framework -------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements matchers to be used together with the MatchFinder to
11 // match AST nodes.
12 //
13 // Matchers are created by generator functions, which can be combined in
14 // a functional in-language DSL to express queries over the C++ AST.
15 //
16 // For example, to match a class with a certain name, one would call:
17 // recordDecl(hasName("MyClass"))
18 // which returns a matcher that can be used to find all AST nodes that declare
19 // a class named 'MyClass'.
20 //
21 // For more complicated match expressions we're often interested in accessing
22 // multiple parts of the matched AST nodes once a match is found. In that case,
23 // use the id(...) matcher around the match expressions that match the nodes
24 // you want to access.
25 //
26 // For example, when we're interested in child classes of a certain class, we
27 // would write:
28 // recordDecl(hasName("MyClass"), hasChild(id("child", recordDecl())))
29 // When the match is found via the MatchFinder, a user provided callback will
30 // be called with a BoundNodes instance that contains a mapping from the
31 // strings that we provided for the id(...) calls to the nodes that were
32 // matched.
33 // In the given example, each time our matcher finds a match we get a callback
34 // where "child" is bound to the CXXRecordDecl node of the matching child
35 // class declaration.
36 //
37 // See ASTMatchersInternal.h for a more in-depth explanation of the
38 // implementation details of the matcher framework.
39 //
40 // See ASTMatchFinder.h for how to use the generated matchers to run over
41 // an AST.
42 //
43 //===----------------------------------------------------------------------===//
44
45 #ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
46 #define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
47
48 #include "clang/AST/DeclFriend.h"
49 #include "clang/AST/DeclTemplate.h"
50 #include "clang/ASTMatchers/ASTMatchersInternal.h"
51 #include "clang/ASTMatchers/ASTMatchersMacros.h"
52 #include "llvm/ADT/Twine.h"
53 #include "llvm/Support/Regex.h"
54 #include <iterator>
55
56 namespace clang {
57 namespace ast_matchers {
58
59 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
60 ///
61 /// The bound nodes are generated by calling \c bind("id") on the node matchers
62 /// of the nodes we want to access later.
63 ///
64 /// The instances of BoundNodes are created by \c MatchFinder when the user's
65 /// callbacks are executed every time a match is found.
66 class BoundNodes {
67 public:
68 /// \brief Returns the AST node bound to \c ID.
69 ///
70 /// Returns NULL if there was no node bound to \c ID or if there is a node but
71 /// it cannot be converted to the specified type.
72 template <typename T>
getNodeAs(StringRef ID)73 const T *getNodeAs(StringRef ID) const {
74 return MyBoundNodes.getNodeAs<T>(ID);
75 }
76
77 /// \brief Deprecated. Please use \c getNodeAs instead.
78 /// @{
79 template <typename T>
getDeclAs(StringRef ID)80 const T *getDeclAs(StringRef ID) const {
81 return getNodeAs<T>(ID);
82 }
83 template <typename T>
getStmtAs(StringRef ID)84 const T *getStmtAs(StringRef ID) const {
85 return getNodeAs<T>(ID);
86 }
87 /// @}
88
89 /// \brief Type of mapping from binding identifiers to bound nodes. This type
90 /// is an associative container with a key type of \c std::string and a value
91 /// type of \c clang::ast_type_traits::DynTypedNode
92 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
93
94 /// \brief Retrieve mapping from binding identifiers to bound nodes.
getMap()95 const IDToNodeMap &getMap() const {
96 return MyBoundNodes.getMap();
97 }
98
99 private:
100 /// \brief Create BoundNodes from a pre-filled map of bindings.
BoundNodes(internal::BoundNodesMap & MyBoundNodes)101 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
102 : MyBoundNodes(MyBoundNodes) {}
103
104 internal::BoundNodesMap MyBoundNodes;
105
106 friend class internal::BoundNodesTreeBuilder;
107 };
108
109 /// \brief If the provided matcher matches a node, binds the node to \c ID.
110 ///
111 /// FIXME: Do we want to support this now that we have bind()?
112 template <typename T>
id(const std::string & ID,const internal::BindableMatcher<T> & InnerMatcher)113 internal::Matcher<T> id(const std::string &ID,
114 const internal::BindableMatcher<T> &InnerMatcher) {
115 return InnerMatcher.bind(ID);
116 }
117
118 /// \brief Types of matchers for the top-level classes in the AST class
119 /// hierarchy.
120 /// @{
121 typedef internal::Matcher<Decl> DeclarationMatcher;
122 typedef internal::Matcher<Stmt> StatementMatcher;
123 typedef internal::Matcher<QualType> TypeMatcher;
124 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
125 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
126 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
127 /// @}
128
129 /// \brief Matches any node.
130 ///
131 /// Useful when another matcher requires a child matcher, but there's no
132 /// additional constraint. This will often be used with an explicit conversion
133 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
134 ///
135 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
136 /// \code
137 /// "int* p" and "void f()" in
138 /// int* p;
139 /// void f();
140 /// \endcode
141 ///
142 /// Usable as: Any Matcher
143 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>
anything()144 anything() {
145 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
146 }
147
148 /// \brief Matches declarations.
149 ///
150 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
151 /// \code
152 /// void X();
153 /// class C {
154 /// friend X;
155 /// };
156 /// \endcode
157 const internal::VariadicAllOfMatcher<Decl> decl;
158
159 /// \brief Matches a declaration of anything that could have a name.
160 ///
161 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
162 /// \code
163 /// typedef int X;
164 /// struct S {
165 /// union {
166 /// int i;
167 /// } U;
168 /// };
169 /// \endcode
170 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
171
172 /// \brief Matches a declaration of a namespace.
173 ///
174 /// Given
175 /// \code
176 /// namespace {}
177 /// namespace test {}
178 /// \endcode
179 /// namespaceDecl()
180 /// matches "namespace {}" and "namespace test {}"
181 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
182
183 /// \brief Matches C++ class declarations.
184 ///
185 /// Example matches \c X, \c Z
186 /// \code
187 /// class X;
188 /// template<class T> class Z {};
189 /// \endcode
190 const internal::VariadicDynCastAllOfMatcher<
191 Decl,
192 CXXRecordDecl> recordDecl;
193
194 /// \brief Matches C++ class template declarations.
195 ///
196 /// Example matches \c Z
197 /// \code
198 /// template<class T> class Z {};
199 /// \endcode
200 const internal::VariadicDynCastAllOfMatcher<
201 Decl,
202 ClassTemplateDecl> classTemplateDecl;
203
204 /// \brief Matches C++ class template specializations.
205 ///
206 /// Given
207 /// \code
208 /// template<typename T> class A {};
209 /// template<> class A<double> {};
210 /// A<int> a;
211 /// \endcode
212 /// classTemplateSpecializationDecl()
213 /// matches the specializations \c A<int> and \c A<double>
214 const internal::VariadicDynCastAllOfMatcher<
215 Decl,
216 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
217
218 /// \brief Matches declarator declarations (field, variable, function
219 /// and non-type template parameter declarations).
220 ///
221 /// Given
222 /// \code
223 /// class X { int y; };
224 /// \endcode
225 /// declaratorDecl()
226 /// matches \c int y.
227 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
228 declaratorDecl;
229
230 /// \brief Matches parameter variable declarations.
231 ///
232 /// Given
233 /// \code
234 /// void f(int x);
235 /// \endcode
236 /// parmVarDecl()
237 /// matches \c int x.
238 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
239
240 /// \brief Matches C++ access specifier declarations.
241 ///
242 /// Given
243 /// \code
244 /// class C {
245 /// public:
246 /// int a;
247 /// };
248 /// \endcode
249 /// accessSpecDecl()
250 /// matches 'public:'
251 const internal::VariadicDynCastAllOfMatcher<
252 Decl,
253 AccessSpecDecl> accessSpecDecl;
254
255 /// \brief Matches constructor initializers.
256 ///
257 /// Examples matches \c i(42).
258 /// \code
259 /// class C {
260 /// C() : i(42) {}
261 /// int i;
262 /// };
263 /// \endcode
264 const internal::VariadicAllOfMatcher<CXXCtorInitializer> ctorInitializer;
265
266 /// \brief Matches public C++ declarations.
267 ///
268 /// Given
269 /// \code
270 /// class C {
271 /// public: int a;
272 /// protected: int b;
273 /// private: int c;
274 /// };
275 /// \endcode
276 /// fieldDecl(isPublic())
277 /// matches 'int a;'
AST_MATCHER(Decl,isPublic)278 AST_MATCHER(Decl, isPublic) {
279 return Node.getAccess() == AS_public;
280 }
281
282 /// \brief Matches protected C++ declarations.
283 ///
284 /// Given
285 /// \code
286 /// class C {
287 /// public: int a;
288 /// protected: int b;
289 /// private: int c;
290 /// };
291 /// \endcode
292 /// fieldDecl(isProtected())
293 /// matches 'int b;'
AST_MATCHER(Decl,isProtected)294 AST_MATCHER(Decl, isProtected) {
295 return Node.getAccess() == AS_protected;
296 }
297
298 /// \brief Matches private C++ declarations.
299 ///
300 /// Given
301 /// \code
302 /// class C {
303 /// public: int a;
304 /// protected: int b;
305 /// private: int c;
306 /// };
307 /// \endcode
308 /// fieldDecl(isPrivate())
309 /// matches 'int c;'
AST_MATCHER(Decl,isPrivate)310 AST_MATCHER(Decl, isPrivate) {
311 return Node.getAccess() == AS_private;
312 }
313
314 /// \brief Matches a declaration that has been implicitly added
315 /// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl,isImplicit)316 AST_MATCHER(Decl, isImplicit) {
317 return Node.isImplicit();
318 }
319
320 /// \brief Matches classTemplateSpecializations that have at least one
321 /// TemplateArgument matching the given InnerMatcher.
322 ///
323 /// Given
324 /// \code
325 /// template<typename T> class A {};
326 /// template<> class A<double> {};
327 /// A<int> a;
328 /// \endcode
329 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
330 /// refersToType(asString("int"))))
331 /// matches the specialization \c A<int>
AST_POLYMORPHIC_MATCHER_P(hasAnyTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES_2 (ClassTemplateSpecializationDecl,TemplateSpecializationType),internal::Matcher<TemplateArgument>,InnerMatcher)332 AST_POLYMORPHIC_MATCHER_P(
333 hasAnyTemplateArgument,
334 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
335 TemplateSpecializationType),
336 internal::Matcher<TemplateArgument>, InnerMatcher) {
337 ArrayRef<TemplateArgument> List =
338 internal::getTemplateSpecializationArgs(Node);
339 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
340 Builder);
341 }
342
343 /// \brief Matches expressions that match InnerMatcher after any implicit casts
344 /// are stripped off.
345 ///
346 /// Parentheses and explicit casts are not discarded.
347 /// Given
348 /// \code
349 /// int arr[5];
350 /// int a = 0;
351 /// char b = 0;
352 /// const int c = a;
353 /// int *d = arr;
354 /// long e = (long) 0l;
355 /// \endcode
356 /// The matchers
357 /// \code
358 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
359 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
360 /// \endcode
361 /// would match the declarations for a, b, c, and d, but not e.
362 /// While
363 /// \code
364 /// varDecl(hasInitializer(integerLiteral()))
365 /// varDecl(hasInitializer(declRefExpr()))
366 /// \endcode
367 /// only match the declarations for b, c, and d.
AST_MATCHER_P(Expr,ignoringImpCasts,internal::Matcher<Expr>,InnerMatcher)368 AST_MATCHER_P(Expr, ignoringImpCasts,
369 internal::Matcher<Expr>, InnerMatcher) {
370 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
371 }
372
373 /// \brief Matches expressions that match InnerMatcher after parentheses and
374 /// casts are stripped off.
375 ///
376 /// Implicit and non-C Style casts are also discarded.
377 /// Given
378 /// \code
379 /// int a = 0;
380 /// char b = (0);
381 /// void* c = reinterpret_cast<char*>(0);
382 /// char d = char(0);
383 /// \endcode
384 /// The matcher
385 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
386 /// would match the declarations for a, b, c, and d.
387 /// while
388 /// varDecl(hasInitializer(integerLiteral()))
389 /// only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenCasts,internal::Matcher<Expr>,InnerMatcher)390 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
391 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
392 }
393
394 /// \brief Matches expressions that match InnerMatcher after implicit casts and
395 /// parentheses are stripped off.
396 ///
397 /// Explicit casts are not discarded.
398 /// Given
399 /// \code
400 /// int arr[5];
401 /// int a = 0;
402 /// char b = (0);
403 /// const int c = a;
404 /// int *d = (arr);
405 /// long e = ((long) 0l);
406 /// \endcode
407 /// The matchers
408 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
409 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
410 /// would match the declarations for a, b, c, and d, but not e.
411 /// while
412 /// varDecl(hasInitializer(integerLiteral()))
413 /// varDecl(hasInitializer(declRefExpr()))
414 /// would only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenImpCasts,internal::Matcher<Expr>,InnerMatcher)415 AST_MATCHER_P(Expr, ignoringParenImpCasts,
416 internal::Matcher<Expr>, InnerMatcher) {
417 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
418 }
419
420 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
421 /// matches the given InnerMatcher.
422 ///
423 /// Given
424 /// \code
425 /// template<typename T, typename U> class A {};
426 /// A<bool, int> b;
427 /// A<int, bool> c;
428 /// \endcode
429 /// classTemplateSpecializationDecl(hasTemplateArgument(
430 /// 1, refersToType(asString("int"))))
431 /// matches the specialization \c A<bool, int>
AST_POLYMORPHIC_MATCHER_P2(hasTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES_2 (ClassTemplateSpecializationDecl,TemplateSpecializationType),unsigned,N,internal::Matcher<TemplateArgument>,InnerMatcher)432 AST_POLYMORPHIC_MATCHER_P2(
433 hasTemplateArgument,
434 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ClassTemplateSpecializationDecl,
435 TemplateSpecializationType),
436 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
437 ArrayRef<TemplateArgument> List =
438 internal::getTemplateSpecializationArgs(Node);
439 if (List.size() <= N)
440 return false;
441 return InnerMatcher.matches(List[N], Finder, Builder);
442 }
443
444 /// \brief Matches a TemplateArgument that refers to a certain type.
445 ///
446 /// Given
447 /// \code
448 /// struct X {};
449 /// template<typename T> struct A {};
450 /// A<X> a;
451 /// \endcode
452 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
453 /// refersToType(class(hasName("X")))))
454 /// matches the specialization \c A<X>
AST_MATCHER_P(TemplateArgument,refersToType,internal::Matcher<QualType>,InnerMatcher)455 AST_MATCHER_P(TemplateArgument, refersToType,
456 internal::Matcher<QualType>, InnerMatcher) {
457 if (Node.getKind() != TemplateArgument::Type)
458 return false;
459 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
460 }
461
462 /// \brief Matches a canonical TemplateArgument that refers to a certain
463 /// declaration.
464 ///
465 /// Given
466 /// \code
467 /// template<typename T> struct A {};
468 /// struct B { B* next; };
469 /// A<&B::next> a;
470 /// \endcode
471 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
472 /// refersToDeclaration(fieldDecl(hasName("next"))))
473 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
474 /// \c B::next
AST_MATCHER_P(TemplateArgument,refersToDeclaration,internal::Matcher<Decl>,InnerMatcher)475 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
476 internal::Matcher<Decl>, InnerMatcher) {
477 if (Node.getKind() == TemplateArgument::Declaration)
478 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
479 return false;
480 }
481
482 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
483 ///
484 /// Given
485 /// \code
486 /// template<typename T> struct A {};
487 /// struct B { B* next; };
488 /// A<&B::next> a;
489 /// \endcode
490 /// templateSpecializationType(hasAnyTemplateArgument(
491 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
492 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
493 /// \c B::next
AST_MATCHER_P(TemplateArgument,isExpr,internal::Matcher<Expr>,InnerMatcher)494 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
495 if (Node.getKind() == TemplateArgument::Expression)
496 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
497 return false;
498 }
499
500 /// \brief Matches C++ constructor declarations.
501 ///
502 /// Example matches Foo::Foo() and Foo::Foo(int)
503 /// \code
504 /// class Foo {
505 /// public:
506 /// Foo();
507 /// Foo(int);
508 /// int DoSomething();
509 /// };
510 /// \endcode
511 const internal::VariadicDynCastAllOfMatcher<
512 Decl,
513 CXXConstructorDecl> constructorDecl;
514
515 /// \brief Matches explicit C++ destructor declarations.
516 ///
517 /// Example matches Foo::~Foo()
518 /// \code
519 /// class Foo {
520 /// public:
521 /// virtual ~Foo();
522 /// };
523 /// \endcode
524 const internal::VariadicDynCastAllOfMatcher<
525 Decl,
526 CXXDestructorDecl> destructorDecl;
527
528 /// \brief Matches enum declarations.
529 ///
530 /// Example matches X
531 /// \code
532 /// enum X {
533 /// A, B, C
534 /// };
535 /// \endcode
536 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
537
538 /// \brief Matches enum constants.
539 ///
540 /// Example matches A, B, C
541 /// \code
542 /// enum X {
543 /// A, B, C
544 /// };
545 /// \endcode
546 const internal::VariadicDynCastAllOfMatcher<
547 Decl,
548 EnumConstantDecl> enumConstantDecl;
549
550 /// \brief Matches method declarations.
551 ///
552 /// Example matches y
553 /// \code
554 /// class X { void y(); };
555 /// \endcode
556 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
557
558 /// \brief Matches variable declarations.
559 ///
560 /// Note: this does not match declarations of member variables, which are
561 /// "field" declarations in Clang parlance.
562 ///
563 /// Example matches a
564 /// \code
565 /// int a;
566 /// \endcode
567 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
568
569 /// \brief Matches field declarations.
570 ///
571 /// Given
572 /// \code
573 /// class X { int m; };
574 /// \endcode
575 /// fieldDecl()
576 /// matches 'm'.
577 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
578
579 /// \brief Matches function declarations.
580 ///
581 /// Example matches f
582 /// \code
583 /// void f();
584 /// \endcode
585 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
586
587 /// \brief Matches C++ function template declarations.
588 ///
589 /// Example matches f
590 /// \code
591 /// template<class T> void f(T t) {}
592 /// \endcode
593 const internal::VariadicDynCastAllOfMatcher<
594 Decl,
595 FunctionTemplateDecl> functionTemplateDecl;
596
597 /// \brief Matches friend declarations.
598 ///
599 /// Given
600 /// \code
601 /// class X { friend void foo(); };
602 /// \endcode
603 /// friendDecl()
604 /// matches 'friend void foo()'.
605 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
606
607 /// \brief Matches statements.
608 ///
609 /// Given
610 /// \code
611 /// { ++a; }
612 /// \endcode
613 /// stmt()
614 /// matches both the compound statement '{ ++a; }' and '++a'.
615 const internal::VariadicAllOfMatcher<Stmt> stmt;
616
617 /// \brief Matches declaration statements.
618 ///
619 /// Given
620 /// \code
621 /// int a;
622 /// \endcode
623 /// declStmt()
624 /// matches 'int a'.
625 const internal::VariadicDynCastAllOfMatcher<
626 Stmt,
627 DeclStmt> declStmt;
628
629 /// \brief Matches member expressions.
630 ///
631 /// Given
632 /// \code
633 /// class Y {
634 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
635 /// int a; static int b;
636 /// };
637 /// \endcode
638 /// memberExpr()
639 /// matches this->x, x, y.x, a, this->b
640 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
641
642 /// \brief Matches call expressions.
643 ///
644 /// Example matches x.y() and y()
645 /// \code
646 /// X x;
647 /// x.y();
648 /// y();
649 /// \endcode
650 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
651
652 /// \brief Matches lambda expressions.
653 ///
654 /// Example matches [&](){return 5;}
655 /// \code
656 /// [&](){return 5;}
657 /// \endcode
658 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
659
660 /// \brief Matches member call expressions.
661 ///
662 /// Example matches x.y()
663 /// \code
664 /// X x;
665 /// x.y();
666 /// \endcode
667 const internal::VariadicDynCastAllOfMatcher<
668 Stmt,
669 CXXMemberCallExpr> memberCallExpr;
670
671 /// \brief Matches expressions that introduce cleanups to be run at the end
672 /// of the sub-expression's evaluation.
673 ///
674 /// Example matches std::string()
675 /// \code
676 /// const std::string str = std::string();
677 /// \endcode
678 const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
679 exprWithCleanups;
680
681 /// \brief Matches init list expressions.
682 ///
683 /// Given
684 /// \code
685 /// int a[] = { 1, 2 };
686 /// struct B { int x, y; };
687 /// B b = { 5, 6 };
688 /// \endcode
689 /// initListExpr()
690 /// matches "{ 1, 2 }" and "{ 5, 6 }"
691 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
692
693 /// \brief Matches substitutions of non-type template parameters.
694 ///
695 /// Given
696 /// \code
697 /// template <int N>
698 /// struct A { static const int n = N; };
699 /// struct B : public A<42> {};
700 /// \endcode
701 /// substNonTypeTemplateParmExpr()
702 /// matches "N" in the right-hand side of "static const int n = N;"
703 const internal::VariadicDynCastAllOfMatcher<Stmt, SubstNonTypeTemplateParmExpr>
704 substNonTypeTemplateParmExpr;
705
706 /// \brief Matches using declarations.
707 ///
708 /// Given
709 /// \code
710 /// namespace X { int x; }
711 /// using X::x;
712 /// \endcode
713 /// usingDecl()
714 /// matches \code using X::x \endcode
715 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
716
717 /// \brief Matches unresolved using value declarations.
718 ///
719 /// Given
720 /// \code
721 /// template<typename X>
722 /// class C : private X {
723 /// using X::x;
724 /// };
725 /// \endcode
726 /// unresolvedUsingValueDecl()
727 /// matches \code using X::x \endcode
728 const internal::VariadicDynCastAllOfMatcher<
729 Decl,
730 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
731
732 /// \brief Matches constructor call expressions (including implicit ones).
733 ///
734 /// Example matches string(ptr, n) and ptr within arguments of f
735 /// (matcher = constructExpr())
736 /// \code
737 /// void f(const string &a, const string &b);
738 /// char *ptr;
739 /// int n;
740 /// f(string(ptr, n), ptr);
741 /// \endcode
742 const internal::VariadicDynCastAllOfMatcher<
743 Stmt,
744 CXXConstructExpr> constructExpr;
745
746 /// \brief Matches unresolved constructor call expressions.
747 ///
748 /// Example matches T(t) in return statement of f
749 /// (matcher = unresolvedConstructExpr())
750 /// \code
751 /// template <typename T>
752 /// void f(const T& t) { return T(t); }
753 /// \endcode
754 const internal::VariadicDynCastAllOfMatcher<
755 Stmt,
756 CXXUnresolvedConstructExpr> unresolvedConstructExpr;
757
758 /// \brief Matches implicit and explicit this expressions.
759 ///
760 /// Example matches the implicit this expression in "return i".
761 /// (matcher = thisExpr())
762 /// \code
763 /// struct foo {
764 /// int i;
765 /// int f() { return i; }
766 /// };
767 /// \endcode
768 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr;
769
770 /// \brief Matches nodes where temporaries are created.
771 ///
772 /// Example matches FunctionTakesString(GetStringByValue())
773 /// (matcher = bindTemporaryExpr())
774 /// \code
775 /// FunctionTakesString(GetStringByValue());
776 /// FunctionTakesStringByPointer(GetStringPointer());
777 /// \endcode
778 const internal::VariadicDynCastAllOfMatcher<
779 Stmt,
780 CXXBindTemporaryExpr> bindTemporaryExpr;
781
782 /// \brief Matches nodes where temporaries are materialized.
783 ///
784 /// Example: Given
785 /// \code
786 /// struct T {void func()};
787 /// T f();
788 /// void g(T);
789 /// \endcode
790 /// materializeTemporaryExpr() matches 'f()' in these statements
791 /// \code
792 /// T u(f());
793 /// g(f());
794 /// \endcode
795 /// but does not match
796 /// \code
797 /// f();
798 /// f().func();
799 /// \endcode
800 const internal::VariadicDynCastAllOfMatcher<
801 Stmt,
802 MaterializeTemporaryExpr> materializeTemporaryExpr;
803
804 /// \brief Matches new expressions.
805 ///
806 /// Given
807 /// \code
808 /// new X;
809 /// \endcode
810 /// newExpr()
811 /// matches 'new X'.
812 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr;
813
814 /// \brief Matches delete expressions.
815 ///
816 /// Given
817 /// \code
818 /// delete X;
819 /// \endcode
820 /// deleteExpr()
821 /// matches 'delete X'.
822 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr;
823
824 /// \brief Matches array subscript expressions.
825 ///
826 /// Given
827 /// \code
828 /// int i = a[1];
829 /// \endcode
830 /// arraySubscriptExpr()
831 /// matches "a[1]"
832 const internal::VariadicDynCastAllOfMatcher<
833 Stmt,
834 ArraySubscriptExpr> arraySubscriptExpr;
835
836 /// \brief Matches the value of a default argument at the call site.
837 ///
838 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
839 /// default value of the second parameter in the call expression f(42)
840 /// (matcher = defaultArgExpr())
841 /// \code
842 /// void f(int x, int y = 0);
843 /// f(42);
844 /// \endcode
845 const internal::VariadicDynCastAllOfMatcher<
846 Stmt,
847 CXXDefaultArgExpr> defaultArgExpr;
848
849 /// \brief Matches overloaded operator calls.
850 ///
851 /// Note that if an operator isn't overloaded, it won't match. Instead, use
852 /// binaryOperator matcher.
853 /// Currently it does not match operators such as new delete.
854 /// FIXME: figure out why these do not match?
855 ///
856 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
857 /// (matcher = operatorCallExpr())
858 /// \code
859 /// ostream &operator<< (ostream &out, int i) { };
860 /// ostream &o; int b = 1, c = 1;
861 /// o << b << c;
862 /// \endcode
863 const internal::VariadicDynCastAllOfMatcher<
864 Stmt,
865 CXXOperatorCallExpr> operatorCallExpr;
866
867 /// \brief Matches expressions.
868 ///
869 /// Example matches x()
870 /// \code
871 /// void f() { x(); }
872 /// \endcode
873 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
874
875 /// \brief Matches expressions that refer to declarations.
876 ///
877 /// Example matches x in if (x)
878 /// \code
879 /// bool x;
880 /// if (x) {}
881 /// \endcode
882 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
883
884 /// \brief Matches if statements.
885 ///
886 /// Example matches 'if (x) {}'
887 /// \code
888 /// if (x) {}
889 /// \endcode
890 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
891
892 /// \brief Matches for statements.
893 ///
894 /// Example matches 'for (;;) {}'
895 /// \code
896 /// for (;;) {}
897 /// int i[] = {1, 2, 3}; for (auto a : i);
898 /// \endcode
899 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
900
901 /// \brief Matches the increment statement of a for loop.
902 ///
903 /// Example:
904 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
905 /// matches '++x' in
906 /// \code
907 /// for (x; x < N; ++x) { }
908 /// \endcode
AST_MATCHER_P(ForStmt,hasIncrement,internal::Matcher<Stmt>,InnerMatcher)909 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
910 InnerMatcher) {
911 const Stmt *const Increment = Node.getInc();
912 return (Increment != nullptr &&
913 InnerMatcher.matches(*Increment, Finder, Builder));
914 }
915
916 /// \brief Matches the initialization statement of a for loop.
917 ///
918 /// Example:
919 /// forStmt(hasLoopInit(declStmt()))
920 /// matches 'int x = 0' in
921 /// \code
922 /// for (int x = 0; x < N; ++x) { }
923 /// \endcode
AST_MATCHER_P(ForStmt,hasLoopInit,internal::Matcher<Stmt>,InnerMatcher)924 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
925 InnerMatcher) {
926 const Stmt *const Init = Node.getInit();
927 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
928 }
929
930 /// \brief Matches range-based for statements.
931 ///
932 /// forRangeStmt() matches 'for (auto a : i)'
933 /// \code
934 /// int i[] = {1, 2, 3}; for (auto a : i);
935 /// for(int j = 0; j < 5; ++j);
936 /// \endcode
937 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt;
938
939 /// \brief Matches the initialization statement of a for loop.
940 ///
941 /// Example:
942 /// forStmt(hasLoopVariable(anything()))
943 /// matches 'int x' in
944 /// \code
945 /// for (int x : a) { }
946 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasLoopVariable,internal::Matcher<VarDecl>,InnerMatcher)947 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
948 InnerMatcher) {
949 const VarDecl *const Var = Node.getLoopVariable();
950 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
951 }
952
953 /// \brief Matches the range initialization statement of a for loop.
954 ///
955 /// Example:
956 /// forStmt(hasRangeInit(anything()))
957 /// matches 'a' in
958 /// \code
959 /// for (int x : a) { }
960 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasRangeInit,internal::Matcher<Expr>,InnerMatcher)961 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
962 InnerMatcher) {
963 const Expr *const Init = Node.getRangeInit();
964 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
965 }
966
967 /// \brief Matches while statements.
968 ///
969 /// Given
970 /// \code
971 /// while (true) {}
972 /// \endcode
973 /// whileStmt()
974 /// matches 'while (true) {}'.
975 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
976
977 /// \brief Matches do statements.
978 ///
979 /// Given
980 /// \code
981 /// do {} while (true);
982 /// \endcode
983 /// doStmt()
984 /// matches 'do {} while(true)'
985 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
986
987 /// \brief Matches break statements.
988 ///
989 /// Given
990 /// \code
991 /// while (true) { break; }
992 /// \endcode
993 /// breakStmt()
994 /// matches 'break'
995 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
996
997 /// \brief Matches continue statements.
998 ///
999 /// Given
1000 /// \code
1001 /// while (true) { continue; }
1002 /// \endcode
1003 /// continueStmt()
1004 /// matches 'continue'
1005 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1006
1007 /// \brief Matches return statements.
1008 ///
1009 /// Given
1010 /// \code
1011 /// return 1;
1012 /// \endcode
1013 /// returnStmt()
1014 /// matches 'return 1'
1015 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1016
1017 /// \brief Matches goto statements.
1018 ///
1019 /// Given
1020 /// \code
1021 /// goto FOO;
1022 /// FOO: bar();
1023 /// \endcode
1024 /// gotoStmt()
1025 /// matches 'goto FOO'
1026 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1027
1028 /// \brief Matches label statements.
1029 ///
1030 /// Given
1031 /// \code
1032 /// goto FOO;
1033 /// FOO: bar();
1034 /// \endcode
1035 /// labelStmt()
1036 /// matches 'FOO:'
1037 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1038
1039 /// \brief Matches switch statements.
1040 ///
1041 /// Given
1042 /// \code
1043 /// switch(a) { case 42: break; default: break; }
1044 /// \endcode
1045 /// switchStmt()
1046 /// matches 'switch(a)'.
1047 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1048
1049 /// \brief Matches case and default statements inside switch statements.
1050 ///
1051 /// Given
1052 /// \code
1053 /// switch(a) { case 42: break; default: break; }
1054 /// \endcode
1055 /// switchCase()
1056 /// matches 'case 42: break;' and 'default: break;'.
1057 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1058
1059 /// \brief Matches case statements inside switch statements.
1060 ///
1061 /// Given
1062 /// \code
1063 /// switch(a) { case 42: break; default: break; }
1064 /// \endcode
1065 /// caseStmt()
1066 /// matches 'case 42: break;'.
1067 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1068
1069 /// \brief Matches default statements inside switch statements.
1070 ///
1071 /// Given
1072 /// \code
1073 /// switch(a) { case 42: break; default: break; }
1074 /// \endcode
1075 /// defaultStmt()
1076 /// matches 'default: break;'.
1077 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1078
1079 /// \brief Matches compound statements.
1080 ///
1081 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1082 /// \code
1083 /// for (;;) {{}}
1084 /// \endcode
1085 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1086
1087 /// \brief Matches catch statements.
1088 ///
1089 /// \code
1090 /// try {} catch(int i) {}
1091 /// \endcode
1092 /// catchStmt()
1093 /// matches 'catch(int i)'
1094 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt;
1095
1096 /// \brief Matches try statements.
1097 ///
1098 /// \code
1099 /// try {} catch(int i) {}
1100 /// \endcode
1101 /// tryStmt()
1102 /// matches 'try {}'
1103 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt;
1104
1105 /// \brief Matches throw expressions.
1106 ///
1107 /// \code
1108 /// try { throw 5; } catch(int i) {}
1109 /// \endcode
1110 /// throwExpr()
1111 /// matches 'throw 5'
1112 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr;
1113
1114 /// \brief Matches null statements.
1115 ///
1116 /// \code
1117 /// foo();;
1118 /// \endcode
1119 /// nullStmt()
1120 /// matches the second ';'
1121 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1122
1123 /// \brief Matches asm statements.
1124 ///
1125 /// \code
1126 /// int i = 100;
1127 /// __asm("mov al, 2");
1128 /// \endcode
1129 /// asmStmt()
1130 /// matches '__asm("mov al, 2")'
1131 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1132
1133 /// \brief Matches bool literals.
1134 ///
1135 /// Example matches true
1136 /// \code
1137 /// true
1138 /// \endcode
1139 const internal::VariadicDynCastAllOfMatcher<
1140 Stmt,
1141 CXXBoolLiteralExpr> boolLiteral;
1142
1143 /// \brief Matches string literals (also matches wide string literals).
1144 ///
1145 /// Example matches "abcd", L"abcd"
1146 /// \code
1147 /// char *s = "abcd"; wchar_t *ws = L"abcd"
1148 /// \endcode
1149 const internal::VariadicDynCastAllOfMatcher<
1150 Stmt,
1151 StringLiteral> stringLiteral;
1152
1153 /// \brief Matches character literals (also matches wchar_t).
1154 ///
1155 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1156 /// though.
1157 ///
1158 /// Example matches 'a', L'a'
1159 /// \code
1160 /// char ch = 'a'; wchar_t chw = L'a';
1161 /// \endcode
1162 const internal::VariadicDynCastAllOfMatcher<
1163 Stmt,
1164 CharacterLiteral> characterLiteral;
1165
1166 /// \brief Matches integer literals of all sizes / encodings, e.g.
1167 /// 1, 1L, 0x1 and 1U.
1168 ///
1169 /// Does not match character-encoded integers such as L'a'.
1170 const internal::VariadicDynCastAllOfMatcher<
1171 Stmt,
1172 IntegerLiteral> integerLiteral;
1173
1174 /// \brief Matches float literals of all sizes / encodings, e.g.
1175 /// 1.0, 1.0f, 1.0L and 1e10.
1176 ///
1177 /// Does not match implicit conversions such as
1178 /// \code
1179 /// float a = 10;
1180 /// \endcode
1181 const internal::VariadicDynCastAllOfMatcher<
1182 Stmt,
1183 FloatingLiteral> floatLiteral;
1184
1185 /// \brief Matches user defined literal operator call.
1186 ///
1187 /// Example match: "foo"_suffix
1188 const internal::VariadicDynCastAllOfMatcher<
1189 Stmt,
1190 UserDefinedLiteral> userDefinedLiteral;
1191
1192 /// \brief Matches compound (i.e. non-scalar) literals
1193 ///
1194 /// Example match: {1}, (1, 2)
1195 /// \code
1196 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1197 /// \endcode
1198 const internal::VariadicDynCastAllOfMatcher<
1199 Stmt,
1200 CompoundLiteralExpr> compoundLiteralExpr;
1201
1202 /// \brief Matches nullptr literal.
1203 const internal::VariadicDynCastAllOfMatcher<
1204 Stmt,
1205 CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
1206
1207 /// \brief Matches binary operator expressions.
1208 ///
1209 /// Example matches a || b
1210 /// \code
1211 /// !(a || b)
1212 /// \endcode
1213 const internal::VariadicDynCastAllOfMatcher<
1214 Stmt,
1215 BinaryOperator> binaryOperator;
1216
1217 /// \brief Matches unary operator expressions.
1218 ///
1219 /// Example matches !a
1220 /// \code
1221 /// !a || b
1222 /// \endcode
1223 const internal::VariadicDynCastAllOfMatcher<
1224 Stmt,
1225 UnaryOperator> unaryOperator;
1226
1227 /// \brief Matches conditional operator expressions.
1228 ///
1229 /// Example matches a ? b : c
1230 /// \code
1231 /// (a ? b : c) + 42
1232 /// \endcode
1233 const internal::VariadicDynCastAllOfMatcher<
1234 Stmt,
1235 ConditionalOperator> conditionalOperator;
1236
1237 /// \brief Matches a reinterpret_cast expression.
1238 ///
1239 /// Either the source expression or the destination type can be matched
1240 /// using has(), but hasDestinationType() is more specific and can be
1241 /// more readable.
1242 ///
1243 /// Example matches reinterpret_cast<char*>(&p) in
1244 /// \code
1245 /// void* p = reinterpret_cast<char*>(&p);
1246 /// \endcode
1247 const internal::VariadicDynCastAllOfMatcher<
1248 Stmt,
1249 CXXReinterpretCastExpr> reinterpretCastExpr;
1250
1251 /// \brief Matches a C++ static_cast expression.
1252 ///
1253 /// \see hasDestinationType
1254 /// \see reinterpretCast
1255 ///
1256 /// Example:
1257 /// staticCastExpr()
1258 /// matches
1259 /// static_cast<long>(8)
1260 /// in
1261 /// \code
1262 /// long eight(static_cast<long>(8));
1263 /// \endcode
1264 const internal::VariadicDynCastAllOfMatcher<
1265 Stmt,
1266 CXXStaticCastExpr> staticCastExpr;
1267
1268 /// \brief Matches a dynamic_cast expression.
1269 ///
1270 /// Example:
1271 /// dynamicCastExpr()
1272 /// matches
1273 /// dynamic_cast<D*>(&b);
1274 /// in
1275 /// \code
1276 /// struct B { virtual ~B() {} }; struct D : B {};
1277 /// B b;
1278 /// D* p = dynamic_cast<D*>(&b);
1279 /// \endcode
1280 const internal::VariadicDynCastAllOfMatcher<
1281 Stmt,
1282 CXXDynamicCastExpr> dynamicCastExpr;
1283
1284 /// \brief Matches a const_cast expression.
1285 ///
1286 /// Example: Matches const_cast<int*>(&r) in
1287 /// \code
1288 /// int n = 42;
1289 /// const int &r(n);
1290 /// int* p = const_cast<int*>(&r);
1291 /// \endcode
1292 const internal::VariadicDynCastAllOfMatcher<
1293 Stmt,
1294 CXXConstCastExpr> constCastExpr;
1295
1296 /// \brief Matches a C-style cast expression.
1297 ///
1298 /// Example: Matches (int*) 2.2f in
1299 /// \code
1300 /// int i = (int) 2.2f;
1301 /// \endcode
1302 const internal::VariadicDynCastAllOfMatcher<
1303 Stmt,
1304 CStyleCastExpr> cStyleCastExpr;
1305
1306 /// \brief Matches explicit cast expressions.
1307 ///
1308 /// Matches any cast expression written in user code, whether it be a
1309 /// C-style cast, a functional-style cast, or a keyword cast.
1310 ///
1311 /// Does not match implicit conversions.
1312 ///
1313 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1314 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1315 /// actual cast expressions.
1316 ///
1317 /// \see hasDestinationType.
1318 ///
1319 /// Example: matches all five of the casts in
1320 /// \code
1321 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1322 /// \endcode
1323 /// but does not match the implicit conversion in
1324 /// \code
1325 /// long ell = 42;
1326 /// \endcode
1327 const internal::VariadicDynCastAllOfMatcher<
1328 Stmt,
1329 ExplicitCastExpr> explicitCastExpr;
1330
1331 /// \brief Matches the implicit cast nodes of Clang's AST.
1332 ///
1333 /// This matches many different places, including function call return value
1334 /// eliding, as well as any type conversions.
1335 const internal::VariadicDynCastAllOfMatcher<
1336 Stmt,
1337 ImplicitCastExpr> implicitCastExpr;
1338
1339 /// \brief Matches any cast nodes of Clang's AST.
1340 ///
1341 /// Example: castExpr() matches each of the following:
1342 /// \code
1343 /// (int) 3;
1344 /// const_cast<Expr *>(SubExpr);
1345 /// char c = 0;
1346 /// \endcode
1347 /// but does not match
1348 /// \code
1349 /// int i = (0);
1350 /// int k = 0;
1351 /// \endcode
1352 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1353
1354 /// \brief Matches functional cast expressions
1355 ///
1356 /// Example: Matches Foo(bar);
1357 /// \code
1358 /// Foo f = bar;
1359 /// Foo g = (Foo) bar;
1360 /// Foo h = Foo(bar);
1361 /// \endcode
1362 const internal::VariadicDynCastAllOfMatcher<
1363 Stmt,
1364 CXXFunctionalCastExpr> functionalCastExpr;
1365
1366 /// \brief Matches functional cast expressions having N != 1 arguments
1367 ///
1368 /// Example: Matches Foo(bar, bar)
1369 /// \code
1370 /// Foo h = Foo(bar, bar);
1371 /// \endcode
1372 const internal::VariadicDynCastAllOfMatcher<
1373 Stmt,
1374 CXXTemporaryObjectExpr> temporaryObjectExpr;
1375
1376 /// \brief Matches \c QualTypes in the clang AST.
1377 const internal::VariadicAllOfMatcher<QualType> qualType;
1378
1379 /// \brief Matches \c Types in the clang AST.
1380 const internal::VariadicAllOfMatcher<Type> type;
1381
1382 /// \brief Matches \c TypeLocs in the clang AST.
1383 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1384
1385 /// \brief Matches if any of the given matchers matches.
1386 ///
1387 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1388 /// matching submatcher.
1389 ///
1390 /// For example, in:
1391 /// \code
1392 /// class A { int a; int b; };
1393 /// \endcode
1394 /// The matcher:
1395 /// \code
1396 /// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1397 /// has(fieldDecl(hasName("b")).bind("v"))))
1398 /// \endcode
1399 /// will generate two results binding "v", the first of which binds
1400 /// the field declaration of \c a, the second the field declaration of
1401 /// \c b.
1402 ///
1403 /// Usable as: Any Matcher
1404 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
1405 internal::EachOfVariadicOperator
1406 };
1407
1408 /// \brief Matches if any of the given matchers matches.
1409 ///
1410 /// Usable as: Any Matcher
1411 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
1412 internal::AnyOfVariadicOperator
1413 };
1414
1415 /// \brief Matches if all given matchers match.
1416 ///
1417 /// Usable as: Any Matcher
1418 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
1419 internal::AllOfVariadicOperator
1420 };
1421
1422 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1423 ///
1424 /// Given
1425 /// \code
1426 /// Foo x = bar;
1427 /// int y = sizeof(x) + alignof(x);
1428 /// \endcode
1429 /// unaryExprOrTypeTraitExpr()
1430 /// matches \c sizeof(x) and \c alignof(x)
1431 const internal::VariadicDynCastAllOfMatcher<
1432 Stmt,
1433 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1434
1435 /// \brief Matches unary expressions that have a specific type of argument.
1436 ///
1437 /// Given
1438 /// \code
1439 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1440 /// \endcode
1441 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1442 /// matches \c sizeof(a) and \c alignof(c)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,hasArgumentOfType,internal::Matcher<QualType>,InnerMatcher)1443 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1444 internal::Matcher<QualType>, InnerMatcher) {
1445 const QualType ArgumentType = Node.getTypeOfArgument();
1446 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1447 }
1448
1449 /// \brief Matches unary expressions of a certain kind.
1450 ///
1451 /// Given
1452 /// \code
1453 /// int x;
1454 /// int s = sizeof(x) + alignof(x)
1455 /// \endcode
1456 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1457 /// matches \c sizeof(x)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,ofKind,UnaryExprOrTypeTrait,Kind)1458 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1459 return Node.getKind() == Kind;
1460 }
1461
1462 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1463 /// alignof.
alignOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)1464 inline internal::Matcher<Stmt> alignOfExpr(
1465 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1466 return stmt(unaryExprOrTypeTraitExpr(allOf(
1467 ofKind(UETT_AlignOf), InnerMatcher)));
1468 }
1469
1470 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1471 /// sizeof.
sizeOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)1472 inline internal::Matcher<Stmt> sizeOfExpr(
1473 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1474 return stmt(unaryExprOrTypeTraitExpr(
1475 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1476 }
1477
1478 /// \brief Matches NamedDecl nodes that have the specified name.
1479 ///
1480 /// Supports specifying enclosing namespaces or classes by prefixing the name
1481 /// with '<enclosing>::'.
1482 /// Does not match typedefs of an underlying type with the given name.
1483 ///
1484 /// Example matches X (Name == "X")
1485 /// \code
1486 /// class X;
1487 /// \endcode
1488 ///
1489 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1490 /// \code
1491 /// namespace a { namespace b { class X; } }
1492 /// \endcode
AST_MATCHER_P(NamedDecl,hasName,std::string,Name)1493 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1494 assert(!Name.empty());
1495 const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1496 const StringRef FullName = FullNameString;
1497 const StringRef Pattern = Name;
1498 if (Pattern.startswith("::")) {
1499 return FullName == Pattern;
1500 } else {
1501 return FullName.endswith(("::" + Pattern).str());
1502 }
1503 }
1504
1505 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1506 /// a substring matched by the given RegExp.
1507 ///
1508 /// Supports specifying enclosing namespaces or classes by
1509 /// prefixing the name with '<enclosing>::'. Does not match typedefs
1510 /// of an underlying type with the given name.
1511 ///
1512 /// Example matches X (regexp == "::X")
1513 /// \code
1514 /// class X;
1515 /// \endcode
1516 ///
1517 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1518 /// \code
1519 /// namespace foo { namespace bar { class X; } }
1520 /// \endcode
AST_MATCHER_P(NamedDecl,matchesName,std::string,RegExp)1521 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1522 assert(!RegExp.empty());
1523 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1524 llvm::Regex RE(RegExp);
1525 return RE.match(FullNameString);
1526 }
1527
1528 /// \brief Matches overloaded operator names.
1529 ///
1530 /// Matches overloaded operator names specified in strings without the
1531 /// "operator" prefix: e.g. "<<".
1532 ///
1533 /// Given:
1534 /// \code
1535 /// class A { int operator*(); };
1536 /// const A &operator<<(const A &a, const A &b);
1537 /// A a;
1538 /// a << a; // <-- This matches
1539 /// \endcode
1540 ///
1541 /// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified
1542 /// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
1543 /// the declaration of \c A.
1544 ///
1545 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl>
1546 inline internal::PolymorphicMatcherWithParam1<
1547 internal::HasOverloadedOperatorNameMatcher, StringRef,
1548 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>
hasOverloadedOperatorName(const StringRef Name)1549 hasOverloadedOperatorName(const StringRef Name) {
1550 return internal::PolymorphicMatcherWithParam1<
1551 internal::HasOverloadedOperatorNameMatcher, StringRef,
1552 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>(
1553 Name);
1554 }
1555
1556 /// \brief Matches C++ classes that are directly or indirectly derived from
1557 /// a class matching \c Base.
1558 ///
1559 /// Note that a class is not considered to be derived from itself.
1560 ///
1561 /// Example matches Y, Z, C (Base == hasName("X"))
1562 /// \code
1563 /// class X;
1564 /// class Y : public X {}; // directly derived
1565 /// class Z : public Y {}; // indirectly derived
1566 /// typedef X A;
1567 /// typedef A B;
1568 /// class C : public B {}; // derived from a typedef of X
1569 /// \endcode
1570 ///
1571 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1572 /// \code
1573 /// class Foo;
1574 /// typedef Foo X;
1575 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
1576 /// \endcode
AST_MATCHER_P(CXXRecordDecl,isDerivedFrom,internal::Matcher<NamedDecl>,Base)1577 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1578 internal::Matcher<NamedDecl>, Base) {
1579 return Finder->classIsDerivedFrom(&Node, Base, Builder);
1580 }
1581
1582 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1583 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, StringRef, BaseName, 1) {
1584 assert(!BaseName.empty());
1585 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1586 }
1587
1588 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1589 /// match \c Base.
1590 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
1591 internal::Matcher<NamedDecl>, Base, 0) {
1592 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
1593 .matches(Node, Finder, Builder);
1594 }
1595
1596 /// \brief Overloaded method as shortcut for
1597 /// \c isSameOrDerivedFrom(hasName(...)).
1598 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, StringRef, BaseName,
1599 1) {
1600 assert(!BaseName.empty());
1601 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1602 }
1603
1604 /// \brief Matches the first method of a class or struct that satisfies \c
1605 /// InnerMatcher.
1606 ///
1607 /// Given:
1608 /// \code
1609 /// class A { void func(); };
1610 /// class B { void member(); };
1611 /// \code
1612 ///
1613 /// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A
1614 /// but not \c B.
AST_MATCHER_P(CXXRecordDecl,hasMethod,internal::Matcher<CXXMethodDecl>,InnerMatcher)1615 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1616 InnerMatcher) {
1617 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
1618 Node.method_end(), Finder, Builder);
1619 }
1620
1621 /// \brief Matches AST nodes that have child AST nodes that match the
1622 /// provided matcher.
1623 ///
1624 /// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1625 /// \code
1626 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1627 /// class Y { class X {}; };
1628 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1629 /// \endcode
1630 ///
1631 /// ChildT must be an AST base type.
1632 ///
1633 /// Usable as: Any Matcher
1634 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
1635 LLVM_ATTRIBUTE_UNUSED has = {};
1636
1637 /// \brief Matches AST nodes that have descendant AST nodes that match the
1638 /// provided matcher.
1639 ///
1640 /// Example matches X, Y, Z
1641 /// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1642 /// \code
1643 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1644 /// class Y { class X {}; };
1645 /// class Z { class Y { class X {}; }; };
1646 /// \endcode
1647 ///
1648 /// DescendantT must be an AST base type.
1649 ///
1650 /// Usable as: Any Matcher
1651 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
1652 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
1653
1654 /// \brief Matches AST nodes that have child AST nodes that match the
1655 /// provided matcher.
1656 ///
1657 /// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1658 /// \code
1659 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1660 /// class Y { class X {}; };
1661 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1662 /// \endcode
1663 ///
1664 /// ChildT must be an AST base type.
1665 ///
1666 /// As opposed to 'has', 'forEach' will cause a match for each result that
1667 /// matches instead of only on the first one.
1668 ///
1669 /// Usable as: Any Matcher
1670 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
1671 LLVM_ATTRIBUTE_UNUSED forEach = {};
1672
1673 /// \brief Matches AST nodes that have descendant AST nodes that match the
1674 /// provided matcher.
1675 ///
1676 /// Example matches X, A, B, C
1677 /// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1678 /// \code
1679 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1680 /// class A { class X {}; };
1681 /// class B { class C { class X {}; }; };
1682 /// \endcode
1683 ///
1684 /// DescendantT must be an AST base type.
1685 ///
1686 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1687 /// each result that matches instead of only on the first one.
1688 ///
1689 /// Note: Recursively combined ForEachDescendant can cause many matches:
1690 /// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1691 /// will match 10 times (plus injected class name matches) on:
1692 /// \code
1693 /// class A { class B { class C { class D { class E {}; }; }; }; };
1694 /// \endcode
1695 ///
1696 /// Usable as: Any Matcher
1697 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
1698 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
1699
1700 /// \brief Matches if the node or any descendant matches.
1701 ///
1702 /// Generates results for each match.
1703 ///
1704 /// For example, in:
1705 /// \code
1706 /// class A { class B {}; class C {}; };
1707 /// \endcode
1708 /// The matcher:
1709 /// \code
1710 /// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1711 /// \endcode
1712 /// will generate results for \c A, \c B and \c C.
1713 ///
1714 /// Usable as: Any Matcher
1715 template <typename T>
findAll(const internal::Matcher<T> & Matcher)1716 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
1717 return eachOf(Matcher, forEachDescendant(Matcher));
1718 }
1719
1720 /// \brief Matches AST nodes that have a parent that matches the provided
1721 /// matcher.
1722 ///
1723 /// Given
1724 /// \code
1725 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1726 /// \endcode
1727 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1728 ///
1729 /// Usable as: Any Matcher
1730 const internal::ArgumentAdaptingMatcherFunc<
1731 internal::HasParentMatcher, internal::TypeList<Decl, Stmt>,
1732 internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasParent = {};
1733
1734 /// \brief Matches AST nodes that have an ancestor that matches the provided
1735 /// matcher.
1736 ///
1737 /// Given
1738 /// \code
1739 /// void f() { if (true) { int x = 42; } }
1740 /// void g() { for (;;) { int x = 43; } }
1741 /// \endcode
1742 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1743 ///
1744 /// Usable as: Any Matcher
1745 const internal::ArgumentAdaptingMatcherFunc<
1746 internal::HasAncestorMatcher, internal::TypeList<Decl, Stmt>,
1747 internal::TypeList<Decl, Stmt> > LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
1748
1749 /// \brief Matches if the provided matcher does not match.
1750 ///
1751 /// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1752 /// \code
1753 /// class X {};
1754 /// class Y {};
1755 /// \endcode
1756 ///
1757 /// Usable as: Any Matcher
1758 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
1759 internal::NotUnaryOperator
1760 };
1761
1762 /// \brief Matches a node if the declaration associated with that node
1763 /// matches the given matcher.
1764 ///
1765 /// The associated declaration is:
1766 /// - for type nodes, the declaration of the underlying type
1767 /// - for CallExpr, the declaration of the callee
1768 /// - for MemberExpr, the declaration of the referenced member
1769 /// - for CXXConstructExpr, the declaration of the constructor
1770 ///
1771 /// Also usable as Matcher<T> for any T supporting the getDecl() member
1772 /// function. e.g. various subtypes of clang::Type and various expressions.
1773 ///
1774 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1775 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
1776 /// Matcher<LabelStmt>, Matcher<MemberExpr>, Matcher<QualType>,
1777 /// Matcher<RecordType>, Matcher<TagType>,
1778 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
1779 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
1780 inline internal::PolymorphicMatcherWithParam1<
1781 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
1782 void(internal::HasDeclarationSupportedTypes)>
hasDeclaration(const internal::Matcher<Decl> & InnerMatcher)1783 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1784 return internal::PolymorphicMatcherWithParam1<
1785 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
1786 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
1787 }
1788
1789 /// \brief Matches on the implicit object argument of a member call expression.
1790 ///
1791 /// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1792 /// \code
1793 /// class Y { public: void x(); };
1794 /// void z() { Y y; y.x(); }",
1795 /// \endcode
1796 ///
1797 /// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr,on,internal::Matcher<Expr>,InnerMatcher)1798 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1799 InnerMatcher) {
1800 const Expr *ExprNode = Node.getImplicitObjectArgument()
1801 ->IgnoreParenImpCasts();
1802 return (ExprNode != nullptr &&
1803 InnerMatcher.matches(*ExprNode, Finder, Builder));
1804 }
1805
1806 /// \brief Matches if the call expression's callee expression matches.
1807 ///
1808 /// Given
1809 /// \code
1810 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
1811 /// void f() { f(); }
1812 /// \endcode
1813 /// callExpr(callee(expr()))
1814 /// matches this->x(), x(), y.x(), f()
1815 /// with callee(...)
1816 /// matching this->x, x, y.x, f respectively
1817 ///
1818 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1819 /// because this introduces ambiguous overloads with calls to Callee taking a
1820 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1821 /// implemented in terms of implicit casts.
AST_MATCHER_P(CallExpr,callee,internal::Matcher<Stmt>,InnerMatcher)1822 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1823 InnerMatcher) {
1824 const Expr *ExprNode = Node.getCallee();
1825 return (ExprNode != nullptr &&
1826 InnerMatcher.matches(*ExprNode, Finder, Builder));
1827 }
1828
1829 /// \brief Matches if the call expression's callee's declaration matches the
1830 /// given matcher.
1831 ///
1832 /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1833 /// \code
1834 /// class Y { public: void x(); };
1835 /// void z() { Y y; y.x();
1836 /// \endcode
1837 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
1838 1) {
1839 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
1840 }
1841
1842 /// \brief Matches if the expression's or declaration's type matches a type
1843 /// matcher.
1844 ///
1845 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1846 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1847 /// \code
1848 /// class X {};
1849 /// void y(X &x) { x; X z; }
1850 /// \endcode
1851 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
1852 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl),
1853 internal::Matcher<QualType>, InnerMatcher, 0) {
1854 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1855 }
1856
1857 /// \brief Overloaded to match the declaration of the expression's or value
1858 /// declaration's type.
1859 ///
1860 /// In case of a value declaration (for example a variable declaration),
1861 /// this resolves one layer of indirection. For example, in the value
1862 /// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1863 /// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1864 /// of x."
1865 ///
1866 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1867 /// and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1868 /// \code
1869 /// class X {};
1870 /// void y(X &x) { x; X z; }
1871 /// \endcode
1872 ///
1873 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1874 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
1875 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl),
1876 internal::Matcher<Decl>, InnerMatcher, 1) {
1877 return qualType(hasDeclaration(InnerMatcher))
1878 .matches(Node.getType(), Finder, Builder);
1879 }
1880
1881 /// \brief Matches if the type location of the declarator decl's type matches
1882 /// the inner matcher.
1883 ///
1884 /// Given
1885 /// \code
1886 /// int x;
1887 /// \endcode
1888 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
1889 /// matches int x
AST_MATCHER_P(DeclaratorDecl,hasTypeLoc,internal::Matcher<TypeLoc>,Inner)1890 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
1891 if (!Node.getTypeSourceInfo())
1892 // This happens for example for implicit destructors.
1893 return false;
1894 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
1895 }
1896
1897 /// \brief Matches if the matched type is represented by the given string.
1898 ///
1899 /// Given
1900 /// \code
1901 /// class Y { public: void x(); };
1902 /// void z() { Y* y; y->x(); }
1903 /// \endcode
1904 /// callExpr(on(hasType(asString("class Y *"))))
1905 /// matches y->x()
AST_MATCHER_P(QualType,asString,std::string,Name)1906 AST_MATCHER_P(QualType, asString, std::string, Name) {
1907 return Name == Node.getAsString();
1908 }
1909
1910 /// \brief Matches if the matched type is a pointer type and the pointee type
1911 /// matches the specified matcher.
1912 ///
1913 /// Example matches y->x()
1914 /// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1915 /// \code
1916 /// class Y { public: void x(); };
1917 /// void z() { Y *y; y->x(); }
1918 /// \endcode
AST_MATCHER_P(QualType,pointsTo,internal::Matcher<QualType>,InnerMatcher)1919 AST_MATCHER_P(
1920 QualType, pointsTo, internal::Matcher<QualType>,
1921 InnerMatcher) {
1922 return (!Node.isNull() && Node->isPointerType() &&
1923 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1924 }
1925
1926 /// \brief Overloaded to match the pointee type's declaration.
1927 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
1928 InnerMatcher, 1) {
1929 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
1930 .matches(Node, Finder, Builder);
1931 }
1932
1933 /// \brief Matches if the matched type is a reference type and the referenced
1934 /// type matches the specified matcher.
1935 ///
1936 /// Example matches X &x and const X &y
1937 /// (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1938 /// \code
1939 /// class X {
1940 /// void a(X b) {
1941 /// X &x = b;
1942 /// const X &y = b;
1943 /// };
1944 /// \endcode
AST_MATCHER_P(QualType,references,internal::Matcher<QualType>,InnerMatcher)1945 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1946 InnerMatcher) {
1947 return (!Node.isNull() && Node->isReferenceType() &&
1948 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1949 }
1950
1951 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1952 ///
1953 /// Given:
1954 /// \code
1955 /// typedef int &int_ref;
1956 /// int a;
1957 /// int_ref b = a;
1958 /// \code
1959 ///
1960 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1961 /// declaration of b but \c
1962 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
AST_MATCHER_P(QualType,hasCanonicalType,internal::Matcher<QualType>,InnerMatcher)1963 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1964 InnerMatcher) {
1965 if (Node.isNull())
1966 return false;
1967 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1968 }
1969
1970 /// \brief Overloaded to match the referenced type's declaration.
1971 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
1972 InnerMatcher, 1) {
1973 return references(qualType(hasDeclaration(InnerMatcher)))
1974 .matches(Node, Finder, Builder);
1975 }
1976
AST_MATCHER_P(CXXMemberCallExpr,onImplicitObjectArgument,internal::Matcher<Expr>,InnerMatcher)1977 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1978 internal::Matcher<Expr>, InnerMatcher) {
1979 const Expr *ExprNode = Node.getImplicitObjectArgument();
1980 return (ExprNode != nullptr &&
1981 InnerMatcher.matches(*ExprNode, Finder, Builder));
1982 }
1983
1984 /// \brief Matches if the expression's type either matches the specified
1985 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1986 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
1987 internal::Matcher<QualType>, InnerMatcher, 0) {
1988 return onImplicitObjectArgument(
1989 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
1990 .matches(Node, Finder, Builder);
1991 }
1992
1993 /// \brief Overloaded to match the type's declaration.
1994 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
1995 internal::Matcher<Decl>, InnerMatcher, 1) {
1996 return onImplicitObjectArgument(
1997 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
1998 .matches(Node, Finder, Builder);
1999 }
2000
2001 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2002 /// specified matcher.
2003 ///
2004 /// Example matches x in if(x)
2005 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2006 /// \code
2007 /// bool x;
2008 /// if (x) {}
2009 /// \endcode
AST_MATCHER_P(DeclRefExpr,to,internal::Matcher<Decl>,InnerMatcher)2010 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2011 InnerMatcher) {
2012 const Decl *DeclNode = Node.getDecl();
2013 return (DeclNode != nullptr &&
2014 InnerMatcher.matches(*DeclNode, Finder, Builder));
2015 }
2016
2017 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2018 /// specific using shadow declaration.
2019 ///
2020 /// FIXME: This currently only works for functions. Fix.
2021 ///
2022 /// Given
2023 /// \code
2024 /// namespace a { void f() {} }
2025 /// using a::f;
2026 /// void g() {
2027 /// f(); // Matches this ..
2028 /// a::f(); // .. but not this.
2029 /// }
2030 /// \endcode
2031 /// declRefExpr(throughUsingDeclaration(anything()))
2032 /// matches \c f()
AST_MATCHER_P(DeclRefExpr,throughUsingDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)2033 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2034 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2035 const NamedDecl *FoundDecl = Node.getFoundDecl();
2036 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2037 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2038 return false;
2039 }
2040
2041 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2042 ///
2043 /// Given
2044 /// \code
2045 /// int a, b;
2046 /// int c;
2047 /// \endcode
2048 /// declStmt(hasSingleDecl(anything()))
2049 /// matches 'int c;' but not 'int a, b;'.
AST_MATCHER_P(DeclStmt,hasSingleDecl,internal::Matcher<Decl>,InnerMatcher)2050 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2051 if (Node.isSingleDecl()) {
2052 const Decl *FoundDecl = Node.getSingleDecl();
2053 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2054 }
2055 return false;
2056 }
2057
2058 /// \brief Matches a variable declaration that has an initializer expression
2059 /// that matches the given matcher.
2060 ///
2061 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2062 /// \code
2063 /// bool y() { return true; }
2064 /// bool x = y();
2065 /// \endcode
AST_MATCHER_P(VarDecl,hasInitializer,internal::Matcher<Expr>,InnerMatcher)2066 AST_MATCHER_P(
2067 VarDecl, hasInitializer, internal::Matcher<Expr>,
2068 InnerMatcher) {
2069 const Expr *Initializer = Node.getAnyInitializer();
2070 return (Initializer != nullptr &&
2071 InnerMatcher.matches(*Initializer, Finder, Builder));
2072 }
2073
2074 /// \brief Matches a variable declaration that has function scope and is a
2075 /// non-static local variable.
2076 ///
2077 /// Example matches x (matcher = varDecl(hasLocalStorage())
2078 /// \code
2079 /// void f() {
2080 /// int x;
2081 /// static int y;
2082 /// }
2083 /// int z;
2084 /// \endcode
AST_MATCHER(VarDecl,hasLocalStorage)2085 AST_MATCHER(VarDecl, hasLocalStorage) {
2086 return Node.hasLocalStorage();
2087 }
2088
2089 /// \brief Matches a variable declaration that does not have local storage.
2090 ///
2091 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2092 /// \code
2093 /// void f() {
2094 /// int x;
2095 /// static int y;
2096 /// }
2097 /// int z;
2098 /// \endcode
AST_MATCHER(VarDecl,hasGlobalStorage)2099 AST_MATCHER(VarDecl, hasGlobalStorage) {
2100 return Node.hasGlobalStorage();
2101 }
2102
2103 /// \brief Checks that a call expression or a constructor call expression has
2104 /// a specific number of arguments (including absent default arguments).
2105 ///
2106 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2107 /// \code
2108 /// void f(int x, int y);
2109 /// f(0, 0);
2110 /// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES_2 (CallExpr,CXXConstructExpr),unsigned,N)2111 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2112 CallExpr, CXXConstructExpr),
2113 unsigned, N) {
2114 return Node.getNumArgs() == N;
2115 }
2116
2117 /// \brief Matches the n'th argument of a call expression or a constructor
2118 /// call expression.
2119 ///
2120 /// Example matches y in x(y)
2121 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2122 /// \code
2123 /// void x(int) { int y; x(y); }
2124 /// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,AST_POLYMORPHIC_SUPPORTED_TYPES_2 (CallExpr,CXXConstructExpr),unsigned,N,internal::Matcher<Expr>,InnerMatcher)2125 AST_POLYMORPHIC_MATCHER_P2(
2126 hasArgument,
2127 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr),
2128 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2129 return (N < Node.getNumArgs() &&
2130 InnerMatcher.matches(
2131 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2132 }
2133
2134 /// \brief Matches declaration statements that contain a specific number of
2135 /// declarations.
2136 ///
2137 /// Example: Given
2138 /// \code
2139 /// int a, b;
2140 /// int c;
2141 /// int d = 2, e;
2142 /// \endcode
2143 /// declCountIs(2)
2144 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
AST_MATCHER_P(DeclStmt,declCountIs,unsigned,N)2145 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2146 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2147 }
2148
2149 /// \brief Matches the n'th declaration of a declaration statement.
2150 ///
2151 /// Note that this does not work for global declarations because the AST
2152 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2153 /// DeclStmt's.
2154 /// Example: Given non-global declarations
2155 /// \code
2156 /// int a, b = 0;
2157 /// int c;
2158 /// int d = 2, e;
2159 /// \endcode
2160 /// declStmt(containsDeclaration(
2161 /// 0, varDecl(hasInitializer(anything()))))
2162 /// matches only 'int d = 2, e;', and
2163 /// declStmt(containsDeclaration(1, varDecl()))
2164 /// \code
2165 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2166 /// but 'int c;' is not matched.
2167 /// \endcode
AST_MATCHER_P2(DeclStmt,containsDeclaration,unsigned,N,internal::Matcher<Decl>,InnerMatcher)2168 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2169 internal::Matcher<Decl>, InnerMatcher) {
2170 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2171 if (N >= NumDecls)
2172 return false;
2173 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2174 std::advance(Iterator, N);
2175 return InnerMatcher.matches(**Iterator, Finder, Builder);
2176 }
2177
2178 /// \brief Matches a constructor initializer.
2179 ///
2180 /// Given
2181 /// \code
2182 /// struct Foo {
2183 /// Foo() : foo_(1) { }
2184 /// int foo_;
2185 /// };
2186 /// \endcode
2187 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2188 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl,hasAnyConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)2189 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2190 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2191 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2192 Node.init_end(), Finder, Builder);
2193 }
2194
2195 /// \brief Matches the field declaration of a constructor initializer.
2196 ///
2197 /// Given
2198 /// \code
2199 /// struct Foo {
2200 /// Foo() : foo_(1) { }
2201 /// int foo_;
2202 /// };
2203 /// \endcode
2204 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2205 /// forField(hasName("foo_"))))))
2206 /// matches Foo
2207 /// with forField matching foo_
AST_MATCHER_P(CXXCtorInitializer,forField,internal::Matcher<FieldDecl>,InnerMatcher)2208 AST_MATCHER_P(CXXCtorInitializer, forField,
2209 internal::Matcher<FieldDecl>, InnerMatcher) {
2210 const FieldDecl *NodeAsDecl = Node.getMember();
2211 return (NodeAsDecl != nullptr &&
2212 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2213 }
2214
2215 /// \brief Matches the initializer expression of a constructor initializer.
2216 ///
2217 /// Given
2218 /// \code
2219 /// struct Foo {
2220 /// Foo() : foo_(1) { }
2221 /// int foo_;
2222 /// };
2223 /// \endcode
2224 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2225 /// withInitializer(integerLiteral(equals(1)))))))
2226 /// matches Foo
2227 /// with withInitializer matching (1)
AST_MATCHER_P(CXXCtorInitializer,withInitializer,internal::Matcher<Expr>,InnerMatcher)2228 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2229 internal::Matcher<Expr>, InnerMatcher) {
2230 const Expr* NodeAsExpr = Node.getInit();
2231 return (NodeAsExpr != nullptr &&
2232 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2233 }
2234
2235 /// \brief Matches a constructor initializer if it is explicitly written in
2236 /// code (as opposed to implicitly added by the compiler).
2237 ///
2238 /// Given
2239 /// \code
2240 /// struct Foo {
2241 /// Foo() { }
2242 /// Foo(int) : foo_("A") { }
2243 /// string foo_;
2244 /// };
2245 /// \endcode
2246 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2247 /// will match Foo(int), but not Foo()
AST_MATCHER(CXXCtorInitializer,isWritten)2248 AST_MATCHER(CXXCtorInitializer, isWritten) {
2249 return Node.isWritten();
2250 }
2251
2252 /// \brief Matches any argument of a call expression or a constructor call
2253 /// expression.
2254 ///
2255 /// Given
2256 /// \code
2257 /// void x(int, int, int) { int y; x(1, y, 42); }
2258 /// \endcode
2259 /// callExpr(hasAnyArgument(declRefExpr()))
2260 /// matches x(1, y, 42)
2261 /// with hasAnyArgument(...)
2262 /// matching y
2263 ///
2264 /// FIXME: Currently this will ignore parentheses and implicit casts on
2265 /// the argument before applying the inner matcher. We'll want to remove
2266 /// this to allow for greater control by the user once \c ignoreImplicit()
2267 /// has been implemented.
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,AST_POLYMORPHIC_SUPPORTED_TYPES_2 (CallExpr,CXXConstructExpr),internal::Matcher<Expr>,InnerMatcher)2268 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2269 CallExpr, CXXConstructExpr),
2270 internal::Matcher<Expr>, InnerMatcher) {
2271 for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2272 BoundNodesTreeBuilder Result(*Builder);
2273 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder,
2274 &Result)) {
2275 *Builder = Result;
2276 return true;
2277 }
2278 }
2279 return false;
2280 }
2281
2282 /// \brief Matches a constructor call expression which uses list initialization.
AST_MATCHER(CXXConstructExpr,isListInitialization)2283 AST_MATCHER(CXXConstructExpr, isListInitialization) {
2284 return Node.isListInitialization();
2285 }
2286
2287 /// \brief Matches the n'th parameter of a function declaration.
2288 ///
2289 /// Given
2290 /// \code
2291 /// class X { void f(int x) {} };
2292 /// \endcode
2293 /// methodDecl(hasParameter(0, hasType(varDecl())))
2294 /// matches f(int x) {}
2295 /// with hasParameter(...)
2296 /// matching int x
AST_MATCHER_P2(FunctionDecl,hasParameter,unsigned,N,internal::Matcher<ParmVarDecl>,InnerMatcher)2297 AST_MATCHER_P2(FunctionDecl, hasParameter,
2298 unsigned, N, internal::Matcher<ParmVarDecl>,
2299 InnerMatcher) {
2300 return (N < Node.getNumParams() &&
2301 InnerMatcher.matches(
2302 *Node.getParamDecl(N), Finder, Builder));
2303 }
2304
2305 /// \brief Matches any parameter of a function declaration.
2306 ///
2307 /// Does not match the 'this' parameter of a method.
2308 ///
2309 /// Given
2310 /// \code
2311 /// class X { void f(int x, int y, int z) {} };
2312 /// \endcode
2313 /// methodDecl(hasAnyParameter(hasName("y")))
2314 /// matches f(int x, int y, int z) {}
2315 /// with hasAnyParameter(...)
2316 /// matching int y
AST_MATCHER_P(FunctionDecl,hasAnyParameter,internal::Matcher<ParmVarDecl>,InnerMatcher)2317 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2318 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2319 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2320 Node.param_end(), Finder, Builder);
2321 }
2322
2323 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2324 ///
2325 /// Given
2326 /// \code
2327 /// void f(int i) {}
2328 /// void g(int i, int j) {}
2329 /// \endcode
2330 /// functionDecl(parameterCountIs(2))
2331 /// matches g(int i, int j) {}
AST_MATCHER_P(FunctionDecl,parameterCountIs,unsigned,N)2332 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2333 return Node.getNumParams() == N;
2334 }
2335
2336 /// \brief Matches the return type of a function declaration.
2337 ///
2338 /// Given:
2339 /// \code
2340 /// class X { int f() { return 1; } };
2341 /// \endcode
2342 /// methodDecl(returns(asString("int")))
2343 /// matches int f() { return 1; }
AST_MATCHER_P(FunctionDecl,returns,internal::Matcher<QualType>,InnerMatcher)2344 AST_MATCHER_P(FunctionDecl, returns,
2345 internal::Matcher<QualType>, InnerMatcher) {
2346 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
2347 }
2348
2349 /// \brief Matches extern "C" function declarations.
2350 ///
2351 /// Given:
2352 /// \code
2353 /// extern "C" void f() {}
2354 /// extern "C" { void g() {} }
2355 /// void h() {}
2356 /// \endcode
2357 /// functionDecl(isExternC())
2358 /// matches the declaration of f and g, but not the declaration h
AST_MATCHER(FunctionDecl,isExternC)2359 AST_MATCHER(FunctionDecl, isExternC) {
2360 return Node.isExternC();
2361 }
2362
2363 /// \brief Matches the condition expression of an if statement, for loop,
2364 /// or conditional operator.
2365 ///
2366 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2367 /// \code
2368 /// if (true) {}
2369 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasCondition,AST_POLYMORPHIC_SUPPORTED_TYPES_5 (IfStmt,ForStmt,WhileStmt,DoStmt,ConditionalOperator),internal::Matcher<Expr>,InnerMatcher)2370 AST_POLYMORPHIC_MATCHER_P(
2371 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5(
2372 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator),
2373 internal::Matcher<Expr>, InnerMatcher) {
2374 const Expr *const Condition = Node.getCond();
2375 return (Condition != nullptr &&
2376 InnerMatcher.matches(*Condition, Finder, Builder));
2377 }
2378
2379 /// \brief Matches the then-statement of an if statement.
2380 ///
2381 /// Examples matches the if statement
2382 /// (matcher = ifStmt(hasThen(boolLiteral(equals(true)))))
2383 /// \code
2384 /// if (false) true; else false;
2385 /// \endcode
AST_MATCHER_P(IfStmt,hasThen,internal::Matcher<Stmt>,InnerMatcher)2386 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
2387 const Stmt *const Then = Node.getThen();
2388 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
2389 }
2390
2391 /// \brief Matches the else-statement of an if statement.
2392 ///
2393 /// Examples matches the if statement
2394 /// (matcher = ifStmt(hasElse(boolLiteral(equals(true)))))
2395 /// \code
2396 /// if (false) false; else true;
2397 /// \endcode
AST_MATCHER_P(IfStmt,hasElse,internal::Matcher<Stmt>,InnerMatcher)2398 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
2399 const Stmt *const Else = Node.getElse();
2400 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
2401 }
2402
2403 /// \brief Matches if a node equals a previously bound node.
2404 ///
2405 /// Matches a node if it equals the node previously bound to \p ID.
2406 ///
2407 /// Given
2408 /// \code
2409 /// class X { int a; int b; };
2410 /// \endcode
2411 /// recordDecl(
2412 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
2413 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
2414 /// matches the class \c X, as \c a and \c b have the same type.
2415 ///
2416 /// Note that when multiple matches are involved via \c forEach* matchers,
2417 /// \c equalsBoundNodes acts as a filter.
2418 /// For example:
2419 /// compoundStmt(
2420 /// forEachDescendant(varDecl().bind("d")),
2421 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
2422 /// will trigger a match for each combination of variable declaration
2423 /// and reference to that variable declaration within a compound statement.
AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,AST_POLYMORPHIC_SUPPORTED_TYPES_4 (Stmt,Decl,Type,QualType),std::string,ID)2424 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4(
2425 Stmt, Decl, Type, QualType),
2426 std::string, ID) {
2427 // FIXME: Figure out whether it makes sense to allow this
2428 // on any other node types.
2429 // For *Loc it probably does not make sense, as those seem
2430 // unique. For NestedNameSepcifier it might make sense, as
2431 // those also have pointer identity, but I'm not sure whether
2432 // they're ever reused.
2433 internal::NotEqualsBoundNodePredicate Predicate;
2434 Predicate.ID = ID;
2435 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
2436 return Builder->removeBindings(Predicate);
2437 }
2438
2439 /// \brief Matches the condition variable statement in an if statement.
2440 ///
2441 /// Given
2442 /// \code
2443 /// if (A* a = GetAPointer()) {}
2444 /// \endcode
2445 /// hasConditionVariableStatement(...)
2446 /// matches 'A* a = GetAPointer()'.
AST_MATCHER_P(IfStmt,hasConditionVariableStatement,internal::Matcher<DeclStmt>,InnerMatcher)2447 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2448 internal::Matcher<DeclStmt>, InnerMatcher) {
2449 const DeclStmt* const DeclarationStatement =
2450 Node.getConditionVariableDeclStmt();
2451 return DeclarationStatement != nullptr &&
2452 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2453 }
2454
2455 /// \brief Matches the index expression of an array subscript expression.
2456 ///
2457 /// Given
2458 /// \code
2459 /// int i[5];
2460 /// void f() { i[1] = 42; }
2461 /// \endcode
2462 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2463 /// matches \c i[1] with the \c integerLiteral() matching \c 1
AST_MATCHER_P(ArraySubscriptExpr,hasIndex,internal::Matcher<Expr>,InnerMatcher)2464 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2465 internal::Matcher<Expr>, InnerMatcher) {
2466 if (const Expr* Expression = Node.getIdx())
2467 return InnerMatcher.matches(*Expression, Finder, Builder);
2468 return false;
2469 }
2470
2471 /// \brief Matches the base expression of an array subscript expression.
2472 ///
2473 /// Given
2474 /// \code
2475 /// int i[5];
2476 /// void f() { i[1] = 42; }
2477 /// \endcode
2478 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2479 /// hasSourceExpression(declRefExpr()))))
2480 /// matches \c i[1] with the \c declRefExpr() matching \c i
AST_MATCHER_P(ArraySubscriptExpr,hasBase,internal::Matcher<Expr>,InnerMatcher)2481 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2482 internal::Matcher<Expr>, InnerMatcher) {
2483 if (const Expr* Expression = Node.getBase())
2484 return InnerMatcher.matches(*Expression, Finder, Builder);
2485 return false;
2486 }
2487
2488 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2489 /// a given body.
2490 ///
2491 /// Given
2492 /// \code
2493 /// for (;;) {}
2494 /// \endcode
2495 /// hasBody(compoundStmt())
2496 /// matches 'for (;;) {}'
2497 /// with compoundStmt()
2498 /// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasBody,AST_POLYMORPHIC_SUPPORTED_TYPES_4 (DoStmt,ForStmt,WhileStmt,CXXForRangeStmt),internal::Matcher<Stmt>,InnerMatcher)2499 AST_POLYMORPHIC_MATCHER_P(hasBody,
2500 AST_POLYMORPHIC_SUPPORTED_TYPES_4(DoStmt, ForStmt,
2501 WhileStmt,
2502 CXXForRangeStmt),
2503 internal::Matcher<Stmt>, InnerMatcher) {
2504 const Stmt *const Statement = Node.getBody();
2505 return (Statement != nullptr &&
2506 InnerMatcher.matches(*Statement, Finder, Builder));
2507 }
2508
2509 /// \brief Matches compound statements where at least one substatement matches
2510 /// a given matcher.
2511 ///
2512 /// Given
2513 /// \code
2514 /// { {}; 1+2; }
2515 /// \endcode
2516 /// hasAnySubstatement(compoundStmt())
2517 /// matches '{ {}; 1+2; }'
2518 /// with compoundStmt()
2519 /// matching '{}'
AST_MATCHER_P(CompoundStmt,hasAnySubstatement,internal::Matcher<Stmt>,InnerMatcher)2520 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2521 internal::Matcher<Stmt>, InnerMatcher) {
2522 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
2523 Node.body_end(), Finder, Builder);
2524 }
2525
2526 /// \brief Checks that a compound statement contains a specific number of
2527 /// child statements.
2528 ///
2529 /// Example: Given
2530 /// \code
2531 /// { for (;;) {} }
2532 /// \endcode
2533 /// compoundStmt(statementCountIs(0)))
2534 /// matches '{}'
2535 /// but does not match the outer compound statement.
AST_MATCHER_P(CompoundStmt,statementCountIs,unsigned,N)2536 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2537 return Node.size() == N;
2538 }
2539
2540 /// \brief Matches literals that are equal to the given value.
2541 ///
2542 /// Example matches true (matcher = boolLiteral(equals(true)))
2543 /// \code
2544 /// true
2545 /// \endcode
2546 ///
2547 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2548 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2549 template <typename ValueT>
2550 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
equals(const ValueT & Value)2551 equals(const ValueT &Value) {
2552 return internal::PolymorphicMatcherWithParam1<
2553 internal::ValueEqualsMatcher,
2554 ValueT>(Value);
2555 }
2556
2557 /// \brief Matches the operator Name of operator expressions (binary or
2558 /// unary).
2559 ///
2560 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2561 /// \code
2562 /// !(a || b)
2563 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasOperatorName,AST_POLYMORPHIC_SUPPORTED_TYPES_2 (BinaryOperator,UnaryOperator),std::string,Name)2564 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2(
2565 BinaryOperator, UnaryOperator),
2566 std::string, Name) {
2567 return Name == Node.getOpcodeStr(Node.getOpcode());
2568 }
2569
2570 /// \brief Matches the left hand side of binary operator expressions.
2571 ///
2572 /// Example matches a (matcher = binaryOperator(hasLHS()))
2573 /// \code
2574 /// a || b
2575 /// \endcode
AST_MATCHER_P(BinaryOperator,hasLHS,internal::Matcher<Expr>,InnerMatcher)2576 AST_MATCHER_P(BinaryOperator, hasLHS,
2577 internal::Matcher<Expr>, InnerMatcher) {
2578 Expr *LeftHandSide = Node.getLHS();
2579 return (LeftHandSide != nullptr &&
2580 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2581 }
2582
2583 /// \brief Matches the right hand side of binary operator expressions.
2584 ///
2585 /// Example matches b (matcher = binaryOperator(hasRHS()))
2586 /// \code
2587 /// a || b
2588 /// \endcode
AST_MATCHER_P(BinaryOperator,hasRHS,internal::Matcher<Expr>,InnerMatcher)2589 AST_MATCHER_P(BinaryOperator, hasRHS,
2590 internal::Matcher<Expr>, InnerMatcher) {
2591 Expr *RightHandSide = Node.getRHS();
2592 return (RightHandSide != nullptr &&
2593 InnerMatcher.matches(*RightHandSide, Finder, Builder));
2594 }
2595
2596 /// \brief Matches if either the left hand side or the right hand side of a
2597 /// binary operator matches.
hasEitherOperand(const internal::Matcher<Expr> & InnerMatcher)2598 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2599 const internal::Matcher<Expr> &InnerMatcher) {
2600 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2601 }
2602
2603 /// \brief Matches if the operand of a unary operator matches.
2604 ///
2605 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2606 /// \code
2607 /// !true
2608 /// \endcode
AST_MATCHER_P(UnaryOperator,hasUnaryOperand,internal::Matcher<Expr>,InnerMatcher)2609 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2610 internal::Matcher<Expr>, InnerMatcher) {
2611 const Expr * const Operand = Node.getSubExpr();
2612 return (Operand != nullptr &&
2613 InnerMatcher.matches(*Operand, Finder, Builder));
2614 }
2615
2616 /// \brief Matches if the cast's source expression matches the given matcher.
2617 ///
2618 /// Example: matches "a string" (matcher =
2619 /// hasSourceExpression(constructExpr()))
2620 /// \code
2621 /// class URL { URL(string); };
2622 /// URL url = "a string";
AST_MATCHER_P(CastExpr,hasSourceExpression,internal::Matcher<Expr>,InnerMatcher)2623 AST_MATCHER_P(CastExpr, hasSourceExpression,
2624 internal::Matcher<Expr>, InnerMatcher) {
2625 const Expr* const SubExpression = Node.getSubExpr();
2626 return (SubExpression != nullptr &&
2627 InnerMatcher.matches(*SubExpression, Finder, Builder));
2628 }
2629
2630 /// \brief Matches casts whose destination type matches a given matcher.
2631 ///
2632 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2633 /// actual casts "explicit" casts.)
AST_MATCHER_P(ExplicitCastExpr,hasDestinationType,internal::Matcher<QualType>,InnerMatcher)2634 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2635 internal::Matcher<QualType>, InnerMatcher) {
2636 const QualType NodeType = Node.getTypeAsWritten();
2637 return InnerMatcher.matches(NodeType, Finder, Builder);
2638 }
2639
2640 /// \brief Matches implicit casts whose destination type matches a given
2641 /// matcher.
2642 ///
2643 /// FIXME: Unit test this matcher
AST_MATCHER_P(ImplicitCastExpr,hasImplicitDestinationType,internal::Matcher<QualType>,InnerMatcher)2644 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2645 internal::Matcher<QualType>, InnerMatcher) {
2646 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2647 }
2648
2649 /// \brief Matches the true branch expression of a conditional operator.
2650 ///
2651 /// Example matches a
2652 /// \code
2653 /// condition ? a : b
2654 /// \endcode
AST_MATCHER_P(ConditionalOperator,hasTrueExpression,internal::Matcher<Expr>,InnerMatcher)2655 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2656 internal::Matcher<Expr>, InnerMatcher) {
2657 Expr *Expression = Node.getTrueExpr();
2658 return (Expression != nullptr &&
2659 InnerMatcher.matches(*Expression, Finder, Builder));
2660 }
2661
2662 /// \brief Matches the false branch expression of a conditional operator.
2663 ///
2664 /// Example matches b
2665 /// \code
2666 /// condition ? a : b
2667 /// \endcode
AST_MATCHER_P(ConditionalOperator,hasFalseExpression,internal::Matcher<Expr>,InnerMatcher)2668 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2669 internal::Matcher<Expr>, InnerMatcher) {
2670 Expr *Expression = Node.getFalseExpr();
2671 return (Expression != nullptr &&
2672 InnerMatcher.matches(*Expression, Finder, Builder));
2673 }
2674
2675 /// \brief Matches if a declaration has a body attached.
2676 ///
2677 /// Example matches A, va, fa
2678 /// \code
2679 /// class A {};
2680 /// class B; // Doesn't match, as it has no body.
2681 /// int va;
2682 /// extern int vb; // Doesn't match, as it doesn't define the variable.
2683 /// void fa() {}
2684 /// void fb(); // Doesn't match, as it has no body.
2685 /// \endcode
2686 ///
2687 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
AST_POLYMORPHIC_MATCHER(isDefinition,AST_POLYMORPHIC_SUPPORTED_TYPES_3 (TagDecl,VarDecl,FunctionDecl))2688 AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3(
2689 TagDecl, VarDecl, FunctionDecl)) {
2690 return Node.isThisDeclarationADefinition();
2691 }
2692
2693 /// \brief Matches the class declaration that the given method declaration
2694 /// belongs to.
2695 ///
2696 /// FIXME: Generalize this for other kinds of declarations.
2697 /// FIXME: What other kind of declarations would we need to generalize
2698 /// this to?
2699 ///
2700 /// Example matches A() in the last line
2701 /// (matcher = constructExpr(hasDeclaration(methodDecl(
2702 /// ofClass(hasName("A"))))))
2703 /// \code
2704 /// class A {
2705 /// public:
2706 /// A();
2707 /// };
2708 /// A a = A();
2709 /// \endcode
AST_MATCHER_P(CXXMethodDecl,ofClass,internal::Matcher<CXXRecordDecl>,InnerMatcher)2710 AST_MATCHER_P(CXXMethodDecl, ofClass,
2711 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2712 const CXXRecordDecl *Parent = Node.getParent();
2713 return (Parent != nullptr &&
2714 InnerMatcher.matches(*Parent, Finder, Builder));
2715 }
2716
2717 /// \brief Matches if the given method declaration is virtual.
2718 ///
2719 /// Given
2720 /// \code
2721 /// class A {
2722 /// public:
2723 /// virtual void x();
2724 /// };
2725 /// \endcode
2726 /// matches A::x
AST_MATCHER(CXXMethodDecl,isVirtual)2727 AST_MATCHER(CXXMethodDecl, isVirtual) {
2728 return Node.isVirtual();
2729 }
2730
2731 /// \brief Matches if the given method declaration is pure.
2732 ///
2733 /// Given
2734 /// \code
2735 /// class A {
2736 /// public:
2737 /// virtual void x() = 0;
2738 /// };
2739 /// \endcode
2740 /// matches A::x
AST_MATCHER(CXXMethodDecl,isPure)2741 AST_MATCHER(CXXMethodDecl, isPure) {
2742 return Node.isPure();
2743 }
2744
2745 /// \brief Matches if the given method declaration is const.
2746 ///
2747 /// Given
2748 /// \code
2749 /// struct A {
2750 /// void foo() const;
2751 /// void bar();
2752 /// };
2753 /// \endcode
2754 ///
2755 /// methodDecl(isConst()) matches A::foo() but not A::bar()
AST_MATCHER(CXXMethodDecl,isConst)2756 AST_MATCHER(CXXMethodDecl, isConst) {
2757 return Node.isConst();
2758 }
2759
2760 /// \brief Matches if the given method declaration overrides another method.
2761 ///
2762 /// Given
2763 /// \code
2764 /// class A {
2765 /// public:
2766 /// virtual void x();
2767 /// };
2768 /// class B : public A {
2769 /// public:
2770 /// virtual void x();
2771 /// };
2772 /// \endcode
2773 /// matches B::x
AST_MATCHER(CXXMethodDecl,isOverride)2774 AST_MATCHER(CXXMethodDecl, isOverride) {
2775 return Node.size_overridden_methods() > 0;
2776 }
2777
2778 /// \brief Matches member expressions that are called with '->' as opposed
2779 /// to '.'.
2780 ///
2781 /// Member calls on the implicit this pointer match as called with '->'.
2782 ///
2783 /// Given
2784 /// \code
2785 /// class Y {
2786 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2787 /// int a;
2788 /// static int b;
2789 /// };
2790 /// \endcode
2791 /// memberExpr(isArrow())
2792 /// matches this->x, x, y.x, a, this->b
AST_MATCHER(MemberExpr,isArrow)2793 AST_MATCHER(MemberExpr, isArrow) {
2794 return Node.isArrow();
2795 }
2796
2797 /// \brief Matches QualType nodes that are of integer type.
2798 ///
2799 /// Given
2800 /// \code
2801 /// void a(int);
2802 /// void b(long);
2803 /// void c(double);
2804 /// \endcode
2805 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2806 /// matches "a(int)", "b(long)", but not "c(double)".
AST_MATCHER(QualType,isInteger)2807 AST_MATCHER(QualType, isInteger) {
2808 return Node->isIntegerType();
2809 }
2810
2811 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2812 /// include "top-level" const.
2813 ///
2814 /// Given
2815 /// \code
2816 /// void a(int);
2817 /// void b(int const);
2818 /// void c(const int);
2819 /// void d(const int*);
2820 /// void e(int const) {};
2821 /// \endcode
2822 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2823 /// matches "void b(int const)", "void c(const int)" and
2824 /// "void e(int const) {}". It does not match d as there
2825 /// is no top-level const on the parameter type "const int *".
AST_MATCHER(QualType,isConstQualified)2826 AST_MATCHER(QualType, isConstQualified) {
2827 return Node.isConstQualified();
2828 }
2829
2830 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2831 /// the node, not hidden within a typedef.
2832 ///
2833 /// Given
2834 /// \code
2835 /// typedef const int const_int;
2836 /// const_int i;
2837 /// int *const j;
2838 /// int *volatile k;
2839 /// int m;
2840 /// \endcode
2841 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2842 /// \c i is const-qualified but the qualifier is not local.
AST_MATCHER(QualType,hasLocalQualifiers)2843 AST_MATCHER(QualType, hasLocalQualifiers) {
2844 return Node.hasLocalQualifiers();
2845 }
2846
2847 /// \brief Matches a member expression where the member is matched by a
2848 /// given matcher.
2849 ///
2850 /// Given
2851 /// \code
2852 /// struct { int first, second; } first, second;
2853 /// int i(second.first);
2854 /// int j(first.second);
2855 /// \endcode
2856 /// memberExpr(member(hasName("first")))
2857 /// matches second.first
2858 /// but not first.second (because the member name there is "second").
AST_MATCHER_P(MemberExpr,member,internal::Matcher<ValueDecl>,InnerMatcher)2859 AST_MATCHER_P(MemberExpr, member,
2860 internal::Matcher<ValueDecl>, InnerMatcher) {
2861 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2862 }
2863
2864 /// \brief Matches a member expression where the object expression is
2865 /// matched by a given matcher.
2866 ///
2867 /// Given
2868 /// \code
2869 /// struct X { int m; };
2870 /// void f(X x) { x.m; m; }
2871 /// \endcode
2872 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2873 /// matches "x.m" and "m"
2874 /// with hasObjectExpression(...)
2875 /// matching "x" and the implicit object expression of "m" which has type X*.
AST_MATCHER_P(MemberExpr,hasObjectExpression,internal::Matcher<Expr>,InnerMatcher)2876 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2877 internal::Matcher<Expr>, InnerMatcher) {
2878 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2879 }
2880
2881 /// \brief Matches any using shadow declaration.
2882 ///
2883 /// Given
2884 /// \code
2885 /// namespace X { void b(); }
2886 /// using X::b;
2887 /// \endcode
2888 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2889 /// matches \code using X::b \endcode
AST_MATCHER_P(UsingDecl,hasAnyUsingShadowDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)2890 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2891 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2892 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
2893 Node.shadow_end(), Finder, Builder);
2894 }
2895
2896 /// \brief Matches a using shadow declaration where the target declaration is
2897 /// matched by the given matcher.
2898 ///
2899 /// Given
2900 /// \code
2901 /// namespace X { int a; void b(); }
2902 /// using X::a;
2903 /// using X::b;
2904 /// \endcode
2905 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2906 /// matches \code using X::b \endcode
2907 /// but not \code using X::a \endcode
AST_MATCHER_P(UsingShadowDecl,hasTargetDecl,internal::Matcher<NamedDecl>,InnerMatcher)2908 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2909 internal::Matcher<NamedDecl>, InnerMatcher) {
2910 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2911 }
2912
2913 /// \brief Matches template instantiations of function, class, or static
2914 /// member variable template instantiations.
2915 ///
2916 /// Given
2917 /// \code
2918 /// template <typename T> class X {}; class A {}; X<A> x;
2919 /// \endcode
2920 /// or
2921 /// \code
2922 /// template <typename T> class X {}; class A {}; template class X<A>;
2923 /// \endcode
2924 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2925 /// matches the template instantiation of X<A>.
2926 ///
2927 /// But given
2928 /// \code
2929 /// template <typename T> class X {}; class A {};
2930 /// template <> class X<A> {}; X<A> x;
2931 /// \endcode
2932 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2933 /// does not match, as X<A> is an explicit template specialization.
2934 ///
2935 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,AST_POLYMORPHIC_SUPPORTED_TYPES_3 (FunctionDecl,VarDecl,CXXRecordDecl))2936 AST_POLYMORPHIC_MATCHER(
2937 isTemplateInstantiation,
2938 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2939 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2940 Node.getTemplateSpecializationKind() ==
2941 TSK_ExplicitInstantiationDefinition);
2942 }
2943
2944 /// \brief Matches explicit template specializations of function, class, or
2945 /// static member variable template instantiations.
2946 ///
2947 /// Given
2948 /// \code
2949 /// template<typename T> void A(T t) { }
2950 /// template<> void A(int N) { }
2951 /// \endcode
2952 /// functionDecl(isExplicitTemplateSpecialization())
2953 /// matches the specialization A<int>().
2954 ///
2955 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,AST_POLYMORPHIC_SUPPORTED_TYPES_3 (FunctionDecl,VarDecl,CXXRecordDecl))2956 AST_POLYMORPHIC_MATCHER(
2957 isExplicitTemplateSpecialization,
2958 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) {
2959 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2960 }
2961
2962 /// \brief Matches \c TypeLocs for which the given inner
2963 /// QualType-matcher matches.
2964 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
2965 internal::Matcher<QualType>, InnerMatcher, 0) {
2966 return internal::BindableMatcher<TypeLoc>(
2967 new internal::TypeLocTypeMatcher(InnerMatcher));
2968 }
2969
2970 /// \brief Matches builtin Types.
2971 ///
2972 /// Given
2973 /// \code
2974 /// struct A {};
2975 /// A a;
2976 /// int b;
2977 /// float c;
2978 /// bool d;
2979 /// \endcode
2980 /// builtinType()
2981 /// matches "int b", "float c" and "bool d"
2982 AST_TYPE_MATCHER(BuiltinType, builtinType);
2983
2984 /// \brief Matches all kinds of arrays.
2985 ///
2986 /// Given
2987 /// \code
2988 /// int a[] = { 2, 3 };
2989 /// int b[4];
2990 /// void f() { int c[a[0]]; }
2991 /// \endcode
2992 /// arrayType()
2993 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
2994 AST_TYPE_MATCHER(ArrayType, arrayType);
2995
2996 /// \brief Matches C99 complex types.
2997 ///
2998 /// Given
2999 /// \code
3000 /// _Complex float f;
3001 /// \endcode
3002 /// complexType()
3003 /// matches "_Complex float f"
3004 AST_TYPE_MATCHER(ComplexType, complexType);
3005
3006 /// \brief Matches arrays and C99 complex types that have a specific element
3007 /// type.
3008 ///
3009 /// Given
3010 /// \code
3011 /// struct A {};
3012 /// A a[7];
3013 /// int b[7];
3014 /// \endcode
3015 /// arrayType(hasElementType(builtinType()))
3016 /// matches "int b[7]"
3017 ///
3018 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
3019 AST_TYPELOC_TRAVERSE_MATCHER(
3020 hasElementType, getElement,
3021 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType));
3022
3023 /// \brief Matches C arrays with a specified constant size.
3024 ///
3025 /// Given
3026 /// \code
3027 /// void() {
3028 /// int a[2];
3029 /// int b[] = { 2, 3 };
3030 /// int c[b[0]];
3031 /// }
3032 /// \endcode
3033 /// constantArrayType()
3034 /// matches "int a[2]"
3035 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
3036
3037 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
3038 ///
3039 /// Given
3040 /// \code
3041 /// int a[42];
3042 /// int b[2 * 21];
3043 /// int c[41], d[43];
3044 /// \endcode
3045 /// constantArrayType(hasSize(42))
3046 /// matches "int a[42]" and "int b[2 * 21]"
AST_MATCHER_P(ConstantArrayType,hasSize,unsigned,N)3047 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
3048 return Node.getSize() == N;
3049 }
3050
3051 /// \brief Matches C++ arrays whose size is a value-dependent expression.
3052 ///
3053 /// Given
3054 /// \code
3055 /// template<typename T, int Size>
3056 /// class array {
3057 /// T data[Size];
3058 /// };
3059 /// \endcode
3060 /// dependentSizedArrayType
3061 /// matches "T data[Size]"
3062 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
3063
3064 /// \brief Matches C arrays with unspecified size.
3065 ///
3066 /// Given
3067 /// \code
3068 /// int a[] = { 2, 3 };
3069 /// int b[42];
3070 /// void f(int c[]) { int d[a[0]]; };
3071 /// \endcode
3072 /// incompleteArrayType()
3073 /// matches "int a[]" and "int c[]"
3074 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
3075
3076 /// \brief Matches C arrays with a specified size that is not an
3077 /// integer-constant-expression.
3078 ///
3079 /// Given
3080 /// \code
3081 /// void f() {
3082 /// int a[] = { 2, 3 }
3083 /// int b[42];
3084 /// int c[a[0]];
3085 /// \endcode
3086 /// variableArrayType()
3087 /// matches "int c[a[0]]"
3088 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
3089
3090 /// \brief Matches \c VariableArrayType nodes that have a specific size
3091 /// expression.
3092 ///
3093 /// Given
3094 /// \code
3095 /// void f(int b) {
3096 /// int a[b];
3097 /// }
3098 /// \endcode
3099 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3100 /// varDecl(hasName("b")))))))
3101 /// matches "int a[b]"
AST_MATCHER_P(VariableArrayType,hasSizeExpr,internal::Matcher<Expr>,InnerMatcher)3102 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
3103 internal::Matcher<Expr>, InnerMatcher) {
3104 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
3105 }
3106
3107 /// \brief Matches atomic types.
3108 ///
3109 /// Given
3110 /// \code
3111 /// _Atomic(int) i;
3112 /// \endcode
3113 /// atomicType()
3114 /// matches "_Atomic(int) i"
3115 AST_TYPE_MATCHER(AtomicType, atomicType);
3116
3117 /// \brief Matches atomic types with a specific value type.
3118 ///
3119 /// Given
3120 /// \code
3121 /// _Atomic(int) i;
3122 /// _Atomic(float) f;
3123 /// \endcode
3124 /// atomicType(hasValueType(isInteger()))
3125 /// matches "_Atomic(int) i"
3126 ///
3127 /// Usable as: Matcher<AtomicType>
3128 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
3129 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType));
3130
3131 /// \brief Matches types nodes representing C++11 auto types.
3132 ///
3133 /// Given:
3134 /// \code
3135 /// auto n = 4;
3136 /// int v[] = { 2, 3 }
3137 /// for (auto i : v) { }
3138 /// \endcode
3139 /// autoType()
3140 /// matches "auto n" and "auto i"
3141 AST_TYPE_MATCHER(AutoType, autoType);
3142
3143 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3144 ///
3145 /// Note: There is no \c TypeLoc for the deduced type and thus no
3146 /// \c getDeducedLoc() matcher.
3147 ///
3148 /// Given
3149 /// \code
3150 /// auto a = 1;
3151 /// auto b = 2.0;
3152 /// \endcode
3153 /// autoType(hasDeducedType(isInteger()))
3154 /// matches "auto a"
3155 ///
3156 /// Usable as: Matcher<AutoType>
3157 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3158 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType));
3159
3160 /// \brief Matches \c FunctionType nodes.
3161 ///
3162 /// Given
3163 /// \code
3164 /// int (*f)(int);
3165 /// void g();
3166 /// \endcode
3167 /// functionType()
3168 /// matches "int (*f)(int)" and the type of "g".
3169 AST_TYPE_MATCHER(FunctionType, functionType);
3170
3171 /// \brief Matches \c ParenType nodes.
3172 ///
3173 /// Given
3174 /// \code
3175 /// int (*ptr_to_array)[4];
3176 /// int *array_of_ptrs[4];
3177 /// \endcode
3178 ///
3179 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3180 /// \c array_of_ptrs.
3181 AST_TYPE_MATCHER(ParenType, parenType);
3182
3183 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
3184 ///
3185 /// Given
3186 /// \code
3187 /// int (*ptr_to_array)[4];
3188 /// int (*ptr_to_func)(int);
3189 /// \endcode
3190 ///
3191 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
3192 /// \c ptr_to_func but not \c ptr_to_array.
3193 ///
3194 /// Usable as: Matcher<ParenType>
3195 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
3196 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType));
3197
3198 /// \brief Matches block pointer types, i.e. types syntactically represented as
3199 /// "void (^)(int)".
3200 ///
3201 /// The \c pointee is always required to be a \c FunctionType.
3202 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
3203
3204 /// \brief Matches member pointer types.
3205 /// Given
3206 /// \code
3207 /// struct A { int i; }
3208 /// A::* ptr = A::i;
3209 /// \endcode
3210 /// memberPointerType()
3211 /// matches "A::* ptr"
3212 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
3213
3214 /// \brief Matches pointer types.
3215 ///
3216 /// Given
3217 /// \code
3218 /// int *a;
3219 /// int &b = *a;
3220 /// int c = 5;
3221 /// \endcode
3222 /// pointerType()
3223 /// matches "int *a"
3224 AST_TYPE_MATCHER(PointerType, pointerType);
3225
3226 /// \brief Matches both lvalue and rvalue reference types.
3227 ///
3228 /// Given
3229 /// \code
3230 /// int *a;
3231 /// int &b = *a;
3232 /// int &&c = 1;
3233 /// auto &d = b;
3234 /// auto &&e = c;
3235 /// auto &&f = 2;
3236 /// int g = 5;
3237 /// \endcode
3238 ///
3239 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3240 AST_TYPE_MATCHER(ReferenceType, referenceType);
3241
3242 /// \brief Matches lvalue reference types.
3243 ///
3244 /// Given:
3245 /// \code
3246 /// int *a;
3247 /// int &b = *a;
3248 /// int &&c = 1;
3249 /// auto &d = b;
3250 /// auto &&e = c;
3251 /// auto &&f = 2;
3252 /// int g = 5;
3253 /// \endcode
3254 ///
3255 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3256 /// matched since the type is deduced as int& by reference collapsing rules.
3257 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3258
3259 /// \brief Matches rvalue reference types.
3260 ///
3261 /// Given:
3262 /// \code
3263 /// int *a;
3264 /// int &b = *a;
3265 /// int &&c = 1;
3266 /// auto &d = b;
3267 /// auto &&e = c;
3268 /// auto &&f = 2;
3269 /// int g = 5;
3270 /// \endcode
3271 ///
3272 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3273 /// matched as it is deduced to int& by reference collapsing rules.
3274 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3275
3276 /// \brief Narrows PointerType (and similar) matchers to those where the
3277 /// \c pointee matches a given matcher.
3278 ///
3279 /// Given
3280 /// \code
3281 /// int *a;
3282 /// int const *b;
3283 /// float const *f;
3284 /// \endcode
3285 /// pointerType(pointee(isConstQualified(), isInteger()))
3286 /// matches "int const *b"
3287 ///
3288 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3289 /// Matcher<PointerType>, Matcher<ReferenceType>
3290 AST_TYPELOC_TRAVERSE_MATCHER(
3291 pointee, getPointee,
3292 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType,
3293 PointerType, ReferenceType));
3294
3295 /// \brief Matches typedef types.
3296 ///
3297 /// Given
3298 /// \code
3299 /// typedef int X;
3300 /// \endcode
3301 /// typedefType()
3302 /// matches "typedef int X"
3303 AST_TYPE_MATCHER(TypedefType, typedefType);
3304
3305 /// \brief Matches template specialization types.
3306 ///
3307 /// Given
3308 /// \code
3309 /// template <typename T>
3310 /// class C { };
3311 ///
3312 /// template class C<int>; // A
3313 /// C<char> var; // B
3314 /// \code
3315 ///
3316 /// \c templateSpecializationType() matches the type of the explicit
3317 /// instantiation in \c A and the type of the variable declaration in \c B.
3318 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3319
3320 /// \brief Matches types nodes representing unary type transformations.
3321 ///
3322 /// Given:
3323 /// \code
3324 /// typedef __underlying_type(T) type;
3325 /// \endcode
3326 /// unaryTransformType()
3327 /// matches "__underlying_type(T)"
3328 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
3329
3330 /// \brief Matches record types (e.g. structs, classes).
3331 ///
3332 /// Given
3333 /// \code
3334 /// class C {};
3335 /// struct S {};
3336 ///
3337 /// C c;
3338 /// S s;
3339 /// \code
3340 ///
3341 /// \c recordType() matches the type of the variable declarations of both \c c
3342 /// and \c s.
3343 AST_TYPE_MATCHER(RecordType, recordType);
3344
3345 /// \brief Matches types specified with an elaborated type keyword or with a
3346 /// qualified name.
3347 ///
3348 /// Given
3349 /// \code
3350 /// namespace N {
3351 /// namespace M {
3352 /// class D {};
3353 /// }
3354 /// }
3355 /// class C {};
3356 ///
3357 /// class C c;
3358 /// N::M::D d;
3359 /// \code
3360 ///
3361 /// \c elaboratedType() matches the type of the variable declarations of both
3362 /// \c c and \c d.
3363 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3364
3365 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3366 /// matches \c InnerMatcher if the qualifier exists.
3367 ///
3368 /// Given
3369 /// \code
3370 /// namespace N {
3371 /// namespace M {
3372 /// class D {};
3373 /// }
3374 /// }
3375 /// N::M::D d;
3376 /// \code
3377 ///
3378 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3379 /// matches the type of the variable declaration of \c d.
AST_MATCHER_P(ElaboratedType,hasQualifier,internal::Matcher<NestedNameSpecifier>,InnerMatcher)3380 AST_MATCHER_P(ElaboratedType, hasQualifier,
3381 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3382 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3383 return InnerMatcher.matches(*Qualifier, Finder, Builder);
3384
3385 return false;
3386 }
3387
3388 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3389 ///
3390 /// Given
3391 /// \code
3392 /// namespace N {
3393 /// namespace M {
3394 /// class D {};
3395 /// }
3396 /// }
3397 /// N::M::D d;
3398 /// \code
3399 ///
3400 /// \c elaboratedType(namesType(recordType(
3401 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3402 /// declaration of \c d.
AST_MATCHER_P(ElaboratedType,namesType,internal::Matcher<QualType>,InnerMatcher)3403 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3404 InnerMatcher) {
3405 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3406 }
3407
3408 /// \brief Matches declarations whose declaration context, interpreted as a
3409 /// Decl, matches \c InnerMatcher.
3410 ///
3411 /// Given
3412 /// \code
3413 /// namespace N {
3414 /// namespace M {
3415 /// class D {};
3416 /// }
3417 /// }
3418 /// \code
3419 ///
3420 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3421 /// declaration of \c class \c D.
AST_MATCHER_P(Decl,hasDeclContext,internal::Matcher<Decl>,InnerMatcher)3422 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3423 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3424 Finder, Builder);
3425 }
3426
3427 /// \brief Matches nested name specifiers.
3428 ///
3429 /// Given
3430 /// \code
3431 /// namespace ns {
3432 /// struct A { static void f(); };
3433 /// void A::f() {}
3434 /// void g() { A::f(); }
3435 /// }
3436 /// ns::A a;
3437 /// \endcode
3438 /// nestedNameSpecifier()
3439 /// matches "ns::" and both "A::"
3440 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3441
3442 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3443 const internal::VariadicAllOfMatcher<
3444 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3445
3446 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3447 /// NestedNameSpecifier-matcher matches.
3448 AST_MATCHER_FUNCTION_P_OVERLOAD(
3449 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
3450 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
3451 return internal::BindableMatcher<NestedNameSpecifierLoc>(
3452 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3453 InnerMatcher));
3454 }
3455
3456 /// \brief Matches nested name specifiers that specify a type matching the
3457 /// given \c QualType matcher without qualifiers.
3458 ///
3459 /// Given
3460 /// \code
3461 /// struct A { struct B { struct C {}; }; };
3462 /// A::B::C c;
3463 /// \endcode
3464 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3465 /// matches "A::"
AST_MATCHER_P(NestedNameSpecifier,specifiesType,internal::Matcher<QualType>,InnerMatcher)3466 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3467 internal::Matcher<QualType>, InnerMatcher) {
3468 if (!Node.getAsType())
3469 return false;
3470 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3471 }
3472
3473 /// \brief Matches nested name specifier locs that specify a type matching the
3474 /// given \c TypeLoc.
3475 ///
3476 /// Given
3477 /// \code
3478 /// struct A { struct B { struct C {}; }; };
3479 /// A::B::C c;
3480 /// \endcode
3481 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3482 /// hasDeclaration(recordDecl(hasName("A")))))))
3483 /// matches "A::"
AST_MATCHER_P(NestedNameSpecifierLoc,specifiesTypeLoc,internal::Matcher<TypeLoc>,InnerMatcher)3484 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3485 internal::Matcher<TypeLoc>, InnerMatcher) {
3486 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3487 }
3488
3489 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3490 ///
3491 /// Given
3492 /// \code
3493 /// struct A { struct B { struct C {}; }; };
3494 /// A::B::C c;
3495 /// \endcode
3496 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3497 /// matches "A::"
3498 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3499 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3500 0) {
3501 NestedNameSpecifier *NextNode = Node.getPrefix();
3502 if (!NextNode)
3503 return false;
3504 return InnerMatcher.matches(*NextNode, Finder, Builder);
3505 }
3506
3507 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3508 ///
3509 /// Given
3510 /// \code
3511 /// struct A { struct B { struct C {}; }; };
3512 /// A::B::C c;
3513 /// \endcode
3514 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3515 /// matches "A::"
3516 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3517 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3518 1) {
3519 NestedNameSpecifierLoc NextNode = Node.getPrefix();
3520 if (!NextNode)
3521 return false;
3522 return InnerMatcher.matches(NextNode, Finder, Builder);
3523 }
3524
3525 /// \brief Matches nested name specifiers that specify a namespace matching the
3526 /// given namespace matcher.
3527 ///
3528 /// Given
3529 /// \code
3530 /// namespace ns { struct A {}; }
3531 /// ns::A a;
3532 /// \endcode
3533 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3534 /// matches "ns::"
AST_MATCHER_P(NestedNameSpecifier,specifiesNamespace,internal::Matcher<NamespaceDecl>,InnerMatcher)3535 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3536 internal::Matcher<NamespaceDecl>, InnerMatcher) {
3537 if (!Node.getAsNamespace())
3538 return false;
3539 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3540 }
3541
3542 /// \brief Overloads for the \c equalsNode matcher.
3543 /// FIXME: Implement for other node types.
3544 /// @{
3545
3546 /// \brief Matches if a node equals another node.
3547 ///
3548 /// \c Decl has pointer identity in the AST.
3549 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
3550 return &Node == Other;
3551 }
3552 /// \brief Matches if a node equals another node.
3553 ///
3554 /// \c Stmt has pointer identity in the AST.
3555 ///
3556 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
3557 return &Node == Other;
3558 }
3559
3560 /// @}
3561
3562 /// \brief Matches each case or default statement belonging to the given switch
3563 /// statement. This matcher may produce multiple matches.
3564 ///
3565 /// Given
3566 /// \code
3567 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
3568 /// \endcode
3569 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
3570 /// matches four times, with "c" binding each of "case 1:", "case 2:",
3571 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
3572 /// "switch (1)", "switch (2)" and "switch (2)".
AST_MATCHER_P(SwitchStmt,forEachSwitchCase,internal::Matcher<SwitchCase>,InnerMatcher)3573 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
3574 InnerMatcher) {
3575 BoundNodesTreeBuilder Result;
3576 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
3577 // iteration order. We should use the more general iterating matchers once
3578 // they are capable of expressing this matcher (for example, it should ignore
3579 // case statements belonging to nested switch statements).
3580 bool Matched = false;
3581 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
3582 SC = SC->getNextSwitchCase()) {
3583 BoundNodesTreeBuilder CaseBuilder(*Builder);
3584 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
3585 if (CaseMatched) {
3586 Matched = true;
3587 Result.addMatch(CaseBuilder);
3588 }
3589 }
3590 *Builder = Result;
3591 return Matched;
3592 }
3593
3594 /// \brief Matches each constructor initializer in a constructor definition.
3595 ///
3596 /// Given
3597 /// \code
3598 /// class A { A() : i(42), j(42) {} int i; int j; };
3599 /// \endcode
3600 /// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x"))))
3601 /// will trigger two matches, binding for 'i' and 'j' respectively.
AST_MATCHER_P(CXXConstructorDecl,forEachConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)3602 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
3603 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3604 BoundNodesTreeBuilder Result;
3605 bool Matched = false;
3606 for (const auto *I : Node.inits()) {
3607 BoundNodesTreeBuilder InitBuilder(*Builder);
3608 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
3609 Matched = true;
3610 Result.addMatch(InitBuilder);
3611 }
3612 }
3613 *Builder = Result;
3614 return Matched;
3615 }
3616
3617 /// \brief If the given case statement does not use the GNU case range
3618 /// extension, matches the constant given in the statement.
3619 ///
3620 /// Given
3621 /// \code
3622 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
3623 /// \endcode
3624 /// caseStmt(hasCaseConstant(integerLiteral()))
3625 /// matches "case 1:"
AST_MATCHER_P(CaseStmt,hasCaseConstant,internal::Matcher<Expr>,InnerMatcher)3626 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
3627 InnerMatcher) {
3628 if (Node.getRHS())
3629 return false;
3630
3631 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
3632 }
3633
3634 } // end namespace ast_matchers
3635 } // end namespace clang
3636
3637 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
3638