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