1 //===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements matchers to be used together with the MatchFinder to
11 // match AST nodes.
12 //
13 // Matchers are created by generator functions, which can be combined in
14 // a functional in-language DSL to express queries over the C++ AST.
15 //
16 // For example, to match a class with a certain name, one would call:
17 // cxxRecordDecl(hasName("MyClass"))
18 // which returns a matcher that can be used to find all AST nodes that declare
19 // a class named 'MyClass'.
20 //
21 // For more complicated match expressions we're often interested in accessing
22 // multiple parts of the matched AST nodes once a match is found. In that case,
23 // use the id(...) matcher around the match expressions that match the nodes
24 // you want to access.
25 //
26 // For example, when we're interested in child classes of a certain class, we
27 // would write:
28 // cxxRecordDecl(hasName("MyClass"), has(id("child", recordDecl())))
29 // When the match is found via the MatchFinder, a user provided callback will
30 // be called with a BoundNodes instance that contains a mapping from the
31 // strings that we provided for the id(...) calls to the nodes that were
32 // matched.
33 // In the given example, each time our matcher finds a match we get a callback
34 // where "child" is bound to the RecordDecl node of the matching child
35 // class declaration.
36 //
37 // See ASTMatchersInternal.h for a more in-depth explanation of the
38 // implementation details of the matcher framework.
39 //
40 // See ASTMatchFinder.h for how to use the generated matchers to run over
41 // an AST.
42 //
43 //===----------------------------------------------------------------------===//
44
45 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
46 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
47
48 #include "clang/AST/ASTContext.h"
49 #include "clang/AST/ASTTypeTraits.h"
50 #include "clang/AST/Attr.h"
51 #include "clang/AST/Decl.h"
52 #include "clang/AST/DeclCXX.h"
53 #include "clang/AST/DeclFriend.h"
54 #include "clang/AST/DeclObjC.h"
55 #include "clang/AST/DeclTemplate.h"
56 #include "clang/AST/Expr.h"
57 #include "clang/AST/ExprCXX.h"
58 #include "clang/AST/ExprObjC.h"
59 #include "clang/AST/NestedNameSpecifier.h"
60 #include "clang/AST/OperationKinds.h"
61 #include "clang/AST/Stmt.h"
62 #include "clang/AST/StmtCXX.h"
63 #include "clang/AST/StmtObjC.h"
64 #include "clang/AST/TemplateBase.h"
65 #include "clang/AST/TemplateName.h"
66 #include "clang/AST/Type.h"
67 #include "clang/AST/TypeLoc.h"
68 #include "clang/ASTMatchers/ASTMatchersInternal.h"
69 #include "clang/ASTMatchers/ASTMatchersMacros.h"
70 #include "clang/Basic/AttrKinds.h"
71 #include "clang/Basic/ExceptionSpecificationType.h"
72 #include "clang/Basic/IdentifierTable.h"
73 #include "clang/Basic/LLVM.h"
74 #include "clang/Basic/SourceManager.h"
75 #include "clang/Basic/Specifiers.h"
76 #include "clang/Basic/TypeTraits.h"
77 #include "llvm/ADT/ArrayRef.h"
78 #include "llvm/ADT/SmallVector.h"
79 #include "llvm/ADT/StringRef.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/Regex.h"
84 #include <cassert>
85 #include <cstddef>
86 #include <iterator>
87 #include <limits>
88 #include <string>
89 #include <utility>
90 #include <vector>
91
92 namespace clang {
93 namespace ast_matchers {
94
95 /// Maps string IDs to AST nodes matched by parts of a matcher.
96 ///
97 /// The bound nodes are generated by calling \c bind("id") on the node matchers
98 /// of the nodes we want to access later.
99 ///
100 /// The instances of BoundNodes are created by \c MatchFinder when the user's
101 /// callbacks are executed every time a match is found.
102 class BoundNodes {
103 public:
104 /// Returns the AST node bound to \c ID.
105 ///
106 /// Returns NULL if there was no node bound to \c ID or if there is a node but
107 /// it cannot be converted to the specified type.
108 template <typename T>
getNodeAs(StringRef ID)109 const T *getNodeAs(StringRef ID) const {
110 return MyBoundNodes.getNodeAs<T>(ID);
111 }
112
113 /// Type of mapping from binding identifiers to bound nodes. This type
114 /// is an associative container with a key type of \c std::string and a value
115 /// type of \c clang::ast_type_traits::DynTypedNode
116 using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
117
118 /// Retrieve mapping from binding identifiers to bound nodes.
getMap()119 const IDToNodeMap &getMap() const {
120 return MyBoundNodes.getMap();
121 }
122
123 private:
124 friend class internal::BoundNodesTreeBuilder;
125
126 /// Create BoundNodes from a pre-filled map of bindings.
BoundNodes(internal::BoundNodesMap & MyBoundNodes)127 BoundNodes(internal::BoundNodesMap &MyBoundNodes)
128 : MyBoundNodes(MyBoundNodes) {}
129
130 internal::BoundNodesMap MyBoundNodes;
131 };
132
133 /// If the provided matcher matches a node, binds the node to \c ID.
134 ///
135 /// FIXME: Do we want to support this now that we have bind()?
136 template <typename T>
id(StringRef ID,const internal::BindableMatcher<T> & InnerMatcher)137 internal::Matcher<T> id(StringRef ID,
138 const internal::BindableMatcher<T> &InnerMatcher) {
139 return InnerMatcher.bind(ID);
140 }
141
142 /// Types of matchers for the top-level classes in the AST class
143 /// hierarchy.
144 /// @{
145 using DeclarationMatcher = internal::Matcher<Decl>;
146 using StatementMatcher = internal::Matcher<Stmt>;
147 using TypeMatcher = internal::Matcher<QualType>;
148 using TypeLocMatcher = internal::Matcher<TypeLoc>;
149 using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
150 using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
151 using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
152 /// @}
153
154 /// Matches any node.
155 ///
156 /// Useful when another matcher requires a child matcher, but there's no
157 /// additional constraint. This will often be used with an explicit conversion
158 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
159 ///
160 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
161 /// \code
162 /// "int* p" and "void f()" in
163 /// int* p;
164 /// void f();
165 /// \endcode
166 ///
167 /// Usable as: Any Matcher
anything()168 inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
169
170 /// Matches the top declaration context.
171 ///
172 /// Given
173 /// \code
174 /// int X;
175 /// namespace NS {
176 /// int Y;
177 /// } // namespace NS
178 /// \endcode
179 /// decl(hasDeclContext(translationUnitDecl()))
180 /// matches "int X", but not "int Y".
181 extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
182 translationUnitDecl;
183
184 /// Matches typedef declarations.
185 ///
186 /// Given
187 /// \code
188 /// typedef int X;
189 /// using Y = int;
190 /// \endcode
191 /// typedefDecl()
192 /// matches "typedef int X", but not "using Y = int"
193 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
194 typedefDecl;
195
196 /// Matches typedef name declarations.
197 ///
198 /// Given
199 /// \code
200 /// typedef int X;
201 /// using Y = int;
202 /// \endcode
203 /// typedefNameDecl()
204 /// matches "typedef int X" and "using Y = int"
205 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
206 typedefNameDecl;
207
208 /// Matches type alias declarations.
209 ///
210 /// Given
211 /// \code
212 /// typedef int X;
213 /// using Y = int;
214 /// \endcode
215 /// typeAliasDecl()
216 /// matches "using Y = int", but not "typedef int X"
217 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
218 typeAliasDecl;
219
220 /// Matches type alias template declarations.
221 ///
222 /// typeAliasTemplateDecl() matches
223 /// \code
224 /// template <typename T>
225 /// using Y = X<T>;
226 /// \endcode
227 extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
228 typeAliasTemplateDecl;
229
230 /// Matches AST nodes that were expanded within the main-file.
231 ///
232 /// Example matches X but not Y
233 /// (matcher = cxxRecordDecl(isExpansionInMainFile())
234 /// \code
235 /// #include <Y.h>
236 /// class X {};
237 /// \endcode
238 /// Y.h:
239 /// \code
240 /// class Y {};
241 /// \endcode
242 ///
243 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc))244 AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
245 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
246 auto &SourceManager = Finder->getASTContext().getSourceManager();
247 return SourceManager.isInMainFile(
248 SourceManager.getExpansionLoc(Node.getLocStart()));
249 }
250
251 /// Matches AST nodes that were expanded within system-header-files.
252 ///
253 /// Example matches Y but not X
254 /// (matcher = cxxRecordDecl(isExpansionInSystemHeader())
255 /// \code
256 /// #include <SystemHeader.h>
257 /// class X {};
258 /// \endcode
259 /// SystemHeader.h:
260 /// \code
261 /// class Y {};
262 /// \endcode
263 ///
264 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc))265 AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
266 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
267 auto &SourceManager = Finder->getASTContext().getSourceManager();
268 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
269 if (ExpansionLoc.isInvalid()) {
270 return false;
271 }
272 return SourceManager.isInSystemHeader(ExpansionLoc);
273 }
274
275 /// Matches AST nodes that were expanded within files whose name is
276 /// partially matching a given regex.
277 ///
278 /// Example matches Y but not X
279 /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
280 /// \code
281 /// #include "ASTMatcher.h"
282 /// class X {};
283 /// \endcode
284 /// ASTMatcher.h:
285 /// \code
286 /// class Y {};
287 /// \endcode
288 ///
289 /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,AST_POLYMORPHIC_SUPPORTED_TYPES (Decl,Stmt,TypeLoc),std::string,RegExp)290 AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching,
291 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
292 std::string, RegExp) {
293 auto &SourceManager = Finder->getASTContext().getSourceManager();
294 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart());
295 if (ExpansionLoc.isInvalid()) {
296 return false;
297 }
298 auto FileEntry =
299 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
300 if (!FileEntry) {
301 return false;
302 }
303
304 auto Filename = FileEntry->getName();
305 llvm::Regex RE(RegExp);
306 return RE.match(Filename);
307 }
308
309 /// Matches declarations.
310 ///
311 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
312 /// \code
313 /// void X();
314 /// class C {
315 /// friend X;
316 /// };
317 /// \endcode
318 extern const internal::VariadicAllOfMatcher<Decl> decl;
319
320 /// Matches a declaration of a linkage specification.
321 ///
322 /// Given
323 /// \code
324 /// extern "C" {}
325 /// \endcode
326 /// linkageSpecDecl()
327 /// matches "extern "C" {}"
328 extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
329 linkageSpecDecl;
330
331 /// Matches a declaration of anything that could have a name.
332 ///
333 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
334 /// \code
335 /// typedef int X;
336 /// struct S {
337 /// union {
338 /// int i;
339 /// } U;
340 /// };
341 /// \endcode
342 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
343
344 /// Matches a declaration of label.
345 ///
346 /// Given
347 /// \code
348 /// goto FOO;
349 /// FOO: bar();
350 /// \endcode
351 /// labelDecl()
352 /// matches 'FOO:'
353 extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
354
355 /// Matches a declaration of a namespace.
356 ///
357 /// Given
358 /// \code
359 /// namespace {}
360 /// namespace test {}
361 /// \endcode
362 /// namespaceDecl()
363 /// matches "namespace {}" and "namespace test {}"
364 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
365 namespaceDecl;
366
367 /// Matches a declaration of a namespace alias.
368 ///
369 /// Given
370 /// \code
371 /// namespace test {}
372 /// namespace alias = ::test;
373 /// \endcode
374 /// namespaceAliasDecl()
375 /// matches "namespace alias" but not "namespace test"
376 extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
377 namespaceAliasDecl;
378
379 /// Matches class, struct, and union declarations.
380 ///
381 /// Example matches \c X, \c Z, \c U, and \c S
382 /// \code
383 /// class X;
384 /// template<class T> class Z {};
385 /// struct S {};
386 /// union U {};
387 /// \endcode
388 extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
389
390 /// Matches C++ class declarations.
391 ///
392 /// Example matches \c X, \c Z
393 /// \code
394 /// class X;
395 /// template<class T> class Z {};
396 /// \endcode
397 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
398 cxxRecordDecl;
399
400 /// Matches C++ class template declarations.
401 ///
402 /// Example matches \c Z
403 /// \code
404 /// template<class T> class Z {};
405 /// \endcode
406 extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
407 classTemplateDecl;
408
409 /// Matches C++ class template specializations.
410 ///
411 /// Given
412 /// \code
413 /// template<typename T> class A {};
414 /// template<> class A<double> {};
415 /// A<int> a;
416 /// \endcode
417 /// classTemplateSpecializationDecl()
418 /// matches the specializations \c A<int> and \c A<double>
419 extern const internal::VariadicDynCastAllOfMatcher<
420 Decl, ClassTemplateSpecializationDecl>
421 classTemplateSpecializationDecl;
422
423 /// Matches declarator declarations (field, variable, function
424 /// and non-type template parameter declarations).
425 ///
426 /// Given
427 /// \code
428 /// class X { int y; };
429 /// \endcode
430 /// declaratorDecl()
431 /// matches \c int y.
432 extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
433 declaratorDecl;
434
435 /// Matches parameter variable declarations.
436 ///
437 /// Given
438 /// \code
439 /// void f(int x);
440 /// \endcode
441 /// parmVarDecl()
442 /// matches \c int x.
443 extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
444 parmVarDecl;
445
446 /// Matches C++ access specifier declarations.
447 ///
448 /// Given
449 /// \code
450 /// class C {
451 /// public:
452 /// int a;
453 /// };
454 /// \endcode
455 /// accessSpecDecl()
456 /// matches 'public:'
457 extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
458 accessSpecDecl;
459
460 /// Matches constructor initializers.
461 ///
462 /// Examples matches \c i(42).
463 /// \code
464 /// class C {
465 /// C() : i(42) {}
466 /// int i;
467 /// };
468 /// \endcode
469 extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
470 cxxCtorInitializer;
471
472 /// Matches template arguments.
473 ///
474 /// Given
475 /// \code
476 /// template <typename T> struct C {};
477 /// C<int> c;
478 /// \endcode
479 /// templateArgument()
480 /// matches 'int' in C<int>.
481 extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
482
483 /// Matches template name.
484 ///
485 /// Given
486 /// \code
487 /// template <typename T> class X { };
488 /// X<int> xi;
489 /// \endcode
490 /// templateName()
491 /// matches 'X' in X<int>.
492 extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
493
494 /// Matches non-type template parameter declarations.
495 ///
496 /// Given
497 /// \code
498 /// template <typename T, int N> struct C {};
499 /// \endcode
500 /// nonTypeTemplateParmDecl()
501 /// matches 'N', but not 'T'.
502 extern const internal::VariadicDynCastAllOfMatcher<Decl,
503 NonTypeTemplateParmDecl>
504 nonTypeTemplateParmDecl;
505
506 /// Matches template type parameter declarations.
507 ///
508 /// Given
509 /// \code
510 /// template <typename T, int N> struct C {};
511 /// \endcode
512 /// templateTypeParmDecl()
513 /// matches 'T', but not 'N'.
514 extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
515 templateTypeParmDecl;
516
517 /// Matches public C++ declarations.
518 ///
519 /// Given
520 /// \code
521 /// class C {
522 /// public: int a;
523 /// protected: int b;
524 /// private: int c;
525 /// };
526 /// \endcode
527 /// fieldDecl(isPublic())
528 /// matches 'int a;'
AST_MATCHER(Decl,isPublic)529 AST_MATCHER(Decl, isPublic) {
530 return Node.getAccess() == AS_public;
531 }
532
533 /// Matches protected C++ declarations.
534 ///
535 /// Given
536 /// \code
537 /// class C {
538 /// public: int a;
539 /// protected: int b;
540 /// private: int c;
541 /// };
542 /// \endcode
543 /// fieldDecl(isProtected())
544 /// matches 'int b;'
AST_MATCHER(Decl,isProtected)545 AST_MATCHER(Decl, isProtected) {
546 return Node.getAccess() == AS_protected;
547 }
548
549 /// Matches private C++ declarations.
550 ///
551 /// Given
552 /// \code
553 /// class C {
554 /// public: int a;
555 /// protected: int b;
556 /// private: int c;
557 /// };
558 /// \endcode
559 /// fieldDecl(isPrivate())
560 /// matches 'int c;'
AST_MATCHER(Decl,isPrivate)561 AST_MATCHER(Decl, isPrivate) {
562 return Node.getAccess() == AS_private;
563 }
564
565 /// Matches non-static data members that are bit-fields.
566 ///
567 /// Given
568 /// \code
569 /// class C {
570 /// int a : 2;
571 /// int b;
572 /// };
573 /// \endcode
574 /// fieldDecl(isBitField())
575 /// matches 'int a;' but not 'int b;'.
AST_MATCHER(FieldDecl,isBitField)576 AST_MATCHER(FieldDecl, isBitField) {
577 return Node.isBitField();
578 }
579
580 /// Matches non-static data members that are bit-fields of the specified
581 /// bit width.
582 ///
583 /// Given
584 /// \code
585 /// class C {
586 /// int a : 2;
587 /// int b : 4;
588 /// int c : 2;
589 /// };
590 /// \endcode
591 /// fieldDecl(hasBitWidth(2))
592 /// matches 'int a;' and 'int c;' but not 'int b;'.
AST_MATCHER_P(FieldDecl,hasBitWidth,unsigned,Width)593 AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
594 return Node.isBitField() &&
595 Node.getBitWidthValue(Finder->getASTContext()) == Width;
596 }
597
598 /// Matches non-static data members that have an in-class initializer.
599 ///
600 /// Given
601 /// \code
602 /// class C {
603 /// int a = 2;
604 /// int b = 3;
605 /// int c;
606 /// };
607 /// \endcode
608 /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
609 /// matches 'int a;' but not 'int b;'.
610 /// fieldDecl(hasInClassInitializer(anything()))
611 /// matches 'int a;' and 'int b;' but not 'int c;'.
AST_MATCHER_P(FieldDecl,hasInClassInitializer,internal::Matcher<Expr>,InnerMatcher)612 AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
613 InnerMatcher) {
614 const Expr *Initializer = Node.getInClassInitializer();
615 return (Initializer != nullptr &&
616 InnerMatcher.matches(*Initializer, Finder, Builder));
617 }
618
619 /// Determines whether the function is "main", which is the entry point
620 /// into an executable program.
AST_MATCHER(FunctionDecl,isMain)621 AST_MATCHER(FunctionDecl, isMain) {
622 return Node.isMain();
623 }
624
625 /// Matches the specialized template of a specialization declaration.
626 ///
627 /// Given
628 /// \code
629 /// tempalate<typename T> class A {};
630 /// typedef A<int> B;
631 /// \endcode
632 /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
633 /// matches 'B' with classTemplateDecl() matching the class template
634 /// declaration of 'A'.
AST_MATCHER_P(ClassTemplateSpecializationDecl,hasSpecializedTemplate,internal::Matcher<ClassTemplateDecl>,InnerMatcher)635 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
636 internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
637 const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
638 return (Decl != nullptr &&
639 InnerMatcher.matches(*Decl, Finder, Builder));
640 }
641
642 /// Matches a declaration that has been implicitly added
643 /// by the compiler (eg. implicit default/copy constructors).
AST_MATCHER(Decl,isImplicit)644 AST_MATCHER(Decl, isImplicit) {
645 return Node.isImplicit();
646 }
647
648 /// Matches classTemplateSpecializations, templateSpecializationType and
649 /// functionDecl that have at least one TemplateArgument matching the given
650 /// InnerMatcher.
651 ///
652 /// Given
653 /// \code
654 /// template<typename T> class A {};
655 /// template<> class A<double> {};
656 /// A<int> a;
657 ///
658 /// template<typename T> f() {};
659 /// void func() { f<int>(); };
660 /// \endcode
661 ///
662 /// \endcode
663 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
664 /// refersToType(asString("int"))))
665 /// matches the specialization \c A<int>
666 ///
667 /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
668 /// matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P(hasAnyTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType,FunctionDecl),internal::Matcher<TemplateArgument>,InnerMatcher)669 AST_POLYMORPHIC_MATCHER_P(
670 hasAnyTemplateArgument,
671 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
672 TemplateSpecializationType,
673 FunctionDecl),
674 internal::Matcher<TemplateArgument>, InnerMatcher) {
675 ArrayRef<TemplateArgument> List =
676 internal::getTemplateSpecializationArgs(Node);
677 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
678 Builder);
679 }
680
681 /// Matches expressions that match InnerMatcher after any implicit AST
682 /// nodes are stripped off.
683 ///
684 /// Parentheses and explicit casts are not discarded.
685 /// Given
686 /// \code
687 /// class C {};
688 /// C a = C();
689 /// C b;
690 /// C c = b;
691 /// \endcode
692 /// The matchers
693 /// \code
694 /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
695 /// \endcode
696 /// would match the declarations for a, b, and c.
697 /// While
698 /// \code
699 /// varDecl(hasInitializer(cxxConstructExpr()))
700 /// \endcode
701 /// only match the declarations for b and c.
AST_MATCHER_P(Expr,ignoringImplicit,internal::Matcher<Expr>,InnerMatcher)702 AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
703 InnerMatcher) {
704 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
705 }
706
707 /// Matches expressions that match InnerMatcher after any implicit casts
708 /// are stripped off.
709 ///
710 /// Parentheses and explicit casts are not discarded.
711 /// Given
712 /// \code
713 /// int arr[5];
714 /// int a = 0;
715 /// char b = 0;
716 /// const int c = a;
717 /// int *d = arr;
718 /// long e = (long) 0l;
719 /// \endcode
720 /// The matchers
721 /// \code
722 /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
723 /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
724 /// \endcode
725 /// would match the declarations for a, b, c, and d, but not e.
726 /// While
727 /// \code
728 /// varDecl(hasInitializer(integerLiteral()))
729 /// varDecl(hasInitializer(declRefExpr()))
730 /// \endcode
731 /// only match the declarations for b, c, and d.
AST_MATCHER_P(Expr,ignoringImpCasts,internal::Matcher<Expr>,InnerMatcher)732 AST_MATCHER_P(Expr, ignoringImpCasts,
733 internal::Matcher<Expr>, InnerMatcher) {
734 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
735 }
736
737 /// Matches expressions that match InnerMatcher after parentheses and
738 /// casts are stripped off.
739 ///
740 /// Implicit and non-C Style casts are also discarded.
741 /// Given
742 /// \code
743 /// int a = 0;
744 /// char b = (0);
745 /// void* c = reinterpret_cast<char*>(0);
746 /// char d = char(0);
747 /// \endcode
748 /// The matcher
749 /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
750 /// would match the declarations for a, b, c, and d.
751 /// while
752 /// varDecl(hasInitializer(integerLiteral()))
753 /// only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenCasts,internal::Matcher<Expr>,InnerMatcher)754 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
755 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
756 }
757
758 /// Matches expressions that match InnerMatcher after implicit casts and
759 /// parentheses are stripped off.
760 ///
761 /// Explicit casts are not discarded.
762 /// Given
763 /// \code
764 /// int arr[5];
765 /// int a = 0;
766 /// char b = (0);
767 /// const int c = a;
768 /// int *d = (arr);
769 /// long e = ((long) 0l);
770 /// \endcode
771 /// The matchers
772 /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
773 /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
774 /// would match the declarations for a, b, c, and d, but not e.
775 /// while
776 /// varDecl(hasInitializer(integerLiteral()))
777 /// varDecl(hasInitializer(declRefExpr()))
778 /// would only match the declaration for a.
AST_MATCHER_P(Expr,ignoringParenImpCasts,internal::Matcher<Expr>,InnerMatcher)779 AST_MATCHER_P(Expr, ignoringParenImpCasts,
780 internal::Matcher<Expr>, InnerMatcher) {
781 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
782 }
783
784 /// Matches types that match InnerMatcher after any parens are stripped.
785 ///
786 /// Given
787 /// \code
788 /// void (*fp)(void);
789 /// \endcode
790 /// The matcher
791 /// \code
792 /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
793 /// \endcode
794 /// would match the declaration for fp.
AST_MATCHER_P(QualType,ignoringParens,internal::Matcher<QualType>,InnerMatcher)795 AST_MATCHER_P(QualType, ignoringParens,
796 internal::Matcher<QualType>, InnerMatcher) {
797 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
798 }
799
800 /// Matches classTemplateSpecializations, templateSpecializationType and
801 /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
802 ///
803 /// Given
804 /// \code
805 /// template<typename T, typename U> class A {};
806 /// A<bool, int> b;
807 /// A<int, bool> c;
808 ///
809 /// template<typename T> void f() {}
810 /// void func() { f<int>(); };
811 /// \endcode
812 /// classTemplateSpecializationDecl(hasTemplateArgument(
813 /// 1, refersToType(asString("int"))))
814 /// matches the specialization \c A<bool, int>
815 ///
816 /// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
817 /// matches the specialization \c f<int>
AST_POLYMORPHIC_MATCHER_P2(hasTemplateArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType,FunctionDecl),unsigned,N,internal::Matcher<TemplateArgument>,InnerMatcher)818 AST_POLYMORPHIC_MATCHER_P2(
819 hasTemplateArgument,
820 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
821 TemplateSpecializationType,
822 FunctionDecl),
823 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
824 ArrayRef<TemplateArgument> List =
825 internal::getTemplateSpecializationArgs(Node);
826 if (List.size() <= N)
827 return false;
828 return InnerMatcher.matches(List[N], Finder, Builder);
829 }
830
831 /// Matches if the number of template arguments equals \p N.
832 ///
833 /// Given
834 /// \code
835 /// template<typename T> struct C {};
836 /// C<int> c;
837 /// \endcode
838 /// classTemplateSpecializationDecl(templateArgumentCountIs(1))
839 /// matches C<int>.
AST_POLYMORPHIC_MATCHER_P(templateArgumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (ClassTemplateSpecializationDecl,TemplateSpecializationType),unsigned,N)840 AST_POLYMORPHIC_MATCHER_P(
841 templateArgumentCountIs,
842 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
843 TemplateSpecializationType),
844 unsigned, N) {
845 return internal::getTemplateSpecializationArgs(Node).size() == N;
846 }
847
848 /// Matches a TemplateArgument that refers to a certain type.
849 ///
850 /// Given
851 /// \code
852 /// struct X {};
853 /// template<typename T> struct A {};
854 /// A<X> a;
855 /// \endcode
856 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
857 /// refersToType(class(hasName("X")))))
858 /// matches the specialization \c A<X>
AST_MATCHER_P(TemplateArgument,refersToType,internal::Matcher<QualType>,InnerMatcher)859 AST_MATCHER_P(TemplateArgument, refersToType,
860 internal::Matcher<QualType>, InnerMatcher) {
861 if (Node.getKind() != TemplateArgument::Type)
862 return false;
863 return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
864 }
865
866 /// Matches a TemplateArgument that refers to a certain template.
867 ///
868 /// Given
869 /// \code
870 /// template<template <typename> class S> class X {};
871 /// template<typename T> class Y {};"
872 /// X<Y> xi;
873 /// \endcode
874 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
875 /// refersToTemplate(templateName())))
876 /// matches the specialization \c X<Y>
AST_MATCHER_P(TemplateArgument,refersToTemplate,internal::Matcher<TemplateName>,InnerMatcher)877 AST_MATCHER_P(TemplateArgument, refersToTemplate,
878 internal::Matcher<TemplateName>, InnerMatcher) {
879 if (Node.getKind() != TemplateArgument::Template)
880 return false;
881 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
882 }
883
884 /// Matches a canonical TemplateArgument that refers to a certain
885 /// declaration.
886 ///
887 /// Given
888 /// \code
889 /// struct B { int next; };
890 /// template<int(B::*next_ptr)> struct A {};
891 /// A<&B::next> a;
892 /// \endcode
893 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
894 /// refersToDeclaration(fieldDecl(hasName("next")))))
895 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
896 /// \c B::next
AST_MATCHER_P(TemplateArgument,refersToDeclaration,internal::Matcher<Decl>,InnerMatcher)897 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
898 internal::Matcher<Decl>, InnerMatcher) {
899 if (Node.getKind() == TemplateArgument::Declaration)
900 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
901 return false;
902 }
903
904 /// Matches a sugar TemplateArgument that refers to a certain expression.
905 ///
906 /// Given
907 /// \code
908 /// struct B { int next; };
909 /// template<int(B::*next_ptr)> struct A {};
910 /// A<&B::next> a;
911 /// \endcode
912 /// templateSpecializationType(hasAnyTemplateArgument(
913 /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
914 /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
915 /// \c B::next
AST_MATCHER_P(TemplateArgument,isExpr,internal::Matcher<Expr>,InnerMatcher)916 AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
917 if (Node.getKind() == TemplateArgument::Expression)
918 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
919 return false;
920 }
921
922 /// Matches a TemplateArgument that is an integral value.
923 ///
924 /// Given
925 /// \code
926 /// template<int T> struct C {};
927 /// C<42> c;
928 /// \endcode
929 /// classTemplateSpecializationDecl(
930 /// hasAnyTemplateArgument(isIntegral()))
931 /// matches the implicit instantiation of C in C<42>
932 /// with isIntegral() matching 42.
AST_MATCHER(TemplateArgument,isIntegral)933 AST_MATCHER(TemplateArgument, isIntegral) {
934 return Node.getKind() == TemplateArgument::Integral;
935 }
936
937 /// Matches a TemplateArgument that referes to an integral type.
938 ///
939 /// Given
940 /// \code
941 /// template<int T> struct C {};
942 /// C<42> c;
943 /// \endcode
944 /// classTemplateSpecializationDecl(
945 /// hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
946 /// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument,refersToIntegralType,internal::Matcher<QualType>,InnerMatcher)947 AST_MATCHER_P(TemplateArgument, refersToIntegralType,
948 internal::Matcher<QualType>, InnerMatcher) {
949 if (Node.getKind() != TemplateArgument::Integral)
950 return false;
951 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
952 }
953
954 /// Matches a TemplateArgument of integral type with a given value.
955 ///
956 /// Note that 'Value' is a string as the template argument's value is
957 /// an arbitrary precision integer. 'Value' must be euqal to the canonical
958 /// representation of that integral value in base 10.
959 ///
960 /// Given
961 /// \code
962 /// template<int T> struct C {};
963 /// C<42> c;
964 /// \endcode
965 /// classTemplateSpecializationDecl(
966 /// hasAnyTemplateArgument(equalsIntegralValue("42")))
967 /// matches the implicit instantiation of C in C<42>.
AST_MATCHER_P(TemplateArgument,equalsIntegralValue,std::string,Value)968 AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
969 std::string, Value) {
970 if (Node.getKind() != TemplateArgument::Integral)
971 return false;
972 return Node.getAsIntegral().toString(10) == Value;
973 }
974
975 /// Matches an Objective-C autorelease pool statement.
976 ///
977 /// Given
978 /// \code
979 /// @autoreleasepool {
980 /// int x = 0;
981 /// }
982 /// \endcode
983 /// autoreleasePoolStmt(stmt()) matches the declaration of "x"
984 /// inside the autorelease pool.
985 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
986 ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
987
988 /// Matches any value declaration.
989 ///
990 /// Example matches A, B, C and F
991 /// \code
992 /// enum X { A, B, C };
993 /// void F();
994 /// \endcode
995 extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
996
997 /// Matches C++ constructor declarations.
998 ///
999 /// Example matches Foo::Foo() and Foo::Foo(int)
1000 /// \code
1001 /// class Foo {
1002 /// public:
1003 /// Foo();
1004 /// Foo(int);
1005 /// int DoSomething();
1006 /// };
1007 /// \endcode
1008 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1009 cxxConstructorDecl;
1010
1011 /// Matches explicit C++ destructor declarations.
1012 ///
1013 /// Example matches Foo::~Foo()
1014 /// \code
1015 /// class Foo {
1016 /// public:
1017 /// virtual ~Foo();
1018 /// };
1019 /// \endcode
1020 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1021 cxxDestructorDecl;
1022
1023 /// Matches enum declarations.
1024 ///
1025 /// Example matches X
1026 /// \code
1027 /// enum X {
1028 /// A, B, C
1029 /// };
1030 /// \endcode
1031 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1032
1033 /// Matches enum constants.
1034 ///
1035 /// Example matches A, B, C
1036 /// \code
1037 /// enum X {
1038 /// A, B, C
1039 /// };
1040 /// \endcode
1041 extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1042 enumConstantDecl;
1043
1044 /// Matches method declarations.
1045 ///
1046 /// Example matches y
1047 /// \code
1048 /// class X { void y(); };
1049 /// \endcode
1050 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1051 cxxMethodDecl;
1052
1053 /// Matches conversion operator declarations.
1054 ///
1055 /// Example matches the operator.
1056 /// \code
1057 /// class X { operator int() const; };
1058 /// \endcode
1059 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1060 cxxConversionDecl;
1061
1062 /// Matches variable declarations.
1063 ///
1064 /// Note: this does not match declarations of member variables, which are
1065 /// "field" declarations in Clang parlance.
1066 ///
1067 /// Example matches a
1068 /// \code
1069 /// int a;
1070 /// \endcode
1071 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1072
1073 /// Matches field declarations.
1074 ///
1075 /// Given
1076 /// \code
1077 /// class X { int m; };
1078 /// \endcode
1079 /// fieldDecl()
1080 /// matches 'm'.
1081 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1082
1083 /// Matches function declarations.
1084 ///
1085 /// Example matches f
1086 /// \code
1087 /// void f();
1088 /// \endcode
1089 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1090 functionDecl;
1091
1092 /// Matches C++ function template declarations.
1093 ///
1094 /// Example matches f
1095 /// \code
1096 /// template<class T> void f(T t) {}
1097 /// \endcode
1098 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1099 functionTemplateDecl;
1100
1101 /// Matches friend declarations.
1102 ///
1103 /// Given
1104 /// \code
1105 /// class X { friend void foo(); };
1106 /// \endcode
1107 /// friendDecl()
1108 /// matches 'friend void foo()'.
1109 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1110
1111 /// Matches statements.
1112 ///
1113 /// Given
1114 /// \code
1115 /// { ++a; }
1116 /// \endcode
1117 /// stmt()
1118 /// matches both the compound statement '{ ++a; }' and '++a'.
1119 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1120
1121 /// Matches declaration statements.
1122 ///
1123 /// Given
1124 /// \code
1125 /// int a;
1126 /// \endcode
1127 /// declStmt()
1128 /// matches 'int a'.
1129 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1130
1131 /// Matches member expressions.
1132 ///
1133 /// Given
1134 /// \code
1135 /// class Y {
1136 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1137 /// int a; static int b;
1138 /// };
1139 /// \endcode
1140 /// memberExpr()
1141 /// matches this->x, x, y.x, a, this->b
1142 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1143
1144 /// Matches call expressions.
1145 ///
1146 /// Example matches x.y() and y()
1147 /// \code
1148 /// X x;
1149 /// x.y();
1150 /// y();
1151 /// \endcode
1152 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1153
1154 /// Matches lambda expressions.
1155 ///
1156 /// Example matches [&](){return 5;}
1157 /// \code
1158 /// [&](){return 5;}
1159 /// \endcode
1160 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1161
1162 /// Matches member call expressions.
1163 ///
1164 /// Example matches x.y()
1165 /// \code
1166 /// X x;
1167 /// x.y();
1168 /// \endcode
1169 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1170 cxxMemberCallExpr;
1171
1172 /// Matches ObjectiveC Message invocation expressions.
1173 ///
1174 /// The innermost message send invokes the "alloc" class method on the
1175 /// NSString class, while the outermost message send invokes the
1176 /// "initWithString" instance method on the object returned from
1177 /// NSString's "alloc". This matcher should match both message sends.
1178 /// \code
1179 /// [[NSString alloc] initWithString:@"Hello"]
1180 /// \endcode
1181 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1182 objcMessageExpr;
1183
1184 /// Matches Objective-C interface declarations.
1185 ///
1186 /// Example matches Foo
1187 /// \code
1188 /// @interface Foo
1189 /// @end
1190 /// \endcode
1191 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1192 objcInterfaceDecl;
1193
1194 /// Matches Objective-C implementation declarations.
1195 ///
1196 /// Example matches Foo
1197 /// \code
1198 /// @implementation Foo
1199 /// @end
1200 /// \endcode
1201 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1202 objcImplementationDecl;
1203
1204 /// Matches Objective-C protocol declarations.
1205 ///
1206 /// Example matches FooDelegate
1207 /// \code
1208 /// @protocol FooDelegate
1209 /// @end
1210 /// \endcode
1211 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1212 objcProtocolDecl;
1213
1214 /// Matches Objective-C category declarations.
1215 ///
1216 /// Example matches Foo (Additions)
1217 /// \code
1218 /// @interface Foo (Additions)
1219 /// @end
1220 /// \endcode
1221 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1222 objcCategoryDecl;
1223
1224 /// Matches Objective-C category definitions.
1225 ///
1226 /// Example matches Foo (Additions)
1227 /// \code
1228 /// @implementation Foo (Additions)
1229 /// @end
1230 /// \endcode
1231 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1232 objcCategoryImplDecl;
1233
1234 /// Matches Objective-C method declarations.
1235 ///
1236 /// Example matches both declaration and definition of -[Foo method]
1237 /// \code
1238 /// @interface Foo
1239 /// - (void)method;
1240 /// @end
1241 ///
1242 /// @implementation Foo
1243 /// - (void)method {}
1244 /// @end
1245 /// \endcode
1246 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1247 objcMethodDecl;
1248
1249 /// Matches block declarations.
1250 ///
1251 /// Example matches the declaration of the nameless block printing an input
1252 /// integer.
1253 ///
1254 /// \code
1255 /// myFunc(^(int p) {
1256 /// printf("%d", p);
1257 /// })
1258 /// \endcode
1259 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1260 blockDecl;
1261
1262 /// Matches Objective-C instance variable declarations.
1263 ///
1264 /// Example matches _enabled
1265 /// \code
1266 /// @implementation Foo {
1267 /// BOOL _enabled;
1268 /// }
1269 /// @end
1270 /// \endcode
1271 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1272 objcIvarDecl;
1273
1274 /// Matches Objective-C property declarations.
1275 ///
1276 /// Example matches enabled
1277 /// \code
1278 /// @interface Foo
1279 /// @property BOOL enabled;
1280 /// @end
1281 /// \endcode
1282 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1283 objcPropertyDecl;
1284
1285 /// Matches Objective-C \@throw statements.
1286 ///
1287 /// Example matches \@throw
1288 /// \code
1289 /// @throw obj;
1290 /// \endcode
1291 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1292 objcThrowStmt;
1293
1294 /// Matches Objective-C @try statements.
1295 ///
1296 /// Example matches @try
1297 /// \code
1298 /// @try {}
1299 /// @catch (...) {}
1300 /// \endcode
1301 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1302 objcTryStmt;
1303
1304 /// Matches Objective-C @catch statements.
1305 ///
1306 /// Example matches @catch
1307 /// \code
1308 /// @try {}
1309 /// @catch (...) {}
1310 /// \endcode
1311 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1312 objcCatchStmt;
1313
1314 /// Matches Objective-C @finally statements.
1315 ///
1316 /// Example matches @finally
1317 /// \code
1318 /// @try {}
1319 /// @finally {}
1320 /// \endcode
1321 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1322 objcFinallyStmt;
1323
1324 /// Matches expressions that introduce cleanups to be run at the end
1325 /// of the sub-expression's evaluation.
1326 ///
1327 /// Example matches std::string()
1328 /// \code
1329 /// const std::string str = std::string();
1330 /// \endcode
1331 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1332 exprWithCleanups;
1333
1334 /// Matches init list expressions.
1335 ///
1336 /// Given
1337 /// \code
1338 /// int a[] = { 1, 2 };
1339 /// struct B { int x, y; };
1340 /// B b = { 5, 6 };
1341 /// \endcode
1342 /// initListExpr()
1343 /// matches "{ 1, 2 }" and "{ 5, 6 }"
1344 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1345 initListExpr;
1346
1347 /// Matches the syntactic form of init list expressions
1348 /// (if expression have it).
AST_MATCHER_P(InitListExpr,hasSyntacticForm,internal::Matcher<Expr>,InnerMatcher)1349 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1350 internal::Matcher<Expr>, InnerMatcher) {
1351 const Expr *SyntForm = Node.getSyntacticForm();
1352 return (SyntForm != nullptr &&
1353 InnerMatcher.matches(*SyntForm, Finder, Builder));
1354 }
1355
1356 /// Matches C++ initializer list expressions.
1357 ///
1358 /// Given
1359 /// \code
1360 /// std::vector<int> a({ 1, 2, 3 });
1361 /// std::vector<int> b = { 4, 5 };
1362 /// int c[] = { 6, 7 };
1363 /// std::pair<int, int> d = { 8, 9 };
1364 /// \endcode
1365 /// cxxStdInitializerListExpr()
1366 /// matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1367 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1368 CXXStdInitializerListExpr>
1369 cxxStdInitializerListExpr;
1370
1371 /// Matches implicit initializers of init list expressions.
1372 ///
1373 /// Given
1374 /// \code
1375 /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1376 /// \endcode
1377 /// implicitValueInitExpr()
1378 /// matches "[0].y" (implicitly)
1379 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1380 implicitValueInitExpr;
1381
1382 /// Matches paren list expressions.
1383 /// ParenListExprs don't have a predefined type and are used for late parsing.
1384 /// In the final AST, they can be met in template declarations.
1385 ///
1386 /// Given
1387 /// \code
1388 /// template<typename T> class X {
1389 /// void f() {
1390 /// X x(*this);
1391 /// int a = 0, b = 1; int i = (a, b);
1392 /// }
1393 /// };
1394 /// \endcode
1395 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1396 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1397 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1398 parenListExpr;
1399
1400 /// Matches substitutions of non-type template parameters.
1401 ///
1402 /// Given
1403 /// \code
1404 /// template <int N>
1405 /// struct A { static const int n = N; };
1406 /// struct B : public A<42> {};
1407 /// \endcode
1408 /// substNonTypeTemplateParmExpr()
1409 /// matches "N" in the right-hand side of "static const int n = N;"
1410 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1411 SubstNonTypeTemplateParmExpr>
1412 substNonTypeTemplateParmExpr;
1413
1414 /// Matches using declarations.
1415 ///
1416 /// Given
1417 /// \code
1418 /// namespace X { int x; }
1419 /// using X::x;
1420 /// \endcode
1421 /// usingDecl()
1422 /// matches \code using X::x \endcode
1423 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1424
1425 /// Matches using namespace declarations.
1426 ///
1427 /// Given
1428 /// \code
1429 /// namespace X { int x; }
1430 /// using namespace X;
1431 /// \endcode
1432 /// usingDirectiveDecl()
1433 /// matches \code using namespace X \endcode
1434 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1435 usingDirectiveDecl;
1436
1437 /// Matches reference to a name that can be looked up during parsing
1438 /// but could not be resolved to a specific declaration.
1439 ///
1440 /// Given
1441 /// \code
1442 /// template<typename T>
1443 /// T foo() { T a; return a; }
1444 /// template<typename T>
1445 /// void bar() {
1446 /// foo<T>();
1447 /// }
1448 /// \endcode
1449 /// unresolvedLookupExpr()
1450 /// matches \code foo<T>() \endcode
1451 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1452 unresolvedLookupExpr;
1453
1454 /// Matches unresolved using value declarations.
1455 ///
1456 /// Given
1457 /// \code
1458 /// template<typename X>
1459 /// class C : private X {
1460 /// using X::x;
1461 /// };
1462 /// \endcode
1463 /// unresolvedUsingValueDecl()
1464 /// matches \code using X::x \endcode
1465 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1466 UnresolvedUsingValueDecl>
1467 unresolvedUsingValueDecl;
1468
1469 /// Matches unresolved using value declarations that involve the
1470 /// typename.
1471 ///
1472 /// Given
1473 /// \code
1474 /// template <typename T>
1475 /// struct Base { typedef T Foo; };
1476 ///
1477 /// template<typename T>
1478 /// struct S : private Base<T> {
1479 /// using typename Base<T>::Foo;
1480 /// };
1481 /// \endcode
1482 /// unresolvedUsingTypenameDecl()
1483 /// matches \code using Base<T>::Foo \endcode
1484 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1485 UnresolvedUsingTypenameDecl>
1486 unresolvedUsingTypenameDecl;
1487
1488 /// Matches parentheses used in expressions.
1489 ///
1490 /// Example matches (foo() + 1)
1491 /// \code
1492 /// int foo() { return 1; }
1493 /// int a = (foo() + 1);
1494 /// \endcode
1495 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1496
1497 /// Matches constructor call expressions (including implicit ones).
1498 ///
1499 /// Example matches string(ptr, n) and ptr within arguments of f
1500 /// (matcher = cxxConstructExpr())
1501 /// \code
1502 /// void f(const string &a, const string &b);
1503 /// char *ptr;
1504 /// int n;
1505 /// f(string(ptr, n), ptr);
1506 /// \endcode
1507 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1508 cxxConstructExpr;
1509
1510 /// Matches unresolved constructor call expressions.
1511 ///
1512 /// Example matches T(t) in return statement of f
1513 /// (matcher = cxxUnresolvedConstructExpr())
1514 /// \code
1515 /// template <typename T>
1516 /// void f(const T& t) { return T(t); }
1517 /// \endcode
1518 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1519 CXXUnresolvedConstructExpr>
1520 cxxUnresolvedConstructExpr;
1521
1522 /// Matches implicit and explicit this expressions.
1523 ///
1524 /// Example matches the implicit this expression in "return i".
1525 /// (matcher = cxxThisExpr())
1526 /// \code
1527 /// struct foo {
1528 /// int i;
1529 /// int f() { return i; }
1530 /// };
1531 /// \endcode
1532 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1533 cxxThisExpr;
1534
1535 /// Matches nodes where temporaries are created.
1536 ///
1537 /// Example matches FunctionTakesString(GetStringByValue())
1538 /// (matcher = cxxBindTemporaryExpr())
1539 /// \code
1540 /// FunctionTakesString(GetStringByValue());
1541 /// FunctionTakesStringByPointer(GetStringPointer());
1542 /// \endcode
1543 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1544 cxxBindTemporaryExpr;
1545
1546 /// Matches nodes where temporaries are materialized.
1547 ///
1548 /// Example: Given
1549 /// \code
1550 /// struct T {void func();};
1551 /// T f();
1552 /// void g(T);
1553 /// \endcode
1554 /// materializeTemporaryExpr() matches 'f()' in these statements
1555 /// \code
1556 /// T u(f());
1557 /// g(f());
1558 /// f().func();
1559 /// \endcode
1560 /// but does not match
1561 /// \code
1562 /// f();
1563 /// \endcode
1564 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1565 MaterializeTemporaryExpr>
1566 materializeTemporaryExpr;
1567
1568 /// Matches new expressions.
1569 ///
1570 /// Given
1571 /// \code
1572 /// new X;
1573 /// \endcode
1574 /// cxxNewExpr()
1575 /// matches 'new X'.
1576 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1577
1578 /// Matches delete expressions.
1579 ///
1580 /// Given
1581 /// \code
1582 /// delete X;
1583 /// \endcode
1584 /// cxxDeleteExpr()
1585 /// matches 'delete X'.
1586 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1587 cxxDeleteExpr;
1588
1589 /// Matches array subscript expressions.
1590 ///
1591 /// Given
1592 /// \code
1593 /// int i = a[1];
1594 /// \endcode
1595 /// arraySubscriptExpr()
1596 /// matches "a[1]"
1597 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1598 arraySubscriptExpr;
1599
1600 /// Matches the value of a default argument at the call site.
1601 ///
1602 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1603 /// default value of the second parameter in the call expression f(42)
1604 /// (matcher = cxxDefaultArgExpr())
1605 /// \code
1606 /// void f(int x, int y = 0);
1607 /// f(42);
1608 /// \endcode
1609 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1610 cxxDefaultArgExpr;
1611
1612 /// Matches overloaded operator calls.
1613 ///
1614 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1615 /// binaryOperator matcher.
1616 /// Currently it does not match operators such as new delete.
1617 /// FIXME: figure out why these do not match?
1618 ///
1619 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1620 /// (matcher = cxxOperatorCallExpr())
1621 /// \code
1622 /// ostream &operator<< (ostream &out, int i) { };
1623 /// ostream &o; int b = 1, c = 1;
1624 /// o << b << c;
1625 /// \endcode
1626 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1627 cxxOperatorCallExpr;
1628
1629 /// Matches expressions.
1630 ///
1631 /// Example matches x()
1632 /// \code
1633 /// void f() { x(); }
1634 /// \endcode
1635 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1636
1637 /// Matches expressions that refer to declarations.
1638 ///
1639 /// Example matches x in if (x)
1640 /// \code
1641 /// bool x;
1642 /// if (x) {}
1643 /// \endcode
1644 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1645 declRefExpr;
1646
1647 /// Matches a reference to an ObjCIvar.
1648 ///
1649 /// Example: matches "a" in "init" method:
1650 /// \code
1651 /// @implementation A {
1652 /// NSString *a;
1653 /// }
1654 /// - (void) init {
1655 /// a = @"hello";
1656 /// }
1657 /// \endcode
1658 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1659 objcIvarRefExpr;
1660
1661 /// Matches if statements.
1662 ///
1663 /// Example matches 'if (x) {}'
1664 /// \code
1665 /// if (x) {}
1666 /// \endcode
1667 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1668
1669 /// Matches for statements.
1670 ///
1671 /// Example matches 'for (;;) {}'
1672 /// \code
1673 /// for (;;) {}
1674 /// int i[] = {1, 2, 3}; for (auto a : i);
1675 /// \endcode
1676 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1677
1678 /// Matches the increment statement of a for loop.
1679 ///
1680 /// Example:
1681 /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1682 /// matches '++x' in
1683 /// \code
1684 /// for (x; x < N; ++x) { }
1685 /// \endcode
AST_MATCHER_P(ForStmt,hasIncrement,internal::Matcher<Stmt>,InnerMatcher)1686 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1687 InnerMatcher) {
1688 const Stmt *const Increment = Node.getInc();
1689 return (Increment != nullptr &&
1690 InnerMatcher.matches(*Increment, Finder, Builder));
1691 }
1692
1693 /// Matches the initialization statement of a for loop.
1694 ///
1695 /// Example:
1696 /// forStmt(hasLoopInit(declStmt()))
1697 /// matches 'int x = 0' in
1698 /// \code
1699 /// for (int x = 0; x < N; ++x) { }
1700 /// \endcode
AST_MATCHER_P(ForStmt,hasLoopInit,internal::Matcher<Stmt>,InnerMatcher)1701 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1702 InnerMatcher) {
1703 const Stmt *const Init = Node.getInit();
1704 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1705 }
1706
1707 /// Matches range-based for statements.
1708 ///
1709 /// cxxForRangeStmt() matches 'for (auto a : i)'
1710 /// \code
1711 /// int i[] = {1, 2, 3}; for (auto a : i);
1712 /// for(int j = 0; j < 5; ++j);
1713 /// \endcode
1714 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1715 cxxForRangeStmt;
1716
1717 /// Matches the initialization statement of a for loop.
1718 ///
1719 /// Example:
1720 /// forStmt(hasLoopVariable(anything()))
1721 /// matches 'int x' in
1722 /// \code
1723 /// for (int x : a) { }
1724 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasLoopVariable,internal::Matcher<VarDecl>,InnerMatcher)1725 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1726 InnerMatcher) {
1727 const VarDecl *const Var = Node.getLoopVariable();
1728 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1729 }
1730
1731 /// Matches the range initialization statement of a for loop.
1732 ///
1733 /// Example:
1734 /// forStmt(hasRangeInit(anything()))
1735 /// matches 'a' in
1736 /// \code
1737 /// for (int x : a) { }
1738 /// \endcode
AST_MATCHER_P(CXXForRangeStmt,hasRangeInit,internal::Matcher<Expr>,InnerMatcher)1739 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1740 InnerMatcher) {
1741 const Expr *const Init = Node.getRangeInit();
1742 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1743 }
1744
1745 /// Matches while statements.
1746 ///
1747 /// Given
1748 /// \code
1749 /// while (true) {}
1750 /// \endcode
1751 /// whileStmt()
1752 /// matches 'while (true) {}'.
1753 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1754
1755 /// Matches do statements.
1756 ///
1757 /// Given
1758 /// \code
1759 /// do {} while (true);
1760 /// \endcode
1761 /// doStmt()
1762 /// matches 'do {} while(true)'
1763 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1764
1765 /// Matches break statements.
1766 ///
1767 /// Given
1768 /// \code
1769 /// while (true) { break; }
1770 /// \endcode
1771 /// breakStmt()
1772 /// matches 'break'
1773 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1774
1775 /// Matches continue statements.
1776 ///
1777 /// Given
1778 /// \code
1779 /// while (true) { continue; }
1780 /// \endcode
1781 /// continueStmt()
1782 /// matches 'continue'
1783 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1784 continueStmt;
1785
1786 /// Matches return statements.
1787 ///
1788 /// Given
1789 /// \code
1790 /// return 1;
1791 /// \endcode
1792 /// returnStmt()
1793 /// matches 'return 1'
1794 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1795
1796 /// Matches goto statements.
1797 ///
1798 /// Given
1799 /// \code
1800 /// goto FOO;
1801 /// FOO: bar();
1802 /// \endcode
1803 /// gotoStmt()
1804 /// matches 'goto FOO'
1805 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1806
1807 /// Matches label statements.
1808 ///
1809 /// Given
1810 /// \code
1811 /// goto FOO;
1812 /// FOO: bar();
1813 /// \endcode
1814 /// labelStmt()
1815 /// matches 'FOO:'
1816 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1817
1818 /// Matches address of label statements (GNU extension).
1819 ///
1820 /// Given
1821 /// \code
1822 /// FOO: bar();
1823 /// void *ptr = &&FOO;
1824 /// goto *bar;
1825 /// \endcode
1826 /// addrLabelExpr()
1827 /// matches '&&FOO'
1828 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
1829 addrLabelExpr;
1830
1831 /// Matches switch statements.
1832 ///
1833 /// Given
1834 /// \code
1835 /// switch(a) { case 42: break; default: break; }
1836 /// \endcode
1837 /// switchStmt()
1838 /// matches 'switch(a)'.
1839 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
1840
1841 /// Matches case and default statements inside switch statements.
1842 ///
1843 /// Given
1844 /// \code
1845 /// switch(a) { case 42: break; default: break; }
1846 /// \endcode
1847 /// switchCase()
1848 /// matches 'case 42:' and 'default:'.
1849 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
1850
1851 /// Matches case statements inside switch statements.
1852 ///
1853 /// Given
1854 /// \code
1855 /// switch(a) { case 42: break; default: break; }
1856 /// \endcode
1857 /// caseStmt()
1858 /// matches 'case 42:'.
1859 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
1860
1861 /// Matches default statements inside switch statements.
1862 ///
1863 /// Given
1864 /// \code
1865 /// switch(a) { case 42: break; default: break; }
1866 /// \endcode
1867 /// defaultStmt()
1868 /// matches 'default:'.
1869 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
1870 defaultStmt;
1871
1872 /// Matches compound statements.
1873 ///
1874 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
1875 /// \code
1876 /// for (;;) {{}}
1877 /// \endcode
1878 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
1879 compoundStmt;
1880
1881 /// Matches catch statements.
1882 ///
1883 /// \code
1884 /// try {} catch(int i) {}
1885 /// \endcode
1886 /// cxxCatchStmt()
1887 /// matches 'catch(int i)'
1888 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
1889 cxxCatchStmt;
1890
1891 /// Matches try statements.
1892 ///
1893 /// \code
1894 /// try {} catch(int i) {}
1895 /// \endcode
1896 /// cxxTryStmt()
1897 /// matches 'try {}'
1898 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
1899
1900 /// Matches throw expressions.
1901 ///
1902 /// \code
1903 /// try { throw 5; } catch(int i) {}
1904 /// \endcode
1905 /// cxxThrowExpr()
1906 /// matches 'throw 5'
1907 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
1908 cxxThrowExpr;
1909
1910 /// Matches null statements.
1911 ///
1912 /// \code
1913 /// foo();;
1914 /// \endcode
1915 /// nullStmt()
1916 /// matches the second ';'
1917 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
1918
1919 /// Matches asm statements.
1920 ///
1921 /// \code
1922 /// int i = 100;
1923 /// __asm("mov al, 2");
1924 /// \endcode
1925 /// asmStmt()
1926 /// matches '__asm("mov al, 2")'
1927 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
1928
1929 /// Matches bool literals.
1930 ///
1931 /// Example matches true
1932 /// \code
1933 /// true
1934 /// \endcode
1935 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
1936 cxxBoolLiteral;
1937
1938 /// Matches string literals (also matches wide string literals).
1939 ///
1940 /// Example matches "abcd", L"abcd"
1941 /// \code
1942 /// char *s = "abcd";
1943 /// wchar_t *ws = L"abcd";
1944 /// \endcode
1945 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
1946 stringLiteral;
1947
1948 /// Matches character literals (also matches wchar_t).
1949 ///
1950 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
1951 /// though.
1952 ///
1953 /// Example matches 'a', L'a'
1954 /// \code
1955 /// char ch = 'a';
1956 /// wchar_t chw = L'a';
1957 /// \endcode
1958 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
1959 characterLiteral;
1960
1961 /// Matches integer literals of all sizes / encodings, e.g.
1962 /// 1, 1L, 0x1 and 1U.
1963 ///
1964 /// Does not match character-encoded integers such as L'a'.
1965 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
1966 integerLiteral;
1967
1968 /// Matches float literals of all sizes / encodings, e.g.
1969 /// 1.0, 1.0f, 1.0L and 1e10.
1970 ///
1971 /// Does not match implicit conversions such as
1972 /// \code
1973 /// float a = 10;
1974 /// \endcode
1975 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
1976 floatLiteral;
1977
1978 /// Matches user defined literal operator call.
1979 ///
1980 /// Example match: "foo"_suffix
1981 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
1982 userDefinedLiteral;
1983
1984 /// Matches compound (i.e. non-scalar) literals
1985 ///
1986 /// Example match: {1}, (1, 2)
1987 /// \code
1988 /// int array[4] = {1};
1989 /// vector int myvec = (vector int)(1, 2);
1990 /// \endcode
1991 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
1992 compoundLiteralExpr;
1993
1994 /// Matches nullptr literal.
1995 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
1996 cxxNullPtrLiteralExpr;
1997
1998 /// Matches GNU __null expression.
1999 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2000 gnuNullExpr;
2001
2002 /// Matches atomic builtins.
2003 /// Example matches __atomic_load_n(ptr, 1)
2004 /// \code
2005 /// void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2006 /// \endcode
2007 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2008
2009 /// Matches statement expression (GNU extension).
2010 ///
2011 /// Example match: ({ int X = 4; X; })
2012 /// \code
2013 /// int C = ({ int X = 4; X; });
2014 /// \endcode
2015 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2016
2017 /// Matches binary operator expressions.
2018 ///
2019 /// Example matches a || b
2020 /// \code
2021 /// !(a || b)
2022 /// \endcode
2023 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2024 binaryOperator;
2025
2026 /// Matches unary operator expressions.
2027 ///
2028 /// Example matches !a
2029 /// \code
2030 /// !a || b
2031 /// \endcode
2032 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2033 unaryOperator;
2034
2035 /// Matches conditional operator expressions.
2036 ///
2037 /// Example matches a ? b : c
2038 /// \code
2039 /// (a ? b : c) + 42
2040 /// \endcode
2041 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2042 conditionalOperator;
2043
2044 /// Matches binary conditional operator expressions (GNU extension).
2045 ///
2046 /// Example matches a ?: b
2047 /// \code
2048 /// (a ?: b) + 42;
2049 /// \endcode
2050 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2051 BinaryConditionalOperator>
2052 binaryConditionalOperator;
2053
2054 /// Matches opaque value expressions. They are used as helpers
2055 /// to reference another expressions and can be met
2056 /// in BinaryConditionalOperators, for example.
2057 ///
2058 /// Example matches 'a'
2059 /// \code
2060 /// (a ?: c) + 42;
2061 /// \endcode
2062 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2063 opaqueValueExpr;
2064
2065 /// Matches a C++ static_assert declaration.
2066 ///
2067 /// Example:
2068 /// staticAssertExpr()
2069 /// matches
2070 /// static_assert(sizeof(S) == sizeof(int))
2071 /// in
2072 /// \code
2073 /// struct S {
2074 /// int x;
2075 /// };
2076 /// static_assert(sizeof(S) == sizeof(int));
2077 /// \endcode
2078 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2079 staticAssertDecl;
2080
2081 /// Matches a reinterpret_cast expression.
2082 ///
2083 /// Either the source expression or the destination type can be matched
2084 /// using has(), but hasDestinationType() is more specific and can be
2085 /// more readable.
2086 ///
2087 /// Example matches reinterpret_cast<char*>(&p) in
2088 /// \code
2089 /// void* p = reinterpret_cast<char*>(&p);
2090 /// \endcode
2091 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2092 cxxReinterpretCastExpr;
2093
2094 /// Matches a C++ static_cast expression.
2095 ///
2096 /// \see hasDestinationType
2097 /// \see reinterpretCast
2098 ///
2099 /// Example:
2100 /// cxxStaticCastExpr()
2101 /// matches
2102 /// static_cast<long>(8)
2103 /// in
2104 /// \code
2105 /// long eight(static_cast<long>(8));
2106 /// \endcode
2107 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2108 cxxStaticCastExpr;
2109
2110 /// Matches a dynamic_cast expression.
2111 ///
2112 /// Example:
2113 /// cxxDynamicCastExpr()
2114 /// matches
2115 /// dynamic_cast<D*>(&b);
2116 /// in
2117 /// \code
2118 /// struct B { virtual ~B() {} }; struct D : B {};
2119 /// B b;
2120 /// D* p = dynamic_cast<D*>(&b);
2121 /// \endcode
2122 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2123 cxxDynamicCastExpr;
2124
2125 /// Matches a const_cast expression.
2126 ///
2127 /// Example: Matches const_cast<int*>(&r) in
2128 /// \code
2129 /// int n = 42;
2130 /// const int &r(n);
2131 /// int* p = const_cast<int*>(&r);
2132 /// \endcode
2133 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2134 cxxConstCastExpr;
2135
2136 /// Matches a C-style cast expression.
2137 ///
2138 /// Example: Matches (int) 2.2f in
2139 /// \code
2140 /// int i = (int) 2.2f;
2141 /// \endcode
2142 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2143 cStyleCastExpr;
2144
2145 /// Matches explicit cast expressions.
2146 ///
2147 /// Matches any cast expression written in user code, whether it be a
2148 /// C-style cast, a functional-style cast, or a keyword cast.
2149 ///
2150 /// Does not match implicit conversions.
2151 ///
2152 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2153 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2154 /// actual cast expressions.
2155 ///
2156 /// \see hasDestinationType.
2157 ///
2158 /// Example: matches all five of the casts in
2159 /// \code
2160 /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2161 /// \endcode
2162 /// but does not match the implicit conversion in
2163 /// \code
2164 /// long ell = 42;
2165 /// \endcode
2166 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2167 explicitCastExpr;
2168
2169 /// Matches the implicit cast nodes of Clang's AST.
2170 ///
2171 /// This matches many different places, including function call return value
2172 /// eliding, as well as any type conversions.
2173 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2174 implicitCastExpr;
2175
2176 /// Matches any cast nodes of Clang's AST.
2177 ///
2178 /// Example: castExpr() matches each of the following:
2179 /// \code
2180 /// (int) 3;
2181 /// const_cast<Expr *>(SubExpr);
2182 /// char c = 0;
2183 /// \endcode
2184 /// but does not match
2185 /// \code
2186 /// int i = (0);
2187 /// int k = 0;
2188 /// \endcode
2189 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2190
2191 /// Matches functional cast expressions
2192 ///
2193 /// Example: Matches Foo(bar);
2194 /// \code
2195 /// Foo f = bar;
2196 /// Foo g = (Foo) bar;
2197 /// Foo h = Foo(bar);
2198 /// \endcode
2199 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2200 cxxFunctionalCastExpr;
2201
2202 /// Matches functional cast expressions having N != 1 arguments
2203 ///
2204 /// Example: Matches Foo(bar, bar)
2205 /// \code
2206 /// Foo h = Foo(bar, bar);
2207 /// \endcode
2208 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2209 cxxTemporaryObjectExpr;
2210
2211 /// Matches predefined identifier expressions [C99 6.4.2.2].
2212 ///
2213 /// Example: Matches __func__
2214 /// \code
2215 /// printf("%s", __func__);
2216 /// \endcode
2217 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2218 predefinedExpr;
2219
2220 /// Matches C99 designated initializer expressions [C99 6.7.8].
2221 ///
2222 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2223 /// \code
2224 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2225 /// \endcode
2226 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2227 designatedInitExpr;
2228
2229 /// Matches designated initializer expressions that contain
2230 /// a specific number of designators.
2231 ///
2232 /// Example: Given
2233 /// \code
2234 /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2235 /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2236 /// \endcode
2237 /// designatorCountIs(2)
2238 /// matches '{ [2].y = 1.0, [0].x = 1.0 }',
2239 /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
AST_MATCHER_P(DesignatedInitExpr,designatorCountIs,unsigned,N)2240 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2241 return Node.size() == N;
2242 }
2243
2244 /// Matches \c QualTypes in the clang AST.
2245 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2246
2247 /// Matches \c Types in the clang AST.
2248 extern const internal::VariadicAllOfMatcher<Type> type;
2249
2250 /// Matches \c TypeLocs in the clang AST.
2251 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2252
2253 /// Matches if any of the given matchers matches.
2254 ///
2255 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2256 /// matching submatcher.
2257 ///
2258 /// For example, in:
2259 /// \code
2260 /// class A { int a; int b; };
2261 /// \endcode
2262 /// The matcher:
2263 /// \code
2264 /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2265 /// has(fieldDecl(hasName("b")).bind("v"))))
2266 /// \endcode
2267 /// will generate two results binding "v", the first of which binds
2268 /// the field declaration of \c a, the second the field declaration of
2269 /// \c b.
2270 ///
2271 /// Usable as: Any Matcher
2272 extern const internal::VariadicOperatorMatcherFunc<
2273 2, std::numeric_limits<unsigned>::max()>
2274 eachOf;
2275
2276 /// Matches if any of the given matchers matches.
2277 ///
2278 /// Usable as: Any Matcher
2279 extern const internal::VariadicOperatorMatcherFunc<
2280 2, std::numeric_limits<unsigned>::max()>
2281 anyOf;
2282
2283 /// Matches if all given matchers match.
2284 ///
2285 /// Usable as: Any Matcher
2286 extern const internal::VariadicOperatorMatcherFunc<
2287 2, std::numeric_limits<unsigned>::max()>
2288 allOf;
2289
2290 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2291 ///
2292 /// Given
2293 /// \code
2294 /// Foo x = bar;
2295 /// int y = sizeof(x) + alignof(x);
2296 /// \endcode
2297 /// unaryExprOrTypeTraitExpr()
2298 /// matches \c sizeof(x) and \c alignof(x)
2299 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2300 UnaryExprOrTypeTraitExpr>
2301 unaryExprOrTypeTraitExpr;
2302
2303 /// Matches unary expressions that have a specific type of argument.
2304 ///
2305 /// Given
2306 /// \code
2307 /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2308 /// \endcode
2309 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2310 /// matches \c sizeof(a) and \c alignof(c)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,hasArgumentOfType,internal::Matcher<QualType>,InnerMatcher)2311 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2312 internal::Matcher<QualType>, InnerMatcher) {
2313 const QualType ArgumentType = Node.getTypeOfArgument();
2314 return InnerMatcher.matches(ArgumentType, Finder, Builder);
2315 }
2316
2317 /// Matches unary expressions of a certain kind.
2318 ///
2319 /// Given
2320 /// \code
2321 /// int x;
2322 /// int s = sizeof(x) + alignof(x)
2323 /// \endcode
2324 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2325 /// matches \c sizeof(x)
AST_MATCHER_P(UnaryExprOrTypeTraitExpr,ofKind,UnaryExprOrTypeTrait,Kind)2326 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2327 return Node.getKind() == Kind;
2328 }
2329
2330 /// Same as unaryExprOrTypeTraitExpr, but only matching
2331 /// alignof.
alignOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)2332 inline internal::Matcher<Stmt> alignOfExpr(
2333 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2334 return stmt(unaryExprOrTypeTraitExpr(allOf(
2335 ofKind(UETT_AlignOf), InnerMatcher)));
2336 }
2337
2338 /// Same as unaryExprOrTypeTraitExpr, but only matching
2339 /// sizeof.
sizeOfExpr(const internal::Matcher<UnaryExprOrTypeTraitExpr> & InnerMatcher)2340 inline internal::Matcher<Stmt> sizeOfExpr(
2341 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2342 return stmt(unaryExprOrTypeTraitExpr(
2343 allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2344 }
2345
2346 /// Matches NamedDecl nodes that have the specified name.
2347 ///
2348 /// Supports specifying enclosing namespaces or classes by prefixing the name
2349 /// with '<enclosing>::'.
2350 /// Does not match typedefs of an underlying type with the given name.
2351 ///
2352 /// Example matches X (Name == "X")
2353 /// \code
2354 /// class X;
2355 /// \endcode
2356 ///
2357 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2358 /// \code
2359 /// namespace a { namespace b { class X; } }
2360 /// \endcode
hasName(const std::string & Name)2361 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2362 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2363 }
2364
2365 /// Matches NamedDecl nodes that have any of the specified names.
2366 ///
2367 /// This matcher is only provided as a performance optimization of hasName.
2368 /// \code
2369 /// hasAnyName(a, b, c)
2370 /// \endcode
2371 /// is equivalent to, but faster than
2372 /// \code
2373 /// anyOf(hasName(a), hasName(b), hasName(c))
2374 /// \endcode
2375 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2376 internal::hasAnyNameFunc>
2377 hasAnyName;
2378
2379 /// Matches NamedDecl nodes whose fully qualified names contain
2380 /// a substring matched by the given RegExp.
2381 ///
2382 /// Supports specifying enclosing namespaces or classes by
2383 /// prefixing the name with '<enclosing>::'. Does not match typedefs
2384 /// of an underlying type with the given name.
2385 ///
2386 /// Example matches X (regexp == "::X")
2387 /// \code
2388 /// class X;
2389 /// \endcode
2390 ///
2391 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2392 /// \code
2393 /// namespace foo { namespace bar { class X; } }
2394 /// \endcode
AST_MATCHER_P(NamedDecl,matchesName,std::string,RegExp)2395 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2396 assert(!RegExp.empty());
2397 std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2398 llvm::Regex RE(RegExp);
2399 return RE.match(FullNameString);
2400 }
2401
2402 /// Matches overloaded operator names.
2403 ///
2404 /// Matches overloaded operator names specified in strings without the
2405 /// "operator" prefix: e.g. "<<".
2406 ///
2407 /// Given:
2408 /// \code
2409 /// class A { int operator*(); };
2410 /// const A &operator<<(const A &a, const A &b);
2411 /// A a;
2412 /// a << a; // <-- This matches
2413 /// \endcode
2414 ///
2415 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2416 /// specified line and
2417 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2418 /// matches the declaration of \c A.
2419 ///
2420 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2421 inline internal::PolymorphicMatcherWithParam1<
2422 internal::HasOverloadedOperatorNameMatcher, StringRef,
2423 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
hasOverloadedOperatorName(StringRef Name)2424 hasOverloadedOperatorName(StringRef Name) {
2425 return internal::PolymorphicMatcherWithParam1<
2426 internal::HasOverloadedOperatorNameMatcher, StringRef,
2427 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2428 }
2429
2430 /// Matches C++ classes that are directly or indirectly derived from
2431 /// a class matching \c Base.
2432 ///
2433 /// Note that a class is not considered to be derived from itself.
2434 ///
2435 /// Example matches Y, Z, C (Base == hasName("X"))
2436 /// \code
2437 /// class X;
2438 /// class Y : public X {}; // directly derived
2439 /// class Z : public Y {}; // indirectly derived
2440 /// typedef X A;
2441 /// typedef A B;
2442 /// class C : public B {}; // derived from a typedef of X
2443 /// \endcode
2444 ///
2445 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2446 /// \code
2447 /// class Foo;
2448 /// typedef Foo X;
2449 /// class Bar : public Foo {}; // derived from a type that X is a typedef of
2450 /// \endcode
AST_MATCHER_P(CXXRecordDecl,isDerivedFrom,internal::Matcher<NamedDecl>,Base)2451 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2452 internal::Matcher<NamedDecl>, Base) {
2453 return Finder->classIsDerivedFrom(&Node, Base, Builder);
2454 }
2455
2456 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2457 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2458 assert(!BaseName.empty());
2459 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2460 }
2461
2462 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2463 /// match \c Base.
2464 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2465 internal::Matcher<NamedDecl>, Base, 0) {
2466 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2467 .matches(Node, Finder, Builder);
2468 }
2469
2470 /// Overloaded method as shortcut for
2471 /// \c isSameOrDerivedFrom(hasName(...)).
2472 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2473 BaseName, 1) {
2474 assert(!BaseName.empty());
2475 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2476 }
2477
2478 /// Matches the first method of a class or struct that satisfies \c
2479 /// InnerMatcher.
2480 ///
2481 /// Given:
2482 /// \code
2483 /// class A { void func(); };
2484 /// class B { void member(); };
2485 /// \endcode
2486 ///
2487 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2488 /// \c A but not \c B.
AST_MATCHER_P(CXXRecordDecl,hasMethod,internal::Matcher<CXXMethodDecl>,InnerMatcher)2489 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2490 InnerMatcher) {
2491 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2492 Node.method_end(), Finder, Builder);
2493 }
2494
2495 /// Matches the generated class of lambda expressions.
2496 ///
2497 /// Given:
2498 /// \code
2499 /// auto x = []{};
2500 /// \endcode
2501 ///
2502 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2503 /// \c decltype(x)
AST_MATCHER(CXXRecordDecl,isLambda)2504 AST_MATCHER(CXXRecordDecl, isLambda) {
2505 return Node.isLambda();
2506 }
2507
2508 /// Matches AST nodes that have child AST nodes that match the
2509 /// provided matcher.
2510 ///
2511 /// Example matches X, Y
2512 /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2513 /// \code
2514 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2515 /// class Y { class X {}; };
2516 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2517 /// \endcode
2518 ///
2519 /// ChildT must be an AST base type.
2520 ///
2521 /// Usable as: Any Matcher
2522 /// Note that has is direct matcher, so it also matches things like implicit
2523 /// casts and paren casts. If you are matching with expr then you should
2524 /// probably consider using ignoringParenImpCasts like:
2525 /// has(ignoringParenImpCasts(expr())).
2526 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2527
2528 /// Matches AST nodes that have descendant AST nodes that match the
2529 /// provided matcher.
2530 ///
2531 /// Example matches X, Y, Z
2532 /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2533 /// \code
2534 /// class X {}; // Matches X, because X::X is a class of name X inside X.
2535 /// class Y { class X {}; };
2536 /// class Z { class Y { class X {}; }; };
2537 /// \endcode
2538 ///
2539 /// DescendantT must be an AST base type.
2540 ///
2541 /// Usable as: Any Matcher
2542 extern const internal::ArgumentAdaptingMatcherFunc<
2543 internal::HasDescendantMatcher>
2544 hasDescendant;
2545
2546 /// Matches AST nodes that have child AST nodes that match the
2547 /// provided matcher.
2548 ///
2549 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2550 /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2551 /// \code
2552 /// class X {};
2553 /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X
2554 /// // inside Y.
2555 /// class Z { class Y { class X {}; }; }; // Does not match Z.
2556 /// \endcode
2557 ///
2558 /// ChildT must be an AST base type.
2559 ///
2560 /// As opposed to 'has', 'forEach' will cause a match for each result that
2561 /// matches instead of only on the first one.
2562 ///
2563 /// Usable as: Any Matcher
2564 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2565 forEach;
2566
2567 /// Matches AST nodes that have descendant AST nodes that match the
2568 /// provided matcher.
2569 ///
2570 /// Example matches X, A, A::X, B, B::C, B::C::X
2571 /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2572 /// \code
2573 /// class X {};
2574 /// class A { class X {}; }; // Matches A, because A::X is a class of name
2575 /// // X inside A.
2576 /// class B { class C { class X {}; }; };
2577 /// \endcode
2578 ///
2579 /// DescendantT must be an AST base type.
2580 ///
2581 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2582 /// each result that matches instead of only on the first one.
2583 ///
2584 /// Note: Recursively combined ForEachDescendant can cause many matches:
2585 /// cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2586 /// forEachDescendant(cxxRecordDecl())
2587 /// )))
2588 /// will match 10 times (plus injected class name matches) on:
2589 /// \code
2590 /// class A { class B { class C { class D { class E {}; }; }; }; };
2591 /// \endcode
2592 ///
2593 /// Usable as: Any Matcher
2594 extern const internal::ArgumentAdaptingMatcherFunc<
2595 internal::ForEachDescendantMatcher>
2596 forEachDescendant;
2597
2598 /// Matches if the node or any descendant matches.
2599 ///
2600 /// Generates results for each match.
2601 ///
2602 /// For example, in:
2603 /// \code
2604 /// class A { class B {}; class C {}; };
2605 /// \endcode
2606 /// The matcher:
2607 /// \code
2608 /// cxxRecordDecl(hasName("::A"),
2609 /// findAll(cxxRecordDecl(isDefinition()).bind("m")))
2610 /// \endcode
2611 /// will generate results for \c A, \c B and \c C.
2612 ///
2613 /// Usable as: Any Matcher
2614 template <typename T>
findAll(const internal::Matcher<T> & Matcher)2615 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2616 return eachOf(Matcher, forEachDescendant(Matcher));
2617 }
2618
2619 /// Matches AST nodes that have a parent that matches the provided
2620 /// matcher.
2621 ///
2622 /// Given
2623 /// \code
2624 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2625 /// \endcode
2626 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2627 ///
2628 /// Usable as: Any Matcher
2629 extern const internal::ArgumentAdaptingMatcherFunc<
2630 internal::HasParentMatcher,
2631 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2632 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2633 hasParent;
2634
2635 /// Matches AST nodes that have an ancestor that matches the provided
2636 /// matcher.
2637 ///
2638 /// Given
2639 /// \code
2640 /// void f() { if (true) { int x = 42; } }
2641 /// void g() { for (;;) { int x = 43; } }
2642 /// \endcode
2643 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2644 ///
2645 /// Usable as: Any Matcher
2646 extern const internal::ArgumentAdaptingMatcherFunc<
2647 internal::HasAncestorMatcher,
2648 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2649 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2650 hasAncestor;
2651
2652 /// Matches if the provided matcher does not match.
2653 ///
2654 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2655 /// \code
2656 /// class X {};
2657 /// class Y {};
2658 /// \endcode
2659 ///
2660 /// Usable as: Any Matcher
2661 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2662
2663 /// Matches a node if the declaration associated with that node
2664 /// matches the given matcher.
2665 ///
2666 /// The associated declaration is:
2667 /// - for type nodes, the declaration of the underlying type
2668 /// - for CallExpr, the declaration of the callee
2669 /// - for MemberExpr, the declaration of the referenced member
2670 /// - for CXXConstructExpr, the declaration of the constructor
2671 /// - for CXXNewExpr, the declaration of the operator new
2672 /// - for ObjCIvarExpr, the declaration of the ivar
2673 ///
2674 /// For type nodes, hasDeclaration will generally match the declaration of the
2675 /// sugared type. Given
2676 /// \code
2677 /// class X {};
2678 /// typedef X Y;
2679 /// Y y;
2680 /// \endcode
2681 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2682 /// typedefDecl. A common use case is to match the underlying, desugared type.
2683 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2684 /// \code
2685 /// varDecl(hasType(hasUnqualifiedDesugaredType(
2686 /// recordType(hasDeclaration(decl())))))
2687 /// \endcode
2688 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2689 ///
2690 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2691 /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2692 /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2693 /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2694 /// Matcher<TagType>, Matcher<TemplateSpecializationType>,
2695 /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2696 /// Matcher<UnresolvedUsingType>
2697 inline internal::PolymorphicMatcherWithParam1<
2698 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2699 void(internal::HasDeclarationSupportedTypes)>
hasDeclaration(const internal::Matcher<Decl> & InnerMatcher)2700 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2701 return internal::PolymorphicMatcherWithParam1<
2702 internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2703 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2704 }
2705
2706 /// Matches a \c NamedDecl whose underlying declaration matches the given
2707 /// matcher.
2708 ///
2709 /// Given
2710 /// \code
2711 /// namespace N { template<class T> void f(T t); }
2712 /// template <class T> void g() { using N::f; f(T()); }
2713 /// \endcode
2714 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2715 /// namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2716 /// matches the use of \c f in \c g() .
AST_MATCHER_P(NamedDecl,hasUnderlyingDecl,internal::Matcher<NamedDecl>,InnerMatcher)2717 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2718 InnerMatcher) {
2719 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2720
2721 return UnderlyingDecl != nullptr &&
2722 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2723 }
2724
2725 /// Matches on the implicit object argument of a member call expression.
2726 ///
2727 /// Example matches y.x()
2728 /// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))))
2729 /// \code
2730 /// class Y { public: void x(); };
2731 /// void z() { Y y; y.x(); }
2732 /// \endcode
2733 ///
2734 /// FIXME: Overload to allow directly matching types?
AST_MATCHER_P(CXXMemberCallExpr,on,internal::Matcher<Expr>,InnerMatcher)2735 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2736 InnerMatcher) {
2737 const Expr *ExprNode = Node.getImplicitObjectArgument()
2738 ->IgnoreParenImpCasts();
2739 return (ExprNode != nullptr &&
2740 InnerMatcher.matches(*ExprNode, Finder, Builder));
2741 }
2742
2743
2744 /// Matches on the receiver of an ObjectiveC Message expression.
2745 ///
2746 /// Example
2747 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2748 /// matches the [webView ...] message invocation.
2749 /// \code
2750 /// NSString *webViewJavaScript = ...
2751 /// UIWebView *webView = ...
2752 /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2753 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,hasReceiverType,internal::Matcher<QualType>,InnerMatcher)2754 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2755 InnerMatcher) {
2756 const QualType TypeDecl = Node.getReceiverType();
2757 return InnerMatcher.matches(TypeDecl, Finder, Builder);
2758 }
2759
2760 /// Returns true when the Objective-C message is sent to an instance.
2761 ///
2762 /// Example
2763 /// matcher = objcMessagaeExpr(isInstanceMessage())
2764 /// matches
2765 /// \code
2766 /// NSString *x = @"hello";
2767 /// [x containsString:@"h"];
2768 /// \endcode
2769 /// but not
2770 /// \code
2771 /// [NSString stringWithFormat:@"format"];
2772 /// \endcode
AST_MATCHER(ObjCMessageExpr,isInstanceMessage)2773 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
2774 return Node.isInstanceMessage();
2775 }
2776
2777 /// Matches if the Objective-C message is sent to an instance,
2778 /// and the inner matcher matches on that instance.
2779 ///
2780 /// For example the method call in
2781 /// \code
2782 /// NSString *x = @"hello";
2783 /// [x containsString:@"h"];
2784 /// \endcode
2785 /// is matched by
2786 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
AST_MATCHER_P(ObjCMessageExpr,hasReceiver,internal::Matcher<Expr>,InnerMatcher)2787 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
2788 InnerMatcher) {
2789 const Expr *ReceiverNode = Node.getInstanceReceiver();
2790 return (ReceiverNode != nullptr &&
2791 InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
2792 Builder));
2793 }
2794
2795 /// Matches when BaseName == Selector.getAsString()
2796 ///
2797 /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
2798 /// matches the outer message expr in the code below, but NOT the message
2799 /// invocation for self.bodyView.
2800 /// \code
2801 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2802 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,hasSelector,std::string,BaseName)2803 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
2804 Selector Sel = Node.getSelector();
2805 return BaseName.compare(Sel.getAsString()) == 0;
2806 }
2807
2808
2809 /// Matches when at least one of the supplied string equals to the
2810 /// Selector.getAsString()
2811 ///
2812 /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
2813 /// matches both of the expressions below:
2814 /// \code
2815 /// [myObj methodA:argA];
2816 /// [myObj methodB:argB];
2817 /// \endcode
2818 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
2819 StringRef,
2820 internal::hasAnySelectorFunc>
2821 hasAnySelector;
2822
2823 /// Matches ObjC selectors whose name contains
2824 /// a substring matched by the given RegExp.
2825 /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
2826 /// matches the outer message expr in the code below, but NOT the message
2827 /// invocation for self.bodyView.
2828 /// \code
2829 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2830 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,matchesSelector,std::string,RegExp)2831 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
2832 assert(!RegExp.empty());
2833 std::string SelectorString = Node.getSelector().getAsString();
2834 llvm::Regex RE(RegExp);
2835 return RE.match(SelectorString);
2836 }
2837
2838 /// Matches when the selector is the empty selector
2839 ///
2840 /// Matches only when the selector of the objCMessageExpr is NULL. This may
2841 /// represent an error condition in the tree!
AST_MATCHER(ObjCMessageExpr,hasNullSelector)2842 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
2843 return Node.getSelector().isNull();
2844 }
2845
2846 /// Matches when the selector is a Unary Selector
2847 ///
2848 /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
2849 /// matches self.bodyView in the code below, but NOT the outer message
2850 /// invocation of "loadHTMLString:baseURL:".
2851 /// \code
2852 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2853 /// \endcode
AST_MATCHER(ObjCMessageExpr,hasUnarySelector)2854 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
2855 return Node.getSelector().isUnarySelector();
2856 }
2857
2858 /// Matches when the selector is a keyword selector
2859 ///
2860 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
2861 /// message expression in
2862 ///
2863 /// \code
2864 /// UIWebView *webView = ...;
2865 /// CGRect bodyFrame = webView.frame;
2866 /// bodyFrame.size.height = self.bodyContentHeight;
2867 /// webView.frame = bodyFrame;
2868 /// // ^---- matches here
2869 /// \endcode
AST_MATCHER(ObjCMessageExpr,hasKeywordSelector)2870 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
2871 return Node.getSelector().isKeywordSelector();
2872 }
2873
2874 /// Matches when the selector has the specified number of arguments
2875 ///
2876 /// matcher = objCMessageExpr(numSelectorArgs(0));
2877 /// matches self.bodyView in the code below
2878 ///
2879 /// matcher = objCMessageExpr(numSelectorArgs(2));
2880 /// matches the invocation of "loadHTMLString:baseURL:" but not that
2881 /// of self.bodyView
2882 /// \code
2883 /// [self.bodyView loadHTMLString:html baseURL:NULL];
2884 /// \endcode
AST_MATCHER_P(ObjCMessageExpr,numSelectorArgs,unsigned,N)2885 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
2886 return Node.getSelector().getNumArgs() == N;
2887 }
2888
2889 /// Matches if the call expression's callee expression matches.
2890 ///
2891 /// Given
2892 /// \code
2893 /// class Y { void x() { this->x(); x(); Y y; y.x(); } };
2894 /// void f() { f(); }
2895 /// \endcode
2896 /// callExpr(callee(expr()))
2897 /// matches this->x(), x(), y.x(), f()
2898 /// with callee(...)
2899 /// matching this->x, x, y.x, f respectively
2900 ///
2901 /// Note: Callee cannot take the more general internal::Matcher<Expr>
2902 /// because this introduces ambiguous overloads with calls to Callee taking a
2903 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
2904 /// implemented in terms of implicit casts.
AST_MATCHER_P(CallExpr,callee,internal::Matcher<Stmt>,InnerMatcher)2905 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
2906 InnerMatcher) {
2907 const Expr *ExprNode = Node.getCallee();
2908 return (ExprNode != nullptr &&
2909 InnerMatcher.matches(*ExprNode, Finder, Builder));
2910 }
2911
2912 /// Matches if the call expression's callee's declaration matches the
2913 /// given matcher.
2914 ///
2915 /// Example matches y.x() (matcher = callExpr(callee(
2916 /// cxxMethodDecl(hasName("x")))))
2917 /// \code
2918 /// class Y { public: void x(); };
2919 /// void z() { Y y; y.x(); }
2920 /// \endcode
2921 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
2922 1) {
2923 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
2924 }
2925
2926 /// Matches if the expression's or declaration's type matches a type
2927 /// matcher.
2928 ///
2929 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2930 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2931 /// and U (matcher = typedefDecl(hasType(asString("int")))
2932 /// and friend class X (matcher = friendDecl(hasType("X"))
2933 /// \code
2934 /// class X {};
2935 /// void y(X &x) { x; X z; }
2936 /// typedef int U;
2937 /// class Y { friend class X; };
2938 /// \endcode
2939 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2940 hasType,
2941 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
2942 ValueDecl),
2943 internal::Matcher<QualType>, InnerMatcher, 0) {
2944 QualType QT = internal::getUnderlyingType(Node);
2945 if (!QT.isNull())
2946 return InnerMatcher.matches(QT, Finder, Builder);
2947 return false;
2948 }
2949
2950 /// Overloaded to match the declaration of the expression's or value
2951 /// declaration's type.
2952 ///
2953 /// In case of a value declaration (for example a variable declaration),
2954 /// this resolves one layer of indirection. For example, in the value
2955 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
2956 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
2957 /// declaration of x.
2958 ///
2959 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
2960 /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
2961 /// and friend class X (matcher = friendDecl(hasType("X"))
2962 /// \code
2963 /// class X {};
2964 /// void y(X &x) { x; X z; }
2965 /// class Y { friend class X; };
2966 /// \endcode
2967 ///
2968 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
2969 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
2970 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
2971 internal::Matcher<Decl>, InnerMatcher, 1) {
2972 QualType QT = internal::getUnderlyingType(Node);
2973 if (!QT.isNull())
2974 return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
2975 return false;
2976 }
2977
2978 /// Matches if the type location of the declarator decl's type matches
2979 /// the inner matcher.
2980 ///
2981 /// Given
2982 /// \code
2983 /// int x;
2984 /// \endcode
2985 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
2986 /// matches int x
AST_MATCHER_P(DeclaratorDecl,hasTypeLoc,internal::Matcher<TypeLoc>,Inner)2987 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
2988 if (!Node.getTypeSourceInfo())
2989 // This happens for example for implicit destructors.
2990 return false;
2991 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
2992 }
2993
2994 /// Matches if the matched type is represented by the given string.
2995 ///
2996 /// Given
2997 /// \code
2998 /// class Y { public: void x(); };
2999 /// void z() { Y* y; y->x(); }
3000 /// \endcode
3001 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3002 /// matches y->x()
AST_MATCHER_P(QualType,asString,std::string,Name)3003 AST_MATCHER_P(QualType, asString, std::string, Name) {
3004 return Name == Node.getAsString();
3005 }
3006
3007 /// Matches if the matched type is a pointer type and the pointee type
3008 /// matches the specified matcher.
3009 ///
3010 /// Example matches y->x()
3011 /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3012 /// cxxRecordDecl(hasName("Y")))))))
3013 /// \code
3014 /// class Y { public: void x(); };
3015 /// void z() { Y *y; y->x(); }
3016 /// \endcode
AST_MATCHER_P(QualType,pointsTo,internal::Matcher<QualType>,InnerMatcher)3017 AST_MATCHER_P(
3018 QualType, pointsTo, internal::Matcher<QualType>,
3019 InnerMatcher) {
3020 return (!Node.isNull() && Node->isAnyPointerType() &&
3021 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3022 }
3023
3024 /// Overloaded to match the pointee type's declaration.
3025 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3026 InnerMatcher, 1) {
3027 return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3028 .matches(Node, Finder, Builder);
3029 }
3030
3031 /// Matches if the matched type matches the unqualified desugared
3032 /// type of the matched node.
3033 ///
3034 /// For example, in:
3035 /// \code
3036 /// class A {};
3037 /// using B = A;
3038 /// \endcode
3039 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3040 /// both B and A.
AST_MATCHER_P(Type,hasUnqualifiedDesugaredType,internal::Matcher<Type>,InnerMatcher)3041 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3042 InnerMatcher) {
3043 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3044 Builder);
3045 }
3046
3047 /// Matches if the matched type is a reference type and the referenced
3048 /// type matches the specified matcher.
3049 ///
3050 /// Example matches X &x and const X &y
3051 /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3052 /// \code
3053 /// class X {
3054 /// void a(X b) {
3055 /// X &x = b;
3056 /// const X &y = b;
3057 /// }
3058 /// };
3059 /// \endcode
AST_MATCHER_P(QualType,references,internal::Matcher<QualType>,InnerMatcher)3060 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3061 InnerMatcher) {
3062 return (!Node.isNull() && Node->isReferenceType() &&
3063 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3064 }
3065
3066 /// Matches QualTypes whose canonical type matches InnerMatcher.
3067 ///
3068 /// Given:
3069 /// \code
3070 /// typedef int &int_ref;
3071 /// int a;
3072 /// int_ref b = a;
3073 /// \endcode
3074 ///
3075 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3076 /// declaration of b but \c
3077 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
AST_MATCHER_P(QualType,hasCanonicalType,internal::Matcher<QualType>,InnerMatcher)3078 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3079 InnerMatcher) {
3080 if (Node.isNull())
3081 return false;
3082 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3083 }
3084
3085 /// Overloaded to match the referenced type's declaration.
3086 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3087 InnerMatcher, 1) {
3088 return references(qualType(hasDeclaration(InnerMatcher)))
3089 .matches(Node, Finder, Builder);
3090 }
3091
AST_MATCHER_P(CXXMemberCallExpr,onImplicitObjectArgument,internal::Matcher<Expr>,InnerMatcher)3092 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3093 internal::Matcher<Expr>, InnerMatcher) {
3094 const Expr *ExprNode = Node.getImplicitObjectArgument();
3095 return (ExprNode != nullptr &&
3096 InnerMatcher.matches(*ExprNode, Finder, Builder));
3097 }
3098
3099 /// Matches if the expression's type either matches the specified
3100 /// matcher, or is a pointer to a type that matches the InnerMatcher.
3101 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3102 internal::Matcher<QualType>, InnerMatcher, 0) {
3103 return onImplicitObjectArgument(
3104 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3105 .matches(Node, Finder, Builder);
3106 }
3107
3108 /// Overloaded to match the type's declaration.
3109 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3110 internal::Matcher<Decl>, InnerMatcher, 1) {
3111 return onImplicitObjectArgument(
3112 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3113 .matches(Node, Finder, Builder);
3114 }
3115
3116 /// Matches a DeclRefExpr that refers to a declaration that matches the
3117 /// specified matcher.
3118 ///
3119 /// Example matches x in if(x)
3120 /// (matcher = declRefExpr(to(varDecl(hasName("x")))))
3121 /// \code
3122 /// bool x;
3123 /// if (x) {}
3124 /// \endcode
AST_MATCHER_P(DeclRefExpr,to,internal::Matcher<Decl>,InnerMatcher)3125 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3126 InnerMatcher) {
3127 const Decl *DeclNode = Node.getDecl();
3128 return (DeclNode != nullptr &&
3129 InnerMatcher.matches(*DeclNode, Finder, Builder));
3130 }
3131
3132 /// Matches a \c DeclRefExpr that refers to a declaration through a
3133 /// specific using shadow declaration.
3134 ///
3135 /// Given
3136 /// \code
3137 /// namespace a { void f() {} }
3138 /// using a::f;
3139 /// void g() {
3140 /// f(); // Matches this ..
3141 /// a::f(); // .. but not this.
3142 /// }
3143 /// \endcode
3144 /// declRefExpr(throughUsingDecl(anything()))
3145 /// matches \c f()
AST_MATCHER_P(DeclRefExpr,throughUsingDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)3146 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3147 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3148 const NamedDecl *FoundDecl = Node.getFoundDecl();
3149 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3150 return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3151 return false;
3152 }
3153
3154 /// Matches an \c OverloadExpr if any of the declarations in the set of
3155 /// overloads matches the given matcher.
3156 ///
3157 /// Given
3158 /// \code
3159 /// template <typename T> void foo(T);
3160 /// template <typename T> void bar(T);
3161 /// template <typename T> void baz(T t) {
3162 /// foo(t);
3163 /// bar(t);
3164 /// }
3165 /// \endcode
3166 /// unresolvedLookupExpr(hasAnyDeclaration(
3167 /// functionTemplateDecl(hasName("foo"))))
3168 /// matches \c foo in \c foo(t); but not \c bar in \c bar(t);
AST_MATCHER_P(OverloadExpr,hasAnyDeclaration,internal::Matcher<Decl>,InnerMatcher)3169 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3170 InnerMatcher) {
3171 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3172 Node.decls_end(), Finder, Builder);
3173 }
3174
3175 /// Matches the Decl of a DeclStmt which has a single declaration.
3176 ///
3177 /// Given
3178 /// \code
3179 /// int a, b;
3180 /// int c;
3181 /// \endcode
3182 /// declStmt(hasSingleDecl(anything()))
3183 /// matches 'int c;' but not 'int a, b;'.
AST_MATCHER_P(DeclStmt,hasSingleDecl,internal::Matcher<Decl>,InnerMatcher)3184 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3185 if (Node.isSingleDecl()) {
3186 const Decl *FoundDecl = Node.getSingleDecl();
3187 return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3188 }
3189 return false;
3190 }
3191
3192 /// Matches a variable declaration that has an initializer expression
3193 /// that matches the given matcher.
3194 ///
3195 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3196 /// \code
3197 /// bool y() { return true; }
3198 /// bool x = y();
3199 /// \endcode
AST_MATCHER_P(VarDecl,hasInitializer,internal::Matcher<Expr>,InnerMatcher)3200 AST_MATCHER_P(
3201 VarDecl, hasInitializer, internal::Matcher<Expr>,
3202 InnerMatcher) {
3203 const Expr *Initializer = Node.getAnyInitializer();
3204 return (Initializer != nullptr &&
3205 InnerMatcher.matches(*Initializer, Finder, Builder));
3206 }
3207
3208 /// Matches a variable declaration that has function scope and is a
3209 /// non-static local variable.
3210 ///
3211 /// Example matches x (matcher = varDecl(hasLocalStorage())
3212 /// \code
3213 /// void f() {
3214 /// int x;
3215 /// static int y;
3216 /// }
3217 /// int z;
3218 /// \endcode
AST_MATCHER(VarDecl,hasLocalStorage)3219 AST_MATCHER(VarDecl, hasLocalStorage) {
3220 return Node.hasLocalStorage();
3221 }
3222
3223 /// Matches a variable declaration that does not have local storage.
3224 ///
3225 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3226 /// \code
3227 /// void f() {
3228 /// int x;
3229 /// static int y;
3230 /// }
3231 /// int z;
3232 /// \endcode
AST_MATCHER(VarDecl,hasGlobalStorage)3233 AST_MATCHER(VarDecl, hasGlobalStorage) {
3234 return Node.hasGlobalStorage();
3235 }
3236
3237 /// Matches a variable declaration that has automatic storage duration.
3238 ///
3239 /// Example matches x, but not y, z, or a.
3240 /// (matcher = varDecl(hasAutomaticStorageDuration())
3241 /// \code
3242 /// void f() {
3243 /// int x;
3244 /// static int y;
3245 /// thread_local int z;
3246 /// }
3247 /// int a;
3248 /// \endcode
AST_MATCHER(VarDecl,hasAutomaticStorageDuration)3249 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3250 return Node.getStorageDuration() == SD_Automatic;
3251 }
3252
3253 /// Matches a variable declaration that has static storage duration.
3254 /// It includes the variable declared at namespace scope and those declared
3255 /// with "static" and "extern" storage class specifiers.
3256 ///
3257 /// \code
3258 /// void f() {
3259 /// int x;
3260 /// static int y;
3261 /// thread_local int z;
3262 /// }
3263 /// int a;
3264 /// static int b;
3265 /// extern int c;
3266 /// varDecl(hasStaticStorageDuration())
3267 /// matches the function declaration y, a, b and c.
3268 /// \endcode
AST_MATCHER(VarDecl,hasStaticStorageDuration)3269 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3270 return Node.getStorageDuration() == SD_Static;
3271 }
3272
3273 /// Matches a variable declaration that has thread storage duration.
3274 ///
3275 /// Example matches z, but not x, z, or a.
3276 /// (matcher = varDecl(hasThreadStorageDuration())
3277 /// \code
3278 /// void f() {
3279 /// int x;
3280 /// static int y;
3281 /// thread_local int z;
3282 /// }
3283 /// int a;
3284 /// \endcode
AST_MATCHER(VarDecl,hasThreadStorageDuration)3285 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3286 return Node.getStorageDuration() == SD_Thread;
3287 }
3288
3289 /// Matches a variable declaration that is an exception variable from
3290 /// a C++ catch block, or an Objective-C \@catch statement.
3291 ///
3292 /// Example matches x (matcher = varDecl(isExceptionVariable())
3293 /// \code
3294 /// void f(int y) {
3295 /// try {
3296 /// } catch (int x) {
3297 /// }
3298 /// }
3299 /// \endcode
AST_MATCHER(VarDecl,isExceptionVariable)3300 AST_MATCHER(VarDecl, isExceptionVariable) {
3301 return Node.isExceptionVariable();
3302 }
3303
3304 /// Checks that a call expression or a constructor call expression has
3305 /// a specific number of arguments (including absent default arguments).
3306 ///
3307 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3308 /// \code
3309 /// void f(int x, int y);
3310 /// f(0, 0);
3311 /// \endcode
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,ObjCMessageExpr),unsigned,N)3312 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3313 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3314 CXXConstructExpr,
3315 ObjCMessageExpr),
3316 unsigned, N) {
3317 return Node.getNumArgs() == N;
3318 }
3319
3320 /// Matches the n'th argument of a call expression or a constructor
3321 /// call expression.
3322 ///
3323 /// Example matches y in x(y)
3324 /// (matcher = callExpr(hasArgument(0, declRefExpr())))
3325 /// \code
3326 /// void x(int) { int y; x(y); }
3327 /// \endcode
AST_POLYMORPHIC_MATCHER_P2(hasArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,ObjCMessageExpr),unsigned,N,internal::Matcher<Expr>,InnerMatcher)3328 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3329 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3330 CXXConstructExpr,
3331 ObjCMessageExpr),
3332 unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3333 return (N < Node.getNumArgs() &&
3334 InnerMatcher.matches(
3335 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3336 }
3337
3338 /// Matches declaration statements that contain a specific number of
3339 /// declarations.
3340 ///
3341 /// Example: Given
3342 /// \code
3343 /// int a, b;
3344 /// int c;
3345 /// int d = 2, e;
3346 /// \endcode
3347 /// declCountIs(2)
3348 /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
AST_MATCHER_P(DeclStmt,declCountIs,unsigned,N)3349 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3350 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3351 }
3352
3353 /// Matches the n'th declaration of a declaration statement.
3354 ///
3355 /// Note that this does not work for global declarations because the AST
3356 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3357 /// DeclStmt's.
3358 /// Example: Given non-global declarations
3359 /// \code
3360 /// int a, b = 0;
3361 /// int c;
3362 /// int d = 2, e;
3363 /// \endcode
3364 /// declStmt(containsDeclaration(
3365 /// 0, varDecl(hasInitializer(anything()))))
3366 /// matches only 'int d = 2, e;', and
3367 /// declStmt(containsDeclaration(1, varDecl()))
3368 /// \code
3369 /// matches 'int a, b = 0' as well as 'int d = 2, e;'
3370 /// but 'int c;' is not matched.
3371 /// \endcode
AST_MATCHER_P2(DeclStmt,containsDeclaration,unsigned,N,internal::Matcher<Decl>,InnerMatcher)3372 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3373 internal::Matcher<Decl>, InnerMatcher) {
3374 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3375 if (N >= NumDecls)
3376 return false;
3377 DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3378 std::advance(Iterator, N);
3379 return InnerMatcher.matches(**Iterator, Finder, Builder);
3380 }
3381
3382 /// Matches a C++ catch statement that has a catch-all handler.
3383 ///
3384 /// Given
3385 /// \code
3386 /// try {
3387 /// // ...
3388 /// } catch (int) {
3389 /// // ...
3390 /// } catch (...) {
3391 /// // ...
3392 /// }
3393 /// /endcode
3394 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
AST_MATCHER(CXXCatchStmt,isCatchAll)3395 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3396 return Node.getExceptionDecl() == nullptr;
3397 }
3398
3399 /// Matches a constructor initializer.
3400 ///
3401 /// Given
3402 /// \code
3403 /// struct Foo {
3404 /// Foo() : foo_(1) { }
3405 /// int foo_;
3406 /// };
3407 /// \endcode
3408 /// cxxRecordDecl(has(cxxConstructorDecl(
3409 /// hasAnyConstructorInitializer(anything())
3410 /// )))
3411 /// record matches Foo, hasAnyConstructorInitializer matches foo_(1)
AST_MATCHER_P(CXXConstructorDecl,hasAnyConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)3412 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3413 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3414 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3415 Node.init_end(), Finder, Builder);
3416 }
3417
3418 /// Matches the field declaration of a constructor initializer.
3419 ///
3420 /// Given
3421 /// \code
3422 /// struct Foo {
3423 /// Foo() : foo_(1) { }
3424 /// int foo_;
3425 /// };
3426 /// \endcode
3427 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3428 /// forField(hasName("foo_"))))))
3429 /// matches Foo
3430 /// with forField matching foo_
AST_MATCHER_P(CXXCtorInitializer,forField,internal::Matcher<FieldDecl>,InnerMatcher)3431 AST_MATCHER_P(CXXCtorInitializer, forField,
3432 internal::Matcher<FieldDecl>, InnerMatcher) {
3433 const FieldDecl *NodeAsDecl = Node.getAnyMember();
3434 return (NodeAsDecl != nullptr &&
3435 InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3436 }
3437
3438 /// Matches the initializer expression of a constructor initializer.
3439 ///
3440 /// Given
3441 /// \code
3442 /// struct Foo {
3443 /// Foo() : foo_(1) { }
3444 /// int foo_;
3445 /// };
3446 /// \endcode
3447 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3448 /// withInitializer(integerLiteral(equals(1)))))))
3449 /// matches Foo
3450 /// with withInitializer matching (1)
AST_MATCHER_P(CXXCtorInitializer,withInitializer,internal::Matcher<Expr>,InnerMatcher)3451 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3452 internal::Matcher<Expr>, InnerMatcher) {
3453 const Expr* NodeAsExpr = Node.getInit();
3454 return (NodeAsExpr != nullptr &&
3455 InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3456 }
3457
3458 /// Matches a constructor initializer if it is explicitly written in
3459 /// code (as opposed to implicitly added by the compiler).
3460 ///
3461 /// Given
3462 /// \code
3463 /// struct Foo {
3464 /// Foo() { }
3465 /// Foo(int) : foo_("A") { }
3466 /// string foo_;
3467 /// };
3468 /// \endcode
3469 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3470 /// will match Foo(int), but not Foo()
AST_MATCHER(CXXCtorInitializer,isWritten)3471 AST_MATCHER(CXXCtorInitializer, isWritten) {
3472 return Node.isWritten();
3473 }
3474
3475 /// Matches a constructor initializer if it is initializing a base, as
3476 /// opposed to a member.
3477 ///
3478 /// Given
3479 /// \code
3480 /// struct B {};
3481 /// struct D : B {
3482 /// int I;
3483 /// D(int i) : I(i) {}
3484 /// };
3485 /// struct E : B {
3486 /// E() : B() {}
3487 /// };
3488 /// \endcode
3489 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3490 /// will match E(), but not match D(int).
AST_MATCHER(CXXCtorInitializer,isBaseInitializer)3491 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3492 return Node.isBaseInitializer();
3493 }
3494
3495 /// Matches a constructor initializer if it is initializing a member, as
3496 /// opposed to a base.
3497 ///
3498 /// Given
3499 /// \code
3500 /// struct B {};
3501 /// struct D : B {
3502 /// int I;
3503 /// D(int i) : I(i) {}
3504 /// };
3505 /// struct E : B {
3506 /// E() : B() {}
3507 /// };
3508 /// \endcode
3509 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3510 /// will match D(int), but not match E().
AST_MATCHER(CXXCtorInitializer,isMemberInitializer)3511 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3512 return Node.isMemberInitializer();
3513 }
3514
3515 /// Matches any argument of a call expression or a constructor call
3516 /// expression, or an ObjC-message-send expression.
3517 ///
3518 /// Given
3519 /// \code
3520 /// void x(int, int, int) { int y; x(1, y, 42); }
3521 /// \endcode
3522 /// callExpr(hasAnyArgument(declRefExpr()))
3523 /// matches x(1, y, 42)
3524 /// with hasAnyArgument(...)
3525 /// matching y
3526 ///
3527 /// For ObjectiveC, given
3528 /// \code
3529 /// @interface I - (void) f:(int) y; @end
3530 /// void foo(I *i) { [i f:12]; }
3531 /// \endcode
3532 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3533 /// matches [i f:12]
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr,ObjCMessageExpr),internal::Matcher<Expr>,InnerMatcher)3534 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3535 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3536 CXXConstructExpr,
3537 ObjCMessageExpr),
3538 internal::Matcher<Expr>, InnerMatcher) {
3539 for (const Expr *Arg : Node.arguments()) {
3540 BoundNodesTreeBuilder Result(*Builder);
3541 if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3542 *Builder = std::move(Result);
3543 return true;
3544 }
3545 }
3546 return false;
3547 }
3548
3549 /// Matches a constructor call expression which uses list initialization.
AST_MATCHER(CXXConstructExpr,isListInitialization)3550 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3551 return Node.isListInitialization();
3552 }
3553
3554 /// Matches a constructor call expression which requires
3555 /// zero initialization.
3556 ///
3557 /// Given
3558 /// \code
3559 /// void foo() {
3560 /// struct point { double x; double y; };
3561 /// point pt[2] = { { 1.0, 2.0 } };
3562 /// }
3563 /// \endcode
3564 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3565 /// will match the implicit array filler for pt[1].
AST_MATCHER(CXXConstructExpr,requiresZeroInitialization)3566 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3567 return Node.requiresZeroInitialization();
3568 }
3569
3570 /// Matches the n'th parameter of a function or an ObjC method
3571 /// declaration or a block.
3572 ///
3573 /// Given
3574 /// \code
3575 /// class X { void f(int x) {} };
3576 /// \endcode
3577 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3578 /// matches f(int x) {}
3579 /// with hasParameter(...)
3580 /// matching int x
3581 ///
3582 /// For ObjectiveC, given
3583 /// \code
3584 /// @interface I - (void) f:(int) y; @end
3585 /// \endcode
3586 //
3587 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3588 /// matches the declaration of method f with hasParameter
3589 /// matching y.
AST_POLYMORPHIC_MATCHER_P2(hasParameter,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,ObjCMethodDecl,BlockDecl),unsigned,N,internal::Matcher<ParmVarDecl>,InnerMatcher)3590 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3591 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3592 ObjCMethodDecl,
3593 BlockDecl),
3594 unsigned, N, internal::Matcher<ParmVarDecl>,
3595 InnerMatcher) {
3596 return (N < Node.parameters().size()
3597 && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3598 }
3599
3600 /// Matches all arguments and their respective ParmVarDecl.
3601 ///
3602 /// Given
3603 /// \code
3604 /// void f(int i);
3605 /// int y;
3606 /// f(y);
3607 /// \endcode
3608 /// callExpr(
3609 /// forEachArgumentWithParam(
3610 /// declRefExpr(to(varDecl(hasName("y")))),
3611 /// parmVarDecl(hasType(isInteger()))
3612 /// ))
3613 /// matches f(y);
3614 /// with declRefExpr(...)
3615 /// matching int y
3616 /// and parmVarDecl(...)
3617 /// matching int i
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,AST_POLYMORPHIC_SUPPORTED_TYPES (CallExpr,CXXConstructExpr),internal::Matcher<Expr>,ArgMatcher,internal::Matcher<ParmVarDecl>,ParamMatcher)3618 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3619 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3620 CXXConstructExpr),
3621 internal::Matcher<Expr>, ArgMatcher,
3622 internal::Matcher<ParmVarDecl>, ParamMatcher) {
3623 BoundNodesTreeBuilder Result;
3624 // The first argument of an overloaded member operator is the implicit object
3625 // argument of the method which should not be matched against a parameter, so
3626 // we skip over it here.
3627 BoundNodesTreeBuilder Matches;
3628 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3629 .matches(Node, Finder, &Matches)
3630 ? 1
3631 : 0;
3632 int ParamIndex = 0;
3633 bool Matched = false;
3634 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3635 BoundNodesTreeBuilder ArgMatches(*Builder);
3636 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3637 Finder, &ArgMatches)) {
3638 BoundNodesTreeBuilder ParamMatches(ArgMatches);
3639 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3640 hasParameter(ParamIndex, ParamMatcher)))),
3641 callExpr(callee(functionDecl(
3642 hasParameter(ParamIndex, ParamMatcher))))))
3643 .matches(Node, Finder, &ParamMatches)) {
3644 Result.addMatch(ParamMatches);
3645 Matched = true;
3646 }
3647 }
3648 ++ParamIndex;
3649 }
3650 *Builder = std::move(Result);
3651 return Matched;
3652 }
3653
3654 /// Matches any parameter of a function or an ObjC method declaration or a
3655 /// block.
3656 ///
3657 /// Does not match the 'this' parameter of a method.
3658 ///
3659 /// Given
3660 /// \code
3661 /// class X { void f(int x, int y, int z) {} };
3662 /// \endcode
3663 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3664 /// matches f(int x, int y, int z) {}
3665 /// with hasAnyParameter(...)
3666 /// matching int y
3667 ///
3668 /// For ObjectiveC, given
3669 /// \code
3670 /// @interface I - (void) f:(int) y; @end
3671 /// \endcode
3672 //
3673 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
3674 /// matches the declaration of method f with hasParameter
3675 /// matching y.
3676 ///
3677 /// For blocks, given
3678 /// \code
3679 /// b = ^(int y) { printf("%d", y) };
3680 /// \endcode
3681 ///
3682 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
3683 /// matches the declaration of the block b with hasParameter
3684 /// matching y.
AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,ObjCMethodDecl,BlockDecl),internal::Matcher<ParmVarDecl>,InnerMatcher)3685 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
3686 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3687 ObjCMethodDecl,
3688 BlockDecl),
3689 internal::Matcher<ParmVarDecl>,
3690 InnerMatcher) {
3691 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3692 Node.param_end(), Finder, Builder);
3693 }
3694
3695 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3696 /// specific parameter count.
3697 ///
3698 /// Given
3699 /// \code
3700 /// void f(int i) {}
3701 /// void g(int i, int j) {}
3702 /// void h(int i, int j);
3703 /// void j(int i);
3704 /// void k(int x, int y, int z, ...);
3705 /// \endcode
3706 /// functionDecl(parameterCountIs(2))
3707 /// matches \c g and \c h
3708 /// functionProtoType(parameterCountIs(2))
3709 /// matches \c g and \c h
3710 /// functionProtoType(parameterCountIs(3))
3711 /// matches \c k
AST_POLYMORPHIC_MATCHER_P(parameterCountIs,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,FunctionProtoType),unsigned,N)3712 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
3713 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3714 FunctionProtoType),
3715 unsigned, N) {
3716 return Node.getNumParams() == N;
3717 }
3718
3719 /// Matches \c FunctionDecls that have a noreturn attribute.
3720 ///
3721 /// Given
3722 /// \code
3723 /// void nope();
3724 /// [[noreturn]] void a();
3725 /// __attribute__((noreturn)) void b();
3726 /// struct c { [[noreturn]] c(); };
3727 /// \endcode
3728 /// functionDecl(isNoReturn())
3729 /// matches all of those except
3730 /// \code
3731 /// void nope();
3732 /// \endcode
AST_MATCHER(FunctionDecl,isNoReturn)3733 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
3734
3735 /// Matches the return type of a function declaration.
3736 ///
3737 /// Given:
3738 /// \code
3739 /// class X { int f() { return 1; } };
3740 /// \endcode
3741 /// cxxMethodDecl(returns(asString("int")))
3742 /// matches int f() { return 1; }
AST_MATCHER_P(FunctionDecl,returns,internal::Matcher<QualType>,InnerMatcher)3743 AST_MATCHER_P(FunctionDecl, returns,
3744 internal::Matcher<QualType>, InnerMatcher) {
3745 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
3746 }
3747
3748 /// Matches extern "C" function or variable declarations.
3749 ///
3750 /// Given:
3751 /// \code
3752 /// extern "C" void f() {}
3753 /// extern "C" { void g() {} }
3754 /// void h() {}
3755 /// extern "C" int x = 1;
3756 /// extern "C" int y = 2;
3757 /// int z = 3;
3758 /// \endcode
3759 /// functionDecl(isExternC())
3760 /// matches the declaration of f and g, but not the declaration of h.
3761 /// varDecl(isExternC())
3762 /// matches the declaration of x and y, but not the declaration of z.
AST_POLYMORPHIC_MATCHER(isExternC,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl))3763 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3764 VarDecl)) {
3765 return Node.isExternC();
3766 }
3767
3768 /// Matches variable/function declarations that have "static" storage
3769 /// class specifier ("static" keyword) written in the source.
3770 ///
3771 /// Given:
3772 /// \code
3773 /// static void f() {}
3774 /// static int i = 0;
3775 /// extern int j;
3776 /// int k;
3777 /// \endcode
3778 /// functionDecl(isStaticStorageClass())
3779 /// matches the function declaration f.
3780 /// varDecl(isStaticStorageClass())
3781 /// matches the variable declaration i.
AST_POLYMORPHIC_MATCHER(isStaticStorageClass,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl))3782 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
3783 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3784 VarDecl)) {
3785 return Node.getStorageClass() == SC_Static;
3786 }
3787
3788 /// Matches deleted function declarations.
3789 ///
3790 /// Given:
3791 /// \code
3792 /// void Func();
3793 /// void DeletedFunc() = delete;
3794 /// \endcode
3795 /// functionDecl(isDeleted())
3796 /// matches the declaration of DeletedFunc, but not Func.
AST_MATCHER(FunctionDecl,isDeleted)3797 AST_MATCHER(FunctionDecl, isDeleted) {
3798 return Node.isDeleted();
3799 }
3800
3801 /// Matches defaulted function declarations.
3802 ///
3803 /// Given:
3804 /// \code
3805 /// class A { ~A(); };
3806 /// class B { ~B() = default; };
3807 /// \endcode
3808 /// functionDecl(isDefaulted())
3809 /// matches the declaration of ~B, but not ~A.
AST_MATCHER(FunctionDecl,isDefaulted)3810 AST_MATCHER(FunctionDecl, isDefaulted) {
3811 return Node.isDefaulted();
3812 }
3813
3814 /// Matches functions that have a dynamic exception specification.
3815 ///
3816 /// Given:
3817 /// \code
3818 /// void f();
3819 /// void g() noexcept;
3820 /// void h() noexcept(true);
3821 /// void i() noexcept(false);
3822 /// void j() throw();
3823 /// void k() throw(int);
3824 /// void l() throw(...);
3825 /// \endcode
3826 /// functionDecl(hasDynamicExceptionSpec()) and
3827 /// functionProtoType(hasDynamicExceptionSpec())
3828 /// match the declarations of j, k, and l, but not f, g, h, or i.
AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,FunctionProtoType))3829 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
3830 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3831 FunctionProtoType)) {
3832 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
3833 return FnTy->hasDynamicExceptionSpec();
3834 return false;
3835 }
3836
3837 /// Matches functions that have a non-throwing exception specification.
3838 ///
3839 /// Given:
3840 /// \code
3841 /// void f();
3842 /// void g() noexcept;
3843 /// void h() throw();
3844 /// void i() throw(int);
3845 /// void j() noexcept(false);
3846 /// \endcode
3847 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
3848 /// match the declarations of g, and h, but not f, i or j.
AST_POLYMORPHIC_MATCHER(isNoThrow,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,FunctionProtoType))3849 AST_POLYMORPHIC_MATCHER(isNoThrow,
3850 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3851 FunctionProtoType)) {
3852 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
3853
3854 // If the function does not have a prototype, then it is assumed to be a
3855 // throwing function (as it would if the function did not have any exception
3856 // specification).
3857 if (!FnTy)
3858 return false;
3859
3860 // Assume the best for any unresolved exception specification.
3861 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
3862 return true;
3863
3864 return FnTy->isNothrow();
3865 }
3866
3867 /// Matches constexpr variable and function declarations,
3868 /// and if constexpr.
3869 ///
3870 /// Given:
3871 /// \code
3872 /// constexpr int foo = 42;
3873 /// constexpr int bar();
3874 /// void baz() { if constexpr(1 > 0) {} }
3875 /// \endcode
3876 /// varDecl(isConstexpr())
3877 /// matches the declaration of foo.
3878 /// functionDecl(isConstexpr())
3879 /// matches the declaration of bar.
3880 /// ifStmt(isConstexpr())
3881 /// matches the if statement in baz.
AST_POLYMORPHIC_MATCHER(isConstexpr,AST_POLYMORPHIC_SUPPORTED_TYPES (VarDecl,FunctionDecl,IfStmt))3882 AST_POLYMORPHIC_MATCHER(isConstexpr,
3883 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
3884 FunctionDecl,
3885 IfStmt)) {
3886 return Node.isConstexpr();
3887 }
3888
3889 /// Matches the condition expression of an if statement, for loop,
3890 /// switch statement or conditional operator.
3891 ///
3892 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
3893 /// \code
3894 /// if (true) {}
3895 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasCondition,AST_POLYMORPHIC_SUPPORTED_TYPES (IfStmt,ForStmt,WhileStmt,DoStmt,SwitchStmt,AbstractConditionalOperator),internal::Matcher<Expr>,InnerMatcher)3896 AST_POLYMORPHIC_MATCHER_P(
3897 hasCondition,
3898 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
3899 SwitchStmt, AbstractConditionalOperator),
3900 internal::Matcher<Expr>, InnerMatcher) {
3901 const Expr *const Condition = Node.getCond();
3902 return (Condition != nullptr &&
3903 InnerMatcher.matches(*Condition, Finder, Builder));
3904 }
3905
3906 /// Matches the then-statement of an if statement.
3907 ///
3908 /// Examples matches the if statement
3909 /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
3910 /// \code
3911 /// if (false) true; else false;
3912 /// \endcode
AST_MATCHER_P(IfStmt,hasThen,internal::Matcher<Stmt>,InnerMatcher)3913 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
3914 const Stmt *const Then = Node.getThen();
3915 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
3916 }
3917
3918 /// Matches the else-statement of an if statement.
3919 ///
3920 /// Examples matches the if statement
3921 /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
3922 /// \code
3923 /// if (false) false; else true;
3924 /// \endcode
AST_MATCHER_P(IfStmt,hasElse,internal::Matcher<Stmt>,InnerMatcher)3925 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
3926 const Stmt *const Else = Node.getElse();
3927 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
3928 }
3929
3930 /// Matches if a node equals a previously bound node.
3931 ///
3932 /// Matches a node if it equals the node previously bound to \p ID.
3933 ///
3934 /// Given
3935 /// \code
3936 /// class X { int a; int b; };
3937 /// \endcode
3938 /// cxxRecordDecl(
3939 /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
3940 /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
3941 /// matches the class \c X, as \c a and \c b have the same type.
3942 ///
3943 /// Note that when multiple matches are involved via \c forEach* matchers,
3944 /// \c equalsBoundNodes acts as a filter.
3945 /// For example:
3946 /// compoundStmt(
3947 /// forEachDescendant(varDecl().bind("d")),
3948 /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
3949 /// will trigger a match for each combination of variable declaration
3950 /// 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)3951 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
3952 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
3953 QualType),
3954 std::string, ID) {
3955 // FIXME: Figure out whether it makes sense to allow this
3956 // on any other node types.
3957 // For *Loc it probably does not make sense, as those seem
3958 // unique. For NestedNameSepcifier it might make sense, as
3959 // those also have pointer identity, but I'm not sure whether
3960 // they're ever reused.
3961 internal::NotEqualsBoundNodePredicate Predicate;
3962 Predicate.ID = ID;
3963 Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
3964 return Builder->removeBindings(Predicate);
3965 }
3966
3967 /// Matches the condition variable statement in an if statement.
3968 ///
3969 /// Given
3970 /// \code
3971 /// if (A* a = GetAPointer()) {}
3972 /// \endcode
3973 /// hasConditionVariableStatement(...)
3974 /// matches 'A* a = GetAPointer()'.
AST_MATCHER_P(IfStmt,hasConditionVariableStatement,internal::Matcher<DeclStmt>,InnerMatcher)3975 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
3976 internal::Matcher<DeclStmt>, InnerMatcher) {
3977 const DeclStmt* const DeclarationStatement =
3978 Node.getConditionVariableDeclStmt();
3979 return DeclarationStatement != nullptr &&
3980 InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
3981 }
3982
3983 /// Matches the index expression of an array subscript expression.
3984 ///
3985 /// Given
3986 /// \code
3987 /// int i[5];
3988 /// void f() { i[1] = 42; }
3989 /// \endcode
3990 /// arraySubscriptExpression(hasIndex(integerLiteral()))
3991 /// matches \c i[1] with the \c integerLiteral() matching \c 1
AST_MATCHER_P(ArraySubscriptExpr,hasIndex,internal::Matcher<Expr>,InnerMatcher)3992 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
3993 internal::Matcher<Expr>, InnerMatcher) {
3994 if (const Expr* Expression = Node.getIdx())
3995 return InnerMatcher.matches(*Expression, Finder, Builder);
3996 return false;
3997 }
3998
3999 /// Matches the base expression of an array subscript expression.
4000 ///
4001 /// Given
4002 /// \code
4003 /// int i[5];
4004 /// void f() { i[1] = 42; }
4005 /// \endcode
4006 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4007 /// hasSourceExpression(declRefExpr()))))
4008 /// matches \c i[1] with the \c declRefExpr() matching \c i
AST_MATCHER_P(ArraySubscriptExpr,hasBase,internal::Matcher<Expr>,InnerMatcher)4009 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4010 internal::Matcher<Expr>, InnerMatcher) {
4011 if (const Expr* Expression = Node.getBase())
4012 return InnerMatcher.matches(*Expression, Finder, Builder);
4013 return false;
4014 }
4015
4016 /// Matches a 'for', 'while', 'do while' statement or a function
4017 /// definition that has a given body.
4018 ///
4019 /// Given
4020 /// \code
4021 /// for (;;) {}
4022 /// \endcode
4023 /// hasBody(compoundStmt())
4024 /// matches 'for (;;) {}'
4025 /// with compoundStmt()
4026 /// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasBody,AST_POLYMORPHIC_SUPPORTED_TYPES (DoStmt,ForStmt,WhileStmt,CXXForRangeStmt,FunctionDecl),internal::Matcher<Stmt>,InnerMatcher)4027 AST_POLYMORPHIC_MATCHER_P(hasBody,
4028 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4029 WhileStmt,
4030 CXXForRangeStmt,
4031 FunctionDecl),
4032 internal::Matcher<Stmt>, InnerMatcher) {
4033 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4034 return (Statement != nullptr &&
4035 InnerMatcher.matches(*Statement, Finder, Builder));
4036 }
4037
4038 /// Matches compound statements where at least one substatement matches
4039 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4040 ///
4041 /// Given
4042 /// \code
4043 /// { {}; 1+2; }
4044 /// \endcode
4045 /// hasAnySubstatement(compoundStmt())
4046 /// matches '{ {}; 1+2; }'
4047 /// with compoundStmt()
4048 /// matching '{}'
AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,AST_POLYMORPHIC_SUPPORTED_TYPES (CompoundStmt,StmtExpr),internal::Matcher<Stmt>,InnerMatcher)4049 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4050 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4051 StmtExpr),
4052 internal::Matcher<Stmt>, InnerMatcher) {
4053 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4054 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4055 CS->body_end(), Finder, Builder);
4056 }
4057
4058 /// Checks that a compound statement contains a specific number of
4059 /// child statements.
4060 ///
4061 /// Example: Given
4062 /// \code
4063 /// { for (;;) {} }
4064 /// \endcode
4065 /// compoundStmt(statementCountIs(0)))
4066 /// matches '{}'
4067 /// but does not match the outer compound statement.
AST_MATCHER_P(CompoundStmt,statementCountIs,unsigned,N)4068 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4069 return Node.size() == N;
4070 }
4071
4072 /// Matches literals that are equal to the given value of type ValueT.
4073 ///
4074 /// Given
4075 /// \code
4076 /// f('\0', false, 3.14, 42);
4077 /// \endcode
4078 /// characterLiteral(equals(0))
4079 /// matches '\0'
4080 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4081 /// match false
4082 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4083 /// match 3.14
4084 /// integerLiteral(equals(42))
4085 /// matches 42
4086 ///
4087 /// Note that you cannot directly match a negative numeric literal because the
4088 /// minus sign is not part of the literal: It is a unary operator whose operand
4089 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4090 /// matcher to match the minus sign:
4091 ///
4092 /// unaryOperator(hasOperatorName("-"),
4093 /// hasUnaryOperand(integerLiteral(equals(13))))
4094 ///
4095 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4096 /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4097 template <typename ValueT>
4098 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
equals(const ValueT & Value)4099 equals(const ValueT &Value) {
4100 return internal::PolymorphicMatcherWithParam1<
4101 internal::ValueEqualsMatcher,
4102 ValueT>(Value);
4103 }
4104
4105 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4106 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4107 CXXBoolLiteralExpr,
4108 IntegerLiteral),
4109 bool, Value, 0) {
4110 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4111 .matchesNode(Node);
4112 }
4113
4114 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4115 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4116 CXXBoolLiteralExpr,
4117 IntegerLiteral),
4118 unsigned, Value, 1) {
4119 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4120 .matchesNode(Node);
4121 }
4122
4123 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4124 AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4125 CXXBoolLiteralExpr,
4126 FloatingLiteral,
4127 IntegerLiteral),
4128 double, Value, 2) {
4129 return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4130 .matchesNode(Node);
4131 }
4132
4133 /// Matches the operator Name of operator expressions (binary or
4134 /// unary).
4135 ///
4136 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4137 /// \code
4138 /// !(a || b)
4139 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasOperatorName,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,UnaryOperator),std::string,Name)4140 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4141 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4142 UnaryOperator),
4143 std::string, Name) {
4144 return Name == Node.getOpcodeStr(Node.getOpcode());
4145 }
4146
4147 /// Matches all kinds of assignment operators.
4148 ///
4149 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4150 /// \code
4151 /// if (a == b)
4152 /// a += b;
4153 /// \endcode
4154 ///
4155 /// Example 2: matches s1 = s2
4156 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4157 /// \code
4158 /// struct S { S& operator=(const S&); };
4159 /// void x() { S s1, s2; s1 = s2; })
4160 /// \endcode
AST_POLYMORPHIC_MATCHER(isAssignmentOperator,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,CXXOperatorCallExpr))4161 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4162 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4163 CXXOperatorCallExpr)) {
4164 return Node.isAssignmentOp();
4165 }
4166
4167 /// Matches the left hand side of binary operator expressions.
4168 ///
4169 /// Example matches a (matcher = binaryOperator(hasLHS()))
4170 /// \code
4171 /// a || b
4172 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasLHS,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,ArraySubscriptExpr),internal::Matcher<Expr>,InnerMatcher)4173 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4174 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4175 ArraySubscriptExpr),
4176 internal::Matcher<Expr>, InnerMatcher) {
4177 const Expr *LeftHandSide = Node.getLHS();
4178 return (LeftHandSide != nullptr &&
4179 InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4180 }
4181
4182 /// Matches the right hand side of binary operator expressions.
4183 ///
4184 /// Example matches b (matcher = binaryOperator(hasRHS()))
4185 /// \code
4186 /// a || b
4187 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasRHS,AST_POLYMORPHIC_SUPPORTED_TYPES (BinaryOperator,ArraySubscriptExpr),internal::Matcher<Expr>,InnerMatcher)4188 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4189 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4190 ArraySubscriptExpr),
4191 internal::Matcher<Expr>, InnerMatcher) {
4192 const Expr *RightHandSide = Node.getRHS();
4193 return (RightHandSide != nullptr &&
4194 InnerMatcher.matches(*RightHandSide, Finder, Builder));
4195 }
4196
4197 /// Matches if either the left hand side or the right hand side of a
4198 /// binary operator matches.
hasEitherOperand(const internal::Matcher<Expr> & InnerMatcher)4199 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4200 const internal::Matcher<Expr> &InnerMatcher) {
4201 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4202 }
4203
4204 /// Matches if the operand of a unary operator matches.
4205 ///
4206 /// Example matches true (matcher = hasUnaryOperand(
4207 /// cxxBoolLiteral(equals(true))))
4208 /// \code
4209 /// !true
4210 /// \endcode
AST_MATCHER_P(UnaryOperator,hasUnaryOperand,internal::Matcher<Expr>,InnerMatcher)4211 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4212 internal::Matcher<Expr>, InnerMatcher) {
4213 const Expr * const Operand = Node.getSubExpr();
4214 return (Operand != nullptr &&
4215 InnerMatcher.matches(*Operand, Finder, Builder));
4216 }
4217
4218 /// Matches if the cast's source expression
4219 /// or opaque value's source expression matches the given matcher.
4220 ///
4221 /// Example 1: matches "a string"
4222 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4223 /// \code
4224 /// class URL { URL(string); };
4225 /// URL url = "a string";
4226 /// \endcode
4227 ///
4228 /// Example 2: matches 'b' (matcher =
4229 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4230 /// \code
4231 /// int a = b ?: 1;
4232 /// \endcode
AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,AST_POLYMORPHIC_SUPPORTED_TYPES (CastExpr,OpaqueValueExpr),internal::Matcher<Expr>,InnerMatcher)4233 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4234 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4235 OpaqueValueExpr),
4236 internal::Matcher<Expr>, InnerMatcher) {
4237 const Expr *const SubExpression =
4238 internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4239 return (SubExpression != nullptr &&
4240 InnerMatcher.matches(*SubExpression, Finder, Builder));
4241 }
4242
4243 /// Matches casts that has a given cast kind.
4244 ///
4245 /// Example: matches the implicit cast around \c 0
4246 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4247 /// \code
4248 /// int *p = 0;
4249 /// \endcode
AST_MATCHER_P(CastExpr,hasCastKind,CastKind,Kind)4250 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4251 return Node.getCastKind() == Kind;
4252 }
4253
4254 /// Matches casts whose destination type matches a given matcher.
4255 ///
4256 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4257 /// actual casts "explicit" casts.)
AST_MATCHER_P(ExplicitCastExpr,hasDestinationType,internal::Matcher<QualType>,InnerMatcher)4258 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4259 internal::Matcher<QualType>, InnerMatcher) {
4260 const QualType NodeType = Node.getTypeAsWritten();
4261 return InnerMatcher.matches(NodeType, Finder, Builder);
4262 }
4263
4264 /// Matches implicit casts whose destination type matches a given
4265 /// matcher.
4266 ///
4267 /// FIXME: Unit test this matcher
AST_MATCHER_P(ImplicitCastExpr,hasImplicitDestinationType,internal::Matcher<QualType>,InnerMatcher)4268 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4269 internal::Matcher<QualType>, InnerMatcher) {
4270 return InnerMatcher.matches(Node.getType(), Finder, Builder);
4271 }
4272
4273 /// Matches RecordDecl object that are spelled with "struct."
4274 ///
4275 /// Example matches S, but not C or U.
4276 /// \code
4277 /// struct S {};
4278 /// class C {};
4279 /// union U {};
4280 /// \endcode
AST_MATCHER(RecordDecl,isStruct)4281 AST_MATCHER(RecordDecl, isStruct) {
4282 return Node.isStruct();
4283 }
4284
4285 /// Matches RecordDecl object that are spelled with "union."
4286 ///
4287 /// Example matches U, but not C or S.
4288 /// \code
4289 /// struct S {};
4290 /// class C {};
4291 /// union U {};
4292 /// \endcode
AST_MATCHER(RecordDecl,isUnion)4293 AST_MATCHER(RecordDecl, isUnion) {
4294 return Node.isUnion();
4295 }
4296
4297 /// Matches RecordDecl object that are spelled with "class."
4298 ///
4299 /// Example matches C, but not S or U.
4300 /// \code
4301 /// struct S {};
4302 /// class C {};
4303 /// union U {};
4304 /// \endcode
AST_MATCHER(RecordDecl,isClass)4305 AST_MATCHER(RecordDecl, isClass) {
4306 return Node.isClass();
4307 }
4308
4309 /// Matches the true branch expression of a conditional operator.
4310 ///
4311 /// Example 1 (conditional ternary operator): matches a
4312 /// \code
4313 /// condition ? a : b
4314 /// \endcode
4315 ///
4316 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4317 /// \code
4318 /// condition ?: b
4319 /// \endcode
AST_MATCHER_P(AbstractConditionalOperator,hasTrueExpression,internal::Matcher<Expr>,InnerMatcher)4320 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4321 internal::Matcher<Expr>, InnerMatcher) {
4322 const Expr *Expression = Node.getTrueExpr();
4323 return (Expression != nullptr &&
4324 InnerMatcher.matches(*Expression, Finder, Builder));
4325 }
4326
4327 /// Matches the false branch expression of a conditional operator
4328 /// (binary or ternary).
4329 ///
4330 /// Example matches b
4331 /// \code
4332 /// condition ? a : b
4333 /// condition ?: b
4334 /// \endcode
AST_MATCHER_P(AbstractConditionalOperator,hasFalseExpression,internal::Matcher<Expr>,InnerMatcher)4335 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4336 internal::Matcher<Expr>, InnerMatcher) {
4337 const Expr *Expression = Node.getFalseExpr();
4338 return (Expression != nullptr &&
4339 InnerMatcher.matches(*Expression, Finder, Builder));
4340 }
4341
4342 /// Matches if a declaration has a body attached.
4343 ///
4344 /// Example matches A, va, fa
4345 /// \code
4346 /// class A {};
4347 /// class B; // Doesn't match, as it has no body.
4348 /// int va;
4349 /// extern int vb; // Doesn't match, as it doesn't define the variable.
4350 /// void fa() {}
4351 /// void fb(); // Doesn't match, as it has no body.
4352 /// @interface X
4353 /// - (void)ma; // Doesn't match, interface is declaration.
4354 /// @end
4355 /// @implementation X
4356 /// - (void)ma {}
4357 /// @end
4358 /// \endcode
4359 ///
4360 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4361 /// Matcher<ObjCMethodDecl>
AST_POLYMORPHIC_MATCHER(isDefinition,AST_POLYMORPHIC_SUPPORTED_TYPES (TagDecl,VarDecl,ObjCMethodDecl,FunctionDecl))4362 AST_POLYMORPHIC_MATCHER(isDefinition,
4363 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4364 ObjCMethodDecl,
4365 FunctionDecl)) {
4366 return Node.isThisDeclarationADefinition();
4367 }
4368
4369 /// Matches if a function declaration is variadic.
4370 ///
4371 /// Example matches f, but not g or h. The function i will not match, even when
4372 /// compiled in C mode.
4373 /// \code
4374 /// void f(...);
4375 /// void g(int);
4376 /// template <typename... Ts> void h(Ts...);
4377 /// void i();
4378 /// \endcode
AST_MATCHER(FunctionDecl,isVariadic)4379 AST_MATCHER(FunctionDecl, isVariadic) {
4380 return Node.isVariadic();
4381 }
4382
4383 /// Matches the class declaration that the given method declaration
4384 /// belongs to.
4385 ///
4386 /// FIXME: Generalize this for other kinds of declarations.
4387 /// FIXME: What other kind of declarations would we need to generalize
4388 /// this to?
4389 ///
4390 /// Example matches A() in the last line
4391 /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4392 /// ofClass(hasName("A"))))))
4393 /// \code
4394 /// class A {
4395 /// public:
4396 /// A();
4397 /// };
4398 /// A a = A();
4399 /// \endcode
AST_MATCHER_P(CXXMethodDecl,ofClass,internal::Matcher<CXXRecordDecl>,InnerMatcher)4400 AST_MATCHER_P(CXXMethodDecl, ofClass,
4401 internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4402 const CXXRecordDecl *Parent = Node.getParent();
4403 return (Parent != nullptr &&
4404 InnerMatcher.matches(*Parent, Finder, Builder));
4405 }
4406
4407 /// Matches each method overridden by the given method. This matcher may
4408 /// produce multiple matches.
4409 ///
4410 /// Given
4411 /// \code
4412 /// class A { virtual void f(); };
4413 /// class B : public A { void f(); };
4414 /// class C : public B { void f(); };
4415 /// \endcode
4416 /// cxxMethodDecl(ofClass(hasName("C")),
4417 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4418 /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4419 /// that B::f is not overridden by C::f).
4420 ///
4421 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4422 /// \code
4423 /// class A1 { virtual void f(); };
4424 /// class A2 { virtual void f(); };
4425 /// class C : public A1, public A2 { void f(); };
4426 /// \endcode
4427 /// cxxMethodDecl(ofClass(hasName("C")),
4428 /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4429 /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4430 /// once with "b" binding "A2::f" and "d" binding "C::f".
AST_MATCHER_P(CXXMethodDecl,forEachOverridden,internal::Matcher<CXXMethodDecl>,InnerMatcher)4431 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4432 internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4433 BoundNodesTreeBuilder Result;
4434 bool Matched = false;
4435 for (const auto *Overridden : Node.overridden_methods()) {
4436 BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4437 const bool OverriddenMatched =
4438 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4439 if (OverriddenMatched) {
4440 Matched = true;
4441 Result.addMatch(OverriddenBuilder);
4442 }
4443 }
4444 *Builder = std::move(Result);
4445 return Matched;
4446 }
4447
4448 /// Matches if the given method declaration is virtual.
4449 ///
4450 /// Given
4451 /// \code
4452 /// class A {
4453 /// public:
4454 /// virtual void x();
4455 /// };
4456 /// \endcode
4457 /// matches A::x
AST_MATCHER(CXXMethodDecl,isVirtual)4458 AST_MATCHER(CXXMethodDecl, isVirtual) {
4459 return Node.isVirtual();
4460 }
4461
4462 /// Matches if the given method declaration has an explicit "virtual".
4463 ///
4464 /// Given
4465 /// \code
4466 /// class A {
4467 /// public:
4468 /// virtual void x();
4469 /// };
4470 /// class B : public A {
4471 /// public:
4472 /// void x();
4473 /// };
4474 /// \endcode
4475 /// matches A::x but not B::x
AST_MATCHER(CXXMethodDecl,isVirtualAsWritten)4476 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4477 return Node.isVirtualAsWritten();
4478 }
4479
4480 /// Matches if the given method or class declaration is final.
4481 ///
4482 /// Given:
4483 /// \code
4484 /// class A final {};
4485 ///
4486 /// struct B {
4487 /// virtual void f();
4488 /// };
4489 ///
4490 /// struct C : B {
4491 /// void f() final;
4492 /// };
4493 /// \endcode
4494 /// matches A and C::f, but not B, C, or B::f
AST_POLYMORPHIC_MATCHER(isFinal,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXRecordDecl,CXXMethodDecl))4495 AST_POLYMORPHIC_MATCHER(isFinal,
4496 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4497 CXXMethodDecl)) {
4498 return Node.template hasAttr<FinalAttr>();
4499 }
4500
4501 /// Matches if the given method declaration is pure.
4502 ///
4503 /// Given
4504 /// \code
4505 /// class A {
4506 /// public:
4507 /// virtual void x() = 0;
4508 /// };
4509 /// \endcode
4510 /// matches A::x
AST_MATCHER(CXXMethodDecl,isPure)4511 AST_MATCHER(CXXMethodDecl, isPure) {
4512 return Node.isPure();
4513 }
4514
4515 /// Matches if the given method declaration is const.
4516 ///
4517 /// Given
4518 /// \code
4519 /// struct A {
4520 /// void foo() const;
4521 /// void bar();
4522 /// };
4523 /// \endcode
4524 ///
4525 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
AST_MATCHER(CXXMethodDecl,isConst)4526 AST_MATCHER(CXXMethodDecl, isConst) {
4527 return Node.isConst();
4528 }
4529
4530 /// Matches if the given method declaration declares a copy assignment
4531 /// operator.
4532 ///
4533 /// Given
4534 /// \code
4535 /// struct A {
4536 /// A &operator=(const A &);
4537 /// A &operator=(A &&);
4538 /// };
4539 /// \endcode
4540 ///
4541 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4542 /// the second one.
AST_MATCHER(CXXMethodDecl,isCopyAssignmentOperator)4543 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4544 return Node.isCopyAssignmentOperator();
4545 }
4546
4547 /// Matches if the given method declaration declares a move assignment
4548 /// operator.
4549 ///
4550 /// Given
4551 /// \code
4552 /// struct A {
4553 /// A &operator=(const A &);
4554 /// A &operator=(A &&);
4555 /// };
4556 /// \endcode
4557 ///
4558 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4559 /// the first one.
AST_MATCHER(CXXMethodDecl,isMoveAssignmentOperator)4560 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4561 return Node.isMoveAssignmentOperator();
4562 }
4563
4564 /// Matches if the given method declaration overrides another method.
4565 ///
4566 /// Given
4567 /// \code
4568 /// class A {
4569 /// public:
4570 /// virtual void x();
4571 /// };
4572 /// class B : public A {
4573 /// public:
4574 /// virtual void x();
4575 /// };
4576 /// \endcode
4577 /// matches B::x
AST_MATCHER(CXXMethodDecl,isOverride)4578 AST_MATCHER(CXXMethodDecl, isOverride) {
4579 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4580 }
4581
4582 /// Matches method declarations that are user-provided.
4583 ///
4584 /// Given
4585 /// \code
4586 /// struct S {
4587 /// S(); // #1
4588 /// S(const S &) = default; // #2
4589 /// S(S &&) = delete; // #3
4590 /// };
4591 /// \endcode
4592 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
AST_MATCHER(CXXMethodDecl,isUserProvided)4593 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4594 return Node.isUserProvided();
4595 }
4596
4597 /// Matches member expressions that are called with '->' as opposed
4598 /// to '.'.
4599 ///
4600 /// Member calls on the implicit this pointer match as called with '->'.
4601 ///
4602 /// Given
4603 /// \code
4604 /// class Y {
4605 /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4606 /// int a;
4607 /// static int b;
4608 /// };
4609 /// \endcode
4610 /// memberExpr(isArrow())
4611 /// matches this->x, x, y.x, a, this->b
AST_MATCHER(MemberExpr,isArrow)4612 AST_MATCHER(MemberExpr, isArrow) {
4613 return Node.isArrow();
4614 }
4615
4616 /// Matches QualType nodes that are of integer type.
4617 ///
4618 /// Given
4619 /// \code
4620 /// void a(int);
4621 /// void b(long);
4622 /// void c(double);
4623 /// \endcode
4624 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4625 /// matches "a(int)", "b(long)", but not "c(double)".
AST_MATCHER(QualType,isInteger)4626 AST_MATCHER(QualType, isInteger) {
4627 return Node->isIntegerType();
4628 }
4629
4630 /// Matches QualType nodes that are of unsigned integer type.
4631 ///
4632 /// Given
4633 /// \code
4634 /// void a(int);
4635 /// void b(unsigned long);
4636 /// void c(double);
4637 /// \endcode
4638 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4639 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
AST_MATCHER(QualType,isUnsignedInteger)4640 AST_MATCHER(QualType, isUnsignedInteger) {
4641 return Node->isUnsignedIntegerType();
4642 }
4643
4644 /// Matches QualType nodes that are of signed integer type.
4645 ///
4646 /// Given
4647 /// \code
4648 /// void a(int);
4649 /// void b(unsigned long);
4650 /// void c(double);
4651 /// \endcode
4652 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4653 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
AST_MATCHER(QualType,isSignedInteger)4654 AST_MATCHER(QualType, isSignedInteger) {
4655 return Node->isSignedIntegerType();
4656 }
4657
4658 /// Matches QualType nodes that are of character type.
4659 ///
4660 /// Given
4661 /// \code
4662 /// void a(char);
4663 /// void b(wchar_t);
4664 /// void c(double);
4665 /// \endcode
4666 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4667 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
AST_MATCHER(QualType,isAnyCharacter)4668 AST_MATCHER(QualType, isAnyCharacter) {
4669 return Node->isAnyCharacterType();
4670 }
4671
4672 /// Matches QualType nodes that are of any pointer type; this includes
4673 /// the Objective-C object pointer type, which is different despite being
4674 /// syntactically similar.
4675 ///
4676 /// Given
4677 /// \code
4678 /// int *i = nullptr;
4679 ///
4680 /// @interface Foo
4681 /// @end
4682 /// Foo *f;
4683 ///
4684 /// int j;
4685 /// \endcode
4686 /// varDecl(hasType(isAnyPointer()))
4687 /// matches "int *i" and "Foo *f", but not "int j".
AST_MATCHER(QualType,isAnyPointer)4688 AST_MATCHER(QualType, isAnyPointer) {
4689 return Node->isAnyPointerType();
4690 }
4691
4692 /// Matches QualType nodes that are const-qualified, i.e., that
4693 /// include "top-level" const.
4694 ///
4695 /// Given
4696 /// \code
4697 /// void a(int);
4698 /// void b(int const);
4699 /// void c(const int);
4700 /// void d(const int*);
4701 /// void e(int const) {};
4702 /// \endcode
4703 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
4704 /// matches "void b(int const)", "void c(const int)" and
4705 /// "void e(int const) {}". It does not match d as there
4706 /// is no top-level const on the parameter type "const int *".
AST_MATCHER(QualType,isConstQualified)4707 AST_MATCHER(QualType, isConstQualified) {
4708 return Node.isConstQualified();
4709 }
4710
4711 /// Matches QualType nodes that are volatile-qualified, i.e., that
4712 /// include "top-level" volatile.
4713 ///
4714 /// Given
4715 /// \code
4716 /// void a(int);
4717 /// void b(int volatile);
4718 /// void c(volatile int);
4719 /// void d(volatile int*);
4720 /// void e(int volatile) {};
4721 /// \endcode
4722 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
4723 /// matches "void b(int volatile)", "void c(volatile int)" and
4724 /// "void e(int volatile) {}". It does not match d as there
4725 /// is no top-level volatile on the parameter type "volatile int *".
AST_MATCHER(QualType,isVolatileQualified)4726 AST_MATCHER(QualType, isVolatileQualified) {
4727 return Node.isVolatileQualified();
4728 }
4729
4730 /// Matches QualType nodes that have local CV-qualifiers attached to
4731 /// the node, not hidden within a typedef.
4732 ///
4733 /// Given
4734 /// \code
4735 /// typedef const int const_int;
4736 /// const_int i;
4737 /// int *const j;
4738 /// int *volatile k;
4739 /// int m;
4740 /// \endcode
4741 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
4742 /// \c i is const-qualified but the qualifier is not local.
AST_MATCHER(QualType,hasLocalQualifiers)4743 AST_MATCHER(QualType, hasLocalQualifiers) {
4744 return Node.hasLocalQualifiers();
4745 }
4746
4747 /// Matches a member expression where the member is matched by a
4748 /// given matcher.
4749 ///
4750 /// Given
4751 /// \code
4752 /// struct { int first, second; } first, second;
4753 /// int i(second.first);
4754 /// int j(first.second);
4755 /// \endcode
4756 /// memberExpr(member(hasName("first")))
4757 /// matches second.first
4758 /// but not first.second (because the member name there is "second").
AST_MATCHER_P(MemberExpr,member,internal::Matcher<ValueDecl>,InnerMatcher)4759 AST_MATCHER_P(MemberExpr, member,
4760 internal::Matcher<ValueDecl>, InnerMatcher) {
4761 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
4762 }
4763
4764 /// Matches a member expression where the object expression is
4765 /// matched by a given matcher.
4766 ///
4767 /// Given
4768 /// \code
4769 /// struct X { int m; };
4770 /// void f(X x) { x.m; m; }
4771 /// \endcode
4772 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))))
4773 /// matches "x.m" and "m"
4774 /// with hasObjectExpression(...)
4775 /// matching "x" and the implicit object expression of "m" which has type X*.
AST_MATCHER_P(MemberExpr,hasObjectExpression,internal::Matcher<Expr>,InnerMatcher)4776 AST_MATCHER_P(MemberExpr, hasObjectExpression,
4777 internal::Matcher<Expr>, InnerMatcher) {
4778 return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
4779 }
4780
4781 /// Matches any using shadow declaration.
4782 ///
4783 /// Given
4784 /// \code
4785 /// namespace X { void b(); }
4786 /// using X::b;
4787 /// \endcode
4788 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
4789 /// matches \code using X::b \endcode
AST_MATCHER_P(UsingDecl,hasAnyUsingShadowDecl,internal::Matcher<UsingShadowDecl>,InnerMatcher)4790 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
4791 internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4792 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
4793 Node.shadow_end(), Finder, Builder);
4794 }
4795
4796 /// Matches a using shadow declaration where the target declaration is
4797 /// matched by the given matcher.
4798 ///
4799 /// Given
4800 /// \code
4801 /// namespace X { int a; void b(); }
4802 /// using X::a;
4803 /// using X::b;
4804 /// \endcode
4805 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
4806 /// matches \code using X::b \endcode
4807 /// but not \code using X::a \endcode
AST_MATCHER_P(UsingShadowDecl,hasTargetDecl,internal::Matcher<NamedDecl>,InnerMatcher)4808 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
4809 internal::Matcher<NamedDecl>, InnerMatcher) {
4810 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
4811 }
4812
4813 /// Matches template instantiations of function, class, or static
4814 /// member variable template instantiations.
4815 ///
4816 /// Given
4817 /// \code
4818 /// template <typename T> class X {}; class A {}; X<A> x;
4819 /// \endcode
4820 /// or
4821 /// \code
4822 /// template <typename T> class X {}; class A {}; template class X<A>;
4823 /// \endcode
4824 /// or
4825 /// \code
4826 /// template <typename T> class X {}; class A {}; extern template class X<A>;
4827 /// \endcode
4828 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4829 /// matches the template instantiation of X<A>.
4830 ///
4831 /// But given
4832 /// \code
4833 /// template <typename T> class X {}; class A {};
4834 /// template <> class X<A> {}; X<A> x;
4835 /// \endcode
4836 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
4837 /// does not match, as X<A> is an explicit template specialization.
4838 ///
4839 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl,CXXRecordDecl))4840 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
4841 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4842 CXXRecordDecl)) {
4843 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
4844 Node.getTemplateSpecializationKind() ==
4845 TSK_ExplicitInstantiationDefinition ||
4846 Node.getTemplateSpecializationKind() ==
4847 TSK_ExplicitInstantiationDeclaration);
4848 }
4849
4850 /// Matches declarations that are template instantiations or are inside
4851 /// template instantiations.
4852 ///
4853 /// Given
4854 /// \code
4855 /// template<typename T> void A(T t) { T i; }
4856 /// A(0);
4857 /// A(0U);
4858 /// \endcode
4859 /// functionDecl(isInstantiated())
4860 /// matches 'A(int) {...};' and 'A(unsigned) {...}'.
AST_MATCHER_FUNCTION(internal::Matcher<Decl>,isInstantiated)4861 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
4862 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4863 functionDecl(isTemplateInstantiation())));
4864 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
4865 }
4866
4867 /// Matches statements inside of a template instantiation.
4868 ///
4869 /// Given
4870 /// \code
4871 /// int j;
4872 /// template<typename T> void A(T t) { T i; j += 42;}
4873 /// A(0);
4874 /// A(0U);
4875 /// \endcode
4876 /// declStmt(isInTemplateInstantiation())
4877 /// matches 'int i;' and 'unsigned i'.
4878 /// unless(stmt(isInTemplateInstantiation()))
4879 /// will NOT match j += 42; as it's shared between the template definition and
4880 /// instantiation.
AST_MATCHER_FUNCTION(internal::Matcher<Stmt>,isInTemplateInstantiation)4881 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
4882 return stmt(
4883 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
4884 functionDecl(isTemplateInstantiation())))));
4885 }
4886
4887 /// Matches explicit template specializations of function, class, or
4888 /// static member variable template instantiations.
4889 ///
4890 /// Given
4891 /// \code
4892 /// template<typename T> void A(T t) { }
4893 /// template<> void A(int N) { }
4894 /// \endcode
4895 /// functionDecl(isExplicitTemplateSpecialization())
4896 /// matches the specialization A<int>().
4897 ///
4898 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,AST_POLYMORPHIC_SUPPORTED_TYPES (FunctionDecl,VarDecl,CXXRecordDecl))4899 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
4900 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
4901 CXXRecordDecl)) {
4902 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
4903 }
4904
4905 /// Matches \c TypeLocs for which the given inner
4906 /// QualType-matcher matches.
4907 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
4908 internal::Matcher<QualType>, InnerMatcher, 0) {
4909 return internal::BindableMatcher<TypeLoc>(
4910 new internal::TypeLocTypeMatcher(InnerMatcher));
4911 }
4912
4913 /// Matches type \c bool.
4914 ///
4915 /// Given
4916 /// \code
4917 /// struct S { bool func(); };
4918 /// \endcode
4919 /// functionDecl(returns(booleanType()))
4920 /// matches "bool func();"
AST_MATCHER(Type,booleanType)4921 AST_MATCHER(Type, booleanType) {
4922 return Node.isBooleanType();
4923 }
4924
4925 /// Matches type \c void.
4926 ///
4927 /// Given
4928 /// \code
4929 /// struct S { void func(); };
4930 /// \endcode
4931 /// functionDecl(returns(voidType()))
4932 /// matches "void func();"
AST_MATCHER(Type,voidType)4933 AST_MATCHER(Type, voidType) {
4934 return Node.isVoidType();
4935 }
4936
4937 template <typename NodeType>
4938 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
4939
4940 /// Matches builtin Types.
4941 ///
4942 /// Given
4943 /// \code
4944 /// struct A {};
4945 /// A a;
4946 /// int b;
4947 /// float c;
4948 /// bool d;
4949 /// \endcode
4950 /// builtinType()
4951 /// matches "int b", "float c" and "bool d"
4952 extern const AstTypeMatcher<BuiltinType> builtinType;
4953
4954 /// Matches all kinds of arrays.
4955 ///
4956 /// Given
4957 /// \code
4958 /// int a[] = { 2, 3 };
4959 /// int b[4];
4960 /// void f() { int c[a[0]]; }
4961 /// \endcode
4962 /// arrayType()
4963 /// matches "int a[]", "int b[4]" and "int c[a[0]]";
4964 extern const AstTypeMatcher<ArrayType> arrayType;
4965
4966 /// Matches C99 complex types.
4967 ///
4968 /// Given
4969 /// \code
4970 /// _Complex float f;
4971 /// \endcode
4972 /// complexType()
4973 /// matches "_Complex float f"
4974 extern const AstTypeMatcher<ComplexType> complexType;
4975
4976 /// Matches any real floating-point type (float, double, long double).
4977 ///
4978 /// Given
4979 /// \code
4980 /// int i;
4981 /// float f;
4982 /// \endcode
4983 /// realFloatingPointType()
4984 /// matches "float f" but not "int i"
AST_MATCHER(Type,realFloatingPointType)4985 AST_MATCHER(Type, realFloatingPointType) {
4986 return Node.isRealFloatingType();
4987 }
4988
4989 /// Matches arrays and C99 complex types that have a specific element
4990 /// type.
4991 ///
4992 /// Given
4993 /// \code
4994 /// struct A {};
4995 /// A a[7];
4996 /// int b[7];
4997 /// \endcode
4998 /// arrayType(hasElementType(builtinType()))
4999 /// matches "int b[7]"
5000 ///
5001 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5002 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5003 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5004 ComplexType));
5005
5006 /// Matches C arrays with a specified constant size.
5007 ///
5008 /// Given
5009 /// \code
5010 /// void() {
5011 /// int a[2];
5012 /// int b[] = { 2, 3 };
5013 /// int c[b[0]];
5014 /// }
5015 /// \endcode
5016 /// constantArrayType()
5017 /// matches "int a[2]"
5018 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5019
5020 /// Matches nodes that have the specified size.
5021 ///
5022 /// Given
5023 /// \code
5024 /// int a[42];
5025 /// int b[2 * 21];
5026 /// int c[41], d[43];
5027 /// char *s = "abcd";
5028 /// wchar_t *ws = L"abcd";
5029 /// char *w = "a";
5030 /// \endcode
5031 /// constantArrayType(hasSize(42))
5032 /// matches "int a[42]" and "int b[2 * 21]"
5033 /// stringLiteral(hasSize(4))
5034 /// matches "abcd", L"abcd"
AST_POLYMORPHIC_MATCHER_P(hasSize,AST_POLYMORPHIC_SUPPORTED_TYPES (ConstantArrayType,StringLiteral),unsigned,N)5035 AST_POLYMORPHIC_MATCHER_P(hasSize,
5036 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5037 StringLiteral),
5038 unsigned, N) {
5039 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5040 }
5041
5042 /// Matches C++ arrays whose size is a value-dependent expression.
5043 ///
5044 /// Given
5045 /// \code
5046 /// template<typename T, int Size>
5047 /// class array {
5048 /// T data[Size];
5049 /// };
5050 /// \endcode
5051 /// dependentSizedArrayType
5052 /// matches "T data[Size]"
5053 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5054
5055 /// Matches C arrays with unspecified size.
5056 ///
5057 /// Given
5058 /// \code
5059 /// int a[] = { 2, 3 };
5060 /// int b[42];
5061 /// void f(int c[]) { int d[a[0]]; };
5062 /// \endcode
5063 /// incompleteArrayType()
5064 /// matches "int a[]" and "int c[]"
5065 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5066
5067 /// Matches C arrays with a specified size that is not an
5068 /// integer-constant-expression.
5069 ///
5070 /// Given
5071 /// \code
5072 /// void f() {
5073 /// int a[] = { 2, 3 }
5074 /// int b[42];
5075 /// int c[a[0]];
5076 /// }
5077 /// \endcode
5078 /// variableArrayType()
5079 /// matches "int c[a[0]]"
5080 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5081
5082 /// Matches \c VariableArrayType nodes that have a specific size
5083 /// expression.
5084 ///
5085 /// Given
5086 /// \code
5087 /// void f(int b) {
5088 /// int a[b];
5089 /// }
5090 /// \endcode
5091 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5092 /// varDecl(hasName("b")))))))
5093 /// matches "int a[b]"
AST_MATCHER_P(VariableArrayType,hasSizeExpr,internal::Matcher<Expr>,InnerMatcher)5094 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5095 internal::Matcher<Expr>, InnerMatcher) {
5096 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5097 }
5098
5099 /// Matches atomic types.
5100 ///
5101 /// Given
5102 /// \code
5103 /// _Atomic(int) i;
5104 /// \endcode
5105 /// atomicType()
5106 /// matches "_Atomic(int) i"
5107 extern const AstTypeMatcher<AtomicType> atomicType;
5108
5109 /// Matches atomic types with a specific value type.
5110 ///
5111 /// Given
5112 /// \code
5113 /// _Atomic(int) i;
5114 /// _Atomic(float) f;
5115 /// \endcode
5116 /// atomicType(hasValueType(isInteger()))
5117 /// matches "_Atomic(int) i"
5118 ///
5119 /// Usable as: Matcher<AtomicType>
5120 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5121 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5122
5123 /// Matches types nodes representing C++11 auto types.
5124 ///
5125 /// Given:
5126 /// \code
5127 /// auto n = 4;
5128 /// int v[] = { 2, 3 }
5129 /// for (auto i : v) { }
5130 /// \endcode
5131 /// autoType()
5132 /// matches "auto n" and "auto i"
5133 extern const AstTypeMatcher<AutoType> autoType;
5134
5135 /// Matches types nodes representing C++11 decltype(<expr>) types.
5136 ///
5137 /// Given:
5138 /// \code
5139 /// short i = 1;
5140 /// int j = 42;
5141 /// decltype(i + j) result = i + j;
5142 /// \endcode
5143 /// decltypeType()
5144 /// matches "decltype(i + j)"
5145 extern const AstTypeMatcher<DecltypeType> decltypeType;
5146
5147 /// Matches \c AutoType nodes where the deduced type is a specific type.
5148 ///
5149 /// Note: There is no \c TypeLoc for the deduced type and thus no
5150 /// \c getDeducedLoc() matcher.
5151 ///
5152 /// Given
5153 /// \code
5154 /// auto a = 1;
5155 /// auto b = 2.0;
5156 /// \endcode
5157 /// autoType(hasDeducedType(isInteger()))
5158 /// matches "auto a"
5159 ///
5160 /// Usable as: Matcher<AutoType>
5161 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5162 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5163
5164 /// Matches \c DecltypeType nodes to find out the underlying type.
5165 ///
5166 /// Given
5167 /// \code
5168 /// decltype(1) a = 1;
5169 /// decltype(2.0) b = 2.0;
5170 /// \endcode
5171 /// decltypeType(hasUnderlyingType(isInteger()))
5172 /// matches "auto a"
5173 ///
5174 /// Usable as: Matcher<DecltypeType>
5175 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
5176 AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
5177
5178 /// Matches \c FunctionType nodes.
5179 ///
5180 /// Given
5181 /// \code
5182 /// int (*f)(int);
5183 /// void g();
5184 /// \endcode
5185 /// functionType()
5186 /// matches "int (*f)(int)" and the type of "g".
5187 extern const AstTypeMatcher<FunctionType> functionType;
5188
5189 /// Matches \c FunctionProtoType nodes.
5190 ///
5191 /// Given
5192 /// \code
5193 /// int (*f)(int);
5194 /// void g();
5195 /// \endcode
5196 /// functionProtoType()
5197 /// matches "int (*f)(int)" and the type of "g" in C++ mode.
5198 /// In C mode, "g" is not matched because it does not contain a prototype.
5199 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
5200
5201 /// Matches \c ParenType nodes.
5202 ///
5203 /// Given
5204 /// \code
5205 /// int (*ptr_to_array)[4];
5206 /// int *array_of_ptrs[4];
5207 /// \endcode
5208 ///
5209 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
5210 /// \c array_of_ptrs.
5211 extern const AstTypeMatcher<ParenType> parenType;
5212
5213 /// Matches \c ParenType nodes where the inner type is a specific type.
5214 ///
5215 /// Given
5216 /// \code
5217 /// int (*ptr_to_array)[4];
5218 /// int (*ptr_to_func)(int);
5219 /// \endcode
5220 ///
5221 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5222 /// \c ptr_to_func but not \c ptr_to_array.
5223 ///
5224 /// Usable as: Matcher<ParenType>
5225 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5226 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5227
5228 /// Matches block pointer types, i.e. types syntactically represented as
5229 /// "void (^)(int)".
5230 ///
5231 /// The \c pointee is always required to be a \c FunctionType.
5232 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5233
5234 /// Matches member pointer types.
5235 /// Given
5236 /// \code
5237 /// struct A { int i; }
5238 /// A::* ptr = A::i;
5239 /// \endcode
5240 /// memberPointerType()
5241 /// matches "A::* ptr"
5242 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5243
5244 /// Matches pointer types, but does not match Objective-C object pointer
5245 /// types.
5246 ///
5247 /// Given
5248 /// \code
5249 /// int *a;
5250 /// int &b = *a;
5251 /// int c = 5;
5252 ///
5253 /// @interface Foo
5254 /// @end
5255 /// Foo *f;
5256 /// \endcode
5257 /// pointerType()
5258 /// matches "int *a", but does not match "Foo *f".
5259 extern const AstTypeMatcher<PointerType> pointerType;
5260
5261 /// Matches an Objective-C object pointer type, which is different from
5262 /// a pointer type, despite being syntactically similar.
5263 ///
5264 /// Given
5265 /// \code
5266 /// int *a;
5267 ///
5268 /// @interface Foo
5269 /// @end
5270 /// Foo *f;
5271 /// \endcode
5272 /// pointerType()
5273 /// matches "Foo *f", but does not match "int *a".
5274 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5275
5276 /// Matches both lvalue and rvalue reference types.
5277 ///
5278 /// Given
5279 /// \code
5280 /// int *a;
5281 /// int &b = *a;
5282 /// int &&c = 1;
5283 /// auto &d = b;
5284 /// auto &&e = c;
5285 /// auto &&f = 2;
5286 /// int g = 5;
5287 /// \endcode
5288 ///
5289 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5290 extern const AstTypeMatcher<ReferenceType> referenceType;
5291
5292 /// Matches lvalue reference types.
5293 ///
5294 /// Given:
5295 /// \code
5296 /// int *a;
5297 /// int &b = *a;
5298 /// int &&c = 1;
5299 /// auto &d = b;
5300 /// auto &&e = c;
5301 /// auto &&f = 2;
5302 /// int g = 5;
5303 /// \endcode
5304 ///
5305 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5306 /// matched since the type is deduced as int& by reference collapsing rules.
5307 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5308
5309 /// Matches rvalue reference types.
5310 ///
5311 /// Given:
5312 /// \code
5313 /// int *a;
5314 /// int &b = *a;
5315 /// int &&c = 1;
5316 /// auto &d = b;
5317 /// auto &&e = c;
5318 /// auto &&f = 2;
5319 /// int g = 5;
5320 /// \endcode
5321 ///
5322 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5323 /// matched as it is deduced to int& by reference collapsing rules.
5324 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5325
5326 /// Narrows PointerType (and similar) matchers to those where the
5327 /// \c pointee matches a given matcher.
5328 ///
5329 /// Given
5330 /// \code
5331 /// int *a;
5332 /// int const *b;
5333 /// float const *f;
5334 /// \endcode
5335 /// pointerType(pointee(isConstQualified(), isInteger()))
5336 /// matches "int const *b"
5337 ///
5338 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5339 /// Matcher<PointerType>, Matcher<ReferenceType>
5340 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5341 pointee, getPointee,
5342 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5343 PointerType, ReferenceType));
5344
5345 /// Matches typedef types.
5346 ///
5347 /// Given
5348 /// \code
5349 /// typedef int X;
5350 /// \endcode
5351 /// typedefType()
5352 /// matches "typedef int X"
5353 extern const AstTypeMatcher<TypedefType> typedefType;
5354
5355 /// Matches enum types.
5356 ///
5357 /// Given
5358 /// \code
5359 /// enum C { Green };
5360 /// enum class S { Red };
5361 ///
5362 /// C c;
5363 /// S s;
5364 /// \endcode
5365 //
5366 /// \c enumType() matches the type of the variable declarations of both \c c and
5367 /// \c s.
5368 extern const AstTypeMatcher<EnumType> enumType;
5369
5370 /// Matches template specialization types.
5371 ///
5372 /// Given
5373 /// \code
5374 /// template <typename T>
5375 /// class C { };
5376 ///
5377 /// template class C<int>; // A
5378 /// C<char> var; // B
5379 /// \endcode
5380 ///
5381 /// \c templateSpecializationType() matches the type of the explicit
5382 /// instantiation in \c A and the type of the variable declaration in \c B.
5383 extern const AstTypeMatcher<TemplateSpecializationType>
5384 templateSpecializationType;
5385
5386 /// Matches types nodes representing unary type transformations.
5387 ///
5388 /// Given:
5389 /// \code
5390 /// typedef __underlying_type(T) type;
5391 /// \endcode
5392 /// unaryTransformType()
5393 /// matches "__underlying_type(T)"
5394 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5395
5396 /// Matches record types (e.g. structs, classes).
5397 ///
5398 /// Given
5399 /// \code
5400 /// class C {};
5401 /// struct S {};
5402 ///
5403 /// C c;
5404 /// S s;
5405 /// \endcode
5406 ///
5407 /// \c recordType() matches the type of the variable declarations of both \c c
5408 /// and \c s.
5409 extern const AstTypeMatcher<RecordType> recordType;
5410
5411 /// Matches tag types (record and enum types).
5412 ///
5413 /// Given
5414 /// \code
5415 /// enum E {};
5416 /// class C {};
5417 ///
5418 /// E e;
5419 /// C c;
5420 /// \endcode
5421 ///
5422 /// \c tagType() matches the type of the variable declarations of both \c e
5423 /// and \c c.
5424 extern const AstTypeMatcher<TagType> tagType;
5425
5426 /// Matches types specified with an elaborated type keyword or with a
5427 /// qualified name.
5428 ///
5429 /// Given
5430 /// \code
5431 /// namespace N {
5432 /// namespace M {
5433 /// class D {};
5434 /// }
5435 /// }
5436 /// class C {};
5437 ///
5438 /// class C c;
5439 /// N::M::D d;
5440 /// \endcode
5441 ///
5442 /// \c elaboratedType() matches the type of the variable declarations of both
5443 /// \c c and \c d.
5444 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5445
5446 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5447 /// matches \c InnerMatcher if the qualifier exists.
5448 ///
5449 /// Given
5450 /// \code
5451 /// namespace N {
5452 /// namespace M {
5453 /// class D {};
5454 /// }
5455 /// }
5456 /// N::M::D d;
5457 /// \endcode
5458 ///
5459 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5460 /// matches the type of the variable declaration of \c d.
AST_MATCHER_P(ElaboratedType,hasQualifier,internal::Matcher<NestedNameSpecifier>,InnerMatcher)5461 AST_MATCHER_P(ElaboratedType, hasQualifier,
5462 internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5463 if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5464 return InnerMatcher.matches(*Qualifier, Finder, Builder);
5465
5466 return false;
5467 }
5468
5469 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5470 ///
5471 /// Given
5472 /// \code
5473 /// namespace N {
5474 /// namespace M {
5475 /// class D {};
5476 /// }
5477 /// }
5478 /// N::M::D d;
5479 /// \endcode
5480 ///
5481 /// \c elaboratedType(namesType(recordType(
5482 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5483 /// declaration of \c d.
AST_MATCHER_P(ElaboratedType,namesType,internal::Matcher<QualType>,InnerMatcher)5484 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5485 InnerMatcher) {
5486 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5487 }
5488
5489 /// Matches types that represent the result of substituting a type for a
5490 /// template type parameter.
5491 ///
5492 /// Given
5493 /// \code
5494 /// template <typename T>
5495 /// void F(T t) {
5496 /// int i = 1 + t;
5497 /// }
5498 /// \endcode
5499 ///
5500 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5501 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5502 substTemplateTypeParmType;
5503
5504 /// Matches template type parameter substitutions that have a replacement
5505 /// type that matches the provided matcher.
5506 ///
5507 /// Given
5508 /// \code
5509 /// template <typename T>
5510 /// double F(T t);
5511 /// int i;
5512 /// double j = F(i);
5513 /// \endcode
5514 ///
5515 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5516 AST_TYPE_TRAVERSE_MATCHER(
5517 hasReplacementType, getReplacementType,
5518 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5519
5520 /// Matches template type parameter types.
5521 ///
5522 /// Example matches T, but not int.
5523 /// (matcher = templateTypeParmType())
5524 /// \code
5525 /// template <typename T> void f(int i);
5526 /// \endcode
5527 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5528
5529 /// Matches injected class name types.
5530 ///
5531 /// Example matches S s, but not S<T> s.
5532 /// (matcher = parmVarDecl(hasType(injectedClassNameType())))
5533 /// \code
5534 /// template <typename T> struct S {
5535 /// void f(S s);
5536 /// void g(S<T> s);
5537 /// };
5538 /// \endcode
5539 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5540
5541 /// Matches decayed type
5542 /// Example matches i[] in declaration of f.
5543 /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5544 /// Example matches i[1].
5545 /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5546 /// \code
5547 /// void f(int i[]) {
5548 /// i[1] = 0;
5549 /// }
5550 /// \endcode
5551 extern const AstTypeMatcher<DecayedType> decayedType;
5552
5553 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
AST_MATCHER_P(DecayedType,hasDecayedType,internal::Matcher<QualType>,InnerType)5554 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5555 InnerType) {
5556 return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5557 }
5558
5559 /// Matches declarations whose declaration context, interpreted as a
5560 /// Decl, matches \c InnerMatcher.
5561 ///
5562 /// Given
5563 /// \code
5564 /// namespace N {
5565 /// namespace M {
5566 /// class D {};
5567 /// }
5568 /// }
5569 /// \endcode
5570 ///
5571 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5572 /// declaration of \c class \c D.
AST_MATCHER_P(Decl,hasDeclContext,internal::Matcher<Decl>,InnerMatcher)5573 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5574 const DeclContext *DC = Node.getDeclContext();
5575 if (!DC) return false;
5576 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5577 }
5578
5579 /// Matches nested name specifiers.
5580 ///
5581 /// Given
5582 /// \code
5583 /// namespace ns {
5584 /// struct A { static void f(); };
5585 /// void A::f() {}
5586 /// void g() { A::f(); }
5587 /// }
5588 /// ns::A a;
5589 /// \endcode
5590 /// nestedNameSpecifier()
5591 /// matches "ns::" and both "A::"
5592 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
5593 nestedNameSpecifier;
5594
5595 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5596 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
5597 nestedNameSpecifierLoc;
5598
5599 /// Matches \c NestedNameSpecifierLocs for which the given inner
5600 /// NestedNameSpecifier-matcher matches.
5601 AST_MATCHER_FUNCTION_P_OVERLOAD(
5602 internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5603 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5604 return internal::BindableMatcher<NestedNameSpecifierLoc>(
5605 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5606 InnerMatcher));
5607 }
5608
5609 /// Matches nested name specifiers that specify a type matching the
5610 /// given \c QualType matcher without qualifiers.
5611 ///
5612 /// Given
5613 /// \code
5614 /// struct A { struct B { struct C {}; }; };
5615 /// A::B::C c;
5616 /// \endcode
5617 /// nestedNameSpecifier(specifiesType(
5618 /// hasDeclaration(cxxRecordDecl(hasName("A")))
5619 /// ))
5620 /// matches "A::"
AST_MATCHER_P(NestedNameSpecifier,specifiesType,internal::Matcher<QualType>,InnerMatcher)5621 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5622 internal::Matcher<QualType>, InnerMatcher) {
5623 if (!Node.getAsType())
5624 return false;
5625 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5626 }
5627
5628 /// Matches nested name specifier locs that specify a type matching the
5629 /// given \c TypeLoc.
5630 ///
5631 /// Given
5632 /// \code
5633 /// struct A { struct B { struct C {}; }; };
5634 /// A::B::C c;
5635 /// \endcode
5636 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5637 /// hasDeclaration(cxxRecordDecl(hasName("A")))))))
5638 /// matches "A::"
AST_MATCHER_P(NestedNameSpecifierLoc,specifiesTypeLoc,internal::Matcher<TypeLoc>,InnerMatcher)5639 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5640 internal::Matcher<TypeLoc>, InnerMatcher) {
5641 return Node && Node.getNestedNameSpecifier()->getAsType() &&
5642 InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5643 }
5644
5645 /// Matches on the prefix of a \c NestedNameSpecifier.
5646 ///
5647 /// Given
5648 /// \code
5649 /// struct A { struct B { struct C {}; }; };
5650 /// A::B::C c;
5651 /// \endcode
5652 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5653 /// matches "A::"
5654 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5655 internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5656 0) {
5657 const NestedNameSpecifier *NextNode = Node.getPrefix();
5658 if (!NextNode)
5659 return false;
5660 return InnerMatcher.matches(*NextNode, Finder, Builder);
5661 }
5662
5663 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
5664 ///
5665 /// Given
5666 /// \code
5667 /// struct A { struct B { struct C {}; }; };
5668 /// A::B::C c;
5669 /// \endcode
5670 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5671 /// matches "A::"
5672 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5673 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
5674 1) {
5675 NestedNameSpecifierLoc NextNode = Node.getPrefix();
5676 if (!NextNode)
5677 return false;
5678 return InnerMatcher.matches(NextNode, Finder, Builder);
5679 }
5680
5681 /// Matches nested name specifiers that specify a namespace matching the
5682 /// given namespace matcher.
5683 ///
5684 /// Given
5685 /// \code
5686 /// namespace ns { struct A {}; }
5687 /// ns::A a;
5688 /// \endcode
5689 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
5690 /// matches "ns::"
AST_MATCHER_P(NestedNameSpecifier,specifiesNamespace,internal::Matcher<NamespaceDecl>,InnerMatcher)5691 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
5692 internal::Matcher<NamespaceDecl>, InnerMatcher) {
5693 if (!Node.getAsNamespace())
5694 return false;
5695 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
5696 }
5697
5698 /// Overloads for the \c equalsNode matcher.
5699 /// FIXME: Implement for other node types.
5700 /// @{
5701
5702 /// Matches if a node equals another node.
5703 ///
5704 /// \c Decl has pointer identity in the AST.
5705 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
5706 return &Node == Other;
5707 }
5708 /// Matches if a node equals another node.
5709 ///
5710 /// \c Stmt has pointer identity in the AST.
5711 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
5712 return &Node == Other;
5713 }
5714 /// Matches if a node equals another node.
5715 ///
5716 /// \c Type has pointer identity in the AST.
5717 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
5718 return &Node == Other;
5719 }
5720
5721 /// @}
5722
5723 /// Matches each case or default statement belonging to the given switch
5724 /// statement. This matcher may produce multiple matches.
5725 ///
5726 /// Given
5727 /// \code
5728 /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
5729 /// \endcode
5730 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
5731 /// matches four times, with "c" binding each of "case 1:", "case 2:",
5732 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
5733 /// "switch (1)", "switch (2)" and "switch (2)".
AST_MATCHER_P(SwitchStmt,forEachSwitchCase,internal::Matcher<SwitchCase>,InnerMatcher)5734 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
5735 InnerMatcher) {
5736 BoundNodesTreeBuilder Result;
5737 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
5738 // iteration order. We should use the more general iterating matchers once
5739 // they are capable of expressing this matcher (for example, it should ignore
5740 // case statements belonging to nested switch statements).
5741 bool Matched = false;
5742 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
5743 SC = SC->getNextSwitchCase()) {
5744 BoundNodesTreeBuilder CaseBuilder(*Builder);
5745 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
5746 if (CaseMatched) {
5747 Matched = true;
5748 Result.addMatch(CaseBuilder);
5749 }
5750 }
5751 *Builder = std::move(Result);
5752 return Matched;
5753 }
5754
5755 /// Matches each constructor initializer in a constructor definition.
5756 ///
5757 /// Given
5758 /// \code
5759 /// class A { A() : i(42), j(42) {} int i; int j; };
5760 /// \endcode
5761 /// cxxConstructorDecl(forEachConstructorInitializer(
5762 /// forField(decl().bind("x"))
5763 /// ))
5764 /// will trigger two matches, binding for 'i' and 'j' respectively.
AST_MATCHER_P(CXXConstructorDecl,forEachConstructorInitializer,internal::Matcher<CXXCtorInitializer>,InnerMatcher)5765 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
5766 internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
5767 BoundNodesTreeBuilder Result;
5768 bool Matched = false;
5769 for (const auto *I : Node.inits()) {
5770 BoundNodesTreeBuilder InitBuilder(*Builder);
5771 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
5772 Matched = true;
5773 Result.addMatch(InitBuilder);
5774 }
5775 }
5776 *Builder = std::move(Result);
5777 return Matched;
5778 }
5779
5780 /// Matches constructor declarations that are copy constructors.
5781 ///
5782 /// Given
5783 /// \code
5784 /// struct S {
5785 /// S(); // #1
5786 /// S(const S &); // #2
5787 /// S(S &&); // #3
5788 /// };
5789 /// \endcode
5790 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
AST_MATCHER(CXXConstructorDecl,isCopyConstructor)5791 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
5792 return Node.isCopyConstructor();
5793 }
5794
5795 /// Matches constructor declarations that are move constructors.
5796 ///
5797 /// Given
5798 /// \code
5799 /// struct S {
5800 /// S(); // #1
5801 /// S(const S &); // #2
5802 /// S(S &&); // #3
5803 /// };
5804 /// \endcode
5805 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
AST_MATCHER(CXXConstructorDecl,isMoveConstructor)5806 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
5807 return Node.isMoveConstructor();
5808 }
5809
5810 /// Matches constructor declarations that are default constructors.
5811 ///
5812 /// Given
5813 /// \code
5814 /// struct S {
5815 /// S(); // #1
5816 /// S(const S &); // #2
5817 /// S(S &&); // #3
5818 /// };
5819 /// \endcode
5820 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
AST_MATCHER(CXXConstructorDecl,isDefaultConstructor)5821 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
5822 return Node.isDefaultConstructor();
5823 }
5824
5825 /// Matches constructors that delegate to another constructor.
5826 ///
5827 /// Given
5828 /// \code
5829 /// struct S {
5830 /// S(); // #1
5831 /// S(int) {} // #2
5832 /// S(S &&) : S() {} // #3
5833 /// };
5834 /// S::S() : S(0) {} // #4
5835 /// \endcode
5836 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
5837 /// #1 or #2.
AST_MATCHER(CXXConstructorDecl,isDelegatingConstructor)5838 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
5839 return Node.isDelegatingConstructor();
5840 }
5841
5842 /// Matches constructor and conversion declarations that are marked with
5843 /// the explicit keyword.
5844 ///
5845 /// Given
5846 /// \code
5847 /// struct S {
5848 /// S(int); // #1
5849 /// explicit S(double); // #2
5850 /// operator int(); // #3
5851 /// explicit operator bool(); // #4
5852 /// };
5853 /// \endcode
5854 /// cxxConstructorDecl(isExplicit()) will match #2, but not #1.
5855 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
AST_POLYMORPHIC_MATCHER(isExplicit,AST_POLYMORPHIC_SUPPORTED_TYPES (CXXConstructorDecl,CXXConversionDecl))5856 AST_POLYMORPHIC_MATCHER(isExplicit,
5857 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl,
5858 CXXConversionDecl)) {
5859 return Node.isExplicit();
5860 }
5861
5862 /// Matches function and namespace declarations that are marked with
5863 /// the inline keyword.
5864 ///
5865 /// Given
5866 /// \code
5867 /// inline void f();
5868 /// void g();
5869 /// namespace n {
5870 /// inline namespace m {}
5871 /// }
5872 /// \endcode
5873 /// functionDecl(isInline()) will match ::f().
5874 /// namespaceDecl(isInline()) will match n::m.
AST_POLYMORPHIC_MATCHER(isInline,AST_POLYMORPHIC_SUPPORTED_TYPES (NamespaceDecl,FunctionDecl))5875 AST_POLYMORPHIC_MATCHER(isInline,
5876 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
5877 FunctionDecl)) {
5878 // This is required because the spelling of the function used to determine
5879 // whether inline is specified or not differs between the polymorphic types.
5880 if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
5881 return FD->isInlineSpecified();
5882 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
5883 return NSD->isInline();
5884 llvm_unreachable("Not a valid polymorphic type");
5885 }
5886
5887 /// Matches anonymous namespace declarations.
5888 ///
5889 /// Given
5890 /// \code
5891 /// namespace n {
5892 /// namespace {} // #1
5893 /// }
5894 /// \endcode
5895 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
AST_MATCHER(NamespaceDecl,isAnonymous)5896 AST_MATCHER(NamespaceDecl, isAnonymous) {
5897 return Node.isAnonymousNamespace();
5898 }
5899
5900 /// If the given case statement does not use the GNU case range
5901 /// extension, matches the constant given in the statement.
5902 ///
5903 /// Given
5904 /// \code
5905 /// switch (1) { case 1: case 1+1: case 3 ... 4: ; }
5906 /// \endcode
5907 /// caseStmt(hasCaseConstant(integerLiteral()))
5908 /// matches "case 1:"
AST_MATCHER_P(CaseStmt,hasCaseConstant,internal::Matcher<Expr>,InnerMatcher)5909 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
5910 InnerMatcher) {
5911 if (Node.getRHS())
5912 return false;
5913
5914 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
5915 }
5916
5917 /// Matches declaration that has a given attribute.
5918 ///
5919 /// Given
5920 /// \code
5921 /// __attribute__((device)) void f() { ... }
5922 /// \endcode
5923 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
5924 /// f. If the matcher is use from clang-query, attr::Kind parameter should be
5925 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
AST_MATCHER_P(Decl,hasAttr,attr::Kind,AttrKind)5926 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
5927 for (const auto *Attr : Node.attrs()) {
5928 if (Attr->getKind() == AttrKind)
5929 return true;
5930 }
5931 return false;
5932 }
5933
5934 /// Matches the return value expression of a return statement
5935 ///
5936 /// Given
5937 /// \code
5938 /// return a + b;
5939 /// \endcode
5940 /// hasReturnValue(binaryOperator())
5941 /// matches 'return a + b'
5942 /// with binaryOperator()
5943 /// matching 'a + b'
AST_MATCHER_P(ReturnStmt,hasReturnValue,internal::Matcher<Expr>,InnerMatcher)5944 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
5945 InnerMatcher) {
5946 if (const auto *RetValue = Node.getRetValue())
5947 return InnerMatcher.matches(*RetValue, Finder, Builder);
5948 return false;
5949 }
5950
5951 /// Matches CUDA kernel call expression.
5952 ///
5953 /// Example matches,
5954 /// \code
5955 /// kernel<<<i,j>>>();
5956 /// \endcode
5957 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
5958 cudaKernelCallExpr;
5959
5960 /// Matches expressions that resolve to a null pointer constant, such as
5961 /// GNU's __null, C++11's nullptr, or C's NULL macro.
5962 ///
5963 /// Given:
5964 /// \code
5965 /// void *v1 = NULL;
5966 /// void *v2 = nullptr;
5967 /// void *v3 = __null; // GNU extension
5968 /// char *cp = (char *)0;
5969 /// int *ip = 0;
5970 /// int i = 0;
5971 /// \endcode
5972 /// expr(nullPointerConstant())
5973 /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the
5974 /// initializer for i.
AST_MATCHER_FUNCTION(internal::Matcher<Expr>,nullPointerConstant)5975 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
5976 return anyOf(
5977 gnuNullExpr(), cxxNullPtrLiteralExpr(),
5978 integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
5979 }
5980
5981 /// Matches declaration of the function the statement belongs to
5982 ///
5983 /// Given:
5984 /// \code
5985 /// F& operator=(const F& o) {
5986 /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
5987 /// return *this;
5988 /// }
5989 /// \endcode
5990 /// returnStmt(forFunction(hasName("operator=")))
5991 /// matches 'return *this'
5992 /// but does match 'return > 0'
AST_MATCHER_P(Stmt,forFunction,internal::Matcher<FunctionDecl>,InnerMatcher)5993 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
5994 InnerMatcher) {
5995 const auto &Parents = Finder->getASTContext().getParents(Node);
5996
5997 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
5998 Parents.end());
5999 while(!Stack.empty()) {
6000 const auto &CurNode = Stack.back();
6001 Stack.pop_back();
6002 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6003 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6004 return true;
6005 }
6006 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6007 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6008 Finder, Builder)) {
6009 return true;
6010 }
6011 } else {
6012 for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6013 Stack.push_back(Parent);
6014 }
6015 }
6016 return false;
6017 }
6018
6019 /// Matches a declaration that has external formal linkage.
6020 ///
6021 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6022 /// \code
6023 /// void f() {
6024 /// int x;
6025 /// static int y;
6026 /// }
6027 /// int z;
6028 /// \endcode
6029 ///
6030 /// Example matches f() because it has external formal linkage despite being
6031 /// unique to the translation unit as though it has internal likage
6032 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6033 ///
6034 /// \code
6035 /// namespace {
6036 /// void f() {}
6037 /// }
6038 /// \endcode
AST_MATCHER(NamedDecl,hasExternalFormalLinkage)6039 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6040 return Node.hasExternalFormalLinkage();
6041 }
6042
6043 /// Matches a declaration that has default arguments.
6044 ///
6045 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6046 /// \code
6047 /// void x(int val) {}
6048 /// void y(int val = 0) {}
6049 /// \endcode
AST_MATCHER(ParmVarDecl,hasDefaultArgument)6050 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6051 return Node.hasDefaultArg();
6052 }
6053
6054 /// Matches array new expressions.
6055 ///
6056 /// Given:
6057 /// \code
6058 /// MyClass *p1 = new MyClass[10];
6059 /// \endcode
6060 /// cxxNewExpr(isArray())
6061 /// matches the expression 'new MyClass[10]'.
AST_MATCHER(CXXNewExpr,isArray)6062 AST_MATCHER(CXXNewExpr, isArray) {
6063 return Node.isArray();
6064 }
6065
6066 /// Matches array new expressions with a given array size.
6067 ///
6068 /// Given:
6069 /// \code
6070 /// MyClass *p1 = new MyClass[10];
6071 /// \endcode
6072 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
6073 /// matches the expression 'new MyClass[10]'.
AST_MATCHER_P(CXXNewExpr,hasArraySize,internal::Matcher<Expr>,InnerMatcher)6074 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
6075 return Node.isArray() &&
6076 InnerMatcher.matches(*Node.getArraySize(), Finder, Builder);
6077 }
6078
6079 /// Matches a class declaration that is defined.
6080 ///
6081 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
6082 /// \code
6083 /// class x {};
6084 /// class y;
6085 /// \endcode
AST_MATCHER(CXXRecordDecl,hasDefinition)6086 AST_MATCHER(CXXRecordDecl, hasDefinition) {
6087 return Node.hasDefinition();
6088 }
6089
6090 /// Matches C++11 scoped enum declaration.
6091 ///
6092 /// Example matches Y (matcher = enumDecl(isScoped()))
6093 /// \code
6094 /// enum X {};
6095 /// enum class Y {};
6096 /// \endcode
AST_MATCHER(EnumDecl,isScoped)6097 AST_MATCHER(EnumDecl, isScoped) {
6098 return Node.isScoped();
6099 }
6100
6101 /// Matches a function declared with a trailing return type.
6102 ///
6103 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
6104 /// \code
6105 /// int X() {}
6106 /// auto Y() -> int {}
6107 /// \endcode
AST_MATCHER(FunctionDecl,hasTrailingReturn)6108 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
6109 if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
6110 return F->hasTrailingReturn();
6111 return false;
6112 }
6113
6114 } // namespace ast_matchers
6115 } // namespace clang
6116
6117 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
6118