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