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