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 // cxxRecordDecl(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 // cxxRecordDecl(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 RecordDecl 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_ASTMATCHERS_ASTMATCHERS_H
46 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
47
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/DeclFriend.h"
50 #include "clang/AST/DeclObjC.h"
51 #include "clang/AST/DeclTemplate.h"
52 #include "clang/ASTMatchers/ASTMatchersInternal.h"
53 #include "clang/ASTMatchers/ASTMatchersMacros.h"
54 #include "llvm/ADT/Twine.h"
55 #include "llvm/Support/Regex.h"
56 #include <iterator>
57
58 namespace clang {
59 namespace ast_matchers {
60
61 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
62 ///
63 /// The bound nodes are generated by calling \c bind("id") on the node matchers
64 /// of the nodes we want to access later.
65 ///
66 /// The instances of BoundNodes are created by \c MatchFinder when the user's
67 /// callbacks are executed every time a match is found.
68 class BoundNodes {
69 public:
70 /// \brief Returns the AST node bound to \c ID.
71 ///
72 /// Returns NULL if there was no node bound to \c ID or if there is a node but
73 /// it cannot be converted to the specified type.
74 template <typename T>
getNodeAs(StringRef ID)75 const T *getNodeAs(StringRef ID) const {
76 return MyBoundNodes.getNodeAs<T>(ID);
77 }
78
79 /// \brief Deprecated. Please use \c getNodeAs instead.
80 /// @{
81 template <typename T>
getDeclAs(StringRef ID)82 const T *getDeclAs(StringRef ID) const {
83 return getNodeAs<T>(ID);
84 }
85 template <typename T>
getStmtAs(StringRef ID)86 const T *getStmtAs(StringRef ID) const {
87 return getNodeAs<T>(ID);
88 }
89 /// @}
90
91 /// \brief Type of mapping from binding identifiers to bound nodes. This type
92 /// is an associative container with a key type of \c std::string and a value
93 /// type of \c clang::ast_type_traits::DynTypedNode
94 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap;
95
96 /// \brief Retrieve mapping from binding identifiers to bound nodes.
getMap()97 const IDToNodeMap &getMap() const {
98 return MyBoundNodes.getMap();
99 }
100
101 private:
102 /// \brief Create BoundNodes from a pre-filled map of bindings.
BoundNodes(internal::BoundNodesMap & MyBoundNodes)103 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
104 : MyBoundNodes(MyBoundNodes) {}
105
106 internal::BoundNodesMap MyBoundNodes;
107
108 friend class internal::BoundNodesTreeBuilder;
109 };
110
111 /// \brief If the provided matcher matches a node, binds the node to \c ID.
112 ///
113 /// FIXME: Do we want to support this now that we have bind()?
114 template <typename T>
id(StringRef ID,const internal::BindableMatcher<T> & InnerMatcher)115 internal::Matcher<T> id(StringRef ID,
116 const internal::BindableMatcher<T> &InnerMatcher) {
117 return InnerMatcher.bind(ID);
118 }
119
120 /// \brief Types of matchers for the top-level classes in the AST class
121 /// hierarchy.
122 /// @{
123 typedef internal::Matcher<Decl> DeclarationMatcher;
124 typedef internal::Matcher<Stmt> StatementMatcher;
125 typedef internal::Matcher<QualType> TypeMatcher;
126 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
127 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
128 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
129 /// @}
130
131 /// \brief Matches any node.
132 ///
133 /// Useful when another matcher requires a child matcher, but there's no
134 /// additional constraint. This will often be used with an explicit conversion
135 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
136 ///
137 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
138 /// \code
139 /// "int* p" and "void f()" in
140 /// int* p;
141 /// void f();
142 /// \endcode
143 ///
144 /// Usable as: Any Matcher
anything()145 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
146
147 /// \brief Matches the top declaration context.
148 ///
149 /// Given
150 /// \code
151 /// int X;
152 /// namespace NS {
153 /// int Y;
154 /// } // namespace NS
155 /// \endcode
156 /// decl(hasDeclContext(translationUnitDecl()))
157 /// matches "int X", but not "int Y".
158 const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
159 translationUnitDecl;
160
161 /// \brief Matches typedef declarations.
162 ///
163 /// Given
164 /// \code
165 /// typedef int X;
166 /// \endcode
167 /// typedefDecl()
168 /// matches "typedef int X"
169 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
170
171 /// \brief Matches AST nodes that were expanded within the main-file.
172 ///
173 /// Example matches X but not Y
174 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
175 /// \code
176 /// #include <Y.h>
177 /// class X {};
178 /// \endcode
179 /// Y.h:
180 /// \code
181 /// class Y {};
182 /// \endcode
183 ///
184 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc))185 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
186 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
187 auto &SourceManager = Finder->getASTContext().getSourceManager();
188 return SourceManager.isInMainFile(
189 SourceManager.getExpansionLoc(Node.getLocStart()));
190 }
191
192 /// \brief Matches AST nodes that were expanded within system-header-files.
193 ///
194 /// Example matches Y but not X
195 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
196 /// \code
197 /// #include <SystemHeader.h>
198 /// class X {};
199 /// \endcode
200 /// SystemHeader.h:
201 /// \code
202 /// class Y {};
203 /// \endcode
204 ///
205 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc))206 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
207 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
208 auto &SourceManager = Finder->getASTContext().getSourceManager();
209 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
210 if (ExpansionLoc.isInvalid()) {
211 return false;
212 }
213 return SourceManager.isInSystemHeader(ExpansionLoc);
214 }
215
216 /// \brief Matches AST nodes that were expanded within files whose name is
217 /// partially matching a given regex.
218 ///
219 /// Example matches Y but not X
220 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
221 /// \code
222 /// #include "ASTMatcher.h"
223 /// class X {};
224 /// \endcode
225 /// ASTMatcher.h:
226 /// \code
227 /// class Y {};
228 /// \endcode
229 ///
230 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc),std::string,RegExp)231 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
232 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
233 std::string, RegExp) {
234 auto &SourceManager = Finder->getASTContext().getSourceManager();
235 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
236 if (ExpansionLoc.isInvalid()) {
237 return false;
238 }
239 auto FileEntry =
240 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
241 if (!FileEntry) {
242 return false;
243 }
244
245 auto Filename = FileEntry->getName();
246 llvm::Regex RE(RegExp);
247 return RE.match(Filename);
248 }
249
250 /// \brief Matches declarations.
251 ///
252 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
253 /// \code
254 /// void X();
255 /// class C {
256 /// friend X;
257 /// };
258 /// \endcode
259 const internal::VariadicAllOfMatcher<Decl> decl;
260
261 /// \brief Matches a declaration of a linkage specification.
262 ///
263 /// Given
264 /// \code
265 /// extern "C" {}
266 /// \endcode
267 /// linkageSpecDecl()
268 /// matches "extern "C" {}"
269 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
270 linkageSpecDecl;
271
272 /// \brief Matches a declaration of anything that could have a name.
273 ///
274 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
275 /// \code
276 /// typedef int X;
277 /// struct S {
278 /// union {
279 /// int i;
280 /// } U;
281 /// };
282 /// \endcode
283 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
284
285 /// \brief Matches a declaration of a namespace.
286 ///
287 /// Given
288 /// \code
289 /// namespace {}
290 /// namespace test {}
291 /// \endcode
292 /// namespaceDecl()
293 /// matches "namespace {}" and "namespace test {}"
294 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
295
296 /// \brief Matches a declaration of a namespace alias.
297 ///
298 /// Given
299 /// \code
300 /// namespace test {}
301 /// namespace alias = ::test;
302 /// \endcode
303 /// namespaceAliasDecl()
304 /// matches "namespace alias" but not "namespace test"
305 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
306 namespaceAliasDecl;
307
308 /// \brief Matches class, struct, and union declarations.
309 ///
310 /// Example matches \c X, \c Z, \c U, and \c S
311 /// \code
312 /// class X;
313 /// template<class T> class Z {};
314 /// struct S {};
315 /// union U {};
316 /// \endcode
317 const internal::VariadicDynCastAllOfMatcher<
318 Decl,
319 RecordDecl> recordDecl;
320
321 /// \brief Matches C++ class declarations.
322 ///
323 /// Example matches \c X, \c Z
324 /// \code
325 /// class X;
326 /// template<class T> class Z {};
327 /// \endcode
328 const internal::VariadicDynCastAllOfMatcher<
329 Decl,
330 CXXRecordDecl> cxxRecordDecl;
331
332 /// \brief Matches C++ class template declarations.
333 ///
334 /// Example matches \c Z
335 /// \code
336 /// template<class T> class Z {};
337 /// \endcode
338 const internal::VariadicDynCastAllOfMatcher<
339 Decl,
340 ClassTemplateDecl> classTemplateDecl;
341
342 /// \brief Matches C++ class template specializations.
343 ///
344 /// Given
345 /// \code
346 /// template<typename T> class A {};
347 /// template<> class A<double> {};
348 /// A<int> a;
349 /// \endcode
350 /// classTemplateSpecializationDecl()
351 /// matches the specializations \c A<int> and \c A<double>
352 const internal::VariadicDynCastAllOfMatcher<
353 Decl,
354 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
355
356 /// \brief Matches declarator declarations (field, variable, function
357 /// and non-type template parameter declarations).
358 ///
359 /// Given
360 /// \code
361 /// class X { int y; };
362 /// \endcode
363 /// declaratorDecl()
364 /// matches \c int y.
365 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
366 declaratorDecl;
367
368 /// \brief Matches parameter variable declarations.
369 ///
370 /// Given
371 /// \code
372 /// void f(int x);
373 /// \endcode
374 /// parmVarDecl()
375 /// matches \c int x.
376 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
377
378 /// \brief Matches C++ access specifier declarations.
379 ///
380 /// Given
381 /// \code
382 /// class C {
383 /// public:
384 /// int a;
385 /// };
386 /// \endcode
387 /// accessSpecDecl()
388 /// matches 'public:'
389 const internal::VariadicDynCastAllOfMatcher<
390 Decl,
391 AccessSpecDecl> accessSpecDecl;
392
393 /// \brief Matches constructor initializers.
394 ///
395 /// Examples matches \c i(42).
396 /// \code
397 /// class C {
398 /// C() : i(42) {}
399 /// int i;
400 /// };
401 /// \endcode
402 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
403
404 /// \brief Matches template arguments.
405 ///
406 /// Given
407 /// \code
408 /// template <typename T> struct C {};
409 /// C<int> c;
410 /// \endcode
411 /// templateArgument()
412 /// matches 'int' in C<int>.
413 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
414
415 /// \brief Matches non-type template parameter declarations.
416 ///
417 /// Given
418 /// \code
419 /// template <typename T, int N> struct C {};
420 /// \endcode
421 /// nonTypeTemplateParmDecl()
422 /// matches 'N', but not 'T'.
423 const internal::VariadicDynCastAllOfMatcher<
424 Decl,
425 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl;
426
427 /// \brief Matches template type parameter declarations.
428 ///
429 /// Given
430 /// \code
431 /// template <typename T, int N> struct C {};
432 /// \endcode
433 /// templateTypeParmDecl()
434 /// matches 'T', but not 'N'.
435 const internal::VariadicDynCastAllOfMatcher<
436 Decl,
437 TemplateTypeParmDecl> templateTypeParmDecl;
438
439 /// \brief Matches public C++ declarations.
440 ///
441 /// Given
442 /// \code
443 /// class C {
444 /// public: int a;
445 /// protected: int b;
446 /// private: int c;
447 /// };
448 /// \endcode
449 /// fieldDecl(isPublic())
450 /// matches 'int a;'
AST_MATCHER(Decl,isPublic)451 AST_MATCHER(Decl, isPublic) {
452 return Node.getAccess() == AS_public;
453 }
454
455 /// \brief Matches protected C++ declarations.
456 ///
457 /// Given
458 /// \code
459 /// class C {
460 /// public: int a;
461 /// protected: int b;
462 /// private: int c;
463 /// };
464 /// \endcode
465 /// fieldDecl(isProtected())
466 /// matches 'int b;'
AST_MATCHER(Decl,isProtected)467 AST_MATCHER(Decl, isProtected) {
468 return Node.getAccess() == AS_protected;
469 }
470
471 /// \brief Matches private C++ declarations.
472 ///
473 /// Given
474 /// \code
475 /// class C {
476 /// public: int a;
477 /// protected: int b;
478 /// private: int c;
479 /// };
480 /// \endcode
481 /// fieldDecl(isPrivate())
482 /// matches 'int c;'
AST_MATCHER(Decl,isPrivate)483 AST_MATCHER(Decl, isPrivate) {
484 return Node.getAccess() == AS_private;
485 }
486
487 /// \brief Matches a declaration that has been implicitly added
488 /// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl,isImplicit)489 AST_MATCHER(Decl, isImplicit) {
490 return Node.isImplicit();
491 }
492
493 /// \brief Matches classTemplateSpecializations that have at least one
494 /// TemplateArgument matching the given InnerMatcher.
495 ///
496 /// Given
497 /// \code
498 /// template<typename T> class A {};
499 /// template<> class A<double> {};
500 /// A<int> a;
501 /// \endcode
502 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
503 /// refersToType(asString("int"))))
504 /// matches the specialization \c A<int>
AST_POLYMORPHIC_MATCHER_P(hasAnyTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType),internal::Matcher<TemplateArgument>,InnerMatcher)505 AST_POLYMORPHIC_MATCHER_P(
506 hasAnyTemplateArgument,
507 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
508 TemplateSpecializationType),
509 internal::Matcher<TemplateArgument>, InnerMatcher) {
510 ArrayRef<TemplateArgument> List =
511 internal::getTemplateSpecializationArgs(Node);
512 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
513 Builder);
514 }
515
516 /// \brief Matches expressions that match InnerMatcher after any implicit casts
517 /// are stripped off.
518 ///
519 /// Parentheses and explicit casts are not discarded.
520 /// Given
521 /// \code
522 /// int arr[5];
523 /// int a = 0;
524 /// char b = 0;
525 /// const int c = a;
526 /// int *d = arr;
527 /// long e = (long) 0l;
528 /// \endcode
529 /// The matchers
530 /// \code
531 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
532 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
533 /// \endcode
534 /// would match the declarations for a, b, c, and d, but not e.
535 /// While
536 /// \code
537 /// varDecl(hasInitializer(integerLiteral()))
538 /// varDecl(hasInitializer(declRefExpr()))
539 /// \endcode
540 /// only match the declarations for b, c, and d.
AST_MATCHER_P(Expr,ignoringImpCasts,internal::Matcher<Expr>,InnerMatcher)541 AST_MATCHER_P(Expr, ignoringImpCasts,
542 internal::Matcher<Expr>, InnerMatcher) {
543 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
544 }
545
546 /// \brief Matches expressions that match InnerMatcher after parentheses and
547 /// casts are stripped off.
548 ///
549 /// Implicit and non-C Style casts are also discarded.
550 /// Given
551 /// \code
552 /// int a = 0;
553 /// char b = (0);
554 /// void* c = reinterpret_cast<char*>(0);
555 /// char d = char(0);
556 /// \endcode
557 /// The matcher
558 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
559 /// would match the declarations for a, b, c, and d.
560 /// while
561 /// varDecl(hasInitializer(integerLiteral()))
562 /// only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenCasts,internal::Matcher<Expr>,InnerMatcher)563 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
564 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
565 }
566
567 /// \brief Matches expressions that match InnerMatcher after implicit casts and
568 /// parentheses are stripped off.
569 ///
570 /// Explicit casts are not discarded.
571 /// Given
572 /// \code
573 /// int arr[5];
574 /// int a = 0;
575 /// char b = (0);
576 /// const int c = a;
577 /// int *d = (arr);
578 /// long e = ((long) 0l);
579 /// \endcode
580 /// The matchers
581 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
582 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
583 /// would match the declarations for a, b, c, and d, but not e.
584 /// while
585 /// varDecl(hasInitializer(integerLiteral()))
586 /// varDecl(hasInitializer(declRefExpr()))
587 /// would only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenImpCasts,internal::Matcher<Expr>,InnerMatcher)588 AST_MATCHER_P(Expr, ignoringParenImpCasts,
589 internal::Matcher<Expr>, InnerMatcher) {
590 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
591 }
592
593 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
594 /// matches the given InnerMatcher.
595 ///
596 /// Given
597 /// \code
598 /// template<typename T, typename U> class A {};
599 /// A<bool, int> b;
600 /// A<int, bool> c;
601 /// \endcode
602 /// classTemplateSpecializationDecl(hasTemplateArgument(
603 /// 1, refersToType(asString("int"))))
604 /// matches the specialization \c A<bool, int>
AST_POLYMORPHIC_MATCHER_P2(hasTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType),unsigned,N,internal::Matcher<TemplateArgument>,InnerMatcher)605 AST_POLYMORPHIC_MATCHER_P2(
606 hasTemplateArgument,
607 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
608 TemplateSpecializationType),
609 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
610 ArrayRef<TemplateArgument> List =
611 internal::getTemplateSpecializationArgs(Node);
612 if (List.size() <= N)
613 return false;
614 return InnerMatcher.matches(List[N], Finder, Builder);
615 }
616
617 /// \brief Matches if the number of template arguments equals \p N.
618 ///
619 /// Given
620 /// \code
621 /// template<typename T> struct C {};
622 /// C<int> c;
623 /// \endcode
624 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
625 /// matches C<int>.
AST_POLYMORPHIC_MATCHER_P(templateArgumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType),unsigned,N)626 AST_POLYMORPHIC_MATCHER_P(
627 templateArgumentCountIs,
628 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
629 TemplateSpecializationType),
630 unsigned, N) {
631 return internal::getTemplateSpecializationArgs(Node).size() == N;
632 }
633
634 /// \brief Matches a TemplateArgument that refers to a certain type.
635 ///
636 /// Given
637 /// \code
638 /// struct X {};
639 /// template<typename T> struct A {};
640 /// A<X> a;
641 /// \endcode
642 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
643 /// refersToType(class(hasName("X")))))
644 /// matches the specialization \c A<X>
AST_MATCHER_P(TemplateArgument,refersToType,internal::Matcher<QualType>,InnerMatcher)645 AST_MATCHER_P(TemplateArgument, refersToType,
646 internal::Matcher<QualType>, InnerMatcher) {
647 if (Node.getKind() != TemplateArgument::Type)
648 return false;
649 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
650 }
651
652 /// \brief Matches a canonical TemplateArgument that refers to a certain
653 /// declaration.
654 ///
655 /// Given
656 /// \code
657 /// template<typename T> struct A {};
658 /// struct B { B* next; };
659 /// A<&B::next> a;
660 /// \endcode
661 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
662 /// refersToDeclaration(fieldDecl(hasName("next"))))
663 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
664 /// \c B::next
AST_MATCHER_P(TemplateArgument,refersToDeclaration,internal::Matcher<Decl>,InnerMatcher)665 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
666 internal::Matcher<Decl>, InnerMatcher) {
667 if (Node.getKind() == TemplateArgument::Declaration)
668 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
669 return false;
670 }
671
672 /// \brief Matches a sugar TemplateArgument that refers to a certain expression.
673 ///
674 /// Given
675 /// \code
676 /// template<typename T> struct A {};
677 /// struct B { B* next; };
678 /// A<&B::next> a;
679 /// \endcode
680 /// templateSpecializationType(hasAnyTemplateArgument(
681 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
682 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
683 /// \c B::next
AST_MATCHER_P(TemplateArgument,isExpr,internal::Matcher<Expr>,InnerMatcher)684 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
685 if (Node.getKind() == TemplateArgument::Expression)
686 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
687 return false;
688 }
689
690 /// \brief Matches a TemplateArgument that is an integral value.
691 ///
692 /// Given
693 /// \code
694 /// template<int T> struct A {};
695 /// C<42> c;
696 /// \endcode
697 /// classTemplateSpecializationDecl(
698 /// hasAnyTemplateArgument(isIntegral()))
699 /// matches the implicit instantiation of C in C<42>
700 /// with isIntegral() matching 42.
AST_MATCHER(TemplateArgument,isIntegral)701 AST_MATCHER(TemplateArgument, isIntegral) {
702 return Node.getKind() == TemplateArgument::Integral;
703 }
704
705 /// \brief Matches a TemplateArgument that referes to an integral type.
706 ///
707 /// Given
708 /// \code
709 /// template<int T> struct A {};
710 /// C<42> c;
711 /// \endcode
712 /// classTemplateSpecializationDecl(
713 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
714 /// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument,refersToIntegralType,internal::Matcher<QualType>,InnerMatcher)715 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
716 internal::Matcher<QualType>, InnerMatcher) {
717 if (Node.getKind() != TemplateArgument::Integral)
718 return false;
719 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
720 }
721
722 /// \brief Matches a TemplateArgument of integral type with a given value.
723 ///
724 /// Note that 'Value' is a string as the template argument's value is
725 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
726 /// representation of that integral value in base 10.
727 ///
728 /// Given
729 /// \code
730 /// template<int T> struct A {};
731 /// C<42> c;
732 /// \endcode
733 /// classTemplateSpecializationDecl(
734 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
735 /// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument,equalsIntegralValue,std::string,Value)736 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
737 std::string, Value) {
738 if (Node.getKind() != TemplateArgument::Integral)
739 return false;
740 return Node.getAsIntegral().toString(10) == Value;
741 }
742
743 /// \brief Matches any value declaration.
744 ///
745 /// Example matches A, B, C and F
746 /// \code
747 /// enum X { A, B, C };
748 /// void F();
749 /// \endcode
750 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
751
752 /// \brief Matches C++ constructor declarations.
753 ///
754 /// Example matches Foo::Foo() and Foo::Foo(int)
755 /// \code
756 /// class Foo {
757 /// public:
758 /// Foo();
759 /// Foo(int);
760 /// int DoSomething();
761 /// };
762 /// \endcode
763 const internal::VariadicDynCastAllOfMatcher<
764 Decl,
765 CXXConstructorDecl> cxxConstructorDecl;
766
767 /// \brief Matches explicit C++ destructor declarations.
768 ///
769 /// Example matches Foo::~Foo()
770 /// \code
771 /// class Foo {
772 /// public:
773 /// virtual ~Foo();
774 /// };
775 /// \endcode
776 const internal::VariadicDynCastAllOfMatcher<
777 Decl,
778 CXXDestructorDecl> cxxDestructorDecl;
779
780 /// \brief Matches enum declarations.
781 ///
782 /// Example matches X
783 /// \code
784 /// enum X {
785 /// A, B, C
786 /// };
787 /// \endcode
788 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
789
790 /// \brief Matches enum constants.
791 ///
792 /// Example matches A, B, C
793 /// \code
794 /// enum X {
795 /// A, B, C
796 /// };
797 /// \endcode
798 const internal::VariadicDynCastAllOfMatcher<
799 Decl,
800 EnumConstantDecl> enumConstantDecl;
801
802 /// \brief Matches method declarations.
803 ///
804 /// Example matches y
805 /// \code
806 /// class X { void y(); };
807 /// \endcode
808 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
809
810 /// \brief Matches conversion operator declarations.
811 ///
812 /// Example matches the operator.
813 /// \code
814 /// class X { operator int() const; };
815 /// \endcode
816 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
817 cxxConversionDecl;
818
819 /// \brief Matches variable declarations.
820 ///
821 /// Note: this does not match declarations of member variables, which are
822 /// "field" declarations in Clang parlance.
823 ///
824 /// Example matches a
825 /// \code
826 /// int a;
827 /// \endcode
828 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
829
830 /// \brief Matches field declarations.
831 ///
832 /// Given
833 /// \code
834 /// class X { int m; };
835 /// \endcode
836 /// fieldDecl()
837 /// matches 'm'.
838 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
839
840 /// \brief Matches function declarations.
841 ///
842 /// Example matches f
843 /// \code
844 /// void f();
845 /// \endcode
846 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
847
848 /// \brief Matches C++ function template declarations.
849 ///
850 /// Example matches f
851 /// \code
852 /// template<class T> void f(T t) {}
853 /// \endcode
854 const internal::VariadicDynCastAllOfMatcher<
855 Decl,
856 FunctionTemplateDecl> functionTemplateDecl;
857
858 /// \brief Matches friend declarations.
859 ///
860 /// Given
861 /// \code
862 /// class X { friend void foo(); };
863 /// \endcode
864 /// friendDecl()
865 /// matches 'friend void foo()'.
866 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
867
868 /// \brief Matches statements.
869 ///
870 /// Given
871 /// \code
872 /// { ++a; }
873 /// \endcode
874 /// stmt()
875 /// matches both the compound statement '{ ++a; }' and '++a'.
876 const internal::VariadicAllOfMatcher<Stmt> stmt;
877
878 /// \brief Matches declaration statements.
879 ///
880 /// Given
881 /// \code
882 /// int a;
883 /// \endcode
884 /// declStmt()
885 /// matches 'int a'.
886 const internal::VariadicDynCastAllOfMatcher<
887 Stmt,
888 DeclStmt> declStmt;
889
890 /// \brief Matches member expressions.
891 ///
892 /// Given
893 /// \code
894 /// class Y {
895 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
896 /// int a; static int b;
897 /// };
898 /// \endcode
899 /// memberExpr()
900 /// matches this->x, x, y.x, a, this->b
901 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
902
903 /// \brief Matches call expressions.
904 ///
905 /// Example matches x.y() and y()
906 /// \code
907 /// X x;
908 /// x.y();
909 /// y();
910 /// \endcode
911 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
912
913 /// \brief Matches lambda expressions.
914 ///
915 /// Example matches [&](){return 5;}
916 /// \code
917 /// [&](){return 5;}
918 /// \endcode
919 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
920
921 /// \brief Matches member call expressions.
922 ///
923 /// Example matches x.y()
924 /// \code
925 /// X x;
926 /// x.y();
927 /// \endcode
928 const internal::VariadicDynCastAllOfMatcher<
929 Stmt,
930 CXXMemberCallExpr> cxxMemberCallExpr;
931
932 /// \brief Matches ObjectiveC Message invocation expressions.
933 ///
934 /// The innermost message send invokes the "alloc" class method on the
935 /// NSString class, while the outermost message send invokes the
936 /// "initWithString" instance method on the object returned from
937 /// NSString's "alloc". This matcher should match both message sends.
938 /// \code
939 /// [[NSString alloc] initWithString:@"Hello"]
940 /// \endcode
941 const internal::VariadicDynCastAllOfMatcher<
942 Stmt,
943 ObjCMessageExpr> objcMessageExpr;
944
945 /// \brief Matches Objective-C interface declarations.
946 ///
947 /// Example matches Foo
948 /// \code
949 /// @interface Foo
950 /// @end
951 /// \endcode
952 const internal::VariadicDynCastAllOfMatcher<
953 Decl,
954 ObjCInterfaceDecl> objcInterfaceDecl;
955
956 /// \brief Matches expressions that introduce cleanups to be run at the end
957 /// of the sub-expression's evaluation.
958 ///
959 /// Example matches std::string()
960 /// \code
961 /// const std::string str = std::string();
962 /// \endcode
963 const internal::VariadicDynCastAllOfMatcher<
964 Stmt,
965 ExprWithCleanups> exprWithCleanups;
966
967 /// \brief Matches init list expressions.
968 ///
969 /// Given
970 /// \code
971 /// int a[] = { 1, 2 };
972 /// struct B { int x, y; };
973 /// B b = { 5, 6 };
974 /// \endcode
975 /// initListExpr()
976 /// matches "{ 1, 2 }" and "{ 5, 6 }"
977 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
978
979 /// \brief Matches substitutions of non-type template parameters.
980 ///
981 /// Given
982 /// \code
983 /// template <int N>
984 /// struct A { static const int n = N; };
985 /// struct B : public A<42> {};
986 /// \endcode
987 /// substNonTypeTemplateParmExpr()
988 /// matches "N" in the right-hand side of "static const int n = N;"
989 const internal::VariadicDynCastAllOfMatcher<
990 Stmt,
991 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr;
992
993 /// \brief Matches using declarations.
994 ///
995 /// Given
996 /// \code
997 /// namespace X { int x; }
998 /// using X::x;
999 /// \endcode
1000 /// usingDecl()
1001 /// matches \code using X::x \endcode
1002 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1003
1004 /// \brief Matches using namespace declarations.
1005 ///
1006 /// Given
1007 /// \code
1008 /// namespace X { int x; }
1009 /// using namespace X;
1010 /// \endcode
1011 /// usingDirectiveDecl()
1012 /// matches \code using namespace X \endcode
1013 const internal::VariadicDynCastAllOfMatcher<
1014 Decl,
1015 UsingDirectiveDecl> usingDirectiveDecl;
1016
1017 /// \brief Matches unresolved using value declarations.
1018 ///
1019 /// Given
1020 /// \code
1021 /// template<typename X>
1022 /// class C : private X {
1023 /// using X::x;
1024 /// };
1025 /// \endcode
1026 /// unresolvedUsingValueDecl()
1027 /// matches \code using X::x \endcode
1028 const internal::VariadicDynCastAllOfMatcher<
1029 Decl,
1030 UnresolvedUsingValueDecl> unresolvedUsingValueDecl;
1031
1032 /// \brief Matches unresolved using value declarations that involve the
1033 /// typename.
1034 ///
1035 /// Given
1036 /// \code
1037 /// template <typename T>
1038 /// struct Base { typedef T Foo; };
1039 ///
1040 /// template<typename T>
1041 /// struct S : private Base<T> {
1042 /// using typename Base<T>::Foo;
1043 /// };
1044 /// \endcode
1045 /// unresolvedUsingTypenameDecl()
1046 /// matches \code using Base<T>::Foo \endcode
1047 const internal::VariadicDynCastAllOfMatcher<
1048 Decl,
1049 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl;
1050
1051 /// \brief Matches constructor call expressions (including implicit ones).
1052 ///
1053 /// Example matches string(ptr, n) and ptr within arguments of f
1054 /// (matcher = cxxConstructExpr())
1055 /// \code
1056 /// void f(const string &a, const string &b);
1057 /// char *ptr;
1058 /// int n;
1059 /// f(string(ptr, n), ptr);
1060 /// \endcode
1061 const internal::VariadicDynCastAllOfMatcher<
1062 Stmt,
1063 CXXConstructExpr> cxxConstructExpr;
1064
1065 /// \brief Matches unresolved constructor call expressions.
1066 ///
1067 /// Example matches T(t) in return statement of f
1068 /// (matcher = cxxUnresolvedConstructExpr())
1069 /// \code
1070 /// template <typename T>
1071 /// void f(const T& t) { return T(t); }
1072 /// \endcode
1073 const internal::VariadicDynCastAllOfMatcher<
1074 Stmt,
1075 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr;
1076
1077 /// \brief Matches implicit and explicit this expressions.
1078 ///
1079 /// Example matches the implicit this expression in "return i".
1080 /// (matcher = cxxThisExpr())
1081 /// \code
1082 /// struct foo {
1083 /// int i;
1084 /// int f() { return i; }
1085 /// };
1086 /// \endcode
1087 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
1088
1089 /// \brief Matches nodes where temporaries are created.
1090 ///
1091 /// Example matches FunctionTakesString(GetStringByValue())
1092 /// (matcher = cxxBindTemporaryExpr())
1093 /// \code
1094 /// FunctionTakesString(GetStringByValue());
1095 /// FunctionTakesStringByPointer(GetStringPointer());
1096 /// \endcode
1097 const internal::VariadicDynCastAllOfMatcher<
1098 Stmt,
1099 CXXBindTemporaryExpr> cxxBindTemporaryExpr;
1100
1101 /// \brief Matches nodes where temporaries are materialized.
1102 ///
1103 /// Example: Given
1104 /// \code
1105 /// struct T {void func()};
1106 /// T f();
1107 /// void g(T);
1108 /// \endcode
1109 /// materializeTemporaryExpr() matches 'f()' in these statements
1110 /// \code
1111 /// T u(f());
1112 /// g(f());
1113 /// \endcode
1114 /// but does not match
1115 /// \code
1116 /// f();
1117 /// f().func();
1118 /// \endcode
1119 const internal::VariadicDynCastAllOfMatcher<
1120 Stmt,
1121 MaterializeTemporaryExpr> materializeTemporaryExpr;
1122
1123 /// \brief Matches new expressions.
1124 ///
1125 /// Given
1126 /// \code
1127 /// new X;
1128 /// \endcode
1129 /// cxxNewExpr()
1130 /// matches 'new X'.
1131 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1132
1133 /// \brief Matches delete expressions.
1134 ///
1135 /// Given
1136 /// \code
1137 /// delete X;
1138 /// \endcode
1139 /// cxxDeleteExpr()
1140 /// matches 'delete X'.
1141 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
1142
1143 /// \brief Matches array subscript expressions.
1144 ///
1145 /// Given
1146 /// \code
1147 /// int i = a[1];
1148 /// \endcode
1149 /// arraySubscriptExpr()
1150 /// matches "a[1]"
1151 const internal::VariadicDynCastAllOfMatcher<
1152 Stmt,
1153 ArraySubscriptExpr> arraySubscriptExpr;
1154
1155 /// \brief Matches the value of a default argument at the call site.
1156 ///
1157 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1158 /// default value of the second parameter in the call expression f(42)
1159 /// (matcher = cxxDefaultArgExpr())
1160 /// \code
1161 /// void f(int x, int y = 0);
1162 /// f(42);
1163 /// \endcode
1164 const internal::VariadicDynCastAllOfMatcher<
1165 Stmt,
1166 CXXDefaultArgExpr> cxxDefaultArgExpr;
1167
1168 /// \brief Matches overloaded operator calls.
1169 ///
1170 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1171 /// binaryOperator matcher.
1172 /// Currently it does not match operators such as new delete.
1173 /// FIXME: figure out why these do not match?
1174 ///
1175 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1176 /// (matcher = cxxOperatorCallExpr())
1177 /// \code
1178 /// ostream &operator<< (ostream &out, int i) { };
1179 /// ostream &o; int b = 1, c = 1;
1180 /// o << b << c;
1181 /// \endcode
1182 const internal::VariadicDynCastAllOfMatcher<
1183 Stmt,
1184 CXXOperatorCallExpr> cxxOperatorCallExpr;
1185
1186 /// \brief Matches expressions.
1187 ///
1188 /// Example matches x()
1189 /// \code
1190 /// void f() { x(); }
1191 /// \endcode
1192 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1193
1194 /// \brief Matches expressions that refer to declarations.
1195 ///
1196 /// Example matches x in if (x)
1197 /// \code
1198 /// bool x;
1199 /// if (x) {}
1200 /// \endcode
1201 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
1202
1203 /// \brief Matches if statements.
1204 ///
1205 /// Example matches 'if (x) {}'
1206 /// \code
1207 /// if (x) {}
1208 /// \endcode
1209 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1210
1211 /// \brief Matches for statements.
1212 ///
1213 /// Example matches 'for (;;) {}'
1214 /// \code
1215 /// for (;;) {}
1216 /// int i[] = {1, 2, 3}; for (auto a : i);
1217 /// \endcode
1218 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1219
1220 /// \brief Matches the increment statement of a for loop.
1221 ///
1222 /// Example:
1223 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1224 /// matches '++x' in
1225 /// \code
1226 /// for (x; x < N; ++x) { }
1227 /// \endcode
AST_MATCHER_P(ForStmt,hasIncrement,internal::Matcher<Stmt>,InnerMatcher)1228 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1229 InnerMatcher) {
1230 const Stmt *const Increment = Node.getInc();
1231 return (Increment != nullptr &&
1232 InnerMatcher.matches(*Increment, Finder, Builder));
1233 }
1234
1235 /// \brief Matches the initialization statement of a for loop.
1236 ///
1237 /// Example:
1238 /// forStmt(hasLoopInit(declStmt()))
1239 /// matches 'int x = 0' in
1240 /// \code
1241 /// for (int x = 0; x < N; ++x) { }
1242 /// \endcode
AST_MATCHER_P(ForStmt,hasLoopInit,internal::Matcher<Stmt>,InnerMatcher)1243 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1244 InnerMatcher) {
1245 const Stmt *const Init = Node.getInit();
1246 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1247 }
1248
1249 /// \brief Matches range-based for statements.
1250 ///
1251 /// cxxForRangeStmt() matches 'for (auto a : i)'
1252 /// \code
1253 /// int i[] = {1, 2, 3}; for (auto a : i);
1254 /// for(int j = 0; j < 5; ++j);
1255 /// \endcode
1256 const internal::VariadicDynCastAllOfMatcher<
1257 Stmt,
1258 CXXForRangeStmt> cxxForRangeStmt;
1259
1260 /// \brief Matches the initialization statement of a for loop.
1261 ///
1262 /// Example:
1263 /// forStmt(hasLoopVariable(anything()))
1264 /// matches 'int x' in
1265 /// \code
1266 /// for (int x : a) { }
1267 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasLoopVariable,internal::Matcher<VarDecl>,InnerMatcher)1268 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1269 InnerMatcher) {
1270 const VarDecl *const Var = Node.getLoopVariable();
1271 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1272 }
1273
1274 /// \brief Matches the range initialization statement of a for loop.
1275 ///
1276 /// Example:
1277 /// forStmt(hasRangeInit(anything()))
1278 /// matches 'a' in
1279 /// \code
1280 /// for (int x : a) { }
1281 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasRangeInit,internal::Matcher<Expr>,InnerMatcher)1282 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1283 InnerMatcher) {
1284 const Expr *const Init = Node.getRangeInit();
1285 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1286 }
1287
1288 /// \brief Matches while statements.
1289 ///
1290 /// Given
1291 /// \code
1292 /// while (true) {}
1293 /// \endcode
1294 /// whileStmt()
1295 /// matches 'while (true) {}'.
1296 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1297
1298 /// \brief Matches do statements.
1299 ///
1300 /// Given
1301 /// \code
1302 /// do {} while (true);
1303 /// \endcode
1304 /// doStmt()
1305 /// matches 'do {} while(true)'
1306 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1307
1308 /// \brief Matches break statements.
1309 ///
1310 /// Given
1311 /// \code
1312 /// while (true) { break; }
1313 /// \endcode
1314 /// breakStmt()
1315 /// matches 'break'
1316 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1317
1318 /// \brief Matches continue statements.
1319 ///
1320 /// Given
1321 /// \code
1322 /// while (true) { continue; }
1323 /// \endcode
1324 /// continueStmt()
1325 /// matches 'continue'
1326 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
1327
1328 /// \brief Matches return statements.
1329 ///
1330 /// Given
1331 /// \code
1332 /// return 1;
1333 /// \endcode
1334 /// returnStmt()
1335 /// matches 'return 1'
1336 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1337
1338 /// \brief Matches goto statements.
1339 ///
1340 /// Given
1341 /// \code
1342 /// goto FOO;
1343 /// FOO: bar();
1344 /// \endcode
1345 /// gotoStmt()
1346 /// matches 'goto FOO'
1347 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1348
1349 /// \brief Matches label statements.
1350 ///
1351 /// Given
1352 /// \code
1353 /// goto FOO;
1354 /// FOO: bar();
1355 /// \endcode
1356 /// labelStmt()
1357 /// matches 'FOO:'
1358 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1359
1360 /// \brief Matches switch statements.
1361 ///
1362 /// Given
1363 /// \code
1364 /// switch(a) { case 42: break; default: break; }
1365 /// \endcode
1366 /// switchStmt()
1367 /// matches 'switch(a)'.
1368 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1369
1370 /// \brief Matches case and default statements inside switch statements.
1371 ///
1372 /// Given
1373 /// \code
1374 /// switch(a) { case 42: break; default: break; }
1375 /// \endcode
1376 /// switchCase()
1377 /// matches 'case 42: break;' and 'default: break;'.
1378 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1379
1380 /// \brief Matches case statements inside switch statements.
1381 ///
1382 /// Given
1383 /// \code
1384 /// switch(a) { case 42: break; default: break; }
1385 /// \endcode
1386 /// caseStmt()
1387 /// matches 'case 42: break;'.
1388 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1389
1390 /// \brief Matches default statements inside switch statements.
1391 ///
1392 /// Given
1393 /// \code
1394 /// switch(a) { case 42: break; default: break; }
1395 /// \endcode
1396 /// defaultStmt()
1397 /// matches 'default: break;'.
1398 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
1399
1400 /// \brief Matches compound statements.
1401 ///
1402 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
1403 /// \code
1404 /// for (;;) {{}}
1405 /// \endcode
1406 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
1407
1408 /// \brief Matches catch statements.
1409 ///
1410 /// \code
1411 /// try {} catch(int i) {}
1412 /// \endcode
1413 /// cxxCatchStmt()
1414 /// matches 'catch(int i)'
1415 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
1416
1417 /// \brief Matches try statements.
1418 ///
1419 /// \code
1420 /// try {} catch(int i) {}
1421 /// \endcode
1422 /// cxxTryStmt()
1423 /// matches 'try {}'
1424 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1425
1426 /// \brief Matches throw expressions.
1427 ///
1428 /// \code
1429 /// try { throw 5; } catch(int i) {}
1430 /// \endcode
1431 /// cxxThrowExpr()
1432 /// matches 'throw 5'
1433 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
1434
1435 /// \brief Matches null statements.
1436 ///
1437 /// \code
1438 /// foo();;
1439 /// \endcode
1440 /// nullStmt()
1441 /// matches the second ';'
1442 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1443
1444 /// \brief Matches asm statements.
1445 ///
1446 /// \code
1447 /// int i = 100;
1448 /// __asm("mov al, 2");
1449 /// \endcode
1450 /// asmStmt()
1451 /// matches '__asm("mov al, 2")'
1452 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1453
1454 /// \brief Matches bool literals.
1455 ///
1456 /// Example matches true
1457 /// \code
1458 /// true
1459 /// \endcode
1460 const internal::VariadicDynCastAllOfMatcher<
1461 Stmt,
1462 CXXBoolLiteralExpr> cxxBoolLiteral;
1463
1464 /// \brief Matches string literals (also matches wide string literals).
1465 ///
1466 /// Example matches "abcd", L"abcd"
1467 /// \code
1468 /// char *s = "abcd"; wchar_t *ws = L"abcd"
1469 /// \endcode
1470 const internal::VariadicDynCastAllOfMatcher<
1471 Stmt,
1472 StringLiteral> stringLiteral;
1473
1474 /// \brief Matches character literals (also matches wchar_t).
1475 ///
1476 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1477 /// though.
1478 ///
1479 /// Example matches 'a', L'a'
1480 /// \code
1481 /// char ch = 'a'; wchar_t chw = L'a';
1482 /// \endcode
1483 const internal::VariadicDynCastAllOfMatcher<
1484 Stmt,
1485 CharacterLiteral> characterLiteral;
1486
1487 /// \brief Matches integer literals of all sizes / encodings, e.g.
1488 /// 1, 1L, 0x1 and 1U.
1489 ///
1490 /// Does not match character-encoded integers such as L'a'.
1491 const internal::VariadicDynCastAllOfMatcher<
1492 Stmt,
1493 IntegerLiteral> integerLiteral;
1494
1495 /// \brief Matches float literals of all sizes / encodings, e.g.
1496 /// 1.0, 1.0f, 1.0L and 1e10.
1497 ///
1498 /// Does not match implicit conversions such as
1499 /// \code
1500 /// float a = 10;
1501 /// \endcode
1502 const internal::VariadicDynCastAllOfMatcher<
1503 Stmt,
1504 FloatingLiteral> floatLiteral;
1505
1506 /// \brief Matches user defined literal operator call.
1507 ///
1508 /// Example match: "foo"_suffix
1509 const internal::VariadicDynCastAllOfMatcher<
1510 Stmt,
1511 UserDefinedLiteral> userDefinedLiteral;
1512
1513 /// \brief Matches compound (i.e. non-scalar) literals
1514 ///
1515 /// Example match: {1}, (1, 2)
1516 /// \code
1517 /// int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1518 /// \endcode
1519 const internal::VariadicDynCastAllOfMatcher<
1520 Stmt,
1521 CompoundLiteralExpr> compoundLiteralExpr;
1522
1523 /// \brief Matches nullptr literal.
1524 const internal::VariadicDynCastAllOfMatcher<
1525 Stmt,
1526 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr;
1527
1528 /// \brief Matches GNU __null expression.
1529 const internal::VariadicDynCastAllOfMatcher<
1530 Stmt,
1531 GNUNullExpr> gnuNullExpr;
1532
1533 /// \brief Matches binary operator expressions.
1534 ///
1535 /// Example matches a || b
1536 /// \code
1537 /// !(a || b)
1538 /// \endcode
1539 const internal::VariadicDynCastAllOfMatcher<
1540 Stmt,
1541 BinaryOperator> binaryOperator;
1542
1543 /// \brief Matches unary operator expressions.
1544 ///
1545 /// Example matches !a
1546 /// \code
1547 /// !a || b
1548 /// \endcode
1549 const internal::VariadicDynCastAllOfMatcher<
1550 Stmt,
1551 UnaryOperator> unaryOperator;
1552
1553 /// \brief Matches conditional operator expressions.
1554 ///
1555 /// Example matches a ? b : c
1556 /// \code
1557 /// (a ? b : c) + 42
1558 /// \endcode
1559 const internal::VariadicDynCastAllOfMatcher<
1560 Stmt,
1561 ConditionalOperator> conditionalOperator;
1562
1563 /// \brief Matches a C++ static_assert declaration.
1564 ///
1565 /// Example:
1566 /// staticAssertExpr()
1567 /// matches
1568 /// static_assert(sizeof(S) == sizeof(int))
1569 /// in
1570 /// \code
1571 /// struct S {
1572 /// int x;
1573 /// };
1574 /// static_assert(sizeof(S) == sizeof(int));
1575 /// \endcode
1576 const internal::VariadicDynCastAllOfMatcher<
1577 Decl,
1578 StaticAssertDecl> staticAssertDecl;
1579
1580 /// \brief Matches a reinterpret_cast expression.
1581 ///
1582 /// Either the source expression or the destination type can be matched
1583 /// using has(), but hasDestinationType() is more specific and can be
1584 /// more readable.
1585 ///
1586 /// Example matches reinterpret_cast<char*>(&p) in
1587 /// \code
1588 /// void* p = reinterpret_cast<char*>(&p);
1589 /// \endcode
1590 const internal::VariadicDynCastAllOfMatcher<
1591 Stmt,
1592 CXXReinterpretCastExpr> cxxReinterpretCastExpr;
1593
1594 /// \brief Matches a C++ static_cast expression.
1595 ///
1596 /// \see hasDestinationType
1597 /// \see reinterpretCast
1598 ///
1599 /// Example:
1600 /// cxxStaticCastExpr()
1601 /// matches
1602 /// static_cast<long>(8)
1603 /// in
1604 /// \code
1605 /// long eight(static_cast<long>(8));
1606 /// \endcode
1607 const internal::VariadicDynCastAllOfMatcher<
1608 Stmt,
1609 CXXStaticCastExpr> cxxStaticCastExpr;
1610
1611 /// \brief Matches a dynamic_cast expression.
1612 ///
1613 /// Example:
1614 /// cxxDynamicCastExpr()
1615 /// matches
1616 /// dynamic_cast<D*>(&b);
1617 /// in
1618 /// \code
1619 /// struct B { virtual ~B() {} }; struct D : B {};
1620 /// B b;
1621 /// D* p = dynamic_cast<D*>(&b);
1622 /// \endcode
1623 const internal::VariadicDynCastAllOfMatcher<
1624 Stmt,
1625 CXXDynamicCastExpr> cxxDynamicCastExpr;
1626
1627 /// \brief Matches a const_cast expression.
1628 ///
1629 /// Example: Matches const_cast<int*>(&r) in
1630 /// \code
1631 /// int n = 42;
1632 /// const int &r(n);
1633 /// int* p = const_cast<int*>(&r);
1634 /// \endcode
1635 const internal::VariadicDynCastAllOfMatcher<
1636 Stmt,
1637 CXXConstCastExpr> cxxConstCastExpr;
1638
1639 /// \brief Matches a C-style cast expression.
1640 ///
1641 /// Example: Matches (int*) 2.2f in
1642 /// \code
1643 /// int i = (int) 2.2f;
1644 /// \endcode
1645 const internal::VariadicDynCastAllOfMatcher<
1646 Stmt,
1647 CStyleCastExpr> cStyleCastExpr;
1648
1649 /// \brief Matches explicit cast expressions.
1650 ///
1651 /// Matches any cast expression written in user code, whether it be a
1652 /// C-style cast, a functional-style cast, or a keyword cast.
1653 ///
1654 /// Does not match implicit conversions.
1655 ///
1656 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1657 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1658 /// actual cast expressions.
1659 ///
1660 /// \see hasDestinationType.
1661 ///
1662 /// Example: matches all five of the casts in
1663 /// \code
1664 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1665 /// \endcode
1666 /// but does not match the implicit conversion in
1667 /// \code
1668 /// long ell = 42;
1669 /// \endcode
1670 const internal::VariadicDynCastAllOfMatcher<
1671 Stmt,
1672 ExplicitCastExpr> explicitCastExpr;
1673
1674 /// \brief Matches the implicit cast nodes of Clang's AST.
1675 ///
1676 /// This matches many different places, including function call return value
1677 /// eliding, as well as any type conversions.
1678 const internal::VariadicDynCastAllOfMatcher<
1679 Stmt,
1680 ImplicitCastExpr> implicitCastExpr;
1681
1682 /// \brief Matches any cast nodes of Clang's AST.
1683 ///
1684 /// Example: castExpr() matches each of the following:
1685 /// \code
1686 /// (int) 3;
1687 /// const_cast<Expr *>(SubExpr);
1688 /// char c = 0;
1689 /// \endcode
1690 /// but does not match
1691 /// \code
1692 /// int i = (0);
1693 /// int k = 0;
1694 /// \endcode
1695 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1696
1697 /// \brief Matches functional cast expressions
1698 ///
1699 /// Example: Matches Foo(bar);
1700 /// \code
1701 /// Foo f = bar;
1702 /// Foo g = (Foo) bar;
1703 /// Foo h = Foo(bar);
1704 /// \endcode
1705 const internal::VariadicDynCastAllOfMatcher<
1706 Stmt,
1707 CXXFunctionalCastExpr> cxxFunctionalCastExpr;
1708
1709 /// \brief Matches functional cast expressions having N != 1 arguments
1710 ///
1711 /// Example: Matches Foo(bar, bar)
1712 /// \code
1713 /// Foo h = Foo(bar, bar);
1714 /// \endcode
1715 const internal::VariadicDynCastAllOfMatcher<
1716 Stmt,
1717 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr;
1718
1719 /// \brief Matches \c QualTypes in the clang AST.
1720 const internal::VariadicAllOfMatcher<QualType> qualType;
1721
1722 /// \brief Matches \c Types in the clang AST.
1723 const internal::VariadicAllOfMatcher<Type> type;
1724
1725 /// \brief Matches \c TypeLocs in the clang AST.
1726 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1727
1728 /// \brief Matches if any of the given matchers matches.
1729 ///
1730 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1731 /// matching submatcher.
1732 ///
1733 /// For example, in:
1734 /// \code
1735 /// class A { int a; int b; };
1736 /// \endcode
1737 /// The matcher:
1738 /// \code
1739 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1740 /// has(fieldDecl(hasName("b")).bind("v"))))
1741 /// \endcode
1742 /// will generate two results binding "v", the first of which binds
1743 /// the field declaration of \c a, the second the field declaration of
1744 /// \c b.
1745 ///
1746 /// Usable as: Any Matcher
1747 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = {
1748 internal::DynTypedMatcher::VO_EachOf
1749 };
1750
1751 /// \brief Matches if any of the given matchers matches.
1752 ///
1753 /// Usable as: Any Matcher
1754 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = {
1755 internal::DynTypedMatcher::VO_AnyOf
1756 };
1757
1758 /// \brief Matches if all given matchers match.
1759 ///
1760 /// Usable as: Any Matcher
1761 const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = {
1762 internal::DynTypedMatcher::VO_AllOf
1763 };
1764
1765 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1766 ///
1767 /// Given
1768 /// \code
1769 /// Foo x = bar;
1770 /// int y = sizeof(x) + alignof(x);
1771 /// \endcode
1772 /// unaryExprOrTypeTraitExpr()
1773 /// matches \c sizeof(x) and \c alignof(x)
1774 const internal::VariadicDynCastAllOfMatcher<
1775 Stmt,
1776 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1777
1778 /// \brief Matches unary expressions that have a specific type of argument.
1779 ///
1780 /// Given
1781 /// \code
1782 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1783 /// \endcode
1784 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1785 /// matches \c sizeof(a) and \c alignof(c)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,hasArgumentOfType,internal::Matcher<QualType>,InnerMatcher)1786 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1787 internal::Matcher<QualType>, InnerMatcher) {
1788 const QualType ArgumentType = Node.getTypeOfArgument();
1789 return InnerMatcher.matches(ArgumentType, Finder, Builder);
1790 }
1791
1792 /// \brief Matches unary expressions of a certain kind.
1793 ///
1794 /// Given
1795 /// \code
1796 /// int x;
1797 /// int s = sizeof(x) + alignof(x)
1798 /// \endcode
1799 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1800 /// matches \c sizeof(x)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,ofKind,UnaryExprOrTypeTrait,Kind)1801 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1802 return Node.getKind() == Kind;
1803 }
1804
1805 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1806 /// alignof.
alignOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)1807 inline internal::Matcher<Stmt> alignOfExpr(
1808 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1809 return stmt(unaryExprOrTypeTraitExpr(allOf(
1810 ofKind(UETT_AlignOf), InnerMatcher)));
1811 }
1812
1813 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1814 /// sizeof.
sizeOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)1815 inline internal::Matcher<Stmt> sizeOfExpr(
1816 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1817 return stmt(unaryExprOrTypeTraitExpr(
1818 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1819 }
1820
1821 /// \brief Matches NamedDecl nodes that have the specified name.
1822 ///
1823 /// Supports specifying enclosing namespaces or classes by prefixing the name
1824 /// with '<enclosing>::'.
1825 /// Does not match typedefs of an underlying type with the given name.
1826 ///
1827 /// Example matches X (Name == "X")
1828 /// \code
1829 /// class X;
1830 /// \endcode
1831 ///
1832 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1833 /// \code
1834 /// namespace a { namespace b { class X; } }
1835 /// \endcode
hasName(const std::string & Name)1836 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
1837 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Name));
1838 }
1839
1840 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1841 /// a substring matched by the given RegExp.
1842 ///
1843 /// Supports specifying enclosing namespaces or classes by
1844 /// prefixing the name with '<enclosing>::'. Does not match typedefs
1845 /// of an underlying type with the given name.
1846 ///
1847 /// Example matches X (regexp == "::X")
1848 /// \code
1849 /// class X;
1850 /// \endcode
1851 ///
1852 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1853 /// \code
1854 /// namespace foo { namespace bar { class X; } }
1855 /// \endcode
AST_MATCHER_P(NamedDecl,matchesName,std::string,RegExp)1856 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1857 assert(!RegExp.empty());
1858 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1859 llvm::Regex RE(RegExp);
1860 return RE.match(FullNameString);
1861 }
1862
1863 /// \brief Matches overloaded operator names.
1864 ///
1865 /// Matches overloaded operator names specified in strings without the
1866 /// "operator" prefix: e.g. "<<".
1867 ///
1868 /// Given:
1869 /// \code
1870 /// class A { int operator*(); };
1871 /// const A &operator<<(const A &a, const A &b);
1872 /// A a;
1873 /// a << a; // <-- This matches
1874 /// \endcode
1875 ///
1876 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
1877 /// specified line and
1878 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
1879 /// matches the declaration of \c A.
1880 ///
1881 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
1882 inline internal::PolymorphicMatcherWithParam1<
1883 internal::HasOverloadedOperatorNameMatcher, StringRef,
1884 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
hasOverloadedOperatorName(StringRef Name)1885 hasOverloadedOperatorName(StringRef Name) {
1886 return internal::PolymorphicMatcherWithParam1<
1887 internal::HasOverloadedOperatorNameMatcher, StringRef,
1888 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
1889 }
1890
1891 /// \brief Matches C++ classes that are directly or indirectly derived from
1892 /// a class matching \c Base.
1893 ///
1894 /// Note that a class is not considered to be derived from itself.
1895 ///
1896 /// Example matches Y, Z, C (Base == hasName("X"))
1897 /// \code
1898 /// class X;
1899 /// class Y : public X {}; // directly derived
1900 /// class Z : public Y {}; // indirectly derived
1901 /// typedef X A;
1902 /// typedef A B;
1903 /// class C : public B {}; // derived from a typedef of X
1904 /// \endcode
1905 ///
1906 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1907 /// \code
1908 /// class Foo;
1909 /// typedef Foo X;
1910 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
1911 /// \endcode
AST_MATCHER_P(CXXRecordDecl,isDerivedFrom,internal::Matcher<NamedDecl>,Base)1912 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1913 internal::Matcher<NamedDecl>, Base) {
1914 return Finder->classIsDerivedFrom(&Node, Base, Builder);
1915 }
1916
1917 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1918 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
1919 assert(!BaseName.empty());
1920 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1921 }
1922
1923 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1924 /// match \c Base.
1925 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
1926 internal::Matcher<NamedDecl>, Base, 0) {
1927 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
1928 .matches(Node, Finder, Builder);
1929 }
1930
1931 /// \brief Overloaded method as shortcut for
1932 /// \c isSameOrDerivedFrom(hasName(...)).
1933 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
1934 BaseName, 1) {
1935 assert(!BaseName.empty());
1936 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
1937 }
1938
1939 /// \brief Matches the first method of a class or struct that satisfies \c
1940 /// InnerMatcher.
1941 ///
1942 /// Given:
1943 /// \code
1944 /// class A { void func(); };
1945 /// class B { void member(); };
1946 /// \endcode
1947 ///
1948 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
1949 /// \c A but not \c B.
AST_MATCHER_P(CXXRecordDecl,hasMethod,internal::Matcher<CXXMethodDecl>,InnerMatcher)1950 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1951 InnerMatcher) {
1952 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
1953 Node.method_end(), Finder, Builder);
1954 }
1955
1956 /// \brief Matches AST nodes that have child AST nodes that match the
1957 /// provided matcher.
1958 ///
1959 /// Example matches X, Y
1960 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
1961 /// \code
1962 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1963 /// class Y { class X {}; };
1964 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1965 /// \endcode
1966 ///
1967 /// ChildT must be an AST base type.
1968 ///
1969 /// Usable as: Any Matcher
1970 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher>
1971 LLVM_ATTRIBUTE_UNUSED has = {};
1972
1973 /// \brief Matches AST nodes that have descendant AST nodes that match the
1974 /// provided matcher.
1975 ///
1976 /// Example matches X, Y, Z
1977 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
1978 /// \code
1979 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1980 /// class Y { class X {}; };
1981 /// class Z { class Y { class X {}; }; };
1982 /// \endcode
1983 ///
1984 /// DescendantT must be an AST base type.
1985 ///
1986 /// Usable as: Any Matcher
1987 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
1988 LLVM_ATTRIBUTE_UNUSED hasDescendant = {};
1989
1990 /// \brief Matches AST nodes that have child AST nodes that match the
1991 /// provided matcher.
1992 ///
1993 /// Example matches X, Y
1994 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
1995 /// \code
1996 /// class X {}; // Matches X, because X::X is a class of name X inside X.
1997 /// class Y { class X {}; };
1998 /// class Z { class Y { class X {}; }; }; // Does not match Z.
1999 /// \endcode
2000 ///
2001 /// ChildT must be an AST base type.
2002 ///
2003 /// As opposed to 'has', 'forEach' will cause a match for each result that
2004 /// matches instead of only on the first one.
2005 ///
2006 /// Usable as: Any Matcher
2007 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2008 LLVM_ATTRIBUTE_UNUSED forEach = {};
2009
2010 /// \brief Matches AST nodes that have descendant AST nodes that match the
2011 /// provided matcher.
2012 ///
2013 /// Example matches X, A, B, C
2014 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2015 /// \code
2016 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2017 /// class A { class X {}; };
2018 /// class B { class C { class X {}; }; };
2019 /// \endcode
2020 ///
2021 /// DescendantT must be an AST base type.
2022 ///
2023 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2024 /// each result that matches instead of only on the first one.
2025 ///
2026 /// Note: Recursively combined ForEachDescendant can cause many matches:
2027 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2028 /// forEachDescendant(cxxRecordDecl())
2029 /// )))
2030 /// will match 10 times (plus injected class name matches) on:
2031 /// \code
2032 /// class A { class B { class C { class D { class E {}; }; }; }; };
2033 /// \endcode
2034 ///
2035 /// Usable as: Any Matcher
2036 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
2037 LLVM_ATTRIBUTE_UNUSED forEachDescendant = {};
2038
2039 /// \brief Matches if the node or any descendant matches.
2040 ///
2041 /// Generates results for each match.
2042 ///
2043 /// For example, in:
2044 /// \code
2045 /// class A { class B {}; class C {}; };
2046 /// \endcode
2047 /// The matcher:
2048 /// \code
2049 /// cxxRecordDecl(hasName("::A"),
2050 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2051 /// \endcode
2052 /// will generate results for \c A, \c B and \c C.
2053 ///
2054 /// Usable as: Any Matcher
2055 template <typename T>
findAll(const internal::Matcher<T> & Matcher)2056 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2057 return eachOf(Matcher, forEachDescendant(Matcher));
2058 }
2059
2060 /// \brief Matches AST nodes that have a parent that matches the provided
2061 /// matcher.
2062 ///
2063 /// Given
2064 /// \code
2065 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2066 /// \endcode
2067 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2068 ///
2069 /// Usable as: Any Matcher
2070 const internal::ArgumentAdaptingMatcherFunc<
2071 internal::HasParentMatcher,
2072 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2073 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2074 LLVM_ATTRIBUTE_UNUSED hasParent = {};
2075
2076 /// \brief Matches AST nodes that have an ancestor that matches the provided
2077 /// matcher.
2078 ///
2079 /// Given
2080 /// \code
2081 /// void f() { if (true) { int x = 42; } }
2082 /// void g() { for (;;) { int x = 43; } }
2083 /// \endcode
2084 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2085 ///
2086 /// Usable as: Any Matcher
2087 const internal::ArgumentAdaptingMatcherFunc<
2088 internal::HasAncestorMatcher,
2089 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2090 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2091 LLVM_ATTRIBUTE_UNUSED hasAncestor = {};
2092
2093 /// \brief Matches if the provided matcher does not match.
2094 ///
2095 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2096 /// \code
2097 /// class X {};
2098 /// class Y {};
2099 /// \endcode
2100 ///
2101 /// Usable as: Any Matcher
2102 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
2103 internal::DynTypedMatcher::VO_UnaryNot
2104 };
2105
2106 /// \brief Matches a node if the declaration associated with that node
2107 /// matches the given matcher.
2108 ///
2109 /// The associated declaration is:
2110 /// - for type nodes, the declaration of the underlying type
2111 /// - for CallExpr, the declaration of the callee
2112 /// - for MemberExpr, the declaration of the referenced member
2113 /// - for CXXConstructExpr, the declaration of the constructor
2114 ///
2115 /// Also usable as Matcher<T> for any T supporting the getDecl() member
2116 /// function. e.g. various subtypes of clang::Type and various expressions.
2117 ///
2118 /// Usable as: Matcher<CallExpr>, Matcher<CXXConstructExpr>,
2119 /// Matcher<DeclRefExpr>, Matcher<EnumType>, Matcher<InjectedClassNameType>,
2120 /// Matcher<LabelStmt>, Matcher<MemberExpr>, Matcher<QualType>,
2121 /// Matcher<RecordType>, Matcher<TagType>,
2122 /// Matcher<TemplateSpecializationType>, Matcher<TemplateTypeParmType>,
2123 /// Matcher<TypedefType>, Matcher<UnresolvedUsingType>
2124 inline internal::PolymorphicMatcherWithParam1<
2125 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2126 void(internal::HasDeclarationSupportedTypes)>
hasDeclaration(const internal::Matcher<Decl> & InnerMatcher)2127 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2128 return internal::PolymorphicMatcherWithParam1<
2129 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2130 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2131 }
2132
2133 /// \brief Matches on the implicit object argument of a member call expression.
2134 ///
2135 /// Example matches y.x()
2136 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2137 /// \code
2138 /// class Y { public: void x(); };
2139 /// void z() { Y y; y.x(); }",
2140 /// \endcode
2141 ///
2142 /// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr,on,internal::Matcher<Expr>,InnerMatcher)2143 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2144 InnerMatcher) {
2145 const Expr *ExprNode = Node.getImplicitObjectArgument()
2146 ->IgnoreParenImpCasts();
2147 return (ExprNode != nullptr &&
2148 InnerMatcher.matches(*ExprNode, Finder, Builder));
2149 }
2150
2151
2152 /// \brief Matches on the receiver of an ObjectiveC Message expression.
2153 ///
2154 /// Example
2155 /// matcher = objCMessageExpr(hasRecieverType(asString("UIWebView *")));
2156 /// matches the [webView ...] message invocation.
2157 /// \code
2158 /// NSString *webViewJavaScript = ...
2159 /// UIWebView *webView = ...
2160 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2161 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,hasReceiverType,internal::Matcher<QualType>,InnerMatcher)2162 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2163 InnerMatcher) {
2164 const QualType TypeDecl = Node.getReceiverType();
2165 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2166 }
2167
2168 /// \brief Matches when BaseName == Selector.getAsString()
2169 ///
2170 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2171 /// matches the outer message expr in the code below, but NOT the message
2172 /// invocation for self.bodyView.
2173 /// \code
2174 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2175 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,hasSelector,std::string,BaseName)2176 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2177 Selector Sel = Node.getSelector();
2178 return BaseName.compare(Sel.getAsString()) == 0;
2179 }
2180
2181
2182 /// \brief Matches ObjC selectors whose name contains
2183 /// a substring matched by the given RegExp.
2184 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2185 /// matches the outer message expr in the code below, but NOT the message
2186 /// invocation for self.bodyView.
2187 /// \code
2188 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2189 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,matchesSelector,std::string,RegExp)2190 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2191 assert(!RegExp.empty());
2192 std::string SelectorString = Node.getSelector().getAsString();
2193 llvm::Regex RE(RegExp);
2194 return RE.match(SelectorString);
2195 }
2196
2197 /// \brief Matches when the selector is the empty selector
2198 ///
2199 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2200 /// represent an error condition in the tree!
AST_MATCHER(ObjCMessageExpr,hasNullSelector)2201 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2202 return Node.getSelector().isNull();
2203 }
2204
2205 /// \brief Matches when the selector is a Unary Selector
2206 ///
2207 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2208 /// matches self.bodyView in the code below, but NOT the outer message
2209 /// invocation of "loadHTMLString:baseURL:".
2210 /// \code
2211 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2212 /// \endcode
AST_MATCHER(ObjCMessageExpr,hasUnarySelector)2213 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2214 return Node.getSelector().isUnarySelector();
2215 }
2216
2217 /// \brief Matches when the selector is a keyword selector
2218 ///
2219 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2220 /// message expression in
2221 ///
2222 /// \code
2223 /// UIWebView *webView = ...;
2224 /// CGRect bodyFrame = webView.frame;
2225 /// bodyFrame.size.height = self.bodyContentHeight;
2226 /// webView.frame = bodyFrame;
2227 /// // ^---- matches here
2228 /// \endcode
AST_MATCHER(ObjCMessageExpr,hasKeywordSelector)2229 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2230 return Node.getSelector().isKeywordSelector();
2231 }
2232
2233 /// \brief Matches when the selector has the specified number of arguments
2234 ///
2235 /// matcher = objCMessageExpr(numSelectorArgs(0));
2236 /// matches self.bodyView in the code below
2237 ///
2238 /// matcher = objCMessageExpr(numSelectorArgs(2));
2239 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2240 /// of self.bodyView
2241 /// \code
2242 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2243 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,numSelectorArgs,unsigned,N)2244 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2245 return Node.getSelector().getNumArgs() == N;
2246 }
2247
2248 /// \brief Matches if the call expression's callee expression matches.
2249 ///
2250 /// Given
2251 /// \code
2252 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2253 /// void f() { f(); }
2254 /// \endcode
2255 /// callExpr(callee(expr()))
2256 /// matches this->x(), x(), y.x(), f()
2257 /// with callee(...)
2258 /// matching this->x, x, y.x, f respectively
2259 ///
2260 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2261 /// because this introduces ambiguous overloads with calls to Callee taking a
2262 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2263 /// implemented in terms of implicit casts.
AST_MATCHER_P(CallExpr,callee,internal::Matcher<Stmt>,InnerMatcher)2264 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2265 InnerMatcher) {
2266 const Expr *ExprNode = Node.getCallee();
2267 return (ExprNode != nullptr &&
2268 InnerMatcher.matches(*ExprNode, Finder, Builder));
2269 }
2270
2271 /// \brief Matches if the call expression's callee's declaration matches the
2272 /// given matcher.
2273 ///
2274 /// Example matches y.x() (matcher = callExpr(callee(
2275 /// cxxMethodDecl(hasName("x")))))
2276 /// \code
2277 /// class Y { public: void x(); };
2278 /// void z() { Y y; y.x(); }
2279 /// \endcode
2280 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2281 1) {
2282 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2283 }
2284
2285 /// \brief Matches if the expression's or declaration's type matches a type
2286 /// matcher.
2287 ///
2288 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2289 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2290 /// \code
2291 /// class X {};
2292 /// void y(X &x) { x; X z; }
2293 /// \endcode
2294 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2295 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, ValueDecl),
2296 internal::Matcher<QualType>, InnerMatcher, 0) {
2297 return InnerMatcher.matches(Node.getType(), Finder, Builder);
2298 }
2299
2300 /// \brief Overloaded to match the declaration of the expression's or value
2301 /// declaration's type.
2302 ///
2303 /// In case of a value declaration (for example a variable declaration),
2304 /// this resolves one layer of indirection. For example, in the value
2305 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2306 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2307 /// declaration of x.
2308 ///
2309 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2310 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2311 /// \code
2312 /// class X {};
2313 /// void y(X &x) { x; X z; }
2314 /// \endcode
2315 ///
2316 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2317 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType,
2318 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr,
2319 ValueDecl),
2320 internal::Matcher<Decl>, InnerMatcher, 1) {
2321 return qualType(hasDeclaration(InnerMatcher))
2322 .matches(Node.getType(), Finder, Builder);
2323 }
2324
2325 /// \brief Matches if the type location of the declarator decl's type matches
2326 /// the inner matcher.
2327 ///
2328 /// Given
2329 /// \code
2330 /// int x;
2331 /// \endcode
2332 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2333 /// matches int x
AST_MATCHER_P(DeclaratorDecl,hasTypeLoc,internal::Matcher<TypeLoc>,Inner)2334 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2335 if (!Node.getTypeSourceInfo())
2336 // This happens for example for implicit destructors.
2337 return false;
2338 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2339 }
2340
2341 /// \brief Matches if the matched type is represented by the given string.
2342 ///
2343 /// Given
2344 /// \code
2345 /// class Y { public: void x(); };
2346 /// void z() { Y* y; y->x(); }
2347 /// \endcode
2348 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
2349 /// matches y->x()
AST_MATCHER_P(QualType,asString,std::string,Name)2350 AST_MATCHER_P(QualType, asString, std::string, Name) {
2351 return Name == Node.getAsString();
2352 }
2353
2354 /// \brief Matches if the matched type is a pointer type and the pointee type
2355 /// matches the specified matcher.
2356 ///
2357 /// Example matches y->x()
2358 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
2359 /// cxxRecordDecl(hasName("Y")))))))
2360 /// \code
2361 /// class Y { public: void x(); };
2362 /// void z() { Y *y; y->x(); }
2363 /// \endcode
AST_MATCHER_P(QualType,pointsTo,internal::Matcher<QualType>,InnerMatcher)2364 AST_MATCHER_P(
2365 QualType, pointsTo, internal::Matcher<QualType>,
2366 InnerMatcher) {
2367 return (!Node.isNull() && Node->isAnyPointerType() &&
2368 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2369 }
2370
2371 /// \brief Overloaded to match the pointee type's declaration.
2372 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
2373 InnerMatcher, 1) {
2374 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
2375 .matches(Node, Finder, Builder);
2376 }
2377
2378 /// \brief Matches if the matched type is a reference type and the referenced
2379 /// type matches the specified matcher.
2380 ///
2381 /// Example matches X &x and const X &y
2382 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
2383 /// \code
2384 /// class X {
2385 /// void a(X b) {
2386 /// X &x = b;
2387 /// const X &y = b;
2388 /// }
2389 /// };
2390 /// \endcode
AST_MATCHER_P(QualType,references,internal::Matcher<QualType>,InnerMatcher)2391 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
2392 InnerMatcher) {
2393 return (!Node.isNull() && Node->isReferenceType() &&
2394 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
2395 }
2396
2397 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
2398 ///
2399 /// Given:
2400 /// \code
2401 /// typedef int &int_ref;
2402 /// int a;
2403 /// int_ref b = a;
2404 /// \endcode
2405 ///
2406 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
2407 /// declaration of b but \c
2408 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
AST_MATCHER_P(QualType,hasCanonicalType,internal::Matcher<QualType>,InnerMatcher)2409 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
2410 InnerMatcher) {
2411 if (Node.isNull())
2412 return false;
2413 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
2414 }
2415
2416 /// \brief Overloaded to match the referenced type's declaration.
2417 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
2418 InnerMatcher, 1) {
2419 return references(qualType(hasDeclaration(InnerMatcher)))
2420 .matches(Node, Finder, Builder);
2421 }
2422
AST_MATCHER_P(CXXMemberCallExpr,onImplicitObjectArgument,internal::Matcher<Expr>,InnerMatcher)2423 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
2424 internal::Matcher<Expr>, InnerMatcher) {
2425 const Expr *ExprNode = Node.getImplicitObjectArgument();
2426 return (ExprNode != nullptr &&
2427 InnerMatcher.matches(*ExprNode, Finder, Builder));
2428 }
2429
2430 /// \brief Matches if the expression's type either matches the specified
2431 /// matcher, or is a pointer to a type that matches the InnerMatcher.
2432 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2433 internal::Matcher<QualType>, InnerMatcher, 0) {
2434 return onImplicitObjectArgument(
2435 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2436 .matches(Node, Finder, Builder);
2437 }
2438
2439 /// \brief Overloaded to match the type's declaration.
2440 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
2441 internal::Matcher<Decl>, InnerMatcher, 1) {
2442 return onImplicitObjectArgument(
2443 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
2444 .matches(Node, Finder, Builder);
2445 }
2446
2447 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
2448 /// specified matcher.
2449 ///
2450 /// Example matches x in if(x)
2451 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
2452 /// \code
2453 /// bool x;
2454 /// if (x) {}
2455 /// \endcode
AST_MATCHER_P(DeclRefExpr,to,internal::Matcher<Decl>,InnerMatcher)2456 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
2457 InnerMatcher) {
2458 const Decl *DeclNode = Node.getDecl();
2459 return (DeclNode != nullptr &&
2460 InnerMatcher.matches(*DeclNode, Finder, Builder));
2461 }
2462
2463 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
2464 /// specific using shadow declaration.
2465 ///
2466 /// Given
2467 /// \code
2468 /// namespace a { void f() {} }
2469 /// using a::f;
2470 /// void g() {
2471 /// f(); // Matches this ..
2472 /// a::f(); // .. but not this.
2473 /// }
2474 /// \endcode
2475 /// declRefExpr(throughUsingDecl(anything()))
2476 /// matches \c f()
AST_MATCHER_P(DeclRefExpr,throughUsingDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)2477 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
2478 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2479 const NamedDecl *FoundDecl = Node.getFoundDecl();
2480 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
2481 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
2482 return false;
2483 }
2484
2485 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
2486 ///
2487 /// Given
2488 /// \code
2489 /// int a, b;
2490 /// int c;
2491 /// \endcode
2492 /// declStmt(hasSingleDecl(anything()))
2493 /// matches 'int c;' but not 'int a, b;'.
AST_MATCHER_P(DeclStmt,hasSingleDecl,internal::Matcher<Decl>,InnerMatcher)2494 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
2495 if (Node.isSingleDecl()) {
2496 const Decl *FoundDecl = Node.getSingleDecl();
2497 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
2498 }
2499 return false;
2500 }
2501
2502 /// \brief Matches a variable declaration that has an initializer expression
2503 /// that matches the given matcher.
2504 ///
2505 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
2506 /// \code
2507 /// bool y() { return true; }
2508 /// bool x = y();
2509 /// \endcode
AST_MATCHER_P(VarDecl,hasInitializer,internal::Matcher<Expr>,InnerMatcher)2510 AST_MATCHER_P(
2511 VarDecl, hasInitializer, internal::Matcher<Expr>,
2512 InnerMatcher) {
2513 const Expr *Initializer = Node.getAnyInitializer();
2514 return (Initializer != nullptr &&
2515 InnerMatcher.matches(*Initializer, Finder, Builder));
2516 }
2517
2518 /// \brief Matches a variable declaration that has function scope and is a
2519 /// non-static local variable.
2520 ///
2521 /// Example matches x (matcher = varDecl(hasLocalStorage())
2522 /// \code
2523 /// void f() {
2524 /// int x;
2525 /// static int y;
2526 /// }
2527 /// int z;
2528 /// \endcode
AST_MATCHER(VarDecl,hasLocalStorage)2529 AST_MATCHER(VarDecl, hasLocalStorage) {
2530 return Node.hasLocalStorage();
2531 }
2532
2533 /// \brief Matches a variable declaration that does not have local storage.
2534 ///
2535 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
2536 /// \code
2537 /// void f() {
2538 /// int x;
2539 /// static int y;
2540 /// }
2541 /// int z;
2542 /// \endcode
AST_MATCHER(VarDecl,hasGlobalStorage)2543 AST_MATCHER(VarDecl, hasGlobalStorage) {
2544 return Node.hasGlobalStorage();
2545 }
2546
2547 /// \brief Matches a variable declaration that has automatic storage duration.
2548 ///
2549 /// Example matches x, but not y, z, or a.
2550 /// (matcher = varDecl(hasAutomaticStorageDuration())
2551 /// \code
2552 /// void f() {
2553 /// int x;
2554 /// static int y;
2555 /// thread_local int z;
2556 /// }
2557 /// int a;
2558 /// \endcode
AST_MATCHER(VarDecl,hasAutomaticStorageDuration)2559 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
2560 return Node.getStorageDuration() == SD_Automatic;
2561 }
2562
2563 /// \brief Matches a variable declaration that has static storage duration.
2564 ///
2565 /// Example matches y and a, but not x or z.
2566 /// (matcher = varDecl(hasStaticStorageDuration())
2567 /// \code
2568 /// void f() {
2569 /// int x;
2570 /// static int y;
2571 /// thread_local int z;
2572 /// }
2573 /// int a;
2574 /// \endcode
AST_MATCHER(VarDecl,hasStaticStorageDuration)2575 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
2576 return Node.getStorageDuration() == SD_Static;
2577 }
2578
2579 /// \brief Matches a variable declaration that has thread storage duration.
2580 ///
2581 /// Example matches z, but not x, z, or a.
2582 /// (matcher = varDecl(hasThreadStorageDuration())
2583 /// \code
2584 /// void f() {
2585 /// int x;
2586 /// static int y;
2587 /// thread_local int z;
2588 /// }
2589 /// int a;
2590 /// \endcode
AST_MATCHER(VarDecl,hasThreadStorageDuration)2591 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
2592 return Node.getStorageDuration() == SD_Thread;
2593 }
2594
2595 /// \brief Matches a variable declaration that is an exception variable from
2596 /// a C++ catch block, or an Objective-C \@catch statement.
2597 ///
2598 /// Example matches x (matcher = varDecl(isExceptionVariable())
2599 /// \code
2600 /// void f(int y) {
2601 /// try {
2602 /// } catch (int x) {
2603 /// }
2604 /// }
2605 /// \endcode
AST_MATCHER(VarDecl,isExceptionVariable)2606 AST_MATCHER(VarDecl, isExceptionVariable) {
2607 return Node.isExceptionVariable();
2608 }
2609
2610 /// \brief Checks that a call expression or a constructor call expression has
2611 /// a specific number of arguments (including absent default arguments).
2612 ///
2613 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
2614 /// \code
2615 /// void f(int x, int y);
2616 /// f(0, 0);
2617 /// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,ObjCMessageExpr),unsigned,N)2618 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
2619 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2620 CXXConstructExpr,
2621 ObjCMessageExpr),
2622 unsigned, N) {
2623 return Node.getNumArgs() == N;
2624 }
2625
2626 /// \brief Matches the n'th argument of a call expression or a constructor
2627 /// call expression.
2628 ///
2629 /// Example matches y in x(y)
2630 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
2631 /// \code
2632 /// void x(int) { int y; x(y); }
2633 /// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,ObjCMessageExpr),unsigned,N,internal::Matcher<Expr>,InnerMatcher)2634 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
2635 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2636 CXXConstructExpr,
2637 ObjCMessageExpr),
2638 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
2639 return (N < Node.getNumArgs() &&
2640 InnerMatcher.matches(
2641 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
2642 }
2643
2644 /// \brief Matches declaration statements that contain a specific number of
2645 /// declarations.
2646 ///
2647 /// Example: Given
2648 /// \code
2649 /// int a, b;
2650 /// int c;
2651 /// int d = 2, e;
2652 /// \endcode
2653 /// declCountIs(2)
2654 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
AST_MATCHER_P(DeclStmt,declCountIs,unsigned,N)2655 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
2656 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
2657 }
2658
2659 /// \brief Matches the n'th declaration of a declaration statement.
2660 ///
2661 /// Note that this does not work for global declarations because the AST
2662 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2663 /// DeclStmt's.
2664 /// Example: Given non-global declarations
2665 /// \code
2666 /// int a, b = 0;
2667 /// int c;
2668 /// int d = 2, e;
2669 /// \endcode
2670 /// declStmt(containsDeclaration(
2671 /// 0, varDecl(hasInitializer(anything()))))
2672 /// matches only 'int d = 2, e;', and
2673 /// declStmt(containsDeclaration(1, varDecl()))
2674 /// \code
2675 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
2676 /// but 'int c;' is not matched.
2677 /// \endcode
AST_MATCHER_P2(DeclStmt,containsDeclaration,unsigned,N,internal::Matcher<Decl>,InnerMatcher)2678 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2679 internal::Matcher<Decl>, InnerMatcher) {
2680 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2681 if (N >= NumDecls)
2682 return false;
2683 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2684 std::advance(Iterator, N);
2685 return InnerMatcher.matches(**Iterator, Finder, Builder);
2686 }
2687
2688 /// \brief Matches a C++ catch statement that has a catch-all handler.
2689 ///
2690 /// Given
2691 /// \code
2692 /// try {
2693 /// // ...
2694 /// } catch (int) {
2695 /// // ...
2696 /// } catch (...) {
2697 /// // ...
2698 /// }
2699 /// /endcode
2700 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
AST_MATCHER(CXXCatchStmt,isCatchAll)2701 AST_MATCHER(CXXCatchStmt, isCatchAll) {
2702 return Node.getExceptionDecl() == nullptr;
2703 }
2704
2705 /// \brief Matches a constructor initializer.
2706 ///
2707 /// Given
2708 /// \code
2709 /// struct Foo {
2710 /// Foo() : foo_(1) { }
2711 /// int foo_;
2712 /// };
2713 /// \endcode
2714 /// cxxRecordDecl(has(cxxConstructorDecl(
2715 /// hasAnyConstructorInitializer(anything())
2716 /// )))
2717 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl,hasAnyConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)2718 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2719 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2720 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
2721 Node.init_end(), Finder, Builder);
2722 }
2723
2724 /// \brief Matches the field declaration of a constructor initializer.
2725 ///
2726 /// Given
2727 /// \code
2728 /// struct Foo {
2729 /// Foo() : foo_(1) { }
2730 /// int foo_;
2731 /// };
2732 /// \endcode
2733 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2734 /// forField(hasName("foo_"))))))
2735 /// matches Foo
2736 /// with forField matching foo_
AST_MATCHER_P(CXXCtorInitializer,forField,internal::Matcher<FieldDecl>,InnerMatcher)2737 AST_MATCHER_P(CXXCtorInitializer, forField,
2738 internal::Matcher<FieldDecl>, InnerMatcher) {
2739 const FieldDecl *NodeAsDecl = Node.getMember();
2740 return (NodeAsDecl != nullptr &&
2741 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2742 }
2743
2744 /// \brief Matches the initializer expression of a constructor initializer.
2745 ///
2746 /// Given
2747 /// \code
2748 /// struct Foo {
2749 /// Foo() : foo_(1) { }
2750 /// int foo_;
2751 /// };
2752 /// \endcode
2753 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
2754 /// withInitializer(integerLiteral(equals(1)))))))
2755 /// matches Foo
2756 /// with withInitializer matching (1)
AST_MATCHER_P(CXXCtorInitializer,withInitializer,internal::Matcher<Expr>,InnerMatcher)2757 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2758 internal::Matcher<Expr>, InnerMatcher) {
2759 const Expr* NodeAsExpr = Node.getInit();
2760 return (NodeAsExpr != nullptr &&
2761 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2762 }
2763
2764 /// \brief Matches a constructor initializer if it is explicitly written in
2765 /// code (as opposed to implicitly added by the compiler).
2766 ///
2767 /// Given
2768 /// \code
2769 /// struct Foo {
2770 /// Foo() { }
2771 /// Foo(int) : foo_("A") { }
2772 /// string foo_;
2773 /// };
2774 /// \endcode
2775 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
2776 /// will match Foo(int), but not Foo()
AST_MATCHER(CXXCtorInitializer,isWritten)2777 AST_MATCHER(CXXCtorInitializer, isWritten) {
2778 return Node.isWritten();
2779 }
2780
2781 /// \brief Matches a constructor initializer if it is initializing a base, as
2782 /// opposed to a member.
2783 ///
2784 /// Given
2785 /// \code
2786 /// struct B {};
2787 /// struct D : B {
2788 /// int I;
2789 /// D(int i) : I(i) {}
2790 /// };
2791 /// struct E : B {
2792 /// E() : B() {}
2793 /// };
2794 /// \endcode
2795 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
2796 /// will match E(), but not match D(int).
AST_MATCHER(CXXCtorInitializer,isBaseInitializer)2797 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
2798 return Node.isBaseInitializer();
2799 }
2800
2801 /// \brief Matches a constructor initializer if it is initializing a member, as
2802 /// opposed to a base.
2803 ///
2804 /// Given
2805 /// \code
2806 /// struct B {};
2807 /// struct D : B {
2808 /// int I;
2809 /// D(int i) : I(i) {}
2810 /// };
2811 /// struct E : B {
2812 /// E() : B() {}
2813 /// };
2814 /// \endcode
2815 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
2816 /// will match D(int), but not match E().
AST_MATCHER(CXXCtorInitializer,isMemberInitializer)2817 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
2818 return Node.isMemberInitializer();
2819 }
2820
2821 /// \brief Matches any argument of a call expression or a constructor call
2822 /// expression.
2823 ///
2824 /// Given
2825 /// \code
2826 /// void x(int, int, int) { int y; x(1, y, 42); }
2827 /// \endcode
2828 /// callExpr(hasAnyArgument(declRefExpr()))
2829 /// matches x(1, y, 42)
2830 /// with hasAnyArgument(...)
2831 /// matching y
2832 ///
2833 /// FIXME: Currently this will ignore parentheses and implicit casts on
2834 /// the argument before applying the inner matcher. We'll want to remove
2835 /// this to allow for greater control by the user once \c ignoreImplicit()
2836 /// has been implemented.
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr),internal::Matcher<Expr>,InnerMatcher)2837 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
2838 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
2839 CXXConstructExpr),
2840 internal::Matcher<Expr>, InnerMatcher) {
2841 for (const Expr *Arg : Node.arguments()) {
2842 BoundNodesTreeBuilder Result(*Builder);
2843 if (InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, &Result)) {
2844 *Builder = std::move(Result);
2845 return true;
2846 }
2847 }
2848 return false;
2849 }
2850
2851 /// \brief Matches a constructor call expression which uses list initialization.
AST_MATCHER(CXXConstructExpr,isListInitialization)2852 AST_MATCHER(CXXConstructExpr, isListInitialization) {
2853 return Node.isListInitialization();
2854 }
2855
2856 /// \brief Matches the n'th parameter of a function declaration.
2857 ///
2858 /// Given
2859 /// \code
2860 /// class X { void f(int x) {} };
2861 /// \endcode
2862 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
2863 /// matches f(int x) {}
2864 /// with hasParameter(...)
2865 /// matching int x
AST_MATCHER_P2(FunctionDecl,hasParameter,unsigned,N,internal::Matcher<ParmVarDecl>,InnerMatcher)2866 AST_MATCHER_P2(FunctionDecl, hasParameter,
2867 unsigned, N, internal::Matcher<ParmVarDecl>,
2868 InnerMatcher) {
2869 return (N < Node.getNumParams() &&
2870 InnerMatcher.matches(
2871 *Node.getParamDecl(N), Finder, Builder));
2872 }
2873
2874 /// \brief Matches any parameter of a function declaration.
2875 ///
2876 /// Does not match the 'this' parameter of a method.
2877 ///
2878 /// Given
2879 /// \code
2880 /// class X { void f(int x, int y, int z) {} };
2881 /// \endcode
2882 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
2883 /// matches f(int x, int y, int z) {}
2884 /// with hasAnyParameter(...)
2885 /// matching int y
AST_MATCHER_P(FunctionDecl,hasAnyParameter,internal::Matcher<ParmVarDecl>,InnerMatcher)2886 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2887 internal::Matcher<ParmVarDecl>, InnerMatcher) {
2888 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
2889 Node.param_end(), Finder, Builder);
2890 }
2891
2892 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2893 ///
2894 /// Given
2895 /// \code
2896 /// void f(int i) {}
2897 /// void g(int i, int j) {}
2898 /// \endcode
2899 /// functionDecl(parameterCountIs(2))
2900 /// matches g(int i, int j) {}
AST_MATCHER_P(FunctionDecl,parameterCountIs,unsigned,N)2901 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2902 return Node.getNumParams() == N;
2903 }
2904
2905 /// \brief Matches the return type of a function declaration.
2906 ///
2907 /// Given:
2908 /// \code
2909 /// class X { int f() { return 1; } };
2910 /// \endcode
2911 /// cxxMethodDecl(returns(asString("int")))
2912 /// matches int f() { return 1; }
AST_MATCHER_P(FunctionDecl,returns,internal::Matcher<QualType>,InnerMatcher)2913 AST_MATCHER_P(FunctionDecl, returns,
2914 internal::Matcher<QualType>, InnerMatcher) {
2915 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
2916 }
2917
2918 /// \brief Matches extern "C" function declarations.
2919 ///
2920 /// Given:
2921 /// \code
2922 /// extern "C" void f() {}
2923 /// extern "C" { void g() {} }
2924 /// void h() {}
2925 /// \endcode
2926 /// functionDecl(isExternC())
2927 /// matches the declaration of f and g, but not the declaration h
AST_MATCHER(FunctionDecl,isExternC)2928 AST_MATCHER(FunctionDecl, isExternC) {
2929 return Node.isExternC();
2930 }
2931
2932 /// \brief Matches deleted function declarations.
2933 ///
2934 /// Given:
2935 /// \code
2936 /// void Func();
2937 /// void DeletedFunc() = delete;
2938 /// \endcode
2939 /// functionDecl(isDeleted())
2940 /// matches the declaration of DeletedFunc, but not Func.
AST_MATCHER(FunctionDecl,isDeleted)2941 AST_MATCHER(FunctionDecl, isDeleted) {
2942 return Node.isDeleted();
2943 }
2944
2945 /// \brief Matches functions that have a non-throwing exception specification.
2946 ///
2947 /// Given:
2948 /// \code
2949 /// void f();
2950 /// void g() noexcept;
2951 /// void h() throw();
2952 /// void i() throw(int);
2953 /// void j() noexcept(false);
2954 /// \endcode
2955 /// functionDecl(isNoThrow())
2956 /// matches the declarations of g, and h, but not f, i or j.
AST_MATCHER(FunctionDecl,isNoThrow)2957 AST_MATCHER(FunctionDecl, isNoThrow) {
2958 const auto *FnTy = Node.getType()->getAs<FunctionProtoType>();
2959
2960 // If the function does not have a prototype, then it is assumed to be a
2961 // throwing function (as it would if the function did not have any exception
2962 // specification).
2963 if (!FnTy)
2964 return false;
2965
2966 // Assume the best for any unresolved exception specification.
2967 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
2968 return true;
2969
2970 return FnTy->isNothrow(Node.getASTContext());
2971 }
2972
2973 /// \brief Matches constexpr variable and function declarations.
2974 ///
2975 /// Given:
2976 /// \code
2977 /// constexpr int foo = 42;
2978 /// constexpr int bar();
2979 /// \endcode
2980 /// varDecl(isConstexpr())
2981 /// matches the declaration of foo.
2982 /// functionDecl(isConstexpr())
2983 /// matches the declaration of bar.
AST_POLYMORPHIC_MATCHER(isConstexpr,AST_POLYMORPHIC_SUPPORTED_TYPES (VarDecl,FunctionDecl))2984 AST_POLYMORPHIC_MATCHER(isConstexpr,
2985 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
2986 FunctionDecl)) {
2987 return Node.isConstexpr();
2988 }
2989
2990 /// \brief Matches the condition expression of an if statement, for loop,
2991 /// or conditional operator.
2992 ///
2993 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
2994 /// \code
2995 /// if (true) {}
2996 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasCondition,AST_POLYMORPHIC_SUPPORTED_TYPES (IfStmt,ForStmt,WhileStmt,DoStmt,ConditionalOperator),internal::Matcher<Expr>,InnerMatcher)2997 AST_POLYMORPHIC_MATCHER_P(hasCondition,
2998 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt,
2999 WhileStmt, DoStmt,
3000 ConditionalOperator),
3001 internal::Matcher<Expr>, InnerMatcher) {
3002 const Expr *const Condition = Node.getCond();
3003 return (Condition != nullptr &&
3004 InnerMatcher.matches(*Condition, Finder, Builder));
3005 }
3006
3007 /// \brief Matches the then-statement of an if statement.
3008 ///
3009 /// Examples matches the if statement
3010 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3011 /// \code
3012 /// if (false) true; else false;
3013 /// \endcode
AST_MATCHER_P(IfStmt,hasThen,internal::Matcher<Stmt>,InnerMatcher)3014 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3015 const Stmt *const Then = Node.getThen();
3016 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3017 }
3018
3019 /// \brief Matches the else-statement of an if statement.
3020 ///
3021 /// Examples matches the if statement
3022 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3023 /// \code
3024 /// if (false) false; else true;
3025 /// \endcode
AST_MATCHER_P(IfStmt,hasElse,internal::Matcher<Stmt>,InnerMatcher)3026 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3027 const Stmt *const Else = Node.getElse();
3028 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3029 }
3030
3031 /// \brief Matches if a node equals a previously bound node.
3032 ///
3033 /// Matches a node if it equals the node previously bound to \p ID.
3034 ///
3035 /// Given
3036 /// \code
3037 /// class X { int a; int b; };
3038 /// \endcode
3039 /// cxxRecordDecl(
3040 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3041 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3042 /// matches the class \c X, as \c a and \c b have the same type.
3043 ///
3044 /// Note that when multiple matches are involved via \c forEach* matchers,
3045 /// \c equalsBoundNodes acts as a filter.
3046 /// For example:
3047 /// compoundStmt(
3048 /// forEachDescendant(varDecl().bind("d")),
3049 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3050 /// will trigger a match for each combination of variable declaration
3051 /// and reference to that variable declaration within a compound statement.
AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,AST_POLYMORPHIC_SUPPORTED_TYPES (Stmt,Decl,Type,QualType),std::string,ID)3052 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3053 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3054 QualType),
3055 std::string, ID) {
3056 // FIXME: Figure out whether it makes sense to allow this
3057 // on any other node types.
3058 // For *Loc it probably does not make sense, as those seem
3059 // unique. For NestedNameSepcifier it might make sense, as
3060 // those also have pointer identity, but I'm not sure whether
3061 // they're ever reused.
3062 internal::NotEqualsBoundNodePredicate Predicate;
3063 Predicate.ID = ID;
3064 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3065 return Builder->removeBindings(Predicate);
3066 }
3067
3068 /// \brief Matches the condition variable statement in an if statement.
3069 ///
3070 /// Given
3071 /// \code
3072 /// if (A* a = GetAPointer()) {}
3073 /// \endcode
3074 /// hasConditionVariableStatement(...)
3075 /// matches 'A* a = GetAPointer()'.
AST_MATCHER_P(IfStmt,hasConditionVariableStatement,internal::Matcher<DeclStmt>,InnerMatcher)3076 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3077 internal::Matcher<DeclStmt>, InnerMatcher) {
3078 const DeclStmt* const DeclarationStatement =
3079 Node.getConditionVariableDeclStmt();
3080 return DeclarationStatement != nullptr &&
3081 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3082 }
3083
3084 /// \brief Matches the index expression of an array subscript expression.
3085 ///
3086 /// Given
3087 /// \code
3088 /// int i[5];
3089 /// void f() { i[1] = 42; }
3090 /// \endcode
3091 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3092 /// matches \c i[1] with the \c integerLiteral() matching \c 1
AST_MATCHER_P(ArraySubscriptExpr,hasIndex,internal::Matcher<Expr>,InnerMatcher)3093 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3094 internal::Matcher<Expr>, InnerMatcher) {
3095 if (const Expr* Expression = Node.getIdx())
3096 return InnerMatcher.matches(*Expression, Finder, Builder);
3097 return false;
3098 }
3099
3100 /// \brief Matches the base expression of an array subscript expression.
3101 ///
3102 /// Given
3103 /// \code
3104 /// int i[5];
3105 /// void f() { i[1] = 42; }
3106 /// \endcode
3107 /// arraySubscriptExpression(hasBase(implicitCastExpr(
3108 /// hasSourceExpression(declRefExpr()))))
3109 /// matches \c i[1] with the \c declRefExpr() matching \c i
AST_MATCHER_P(ArraySubscriptExpr,hasBase,internal::Matcher<Expr>,InnerMatcher)3110 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
3111 internal::Matcher<Expr>, InnerMatcher) {
3112 if (const Expr* Expression = Node.getBase())
3113 return InnerMatcher.matches(*Expression, Finder, Builder);
3114 return false;
3115 }
3116
3117 /// \brief Matches a 'for', 'while', or 'do while' statement that has
3118 /// a given body.
3119 ///
3120 /// Given
3121 /// \code
3122 /// for (;;) {}
3123 /// \endcode
3124 /// hasBody(compoundStmt())
3125 /// matches 'for (;;) {}'
3126 /// with compoundStmt()
3127 /// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasBody,AST_POLYMORPHIC_SUPPORTED_TYPES (DoStmt,ForStmt,WhileStmt,CXXForRangeStmt),internal::Matcher<Stmt>,InnerMatcher)3128 AST_POLYMORPHIC_MATCHER_P(hasBody,
3129 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
3130 WhileStmt,
3131 CXXForRangeStmt),
3132 internal::Matcher<Stmt>, InnerMatcher) {
3133 const Stmt *const Statement = Node.getBody();
3134 return (Statement != nullptr &&
3135 InnerMatcher.matches(*Statement, Finder, Builder));
3136 }
3137
3138 /// \brief Matches compound statements where at least one substatement matches
3139 /// a given matcher.
3140 ///
3141 /// Given
3142 /// \code
3143 /// { {}; 1+2; }
3144 /// \endcode
3145 /// hasAnySubstatement(compoundStmt())
3146 /// matches '{ {}; 1+2; }'
3147 /// with compoundStmt()
3148 /// matching '{}'
AST_MATCHER_P(CompoundStmt,hasAnySubstatement,internal::Matcher<Stmt>,InnerMatcher)3149 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
3150 internal::Matcher<Stmt>, InnerMatcher) {
3151 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(),
3152 Node.body_end(), Finder, Builder);
3153 }
3154
3155 /// \brief Checks that a compound statement contains a specific number of
3156 /// child statements.
3157 ///
3158 /// Example: Given
3159 /// \code
3160 /// { for (;;) {} }
3161 /// \endcode
3162 /// compoundStmt(statementCountIs(0)))
3163 /// matches '{}'
3164 /// but does not match the outer compound statement.
AST_MATCHER_P(CompoundStmt,statementCountIs,unsigned,N)3165 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
3166 return Node.size() == N;
3167 }
3168
3169 /// \brief Matches literals that are equal to the given value.
3170 ///
3171 /// Example matches true (matcher = cxxBoolLiteral(equals(true)))
3172 /// \code
3173 /// true
3174 /// \endcode
3175 ///
3176 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
3177 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
3178 template <typename ValueT>
3179 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
equals(const ValueT & Value)3180 equals(const ValueT &Value) {
3181 return internal::PolymorphicMatcherWithParam1<
3182 internal::ValueEqualsMatcher,
3183 ValueT>(Value);
3184 }
3185
3186 /// \brief Matches the operator Name of operator expressions (binary or
3187 /// unary).
3188 ///
3189 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
3190 /// \code
3191 /// !(a || b)
3192 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasOperatorName,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,UnaryOperator),std::string,Name)3193 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
3194 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3195 UnaryOperator),
3196 std::string, Name) {
3197 return Name == Node.getOpcodeStr(Node.getOpcode());
3198 }
3199
3200 /// \brief Matches the left hand side of binary operator expressions.
3201 ///
3202 /// Example matches a (matcher = binaryOperator(hasLHS()))
3203 /// \code
3204 /// a || b
3205 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasLHS,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,ArraySubscriptExpr),internal::Matcher<Expr>,InnerMatcher)3206 AST_POLYMORPHIC_MATCHER_P(hasLHS,
3207 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3208 ArraySubscriptExpr),
3209 internal::Matcher<Expr>, InnerMatcher) {
3210 const Expr *LeftHandSide = Node.getLHS();
3211 return (LeftHandSide != nullptr &&
3212 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
3213 }
3214
3215 /// \brief Matches the right hand side of binary operator expressions.
3216 ///
3217 /// Example matches b (matcher = binaryOperator(hasRHS()))
3218 /// \code
3219 /// a || b
3220 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasRHS,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,ArraySubscriptExpr),internal::Matcher<Expr>,InnerMatcher)3221 AST_POLYMORPHIC_MATCHER_P(hasRHS,
3222 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
3223 ArraySubscriptExpr),
3224 internal::Matcher<Expr>, InnerMatcher) {
3225 const Expr *RightHandSide = Node.getRHS();
3226 return (RightHandSide != nullptr &&
3227 InnerMatcher.matches(*RightHandSide, Finder, Builder));
3228 }
3229
3230 /// \brief Matches if either the left hand side or the right hand side of a
3231 /// binary operator matches.
hasEitherOperand(const internal::Matcher<Expr> & InnerMatcher)3232 inline internal::Matcher<BinaryOperator> hasEitherOperand(
3233 const internal::Matcher<Expr> &InnerMatcher) {
3234 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
3235 }
3236
3237 /// \brief Matches if the operand of a unary operator matches.
3238 ///
3239 /// Example matches true (matcher = hasUnaryOperand(
3240 /// cxxBoolLiteral(equals(true))))
3241 /// \code
3242 /// !true
3243 /// \endcode
AST_MATCHER_P(UnaryOperator,hasUnaryOperand,internal::Matcher<Expr>,InnerMatcher)3244 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
3245 internal::Matcher<Expr>, InnerMatcher) {
3246 const Expr * const Operand = Node.getSubExpr();
3247 return (Operand != nullptr &&
3248 InnerMatcher.matches(*Operand, Finder, Builder));
3249 }
3250
3251 /// \brief Matches if the cast's source expression matches the given matcher.
3252 ///
3253 /// Example: matches "a string" (matcher =
3254 /// hasSourceExpression(cxxConstructExpr()))
3255 /// \code
3256 /// class URL { URL(string); };
3257 /// URL url = "a string";
3258 /// \endcode
AST_MATCHER_P(CastExpr,hasSourceExpression,internal::Matcher<Expr>,InnerMatcher)3259 AST_MATCHER_P(CastExpr, hasSourceExpression,
3260 internal::Matcher<Expr>, InnerMatcher) {
3261 const Expr* const SubExpression = Node.getSubExpr();
3262 return (SubExpression != nullptr &&
3263 InnerMatcher.matches(*SubExpression, Finder, Builder));
3264 }
3265
3266 /// \brief Matches casts whose destination type matches a given matcher.
3267 ///
3268 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
3269 /// actual casts "explicit" casts.)
AST_MATCHER_P(ExplicitCastExpr,hasDestinationType,internal::Matcher<QualType>,InnerMatcher)3270 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
3271 internal::Matcher<QualType>, InnerMatcher) {
3272 const QualType NodeType = Node.getTypeAsWritten();
3273 return InnerMatcher.matches(NodeType, Finder, Builder);
3274 }
3275
3276 /// \brief Matches implicit casts whose destination type matches a given
3277 /// matcher.
3278 ///
3279 /// FIXME: Unit test this matcher
AST_MATCHER_P(ImplicitCastExpr,hasImplicitDestinationType,internal::Matcher<QualType>,InnerMatcher)3280 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
3281 internal::Matcher<QualType>, InnerMatcher) {
3282 return InnerMatcher.matches(Node.getType(), Finder, Builder);
3283 }
3284
3285 /// \brief Matches RecordDecl object that are spelled with "struct."
3286 ///
3287 /// Example matches S, but not C or U.
3288 /// \code
3289 /// struct S {};
3290 /// class C {};
3291 /// union U {};
3292 /// \endcode
AST_MATCHER(RecordDecl,isStruct)3293 AST_MATCHER(RecordDecl, isStruct) {
3294 return Node.isStruct();
3295 }
3296
3297 /// \brief Matches RecordDecl object that are spelled with "union."
3298 ///
3299 /// Example matches U, but not C or S.
3300 /// \code
3301 /// struct S {};
3302 /// class C {};
3303 /// union U {};
3304 /// \endcode
AST_MATCHER(RecordDecl,isUnion)3305 AST_MATCHER(RecordDecl, isUnion) {
3306 return Node.isUnion();
3307 }
3308
3309 /// \brief Matches RecordDecl object that are spelled with "class."
3310 ///
3311 /// Example matches C, but not S or U.
3312 /// \code
3313 /// struct S {};
3314 /// class C {};
3315 /// union U {};
3316 /// \endcode
AST_MATCHER(RecordDecl,isClass)3317 AST_MATCHER(RecordDecl, isClass) {
3318 return Node.isClass();
3319 }
3320
3321 /// \brief Matches the true branch expression of a conditional operator.
3322 ///
3323 /// Example matches a
3324 /// \code
3325 /// condition ? a : b
3326 /// \endcode
AST_MATCHER_P(ConditionalOperator,hasTrueExpression,internal::Matcher<Expr>,InnerMatcher)3327 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
3328 internal::Matcher<Expr>, InnerMatcher) {
3329 const Expr *Expression = Node.getTrueExpr();
3330 return (Expression != nullptr &&
3331 InnerMatcher.matches(*Expression, Finder, Builder));
3332 }
3333
3334 /// \brief Matches the false branch expression of a conditional operator.
3335 ///
3336 /// Example matches b
3337 /// \code
3338 /// condition ? a : b
3339 /// \endcode
AST_MATCHER_P(ConditionalOperator,hasFalseExpression,internal::Matcher<Expr>,InnerMatcher)3340 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
3341 internal::Matcher<Expr>, InnerMatcher) {
3342 const Expr *Expression = Node.getFalseExpr();
3343 return (Expression != nullptr &&
3344 InnerMatcher.matches(*Expression, Finder, Builder));
3345 }
3346
3347 /// \brief Matches if a declaration has a body attached.
3348 ///
3349 /// Example matches A, va, fa
3350 /// \code
3351 /// class A {};
3352 /// class B; // Doesn't match, as it has no body.
3353 /// int va;
3354 /// extern int vb; // Doesn't match, as it doesn't define the variable.
3355 /// void fa() {}
3356 /// void fb(); // Doesn't match, as it has no body.
3357 /// \endcode
3358 ///
3359 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
AST_POLYMORPHIC_MATCHER(isDefinition,AST_POLYMORPHIC_SUPPORTED_TYPES (TagDecl,VarDecl,FunctionDecl))3360 AST_POLYMORPHIC_MATCHER(isDefinition,
3361 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
3362 FunctionDecl)) {
3363 return Node.isThisDeclarationADefinition();
3364 }
3365
3366 /// \brief Matches if a function declaration is variadic.
3367 ///
3368 /// Example matches f, but not g or h. The function i will not match, even when
3369 /// compiled in C mode.
3370 /// \code
3371 /// void f(...);
3372 /// void g(int);
3373 /// template <typename... Ts> void h(Ts...);
3374 /// void i();
3375 /// \endcode
AST_MATCHER(FunctionDecl,isVariadic)3376 AST_MATCHER(FunctionDecl, isVariadic) {
3377 return Node.isVariadic();
3378 }
3379
3380 /// \brief Matches the class declaration that the given method declaration
3381 /// belongs to.
3382 ///
3383 /// FIXME: Generalize this for other kinds of declarations.
3384 /// FIXME: What other kind of declarations would we need to generalize
3385 /// this to?
3386 ///
3387 /// Example matches A() in the last line
3388 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
3389 /// ofClass(hasName("A"))))))
3390 /// \code
3391 /// class A {
3392 /// public:
3393 /// A();
3394 /// };
3395 /// A a = A();
3396 /// \endcode
AST_MATCHER_P(CXXMethodDecl,ofClass,internal::Matcher<CXXRecordDecl>,InnerMatcher)3397 AST_MATCHER_P(CXXMethodDecl, ofClass,
3398 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
3399 const CXXRecordDecl *Parent = Node.getParent();
3400 return (Parent != nullptr &&
3401 InnerMatcher.matches(*Parent, Finder, Builder));
3402 }
3403
3404 /// \brief Matches if the given method declaration is virtual.
3405 ///
3406 /// Given
3407 /// \code
3408 /// class A {
3409 /// public:
3410 /// virtual void x();
3411 /// };
3412 /// \endcode
3413 /// matches A::x
AST_MATCHER(CXXMethodDecl,isVirtual)3414 AST_MATCHER(CXXMethodDecl, isVirtual) {
3415 return Node.isVirtual();
3416 }
3417
3418 /// \brief Matches if the given method or class declaration is final.
3419 ///
3420 /// Given:
3421 /// \code
3422 /// class A final {};
3423 ///
3424 /// struct B {
3425 /// virtual void f();
3426 /// };
3427 ///
3428 /// struct C : B {
3429 /// void f() final;
3430 /// };
3431 /// \endcode
3432 /// matches A and C::f, but not B, C, or B::f
AST_POLYMORPHIC_MATCHER(isFinal,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXRecordDecl,CXXMethodDecl))3433 AST_POLYMORPHIC_MATCHER(isFinal,
3434 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
3435 CXXMethodDecl)) {
3436 return Node.template hasAttr<FinalAttr>();
3437 }
3438
3439 /// \brief Matches if the given method declaration is pure.
3440 ///
3441 /// Given
3442 /// \code
3443 /// class A {
3444 /// public:
3445 /// virtual void x() = 0;
3446 /// };
3447 /// \endcode
3448 /// matches A::x
AST_MATCHER(CXXMethodDecl,isPure)3449 AST_MATCHER(CXXMethodDecl, isPure) {
3450 return Node.isPure();
3451 }
3452
3453 /// \brief Matches if the given method declaration is const.
3454 ///
3455 /// Given
3456 /// \code
3457 /// struct A {
3458 /// void foo() const;
3459 /// void bar();
3460 /// };
3461 /// \endcode
3462 ///
3463 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
AST_MATCHER(CXXMethodDecl,isConst)3464 AST_MATCHER(CXXMethodDecl, isConst) {
3465 return Node.isConst();
3466 }
3467
3468 /// \brief Matches if the given method declaration declares a copy assignment
3469 /// operator.
3470 ///
3471 /// Given
3472 /// \code
3473 /// struct A {
3474 /// A &operator=(const A &);
3475 /// A &operator=(A &&);
3476 /// };
3477 /// \endcode
3478 ///
3479 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
3480 /// the second one.
AST_MATCHER(CXXMethodDecl,isCopyAssignmentOperator)3481 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
3482 return Node.isCopyAssignmentOperator();
3483 }
3484
3485 /// \brief Matches if the given method declaration overrides another method.
3486 ///
3487 /// Given
3488 /// \code
3489 /// class A {
3490 /// public:
3491 /// virtual void x();
3492 /// };
3493 /// class B : public A {
3494 /// public:
3495 /// virtual void x();
3496 /// };
3497 /// \endcode
3498 /// matches B::x
AST_MATCHER(CXXMethodDecl,isOverride)3499 AST_MATCHER(CXXMethodDecl, isOverride) {
3500 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
3501 }
3502
3503 /// \brief Matches member expressions that are called with '->' as opposed
3504 /// to '.'.
3505 ///
3506 /// Member calls on the implicit this pointer match as called with '->'.
3507 ///
3508 /// Given
3509 /// \code
3510 /// class Y {
3511 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
3512 /// int a;
3513 /// static int b;
3514 /// };
3515 /// \endcode
3516 /// memberExpr(isArrow())
3517 /// matches this->x, x, y.x, a, this->b
AST_MATCHER(MemberExpr,isArrow)3518 AST_MATCHER(MemberExpr, isArrow) {
3519 return Node.isArrow();
3520 }
3521
3522 /// \brief Matches QualType nodes that are of integer type.
3523 ///
3524 /// Given
3525 /// \code
3526 /// void a(int);
3527 /// void b(long);
3528 /// void c(double);
3529 /// \endcode
3530 /// functionDecl(hasAnyParameter(hasType(isInteger())))
3531 /// matches "a(int)", "b(long)", but not "c(double)".
AST_MATCHER(QualType,isInteger)3532 AST_MATCHER(QualType, isInteger) {
3533 return Node->isIntegerType();
3534 }
3535
3536 /// \brief Matches QualType nodes that are of character type.
3537 ///
3538 /// Given
3539 /// \code
3540 /// void a(char);
3541 /// void b(wchar_t);
3542 /// void c(double);
3543 /// \endcode
3544 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
3545 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
AST_MATCHER(QualType,isAnyCharacter)3546 AST_MATCHER(QualType, isAnyCharacter) {
3547 return Node->isAnyCharacterType();
3548 }
3549
3550 /// \brief Matches QualType nodes that are const-qualified, i.e., that
3551 /// include "top-level" const.
3552 ///
3553 /// Given
3554 /// \code
3555 /// void a(int);
3556 /// void b(int const);
3557 /// void c(const int);
3558 /// void d(const int*);
3559 /// void e(int const) {};
3560 /// \endcode
3561 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
3562 /// matches "void b(int const)", "void c(const int)" and
3563 /// "void e(int const) {}". It does not match d as there
3564 /// is no top-level const on the parameter type "const int *".
AST_MATCHER(QualType,isConstQualified)3565 AST_MATCHER(QualType, isConstQualified) {
3566 return Node.isConstQualified();
3567 }
3568
3569 /// \brief Matches QualType nodes that are volatile-qualified, i.e., that
3570 /// include "top-level" volatile.
3571 ///
3572 /// Given
3573 /// \code
3574 /// void a(int);
3575 /// void b(int volatile);
3576 /// void c(volatile int);
3577 /// void d(volatile int*);
3578 /// void e(int volatile) {};
3579 /// \endcode
3580 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
3581 /// matches "void b(int volatile)", "void c(volatile int)" and
3582 /// "void e(int volatile) {}". It does not match d as there
3583 /// is no top-level volatile on the parameter type "volatile int *".
AST_MATCHER(QualType,isVolatileQualified)3584 AST_MATCHER(QualType, isVolatileQualified) {
3585 return Node.isVolatileQualified();
3586 }
3587
3588 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
3589 /// the node, not hidden within a typedef.
3590 ///
3591 /// Given
3592 /// \code
3593 /// typedef const int const_int;
3594 /// const_int i;
3595 /// int *const j;
3596 /// int *volatile k;
3597 /// int m;
3598 /// \endcode
3599 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
3600 /// \c i is const-qualified but the qualifier is not local.
AST_MATCHER(QualType,hasLocalQualifiers)3601 AST_MATCHER(QualType, hasLocalQualifiers) {
3602 return Node.hasLocalQualifiers();
3603 }
3604
3605 /// \brief Matches a member expression where the member is matched by a
3606 /// given matcher.
3607 ///
3608 /// Given
3609 /// \code
3610 /// struct { int first, second; } first, second;
3611 /// int i(second.first);
3612 /// int j(first.second);
3613 /// \endcode
3614 /// memberExpr(member(hasName("first")))
3615 /// matches second.first
3616 /// but not first.second (because the member name there is "second").
AST_MATCHER_P(MemberExpr,member,internal::Matcher<ValueDecl>,InnerMatcher)3617 AST_MATCHER_P(MemberExpr, member,
3618 internal::Matcher<ValueDecl>, InnerMatcher) {
3619 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
3620 }
3621
3622 /// \brief Matches a member expression where the object expression is
3623 /// matched by a given matcher.
3624 ///
3625 /// Given
3626 /// \code
3627 /// struct X { int m; };
3628 /// void f(X x) { x.m; m; }
3629 /// \endcode
3630 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
3631 /// matches "x.m" and "m"
3632 /// with hasObjectExpression(...)
3633 /// matching "x" and the implicit object expression of "m" which has type X*.
AST_MATCHER_P(MemberExpr,hasObjectExpression,internal::Matcher<Expr>,InnerMatcher)3634 AST_MATCHER_P(MemberExpr, hasObjectExpression,
3635 internal::Matcher<Expr>, InnerMatcher) {
3636 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
3637 }
3638
3639 /// \brief Matches any using shadow declaration.
3640 ///
3641 /// Given
3642 /// \code
3643 /// namespace X { void b(); }
3644 /// using X::b;
3645 /// \endcode
3646 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
3647 /// matches \code using X::b \endcode
AST_MATCHER_P(UsingDecl,hasAnyUsingShadowDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)3648 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
3649 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3650 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
3651 Node.shadow_end(), Finder, Builder);
3652 }
3653
3654 /// \brief Matches a using shadow declaration where the target declaration is
3655 /// matched by the given matcher.
3656 ///
3657 /// Given
3658 /// \code
3659 /// namespace X { int a; void b(); }
3660 /// using X::a;
3661 /// using X::b;
3662 /// \endcode
3663 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
3664 /// matches \code using X::b \endcode
3665 /// but not \code using X::a \endcode
AST_MATCHER_P(UsingShadowDecl,hasTargetDecl,internal::Matcher<NamedDecl>,InnerMatcher)3666 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
3667 internal::Matcher<NamedDecl>, InnerMatcher) {
3668 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
3669 }
3670
3671 /// \brief Matches template instantiations of function, class, or static
3672 /// member variable template instantiations.
3673 ///
3674 /// Given
3675 /// \code
3676 /// template <typename T> class X {}; class A {}; X<A> x;
3677 /// \endcode
3678 /// or
3679 /// \code
3680 /// template <typename T> class X {}; class A {}; template class X<A>;
3681 /// \endcode
3682 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
3683 /// matches the template instantiation of X<A>.
3684 ///
3685 /// But given
3686 /// \code
3687 /// template <typename T> class X {}; class A {};
3688 /// template <> class X<A> {}; X<A> x;
3689 /// \endcode
3690 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
3691 /// does not match, as X<A> is an explicit template specialization.
3692 ///
3693 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl,CXXRecordDecl))3694 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
3695 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
3696 CXXRecordDecl)) {
3697 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
3698 Node.getTemplateSpecializationKind() ==
3699 TSK_ExplicitInstantiationDefinition);
3700 }
3701
3702 /// \brief Matches declarations that are template instantiations or are inside
3703 /// template instantiations.
3704 ///
3705 /// Given
3706 /// \code
3707 /// template<typename T> void A(T t) { T i; }
3708 /// A(0);
3709 /// A(0U);
3710 /// \endcode
3711 /// functionDecl(isInstantiated())
3712 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
AST_MATCHER_FUNCTION(internal::Matcher<Decl>,isInstantiated)3713 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
3714 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
3715 functionDecl(isTemplateInstantiation())));
3716 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
3717 }
3718
3719 /// \brief Matches statements inside of a template instantiation.
3720 ///
3721 /// Given
3722 /// \code
3723 /// int j;
3724 /// template<typename T> void A(T t) { T i; j += 42;}
3725 /// A(0);
3726 /// A(0U);
3727 /// \endcode
3728 /// declStmt(isInTemplateInstantiation())
3729 /// matches 'int i;' and 'unsigned i'.
3730 /// unless(stmt(isInTemplateInstantiation()))
3731 /// will NOT match j += 42; as it's shared between the template definition and
3732 /// instantiation.
AST_MATCHER_FUNCTION(internal::Matcher<Stmt>,isInTemplateInstantiation)3733 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
3734 return stmt(
3735 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
3736 functionDecl(isTemplateInstantiation())))));
3737 }
3738
3739 /// \brief Matches explicit template specializations of function, class, or
3740 /// static member variable template instantiations.
3741 ///
3742 /// Given
3743 /// \code
3744 /// template<typename T> void A(T t) { }
3745 /// template<> void A(int N) { }
3746 /// \endcode
3747 /// functionDecl(isExplicitTemplateSpecialization())
3748 /// matches the specialization A<int>().
3749 ///
3750 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl,CXXRecordDecl))3751 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
3752 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
3753 CXXRecordDecl)) {
3754 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
3755 }
3756
3757 /// \brief Matches \c TypeLocs for which the given inner
3758 /// QualType-matcher matches.
3759 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
3760 internal::Matcher<QualType>, InnerMatcher, 0) {
3761 return internal::BindableMatcher<TypeLoc>(
3762 new internal::TypeLocTypeMatcher(InnerMatcher));
3763 }
3764
3765 /// \brief Matches type \c void.
3766 ///
3767 /// Given
3768 /// \code
3769 /// struct S { void func(); };
3770 /// \endcode
3771 /// functionDecl(returns(voidType()))
3772 /// matches "void func();"
AST_MATCHER(Type,voidType)3773 AST_MATCHER(Type, voidType) {
3774 return Node.isVoidType();
3775 }
3776
3777 /// \brief Matches builtin Types.
3778 ///
3779 /// Given
3780 /// \code
3781 /// struct A {};
3782 /// A a;
3783 /// int b;
3784 /// float c;
3785 /// bool d;
3786 /// \endcode
3787 /// builtinType()
3788 /// matches "int b", "float c" and "bool d"
3789 AST_TYPE_MATCHER(BuiltinType, builtinType);
3790
3791 /// \brief Matches all kinds of arrays.
3792 ///
3793 /// Given
3794 /// \code
3795 /// int a[] = { 2, 3 };
3796 /// int b[4];
3797 /// void f() { int c[a[0]]; }
3798 /// \endcode
3799 /// arrayType()
3800 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
3801 AST_TYPE_MATCHER(ArrayType, arrayType);
3802
3803 /// \brief Matches C99 complex types.
3804 ///
3805 /// Given
3806 /// \code
3807 /// _Complex float f;
3808 /// \endcode
3809 /// complexType()
3810 /// matches "_Complex float f"
3811 AST_TYPE_MATCHER(ComplexType, complexType);
3812
3813 /// \brief Matches arrays and C99 complex types that have a specific element
3814 /// type.
3815 ///
3816 /// Given
3817 /// \code
3818 /// struct A {};
3819 /// A a[7];
3820 /// int b[7];
3821 /// \endcode
3822 /// arrayType(hasElementType(builtinType()))
3823 /// matches "int b[7]"
3824 ///
3825 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
3826 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement,
3827 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
3828 ComplexType));
3829
3830 /// \brief Matches C arrays with a specified constant size.
3831 ///
3832 /// Given
3833 /// \code
3834 /// void() {
3835 /// int a[2];
3836 /// int b[] = { 2, 3 };
3837 /// int c[b[0]];
3838 /// }
3839 /// \endcode
3840 /// constantArrayType()
3841 /// matches "int a[2]"
3842 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
3843
3844 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
3845 ///
3846 /// Given
3847 /// \code
3848 /// int a[42];
3849 /// int b[2 * 21];
3850 /// int c[41], d[43];
3851 /// \endcode
3852 /// constantArrayType(hasSize(42))
3853 /// matches "int a[42]" and "int b[2 * 21]"
AST_MATCHER_P(ConstantArrayType,hasSize,unsigned,N)3854 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
3855 return Node.getSize() == N;
3856 }
3857
3858 /// \brief Matches C++ arrays whose size is a value-dependent expression.
3859 ///
3860 /// Given
3861 /// \code
3862 /// template<typename T, int Size>
3863 /// class array {
3864 /// T data[Size];
3865 /// };
3866 /// \endcode
3867 /// dependentSizedArrayType
3868 /// matches "T data[Size]"
3869 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
3870
3871 /// \brief Matches C arrays with unspecified size.
3872 ///
3873 /// Given
3874 /// \code
3875 /// int a[] = { 2, 3 };
3876 /// int b[42];
3877 /// void f(int c[]) { int d[a[0]]; };
3878 /// \endcode
3879 /// incompleteArrayType()
3880 /// matches "int a[]" and "int c[]"
3881 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
3882
3883 /// \brief Matches C arrays with a specified size that is not an
3884 /// integer-constant-expression.
3885 ///
3886 /// Given
3887 /// \code
3888 /// void f() {
3889 /// int a[] = { 2, 3 }
3890 /// int b[42];
3891 /// int c[a[0]];
3892 /// }
3893 /// \endcode
3894 /// variableArrayType()
3895 /// matches "int c[a[0]]"
3896 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
3897
3898 /// \brief Matches \c VariableArrayType nodes that have a specific size
3899 /// expression.
3900 ///
3901 /// Given
3902 /// \code
3903 /// void f(int b) {
3904 /// int a[b];
3905 /// }
3906 /// \endcode
3907 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
3908 /// varDecl(hasName("b")))))))
3909 /// matches "int a[b]"
AST_MATCHER_P(VariableArrayType,hasSizeExpr,internal::Matcher<Expr>,InnerMatcher)3910 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
3911 internal::Matcher<Expr>, InnerMatcher) {
3912 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
3913 }
3914
3915 /// \brief Matches atomic types.
3916 ///
3917 /// Given
3918 /// \code
3919 /// _Atomic(int) i;
3920 /// \endcode
3921 /// atomicType()
3922 /// matches "_Atomic(int) i"
3923 AST_TYPE_MATCHER(AtomicType, atomicType);
3924
3925 /// \brief Matches atomic types with a specific value type.
3926 ///
3927 /// Given
3928 /// \code
3929 /// _Atomic(int) i;
3930 /// _Atomic(float) f;
3931 /// \endcode
3932 /// atomicType(hasValueType(isInteger()))
3933 /// matches "_Atomic(int) i"
3934 ///
3935 /// Usable as: Matcher<AtomicType>
3936 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue,
3937 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
3938
3939 /// \brief Matches types nodes representing C++11 auto types.
3940 ///
3941 /// Given:
3942 /// \code
3943 /// auto n = 4;
3944 /// int v[] = { 2, 3 }
3945 /// for (auto i : v) { }
3946 /// \endcode
3947 /// autoType()
3948 /// matches "auto n" and "auto i"
3949 AST_TYPE_MATCHER(AutoType, autoType);
3950
3951 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
3952 ///
3953 /// Note: There is no \c TypeLoc for the deduced type and thus no
3954 /// \c getDeducedLoc() matcher.
3955 ///
3956 /// Given
3957 /// \code
3958 /// auto a = 1;
3959 /// auto b = 2.0;
3960 /// \endcode
3961 /// autoType(hasDeducedType(isInteger()))
3962 /// matches "auto a"
3963 ///
3964 /// Usable as: Matcher<AutoType>
3965 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
3966 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
3967
3968 /// \brief Matches \c FunctionType nodes.
3969 ///
3970 /// Given
3971 /// \code
3972 /// int (*f)(int);
3973 /// void g();
3974 /// \endcode
3975 /// functionType()
3976 /// matches "int (*f)(int)" and the type of "g".
3977 AST_TYPE_MATCHER(FunctionType, functionType);
3978
3979 /// \brief Matches \c ParenType nodes.
3980 ///
3981 /// Given
3982 /// \code
3983 /// int (*ptr_to_array)[4];
3984 /// int *array_of_ptrs[4];
3985 /// \endcode
3986 ///
3987 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
3988 /// \c array_of_ptrs.
3989 AST_TYPE_MATCHER(ParenType, parenType);
3990
3991 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
3992 ///
3993 /// Given
3994 /// \code
3995 /// int (*ptr_to_array)[4];
3996 /// int (*ptr_to_func)(int);
3997 /// \endcode
3998 ///
3999 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
4000 /// \c ptr_to_func but not \c ptr_to_array.
4001 ///
4002 /// Usable as: Matcher<ParenType>
4003 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
4004 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
4005
4006 /// \brief Matches block pointer types, i.e. types syntactically represented as
4007 /// "void (^)(int)".
4008 ///
4009 /// The \c pointee is always required to be a \c FunctionType.
4010 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
4011
4012 /// \brief Matches member pointer types.
4013 /// Given
4014 /// \code
4015 /// struct A { int i; }
4016 /// A::* ptr = A::i;
4017 /// \endcode
4018 /// memberPointerType()
4019 /// matches "A::* ptr"
4020 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
4021
4022 /// \brief Matches pointer types, but does not match Objective-C object pointer
4023 /// types.
4024 ///
4025 /// Given
4026 /// \code
4027 /// int *a;
4028 /// int &b = *a;
4029 /// int c = 5;
4030 ///
4031 /// @interface Foo
4032 /// @end
4033 /// Foo *f;
4034 /// \endcode
4035 /// pointerType()
4036 /// matches "int *a", but does not match "Foo *f".
4037 AST_TYPE_MATCHER(PointerType, pointerType);
4038
4039 /// \brief Matches an Objective-C object pointer type, which is different from
4040 /// a pointer type, despite being syntactically similar.
4041 ///
4042 /// Given
4043 /// \code
4044 /// int *a;
4045 ///
4046 /// @interface Foo
4047 /// @end
4048 /// Foo *f;
4049 /// \endcode
4050 /// pointerType()
4051 /// matches "Foo *f", but does not match "int *a".
4052 AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType);
4053
4054 /// \brief Matches both lvalue and rvalue reference types.
4055 ///
4056 /// Given
4057 /// \code
4058 /// int *a;
4059 /// int &b = *a;
4060 /// int &&c = 1;
4061 /// auto &d = b;
4062 /// auto &&e = c;
4063 /// auto &&f = 2;
4064 /// int g = 5;
4065 /// \endcode
4066 ///
4067 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
4068 AST_TYPE_MATCHER(ReferenceType, referenceType);
4069
4070 /// \brief Matches lvalue reference types.
4071 ///
4072 /// Given:
4073 /// \code
4074 /// int *a;
4075 /// int &b = *a;
4076 /// int &&c = 1;
4077 /// auto &d = b;
4078 /// auto &&e = c;
4079 /// auto &&f = 2;
4080 /// int g = 5;
4081 /// \endcode
4082 ///
4083 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
4084 /// matched since the type is deduced as int& by reference collapsing rules.
4085 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
4086
4087 /// \brief Matches rvalue reference types.
4088 ///
4089 /// Given:
4090 /// \code
4091 /// int *a;
4092 /// int &b = *a;
4093 /// int &&c = 1;
4094 /// auto &d = b;
4095 /// auto &&e = c;
4096 /// auto &&f = 2;
4097 /// int g = 5;
4098 /// \endcode
4099 ///
4100 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
4101 /// matched as it is deduced to int& by reference collapsing rules.
4102 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
4103
4104 /// \brief Narrows PointerType (and similar) matchers to those where the
4105 /// \c pointee matches a given matcher.
4106 ///
4107 /// Given
4108 /// \code
4109 /// int *a;
4110 /// int const *b;
4111 /// float const *f;
4112 /// \endcode
4113 /// pointerType(pointee(isConstQualified(), isInteger()))
4114 /// matches "int const *b"
4115 ///
4116 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
4117 /// Matcher<PointerType>, Matcher<ReferenceType>
4118 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee,
4119 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType,
4120 MemberPointerType,
4121 PointerType,
4122 ReferenceType));
4123
4124 /// \brief Matches typedef types.
4125 ///
4126 /// Given
4127 /// \code
4128 /// typedef int X;
4129 /// \endcode
4130 /// typedefType()
4131 /// matches "typedef int X"
4132 AST_TYPE_MATCHER(TypedefType, typedefType);
4133
4134 /// \brief Matches template specialization types.
4135 ///
4136 /// Given
4137 /// \code
4138 /// template <typename T>
4139 /// class C { };
4140 ///
4141 /// template class C<int>; // A
4142 /// C<char> var; // B
4143 /// \endcode
4144 ///
4145 /// \c templateSpecializationType() matches the type of the explicit
4146 /// instantiation in \c A and the type of the variable declaration in \c B.
4147 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
4148
4149 /// \brief Matches types nodes representing unary type transformations.
4150 ///
4151 /// Given:
4152 /// \code
4153 /// typedef __underlying_type(T) type;
4154 /// \endcode
4155 /// unaryTransformType()
4156 /// matches "__underlying_type(T)"
4157 AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType);
4158
4159 /// \brief Matches record types (e.g. structs, classes).
4160 ///
4161 /// Given
4162 /// \code
4163 /// class C {};
4164 /// struct S {};
4165 ///
4166 /// C c;
4167 /// S s;
4168 /// \endcode
4169 ///
4170 /// \c recordType() matches the type of the variable declarations of both \c c
4171 /// and \c s.
4172 AST_TYPE_MATCHER(RecordType, recordType);
4173
4174 /// \brief Matches types specified with an elaborated type keyword or with a
4175 /// qualified name.
4176 ///
4177 /// Given
4178 /// \code
4179 /// namespace N {
4180 /// namespace M {
4181 /// class D {};
4182 /// }
4183 /// }
4184 /// class C {};
4185 ///
4186 /// class C c;
4187 /// N::M::D d;
4188 /// \endcode
4189 ///
4190 /// \c elaboratedType() matches the type of the variable declarations of both
4191 /// \c c and \c d.
4192 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
4193
4194 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
4195 /// matches \c InnerMatcher if the qualifier exists.
4196 ///
4197 /// Given
4198 /// \code
4199 /// namespace N {
4200 /// namespace M {
4201 /// class D {};
4202 /// }
4203 /// }
4204 /// N::M::D d;
4205 /// \endcode
4206 ///
4207 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
4208 /// matches the type of the variable declaration of \c d.
AST_MATCHER_P(ElaboratedType,hasQualifier,internal::Matcher<NestedNameSpecifier>,InnerMatcher)4209 AST_MATCHER_P(ElaboratedType, hasQualifier,
4210 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
4211 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
4212 return InnerMatcher.matches(*Qualifier, Finder, Builder);
4213
4214 return false;
4215 }
4216
4217 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
4218 ///
4219 /// Given
4220 /// \code
4221 /// namespace N {
4222 /// namespace M {
4223 /// class D {};
4224 /// }
4225 /// }
4226 /// N::M::D d;
4227 /// \endcode
4228 ///
4229 /// \c elaboratedType(namesType(recordType(
4230 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
4231 /// declaration of \c d.
AST_MATCHER_P(ElaboratedType,namesType,internal::Matcher<QualType>,InnerMatcher)4232 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
4233 InnerMatcher) {
4234 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
4235 }
4236
4237 /// \brief Matches types that represent the result of substituting a type for a
4238 /// template type parameter.
4239 ///
4240 /// Given
4241 /// \code
4242 /// template <typename T>
4243 /// void F(T t) {
4244 /// int i = 1 + t;
4245 /// }
4246 /// \endcode
4247 ///
4248 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
4249 AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType);
4250
4251 /// \brief Matches template type parameter types.
4252 ///
4253 /// Example matches T, but not int.
4254 /// (matcher = templateTypeParmType())
4255 /// \code
4256 /// template <typename T> void f(int i);
4257 /// \endcode
4258 AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType);
4259
4260 /// \brief Matches injected class name types.
4261 ///
4262 /// Example matches S s, but not S<T> s.
4263 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
4264 /// \code
4265 /// template <typename T> struct S {
4266 /// void f(S s);
4267 /// void g(S<T> s);
4268 /// };
4269 /// \endcode
4270 AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType);
4271
4272 /// \brief Matches decayed type
4273 /// Example matches i[] in declaration of f.
4274 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
4275 /// Example matches i[1].
4276 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
4277 /// \code
4278 /// void f(int i[]) {
4279 /// i[1] = 0;
4280 /// }
4281 /// \endcode
4282 AST_TYPE_MATCHER(DecayedType, decayedType);
4283
4284 /// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher
AST_MATCHER_P(DecayedType,hasDecayedType,internal::Matcher<QualType>,InnerType)4285 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
4286 InnerType) {
4287 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
4288 }
4289
4290 /// \brief Matches declarations whose declaration context, interpreted as a
4291 /// Decl, matches \c InnerMatcher.
4292 ///
4293 /// Given
4294 /// \code
4295 /// namespace N {
4296 /// namespace M {
4297 /// class D {};
4298 /// }
4299 /// }
4300 /// \endcode
4301 ///
4302 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
4303 /// declaration of \c class \c D.
AST_MATCHER_P(Decl,hasDeclContext,internal::Matcher<Decl>,InnerMatcher)4304 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
4305 const DeclContext *DC = Node.getDeclContext();
4306 if (!DC) return false;
4307 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
4308 }
4309
4310 /// \brief Matches nested name specifiers.
4311 ///
4312 /// Given
4313 /// \code
4314 /// namespace ns {
4315 /// struct A { static void f(); };
4316 /// void A::f() {}
4317 /// void g() { A::f(); }
4318 /// }
4319 /// ns::A a;
4320 /// \endcode
4321 /// nestedNameSpecifier()
4322 /// matches "ns::" and both "A::"
4323 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
4324
4325 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
4326 const internal::VariadicAllOfMatcher<
4327 NestedNameSpecifierLoc> nestedNameSpecifierLoc;
4328
4329 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
4330 /// NestedNameSpecifier-matcher matches.
4331 AST_MATCHER_FUNCTION_P_OVERLOAD(
4332 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
4333 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
4334 return internal::BindableMatcher<NestedNameSpecifierLoc>(
4335 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
4336 InnerMatcher));
4337 }
4338
4339 /// \brief Matches nested name specifiers that specify a type matching the
4340 /// given \c QualType matcher without qualifiers.
4341 ///
4342 /// Given
4343 /// \code
4344 /// struct A { struct B { struct C {}; }; };
4345 /// A::B::C c;
4346 /// \endcode
4347 /// nestedNameSpecifier(specifiesType(
4348 /// hasDeclaration(cxxRecordDecl(hasName("A")))
4349 /// ))
4350 /// matches "A::"
AST_MATCHER_P(NestedNameSpecifier,specifiesType,internal::Matcher<QualType>,InnerMatcher)4351 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
4352 internal::Matcher<QualType>, InnerMatcher) {
4353 if (!Node.getAsType())
4354 return false;
4355 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
4356 }
4357
4358 /// \brief Matches nested name specifier locs that specify a type matching the
4359 /// given \c TypeLoc.
4360 ///
4361 /// Given
4362 /// \code
4363 /// struct A { struct B { struct C {}; }; };
4364 /// A::B::C c;
4365 /// \endcode
4366 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
4367 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
4368 /// matches "A::"
AST_MATCHER_P(NestedNameSpecifierLoc,specifiesTypeLoc,internal::Matcher<TypeLoc>,InnerMatcher)4369 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
4370 internal::Matcher<TypeLoc>, InnerMatcher) {
4371 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
4372 }
4373
4374 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
4375 ///
4376 /// Given
4377 /// \code
4378 /// struct A { struct B { struct C {}; }; };
4379 /// A::B::C c;
4380 /// \endcode
4381 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
4382 /// matches "A::"
4383 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
4384 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
4385 0) {
4386 const NestedNameSpecifier *NextNode = Node.getPrefix();
4387 if (!NextNode)
4388 return false;
4389 return InnerMatcher.matches(*NextNode, Finder, Builder);
4390 }
4391
4392 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
4393 ///
4394 /// Given
4395 /// \code
4396 /// struct A { struct B { struct C {}; }; };
4397 /// A::B::C c;
4398 /// \endcode
4399 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
4400 /// matches "A::"
4401 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
4402 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
4403 1) {
4404 NestedNameSpecifierLoc NextNode = Node.getPrefix();
4405 if (!NextNode)
4406 return false;
4407 return InnerMatcher.matches(NextNode, Finder, Builder);
4408 }
4409
4410 /// \brief Matches nested name specifiers that specify a namespace matching the
4411 /// given namespace matcher.
4412 ///
4413 /// Given
4414 /// \code
4415 /// namespace ns { struct A {}; }
4416 /// ns::A a;
4417 /// \endcode
4418 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
4419 /// matches "ns::"
AST_MATCHER_P(NestedNameSpecifier,specifiesNamespace,internal::Matcher<NamespaceDecl>,InnerMatcher)4420 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
4421 internal::Matcher<NamespaceDecl>, InnerMatcher) {
4422 if (!Node.getAsNamespace())
4423 return false;
4424 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
4425 }
4426
4427 /// \brief Overloads for the \c equalsNode matcher.
4428 /// FIXME: Implement for other node types.
4429 /// @{
4430
4431 /// \brief Matches if a node equals another node.
4432 ///
4433 /// \c Decl has pointer identity in the AST.
4434 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
4435 return &Node == Other;
4436 }
4437 /// \brief Matches if a node equals another node.
4438 ///
4439 /// \c Stmt has pointer identity in the AST.
4440 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
4441 return &Node == Other;
4442 }
4443 /// \brief Matches if a node equals another node.
4444 ///
4445 /// \c Type has pointer identity in the AST.
4446 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
4447 return &Node == Other;
4448 }
4449
4450 /// @}
4451
4452 /// \brief Matches each case or default statement belonging to the given switch
4453 /// statement. This matcher may produce multiple matches.
4454 ///
4455 /// Given
4456 /// \code
4457 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
4458 /// \endcode
4459 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
4460 /// matches four times, with "c" binding each of "case 1:", "case 2:",
4461 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
4462 /// "switch (1)", "switch (2)" and "switch (2)".
AST_MATCHER_P(SwitchStmt,forEachSwitchCase,internal::Matcher<SwitchCase>,InnerMatcher)4463 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
4464 InnerMatcher) {
4465 BoundNodesTreeBuilder Result;
4466 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
4467 // iteration order. We should use the more general iterating matchers once
4468 // they are capable of expressing this matcher (for example, it should ignore
4469 // case statements belonging to nested switch statements).
4470 bool Matched = false;
4471 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
4472 SC = SC->getNextSwitchCase()) {
4473 BoundNodesTreeBuilder CaseBuilder(*Builder);
4474 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
4475 if (CaseMatched) {
4476 Matched = true;
4477 Result.addMatch(CaseBuilder);
4478 }
4479 }
4480 *Builder = std::move(Result);
4481 return Matched;
4482 }
4483
4484 /// \brief Matches each constructor initializer in a constructor definition.
4485 ///
4486 /// Given
4487 /// \code
4488 /// class A { A() : i(42), j(42) {} int i; int j; };
4489 /// \endcode
4490 /// cxxConstructorDecl(forEachConstructorInitializer(
4491 /// forField(decl().bind("x"))
4492 /// ))
4493 /// will trigger two matches, binding for 'i' and 'j' respectively.
AST_MATCHER_P(CXXConstructorDecl,forEachConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)4494 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
4495 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4496 BoundNodesTreeBuilder Result;
4497 bool Matched = false;
4498 for (const auto *I : Node.inits()) {
4499 BoundNodesTreeBuilder InitBuilder(*Builder);
4500 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
4501 Matched = true;
4502 Result.addMatch(InitBuilder);
4503 }
4504 }
4505 *Builder = std::move(Result);
4506 return Matched;
4507 }
4508
4509 /// \brief Matches constructor declarations that are copy constructors.
4510 ///
4511 /// Given
4512 /// \code
4513 /// struct S {
4514 /// S(); // #1
4515 /// S(const S &); // #2
4516 /// S(S &&); // #3
4517 /// };
4518 /// \endcode
4519 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
AST_MATCHER(CXXConstructorDecl,isCopyConstructor)4520 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
4521 return Node.isCopyConstructor();
4522 }
4523
4524 /// \brief Matches constructor declarations that are move constructors.
4525 ///
4526 /// Given
4527 /// \code
4528 /// struct S {
4529 /// S(); // #1
4530 /// S(const S &); // #2
4531 /// S(S &&); // #3
4532 /// };
4533 /// \endcode
4534 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
AST_MATCHER(CXXConstructorDecl,isMoveConstructor)4535 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
4536 return Node.isMoveConstructor();
4537 }
4538
4539 /// \brief Matches constructor declarations that are default constructors.
4540 ///
4541 /// Given
4542 /// \code
4543 /// struct S {
4544 /// S(); // #1
4545 /// S(const S &); // #2
4546 /// S(S &&); // #3
4547 /// };
4548 /// \endcode
4549 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
AST_MATCHER(CXXConstructorDecl,isDefaultConstructor)4550 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
4551 return Node.isDefaultConstructor();
4552 }
4553
4554 /// \brief Matches constructor and conversion declarations that are marked with
4555 /// the explicit keyword.
4556 ///
4557 /// Given
4558 /// \code
4559 /// struct S {
4560 /// S(int); // #1
4561 /// explicit S(double); // #2
4562 /// operator int(); // #3
4563 /// explicit operator bool(); // #4
4564 /// };
4565 /// \endcode
4566 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
4567 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
AST_POLYMORPHIC_MATCHER(isExplicit,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXConstructorDecl,CXXConversionDecl))4568 AST_POLYMORPHIC_MATCHER(isExplicit,
4569 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
4570 CXXConversionDecl)) {
4571 return Node.isExplicit();
4572 }
4573
4574 /// \brief Matches function and namespace declarations that are marked with
4575 /// the inline keyword.
4576 ///
4577 /// Given
4578 /// \code
4579 /// inline void f();
4580 /// void g();
4581 /// namespace n {
4582 /// inline namespace m {}
4583 /// }
4584 /// \endcode
4585 /// functionDecl(isInline()) will match ::f().
4586 /// namespaceDecl(isInline()) will match n::m.
AST_POLYMORPHIC_MATCHER(isInline,AST_POLYMORPHIC_SUPPORTED_TYPES (NamespaceDecl,FunctionDecl))4587 AST_POLYMORPHIC_MATCHER(isInline,
4588 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
4589 FunctionDecl)) {
4590 // This is required because the spelling of the function used to determine
4591 // whether inline is specified or not differs between the polymorphic types.
4592 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
4593 return FD->isInlineSpecified();
4594 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
4595 return NSD->isInline();
4596 llvm_unreachable("Not a valid polymorphic type");
4597 }
4598
4599 /// \brief Matches anonymous namespace declarations.
4600 ///
4601 /// Given
4602 /// \code
4603 /// namespace n {
4604 /// namespace {} // #1
4605 /// }
4606 /// \endcode
4607 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
AST_MATCHER(NamespaceDecl,isAnonymous)4608 AST_MATCHER(NamespaceDecl, isAnonymous) {
4609 return Node.isAnonymousNamespace();
4610 }
4611
4612 /// \brief If the given case statement does not use the GNU case range
4613 /// extension, matches the constant given in the statement.
4614 ///
4615 /// Given
4616 /// \code
4617 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
4618 /// \endcode
4619 /// caseStmt(hasCaseConstant(integerLiteral()))
4620 /// matches "case 1:"
AST_MATCHER_P(CaseStmt,hasCaseConstant,internal::Matcher<Expr>,InnerMatcher)4621 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
4622 InnerMatcher) {
4623 if (Node.getRHS())
4624 return false;
4625
4626 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
4627 }
4628
4629 /// \brief Matches declaration that has a given attribute.
4630 ///
4631 /// Given
4632 /// \code
4633 /// __attribute__((device)) void f() { ... }
4634 /// \endcode
4635 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
4636 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
4637 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
AST_MATCHER_P(Decl,hasAttr,attr::Kind,AttrKind)4638 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
4639 for (const auto *Attr : Node.attrs()) {
4640 if (Attr->getKind() == AttrKind)
4641 return true;
4642 }
4643 return false;
4644 }
4645
4646 /// \brief Matches CUDA kernel call expression.
4647 ///
4648 /// Example matches,
4649 /// \code
4650 /// kernel<<<i,j>>>();
4651 /// \endcode
4652 const internal::VariadicDynCastAllOfMatcher<
4653 Stmt,
4654 CUDAKernelCallExpr> cudaKernelCallExpr;
4655
4656 } // end namespace ast_matchers
4657 } // end namespace clang
4658
4659 #endif
4660