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