]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/ASTMatchers/ASTMatchers.h
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / ASTMatchers / ASTMatchers.h
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"
48 #include "clang/AST/ASTTypeTraits.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"
58 #include "clang/AST/NestedNameSpecifier.h"
59 #include "clang/AST/OpenMPClause.h"
60 #include "clang/AST/OperationKinds.h"
61 #include "clang/AST/Stmt.h"
62 #include "clang/AST/StmtCXX.h"
63 #include "clang/AST/StmtObjC.h"
64 #include "clang/AST/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"
69 #include "clang/ASTMatchers/ASTMatchersInternal.h"
70 #include "clang/ASTMatchers/ASTMatchersMacros.h"
71 #include "clang/Basic/AttrKinds.h"
72 #include "clang/Basic/ExceptionSpecificationType.h"
73 #include "clang/Basic/IdentifierTable.h"
74 #include "clang/Basic/LLVM.h"
75 #include "clang/Basic/SourceManager.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:
125   friend class internal::BoundNodesTreeBuilder;
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>
183     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>
207     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>
219     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>
229     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,
246                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
247   auto &SourceManager = Finder->getASTContext().getSourceManager();
248   return SourceManager.isInMainFile(
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,
267                         AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
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,
292                           AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
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 =
300       SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
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>
330     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>
366     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>
378     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>
399     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>
408     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<
421     Decl, ClassTemplateSpecializationDecl>
422     classTemplateSpecializationDecl;
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<
440     Decl, ClassTemplatePartialSpecializationDecl>
441     classTemplatePartialSpecializationDecl;
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>
453     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>
478     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>
490     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,
523                                                    NonTypeTemplateParmDecl>
524     nonTypeTemplateParmDecl;
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>
535     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.
641 AST_MATCHER(FunctionDecl, isMain) {
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.
655 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
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>
689 AST_POLYMORPHIC_MATCHER_P(
690     hasAnyTemplateArgument,
691     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
692                                     TemplateSpecializationType,
693                                     FunctionDecl),
694     internal::Matcher<TemplateArgument>, InnerMatcher) {
695   ArrayRef<TemplateArgument> List =
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>
897 AST_POLYMORPHIC_MATCHER_P2(
898     hasTemplateArgument,
899     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
900                                     TemplateSpecializationType,
901                                     FunctionDecl),
902     unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
903   ArrayRef<TemplateArgument> List =
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>.
919 AST_POLYMORPHIC_MATCHER_P(
920     templateArgumentCountIs,
921     AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
922                                     TemplateSpecializationType),
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>
938 AST_MATCHER_P(TemplateArgument, refersToType,
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.
1012 AST_MATCHER(TemplateArgument, isIntegral) {
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,
1065        ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
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>
1088     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>
1100     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>
1121     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>
1139     cxxConversionDecl;
1140
1141 /// Matches user-defined and implicitly generated deduction guide.
1142 ///
1143 /// Example matches the deduction guide.
1144 /// \code
1145 ///   template<typename T>
1146 ///   class X { X(int) };
1147 ///   X(int) -> X<int>;
1148 /// \endcode
1149 extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1150     cxxDeductionGuideDecl;
1151
1152 /// Matches variable declarations.
1153 ///
1154 /// Note: this does not match declarations of member variables, which are
1155 /// "field" declarations in Clang parlance.
1156 ///
1157 /// Example matches a
1158 /// \code
1159 ///   int a;
1160 /// \endcode
1161 extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1162
1163 /// Matches field declarations.
1164 ///
1165 /// Given
1166 /// \code
1167 ///   class X { int m; };
1168 /// \endcode
1169 /// fieldDecl()
1170 ///   matches 'm'.
1171 extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1172
1173 /// Matches indirect field declarations.
1174 ///
1175 /// Given
1176 /// \code
1177 ///   struct X { struct { int a; }; };
1178 /// \endcode
1179 /// indirectFieldDecl()
1180 ///   matches 'a'.
1181 extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1182     indirectFieldDecl;
1183
1184 /// Matches function declarations.
1185 ///
1186 /// Example matches f
1187 /// \code
1188 ///   void f();
1189 /// \endcode
1190 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1191     functionDecl;
1192
1193 /// Matches C++ function template declarations.
1194 ///
1195 /// Example matches f
1196 /// \code
1197 ///   template<class T> void f(T t) {}
1198 /// \endcode
1199 extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1200     functionTemplateDecl;
1201
1202 /// Matches friend declarations.
1203 ///
1204 /// Given
1205 /// \code
1206 ///   class X { friend void foo(); };
1207 /// \endcode
1208 /// friendDecl()
1209 ///   matches 'friend void foo()'.
1210 extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1211
1212 /// Matches statements.
1213 ///
1214 /// Given
1215 /// \code
1216 ///   { ++a; }
1217 /// \endcode
1218 /// stmt()
1219 ///   matches both the compound statement '{ ++a; }' and '++a'.
1220 extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1221
1222 /// Matches declaration statements.
1223 ///
1224 /// Given
1225 /// \code
1226 ///   int a;
1227 /// \endcode
1228 /// declStmt()
1229 ///   matches 'int a'.
1230 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1231
1232 /// Matches member expressions.
1233 ///
1234 /// Given
1235 /// \code
1236 ///   class Y {
1237 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1238 ///     int a; static int b;
1239 ///   };
1240 /// \endcode
1241 /// memberExpr()
1242 ///   matches this->x, x, y.x, a, this->b
1243 extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1244
1245 /// Matches unresolved member expressions.
1246 ///
1247 /// Given
1248 /// \code
1249 ///   struct X {
1250 ///     template <class T> void f();
1251 ///     void g();
1252 ///   };
1253 ///   template <class T> void h() { X x; x.f<T>(); x.g(); }
1254 /// \endcode
1255 /// unresolvedMemberExpr()
1256 ///   matches x.f<T>
1257 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1258     unresolvedMemberExpr;
1259
1260 /// Matches member expressions where the actual member referenced could not be
1261 /// resolved because the base expression or the member name was dependent.
1262 ///
1263 /// Given
1264 /// \code
1265 ///   template <class T> void f() { T t; t.g(); }
1266 /// \endcode
1267 /// cxxDependentScopeMemberExpr()
1268 ///   matches t.g
1269 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1270                                                    CXXDependentScopeMemberExpr>
1271     cxxDependentScopeMemberExpr;
1272
1273 /// Matches call expressions.
1274 ///
1275 /// Example matches x.y() and y()
1276 /// \code
1277 ///   X x;
1278 ///   x.y();
1279 ///   y();
1280 /// \endcode
1281 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1282
1283 /// Matches call expressions which were resolved using ADL.
1284 ///
1285 /// Example matches y(x) but not y(42) or NS::y(x).
1286 /// \code
1287 ///   namespace NS {
1288 ///     struct X {};
1289 ///     void y(X);
1290 ///   }
1291 ///
1292 ///   void y(...);
1293 ///
1294 ///   void test() {
1295 ///     NS::X x;
1296 ///     y(x); // Matches
1297 ///     NS::y(x); // Doesn't match
1298 ///     y(42); // Doesn't match
1299 ///     using NS::y;
1300 ///     y(x); // Found by both unqualified lookup and ADL, doesn't match
1301 //    }
1302 /// \endcode
1303 AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1304
1305 /// Matches lambda expressions.
1306 ///
1307 /// Example matches [&](){return 5;}
1308 /// \code
1309 ///   [&](){return 5;}
1310 /// \endcode
1311 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1312
1313 /// Matches member call expressions.
1314 ///
1315 /// Example matches x.y()
1316 /// \code
1317 ///   X x;
1318 ///   x.y();
1319 /// \endcode
1320 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1321     cxxMemberCallExpr;
1322
1323 /// Matches ObjectiveC Message invocation expressions.
1324 ///
1325 /// The innermost message send invokes the "alloc" class method on the
1326 /// NSString class, while the outermost message send invokes the
1327 /// "initWithString" instance method on the object returned from
1328 /// NSString's "alloc". This matcher should match both message sends.
1329 /// \code
1330 ///   [[NSString alloc] initWithString:@"Hello"]
1331 /// \endcode
1332 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1333     objcMessageExpr;
1334
1335 /// Matches Objective-C interface declarations.
1336 ///
1337 /// Example matches Foo
1338 /// \code
1339 ///   @interface Foo
1340 ///   @end
1341 /// \endcode
1342 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1343     objcInterfaceDecl;
1344
1345 /// Matches Objective-C implementation declarations.
1346 ///
1347 /// Example matches Foo
1348 /// \code
1349 ///   @implementation Foo
1350 ///   @end
1351 /// \endcode
1352 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1353     objcImplementationDecl;
1354
1355 /// Matches Objective-C protocol declarations.
1356 ///
1357 /// Example matches FooDelegate
1358 /// \code
1359 ///   @protocol FooDelegate
1360 ///   @end
1361 /// \endcode
1362 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1363     objcProtocolDecl;
1364
1365 /// Matches Objective-C category declarations.
1366 ///
1367 /// Example matches Foo (Additions)
1368 /// \code
1369 ///   @interface Foo (Additions)
1370 ///   @end
1371 /// \endcode
1372 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1373     objcCategoryDecl;
1374
1375 /// Matches Objective-C category definitions.
1376 ///
1377 /// Example matches Foo (Additions)
1378 /// \code
1379 ///   @implementation Foo (Additions)
1380 ///   @end
1381 /// \endcode
1382 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1383     objcCategoryImplDecl;
1384
1385 /// Matches Objective-C method declarations.
1386 ///
1387 /// Example matches both declaration and definition of -[Foo method]
1388 /// \code
1389 ///   @interface Foo
1390 ///   - (void)method;
1391 ///   @end
1392 ///
1393 ///   @implementation Foo
1394 ///   - (void)method {}
1395 ///   @end
1396 /// \endcode
1397 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1398     objcMethodDecl;
1399
1400 /// Matches block declarations.
1401 ///
1402 /// Example matches the declaration of the nameless block printing an input
1403 /// integer.
1404 ///
1405 /// \code
1406 ///   myFunc(^(int p) {
1407 ///     printf("%d", p);
1408 ///   })
1409 /// \endcode
1410 extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1411     blockDecl;
1412
1413 /// Matches Objective-C instance variable declarations.
1414 ///
1415 /// Example matches _enabled
1416 /// \code
1417 ///   @implementation Foo {
1418 ///     BOOL _enabled;
1419 ///   }
1420 ///   @end
1421 /// \endcode
1422 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1423     objcIvarDecl;
1424
1425 /// Matches Objective-C property declarations.
1426 ///
1427 /// Example matches enabled
1428 /// \code
1429 ///   @interface Foo
1430 ///   @property BOOL enabled;
1431 ///   @end
1432 /// \endcode
1433 extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1434     objcPropertyDecl;
1435
1436 /// Matches Objective-C \@throw statements.
1437 ///
1438 /// Example matches \@throw
1439 /// \code
1440 ///   @throw obj;
1441 /// \endcode
1442 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1443     objcThrowStmt;
1444
1445 /// Matches Objective-C @try statements.
1446 ///
1447 /// Example matches @try
1448 /// \code
1449 ///   @try {}
1450 ///   @catch (...) {}
1451 /// \endcode
1452 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1453     objcTryStmt;
1454
1455 /// Matches Objective-C @catch statements.
1456 ///
1457 /// Example matches @catch
1458 /// \code
1459 ///   @try {}
1460 ///   @catch (...) {}
1461 /// \endcode
1462 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1463     objcCatchStmt;
1464
1465 /// Matches Objective-C @finally statements.
1466 ///
1467 /// Example matches @finally
1468 /// \code
1469 ///   @try {}
1470 ///   @finally {}
1471 /// \endcode
1472 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1473     objcFinallyStmt;
1474
1475 /// Matches expressions that introduce cleanups to be run at the end
1476 /// of the sub-expression's evaluation.
1477 ///
1478 /// Example matches std::string()
1479 /// \code
1480 ///   const std::string str = std::string();
1481 /// \endcode
1482 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1483     exprWithCleanups;
1484
1485 /// Matches init list expressions.
1486 ///
1487 /// Given
1488 /// \code
1489 ///   int a[] = { 1, 2 };
1490 ///   struct B { int x, y; };
1491 ///   B b = { 5, 6 };
1492 /// \endcode
1493 /// initListExpr()
1494 ///   matches "{ 1, 2 }" and "{ 5, 6 }"
1495 extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1496     initListExpr;
1497
1498 /// Matches the syntactic form of init list expressions
1499 /// (if expression have it).
1500 AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1501               internal::Matcher<Expr>, InnerMatcher) {
1502   const Expr *SyntForm = Node.getSyntacticForm();
1503   return (SyntForm != nullptr &&
1504           InnerMatcher.matches(*SyntForm, Finder, Builder));
1505 }
1506
1507 /// Matches C++ initializer list expressions.
1508 ///
1509 /// Given
1510 /// \code
1511 ///   std::vector<int> a({ 1, 2, 3 });
1512 ///   std::vector<int> b = { 4, 5 };
1513 ///   int c[] = { 6, 7 };
1514 ///   std::pair<int, int> d = { 8, 9 };
1515 /// \endcode
1516 /// cxxStdInitializerListExpr()
1517 ///   matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1518 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1519                                                    CXXStdInitializerListExpr>
1520     cxxStdInitializerListExpr;
1521
1522 /// Matches implicit initializers of init list expressions.
1523 ///
1524 /// Given
1525 /// \code
1526 ///   point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1527 /// \endcode
1528 /// implicitValueInitExpr()
1529 ///   matches "[0].y" (implicitly)
1530 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1531     implicitValueInitExpr;
1532
1533 /// Matches paren list expressions.
1534 /// ParenListExprs don't have a predefined type and are used for late parsing.
1535 /// In the final AST, they can be met in template declarations.
1536 ///
1537 /// Given
1538 /// \code
1539 ///   template<typename T> class X {
1540 ///     void f() {
1541 ///       X x(*this);
1542 ///       int a = 0, b = 1; int i = (a, b);
1543 ///     }
1544 ///   };
1545 /// \endcode
1546 /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1547 /// has a predefined type and is a ParenExpr, not a ParenListExpr.
1548 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1549     parenListExpr;
1550
1551 /// Matches substitutions of non-type template parameters.
1552 ///
1553 /// Given
1554 /// \code
1555 ///   template <int N>
1556 ///   struct A { static const int n = N; };
1557 ///   struct B : public A<42> {};
1558 /// \endcode
1559 /// substNonTypeTemplateParmExpr()
1560 ///   matches "N" in the right-hand side of "static const int n = N;"
1561 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1562                                                    SubstNonTypeTemplateParmExpr>
1563     substNonTypeTemplateParmExpr;
1564
1565 /// Matches using declarations.
1566 ///
1567 /// Given
1568 /// \code
1569 ///   namespace X { int x; }
1570 ///   using X::x;
1571 /// \endcode
1572 /// usingDecl()
1573 ///   matches \code using X::x \endcode
1574 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1575
1576 /// Matches using namespace declarations.
1577 ///
1578 /// Given
1579 /// \code
1580 ///   namespace X { int x; }
1581 ///   using namespace X;
1582 /// \endcode
1583 /// usingDirectiveDecl()
1584 ///   matches \code using namespace X \endcode
1585 extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1586     usingDirectiveDecl;
1587
1588 /// Matches reference to a name that can be looked up during parsing
1589 /// but could not be resolved to a specific declaration.
1590 ///
1591 /// Given
1592 /// \code
1593 ///   template<typename T>
1594 ///   T foo() { T a; return a; }
1595 ///   template<typename T>
1596 ///   void bar() {
1597 ///     foo<T>();
1598 ///   }
1599 /// \endcode
1600 /// unresolvedLookupExpr()
1601 ///   matches \code foo<T>() \endcode
1602 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1603     unresolvedLookupExpr;
1604
1605 /// Matches unresolved using value declarations.
1606 ///
1607 /// Given
1608 /// \code
1609 ///   template<typename X>
1610 ///   class C : private X {
1611 ///     using X::x;
1612 ///   };
1613 /// \endcode
1614 /// unresolvedUsingValueDecl()
1615 ///   matches \code using X::x \endcode
1616 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1617                                                    UnresolvedUsingValueDecl>
1618     unresolvedUsingValueDecl;
1619
1620 /// Matches unresolved using value declarations that involve the
1621 /// typename.
1622 ///
1623 /// Given
1624 /// \code
1625 ///   template <typename T>
1626 ///   struct Base { typedef T Foo; };
1627 ///
1628 ///   template<typename T>
1629 ///   struct S : private Base<T> {
1630 ///     using typename Base<T>::Foo;
1631 ///   };
1632 /// \endcode
1633 /// unresolvedUsingTypenameDecl()
1634 ///   matches \code using Base<T>::Foo \endcode
1635 extern const internal::VariadicDynCastAllOfMatcher<Decl,
1636                                                    UnresolvedUsingTypenameDecl>
1637     unresolvedUsingTypenameDecl;
1638
1639 /// Matches a constant expression wrapper.
1640 ///
1641 /// Example matches the constant in the case statement:
1642 ///     (matcher = constantExpr())
1643 /// \code
1644 ///   switch (a) {
1645 ///   case 37: break;
1646 ///   }
1647 /// \endcode
1648 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1649     constantExpr;
1650
1651 /// Matches parentheses used in expressions.
1652 ///
1653 /// Example matches (foo() + 1)
1654 /// \code
1655 ///   int foo() { return 1; }
1656 ///   int a = (foo() + 1);
1657 /// \endcode
1658 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1659
1660 /// Matches constructor call expressions (including implicit ones).
1661 ///
1662 /// Example matches string(ptr, n) and ptr within arguments of f
1663 ///     (matcher = cxxConstructExpr())
1664 /// \code
1665 ///   void f(const string &a, const string &b);
1666 ///   char *ptr;
1667 ///   int n;
1668 ///   f(string(ptr, n), ptr);
1669 /// \endcode
1670 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1671     cxxConstructExpr;
1672
1673 /// Matches unresolved constructor call expressions.
1674 ///
1675 /// Example matches T(t) in return statement of f
1676 ///     (matcher = cxxUnresolvedConstructExpr())
1677 /// \code
1678 ///   template <typename T>
1679 ///   void f(const T& t) { return T(t); }
1680 /// \endcode
1681 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1682                                                    CXXUnresolvedConstructExpr>
1683     cxxUnresolvedConstructExpr;
1684
1685 /// Matches implicit and explicit this expressions.
1686 ///
1687 /// Example matches the implicit this expression in "return i".
1688 ///     (matcher = cxxThisExpr())
1689 /// \code
1690 /// struct foo {
1691 ///   int i;
1692 ///   int f() { return i; }
1693 /// };
1694 /// \endcode
1695 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1696     cxxThisExpr;
1697
1698 /// Matches nodes where temporaries are created.
1699 ///
1700 /// Example matches FunctionTakesString(GetStringByValue())
1701 ///     (matcher = cxxBindTemporaryExpr())
1702 /// \code
1703 ///   FunctionTakesString(GetStringByValue());
1704 ///   FunctionTakesStringByPointer(GetStringPointer());
1705 /// \endcode
1706 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1707     cxxBindTemporaryExpr;
1708
1709 /// Matches nodes where temporaries are materialized.
1710 ///
1711 /// Example: Given
1712 /// \code
1713 ///   struct T {void func();};
1714 ///   T f();
1715 ///   void g(T);
1716 /// \endcode
1717 /// materializeTemporaryExpr() matches 'f()' in these statements
1718 /// \code
1719 ///   T u(f());
1720 ///   g(f());
1721 ///   f().func();
1722 /// \endcode
1723 /// but does not match
1724 /// \code
1725 ///   f();
1726 /// \endcode
1727 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1728                                                    MaterializeTemporaryExpr>
1729     materializeTemporaryExpr;
1730
1731 /// Matches new expressions.
1732 ///
1733 /// Given
1734 /// \code
1735 ///   new X;
1736 /// \endcode
1737 /// cxxNewExpr()
1738 ///   matches 'new X'.
1739 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1740
1741 /// Matches delete expressions.
1742 ///
1743 /// Given
1744 /// \code
1745 ///   delete X;
1746 /// \endcode
1747 /// cxxDeleteExpr()
1748 ///   matches 'delete X'.
1749 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1750     cxxDeleteExpr;
1751
1752 /// Matches array subscript expressions.
1753 ///
1754 /// Given
1755 /// \code
1756 ///   int i = a[1];
1757 /// \endcode
1758 /// arraySubscriptExpr()
1759 ///   matches "a[1]"
1760 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1761     arraySubscriptExpr;
1762
1763 /// Matches the value of a default argument at the call site.
1764 ///
1765 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
1766 ///     default value of the second parameter in the call expression f(42)
1767 ///     (matcher = cxxDefaultArgExpr())
1768 /// \code
1769 ///   void f(int x, int y = 0);
1770 ///   f(42);
1771 /// \endcode
1772 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1773     cxxDefaultArgExpr;
1774
1775 /// Matches overloaded operator calls.
1776 ///
1777 /// Note that if an operator isn't overloaded, it won't match. Instead, use
1778 /// binaryOperator matcher.
1779 /// Currently it does not match operators such as new delete.
1780 /// FIXME: figure out why these do not match?
1781 ///
1782 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
1783 ///     (matcher = cxxOperatorCallExpr())
1784 /// \code
1785 ///   ostream &operator<< (ostream &out, int i) { };
1786 ///   ostream &o; int b = 1, c = 1;
1787 ///   o << b << c;
1788 /// \endcode
1789 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1790     cxxOperatorCallExpr;
1791
1792 /// Matches expressions.
1793 ///
1794 /// Example matches x()
1795 /// \code
1796 ///   void f() { x(); }
1797 /// \endcode
1798 extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
1799
1800 /// Matches expressions that refer to declarations.
1801 ///
1802 /// Example matches x in if (x)
1803 /// \code
1804 ///   bool x;
1805 ///   if (x) {}
1806 /// \endcode
1807 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
1808     declRefExpr;
1809
1810 /// Matches a reference to an ObjCIvar.
1811 ///
1812 /// Example: matches "a" in "init" method:
1813 /// \code
1814 /// @implementation A {
1815 ///   NSString *a;
1816 /// }
1817 /// - (void) init {
1818 ///   a = @"hello";
1819 /// }
1820 /// \endcode
1821 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
1822     objcIvarRefExpr;
1823
1824 /// Matches a reference to a block.
1825 ///
1826 /// Example: matches "^{}":
1827 /// \code
1828 ///   void f() { ^{}(); }
1829 /// \endcode
1830 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
1831
1832 /// Matches if statements.
1833 ///
1834 /// Example matches 'if (x) {}'
1835 /// \code
1836 ///   if (x) {}
1837 /// \endcode
1838 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
1839
1840 /// Matches for statements.
1841 ///
1842 /// Example matches 'for (;;) {}'
1843 /// \code
1844 ///   for (;;) {}
1845 ///   int i[] =  {1, 2, 3}; for (auto a : i);
1846 /// \endcode
1847 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
1848
1849 /// Matches the increment statement of a for loop.
1850 ///
1851 /// Example:
1852 ///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
1853 /// matches '++x' in
1854 /// \code
1855 ///     for (x; x < N; ++x) { }
1856 /// \endcode
1857 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
1858               InnerMatcher) {
1859   const Stmt *const Increment = Node.getInc();
1860   return (Increment != nullptr &&
1861           InnerMatcher.matches(*Increment, Finder, Builder));
1862 }
1863
1864 /// Matches the initialization statement of a for loop.
1865 ///
1866 /// Example:
1867 ///     forStmt(hasLoopInit(declStmt()))
1868 /// matches 'int x = 0' in
1869 /// \code
1870 ///     for (int x = 0; x < N; ++x) { }
1871 /// \endcode
1872 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
1873               InnerMatcher) {
1874   const Stmt *const Init = Node.getInit();
1875   return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1876 }
1877
1878 /// Matches range-based for statements.
1879 ///
1880 /// cxxForRangeStmt() matches 'for (auto a : i)'
1881 /// \code
1882 ///   int i[] =  {1, 2, 3}; for (auto a : i);
1883 ///   for(int j = 0; j < 5; ++j);
1884 /// \endcode
1885 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
1886     cxxForRangeStmt;
1887
1888 /// Matches the initialization statement of a for loop.
1889 ///
1890 /// Example:
1891 ///     forStmt(hasLoopVariable(anything()))
1892 /// matches 'int x' in
1893 /// \code
1894 ///     for (int x : a) { }
1895 /// \endcode
1896 AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
1897               InnerMatcher) {
1898   const VarDecl *const Var = Node.getLoopVariable();
1899   return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
1900 }
1901
1902 /// Matches the range initialization statement of a for loop.
1903 ///
1904 /// Example:
1905 ///     forStmt(hasRangeInit(anything()))
1906 /// matches 'a' in
1907 /// \code
1908 ///     for (int x : a) { }
1909 /// \endcode
1910 AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
1911               InnerMatcher) {
1912   const Expr *const Init = Node.getRangeInit();
1913   return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
1914 }
1915
1916 /// Matches while statements.
1917 ///
1918 /// Given
1919 /// \code
1920 ///   while (true) {}
1921 /// \endcode
1922 /// whileStmt()
1923 ///   matches 'while (true) {}'.
1924 extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
1925
1926 /// Matches do statements.
1927 ///
1928 /// Given
1929 /// \code
1930 ///   do {} while (true);
1931 /// \endcode
1932 /// doStmt()
1933 ///   matches 'do {} while(true)'
1934 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
1935
1936 /// Matches break statements.
1937 ///
1938 /// Given
1939 /// \code
1940 ///   while (true) { break; }
1941 /// \endcode
1942 /// breakStmt()
1943 ///   matches 'break'
1944 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
1945
1946 /// Matches continue statements.
1947 ///
1948 /// Given
1949 /// \code
1950 ///   while (true) { continue; }
1951 /// \endcode
1952 /// continueStmt()
1953 ///   matches 'continue'
1954 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
1955     continueStmt;
1956
1957 /// Matches return statements.
1958 ///
1959 /// Given
1960 /// \code
1961 ///   return 1;
1962 /// \endcode
1963 /// returnStmt()
1964 ///   matches 'return 1'
1965 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
1966
1967 /// Matches goto statements.
1968 ///
1969 /// Given
1970 /// \code
1971 ///   goto FOO;
1972 ///   FOO: bar();
1973 /// \endcode
1974 /// gotoStmt()
1975 ///   matches 'goto FOO'
1976 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
1977
1978 /// Matches label statements.
1979 ///
1980 /// Given
1981 /// \code
1982 ///   goto FOO;
1983 ///   FOO: bar();
1984 /// \endcode
1985 /// labelStmt()
1986 ///   matches 'FOO:'
1987 extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
1988
1989 /// Matches address of label statements (GNU extension).
1990 ///
1991 /// Given
1992 /// \code
1993 ///   FOO: bar();
1994 ///   void *ptr = &&FOO;
1995 ///   goto *bar;
1996 /// \endcode
1997 /// addrLabelExpr()
1998 ///   matches '&&FOO'
1999 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2000     addrLabelExpr;
2001
2002 /// Matches switch statements.
2003 ///
2004 /// Given
2005 /// \code
2006 ///   switch(a) { case 42: break; default: break; }
2007 /// \endcode
2008 /// switchStmt()
2009 ///   matches 'switch(a)'.
2010 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2011
2012 /// Matches case and default statements inside switch statements.
2013 ///
2014 /// Given
2015 /// \code
2016 ///   switch(a) { case 42: break; default: break; }
2017 /// \endcode
2018 /// switchCase()
2019 ///   matches 'case 42:' and 'default:'.
2020 extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2021
2022 /// Matches case statements inside switch statements.
2023 ///
2024 /// Given
2025 /// \code
2026 ///   switch(a) { case 42: break; default: break; }
2027 /// \endcode
2028 /// caseStmt()
2029 ///   matches 'case 42:'.
2030 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2031
2032 /// Matches default statements inside switch statements.
2033 ///
2034 /// Given
2035 /// \code
2036 ///   switch(a) { case 42: break; default: break; }
2037 /// \endcode
2038 /// defaultStmt()
2039 ///   matches 'default:'.
2040 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2041     defaultStmt;
2042
2043 /// Matches compound statements.
2044 ///
2045 /// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2046 /// \code
2047 ///   for (;;) {{}}
2048 /// \endcode
2049 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2050     compoundStmt;
2051
2052 /// Matches catch statements.
2053 ///
2054 /// \code
2055 ///   try {} catch(int i) {}
2056 /// \endcode
2057 /// cxxCatchStmt()
2058 ///   matches 'catch(int i)'
2059 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2060     cxxCatchStmt;
2061
2062 /// Matches try statements.
2063 ///
2064 /// \code
2065 ///   try {} catch(int i) {}
2066 /// \endcode
2067 /// cxxTryStmt()
2068 ///   matches 'try {}'
2069 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2070
2071 /// Matches throw expressions.
2072 ///
2073 /// \code
2074 ///   try { throw 5; } catch(int i) {}
2075 /// \endcode
2076 /// cxxThrowExpr()
2077 ///   matches 'throw 5'
2078 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2079     cxxThrowExpr;
2080
2081 /// Matches null statements.
2082 ///
2083 /// \code
2084 ///   foo();;
2085 /// \endcode
2086 /// nullStmt()
2087 ///   matches the second ';'
2088 extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2089
2090 /// Matches asm statements.
2091 ///
2092 /// \code
2093 ///  int i = 100;
2094 ///   __asm("mov al, 2");
2095 /// \endcode
2096 /// asmStmt()
2097 ///   matches '__asm("mov al, 2")'
2098 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2099
2100 /// Matches bool literals.
2101 ///
2102 /// Example matches true
2103 /// \code
2104 ///   true
2105 /// \endcode
2106 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2107     cxxBoolLiteral;
2108
2109 /// Matches string literals (also matches wide string literals).
2110 ///
2111 /// Example matches "abcd", L"abcd"
2112 /// \code
2113 ///   char *s = "abcd";
2114 ///   wchar_t *ws = L"abcd";
2115 /// \endcode
2116 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2117     stringLiteral;
2118
2119 /// Matches character literals (also matches wchar_t).
2120 ///
2121 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2122 /// though.
2123 ///
2124 /// Example matches 'a', L'a'
2125 /// \code
2126 ///   char ch = 'a';
2127 ///   wchar_t chw = L'a';
2128 /// \endcode
2129 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2130     characterLiteral;
2131
2132 /// Matches integer literals of all sizes / encodings, e.g.
2133 /// 1, 1L, 0x1 and 1U.
2134 ///
2135 /// Does not match character-encoded integers such as L'a'.
2136 extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2137     integerLiteral;
2138
2139 /// Matches float literals of all sizes / encodings, e.g.
2140 /// 1.0, 1.0f, 1.0L and 1e10.
2141 ///
2142 /// Does not match implicit conversions such as
2143 /// \code
2144 ///   float a = 10;
2145 /// \endcode
2146 extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2147     floatLiteral;
2148
2149 /// Matches imaginary literals, which are based on integer and floating
2150 /// point literals e.g.: 1i, 1.0i
2151 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2152     imaginaryLiteral;
2153
2154 /// Matches user defined literal operator call.
2155 ///
2156 /// Example match: "foo"_suffix
2157 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2158     userDefinedLiteral;
2159
2160 /// Matches compound (i.e. non-scalar) literals
2161 ///
2162 /// Example match: {1}, (1, 2)
2163 /// \code
2164 ///   int array[4] = {1};
2165 ///   vector int myvec = (vector int)(1, 2);
2166 /// \endcode
2167 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2168     compoundLiteralExpr;
2169
2170 /// Matches nullptr literal.
2171 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2172     cxxNullPtrLiteralExpr;
2173
2174 /// Matches GNU __builtin_choose_expr.
2175 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2176     chooseExpr;
2177
2178 /// Matches GNU __null expression.
2179 extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2180     gnuNullExpr;
2181
2182 /// Matches atomic builtins.
2183 /// Example matches __atomic_load_n(ptr, 1)
2184 /// \code
2185 ///   void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2186 /// \endcode
2187 extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2188
2189 /// Matches statement expression (GNU extension).
2190 ///
2191 /// Example match: ({ int X = 4; X; })
2192 /// \code
2193 ///   int C = ({ int X = 4; X; });
2194 /// \endcode
2195 extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2196
2197 /// Matches binary operator expressions.
2198 ///
2199 /// Example matches a || b
2200 /// \code
2201 ///   !(a || b)
2202 /// \endcode
2203 extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2204     binaryOperator;
2205
2206 /// Matches unary operator expressions.
2207 ///
2208 /// Example matches !a
2209 /// \code
2210 ///   !a || b
2211 /// \endcode
2212 extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2213     unaryOperator;
2214
2215 /// Matches conditional operator expressions.
2216 ///
2217 /// Example matches a ? b : c
2218 /// \code
2219 ///   (a ? b : c) + 42
2220 /// \endcode
2221 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2222     conditionalOperator;
2223
2224 /// Matches binary conditional operator expressions (GNU extension).
2225 ///
2226 /// Example matches a ?: b
2227 /// \code
2228 ///   (a ?: b) + 42;
2229 /// \endcode
2230 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2231                                                    BinaryConditionalOperator>
2232     binaryConditionalOperator;
2233
2234 /// Matches opaque value expressions. They are used as helpers
2235 /// to reference another expressions and can be met
2236 /// in BinaryConditionalOperators, for example.
2237 ///
2238 /// Example matches 'a'
2239 /// \code
2240 ///   (a ?: c) + 42;
2241 /// \endcode
2242 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2243     opaqueValueExpr;
2244
2245 /// Matches a C++ static_assert declaration.
2246 ///
2247 /// Example:
2248 ///   staticAssertExpr()
2249 /// matches
2250 ///   static_assert(sizeof(S) == sizeof(int))
2251 /// in
2252 /// \code
2253 ///   struct S {
2254 ///     int x;
2255 ///   };
2256 ///   static_assert(sizeof(S) == sizeof(int));
2257 /// \endcode
2258 extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2259     staticAssertDecl;
2260
2261 /// Matches a reinterpret_cast expression.
2262 ///
2263 /// Either the source expression or the destination type can be matched
2264 /// using has(), but hasDestinationType() is more specific and can be
2265 /// more readable.
2266 ///
2267 /// Example matches reinterpret_cast<char*>(&p) in
2268 /// \code
2269 ///   void* p = reinterpret_cast<char*>(&p);
2270 /// \endcode
2271 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2272     cxxReinterpretCastExpr;
2273
2274 /// Matches a C++ static_cast expression.
2275 ///
2276 /// \see hasDestinationType
2277 /// \see reinterpretCast
2278 ///
2279 /// Example:
2280 ///   cxxStaticCastExpr()
2281 /// matches
2282 ///   static_cast<long>(8)
2283 /// in
2284 /// \code
2285 ///   long eight(static_cast<long>(8));
2286 /// \endcode
2287 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2288     cxxStaticCastExpr;
2289
2290 /// Matches a dynamic_cast expression.
2291 ///
2292 /// Example:
2293 ///   cxxDynamicCastExpr()
2294 /// matches
2295 ///   dynamic_cast<D*>(&b);
2296 /// in
2297 /// \code
2298 ///   struct B { virtual ~B() {} }; struct D : B {};
2299 ///   B b;
2300 ///   D* p = dynamic_cast<D*>(&b);
2301 /// \endcode
2302 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2303     cxxDynamicCastExpr;
2304
2305 /// Matches a const_cast expression.
2306 ///
2307 /// Example: Matches const_cast<int*>(&r) in
2308 /// \code
2309 ///   int n = 42;
2310 ///   const int &r(n);
2311 ///   int* p = const_cast<int*>(&r);
2312 /// \endcode
2313 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2314     cxxConstCastExpr;
2315
2316 /// Matches a C-style cast expression.
2317 ///
2318 /// Example: Matches (int) 2.2f in
2319 /// \code
2320 ///   int i = (int) 2.2f;
2321 /// \endcode
2322 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2323     cStyleCastExpr;
2324
2325 /// Matches explicit cast expressions.
2326 ///
2327 /// Matches any cast expression written in user code, whether it be a
2328 /// C-style cast, a functional-style cast, or a keyword cast.
2329 ///
2330 /// Does not match implicit conversions.
2331 ///
2332 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2333 /// Clang uses the term "cast" to apply to implicit conversions as well as to
2334 /// actual cast expressions.
2335 ///
2336 /// \see hasDestinationType.
2337 ///
2338 /// Example: matches all five of the casts in
2339 /// \code
2340 ///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2341 /// \endcode
2342 /// but does not match the implicit conversion in
2343 /// \code
2344 ///   long ell = 42;
2345 /// \endcode
2346 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2347     explicitCastExpr;
2348
2349 /// Matches the implicit cast nodes of Clang's AST.
2350 ///
2351 /// This matches many different places, including function call return value
2352 /// eliding, as well as any type conversions.
2353 extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2354     implicitCastExpr;
2355
2356 /// Matches any cast nodes of Clang's AST.
2357 ///
2358 /// Example: castExpr() matches each of the following:
2359 /// \code
2360 ///   (int) 3;
2361 ///   const_cast<Expr *>(SubExpr);
2362 ///   char c = 0;
2363 /// \endcode
2364 /// but does not match
2365 /// \code
2366 ///   int i = (0);
2367 ///   int k = 0;
2368 /// \endcode
2369 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2370
2371 /// Matches functional cast expressions
2372 ///
2373 /// Example: Matches Foo(bar);
2374 /// \code
2375 ///   Foo f = bar;
2376 ///   Foo g = (Foo) bar;
2377 ///   Foo h = Foo(bar);
2378 /// \endcode
2379 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2380     cxxFunctionalCastExpr;
2381
2382 /// Matches functional cast expressions having N != 1 arguments
2383 ///
2384 /// Example: Matches Foo(bar, bar)
2385 /// \code
2386 ///   Foo h = Foo(bar, bar);
2387 /// \endcode
2388 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2389     cxxTemporaryObjectExpr;
2390
2391 /// Matches predefined identifier expressions [C99 6.4.2.2].
2392 ///
2393 /// Example: Matches __func__
2394 /// \code
2395 ///   printf("%s", __func__);
2396 /// \endcode
2397 extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2398     predefinedExpr;
2399
2400 /// Matches C99 designated initializer expressions [C99 6.7.8].
2401 ///
2402 /// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2403 /// \code
2404 ///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2405 /// \endcode
2406 extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2407     designatedInitExpr;
2408
2409 /// Matches designated initializer expressions that contain
2410 /// a specific number of designators.
2411 ///
2412 /// Example: Given
2413 /// \code
2414 ///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2415 ///   point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2416 /// \endcode
2417 /// designatorCountIs(2)
2418 ///   matches '{ [2].y = 1.0, [0].x = 1.0 }',
2419 ///   but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2420 AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2421   return Node.size() == N;
2422 }
2423
2424 /// Matches \c QualTypes in the clang AST.
2425 extern const internal::VariadicAllOfMatcher<QualType> qualType;
2426
2427 /// Matches \c Types in the clang AST.
2428 extern const internal::VariadicAllOfMatcher<Type> type;
2429
2430 /// Matches \c TypeLocs in the clang AST.
2431 extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2432
2433 /// Matches if any of the given matchers matches.
2434 ///
2435 /// Unlike \c anyOf, \c eachOf will generate a match result for each
2436 /// matching submatcher.
2437 ///
2438 /// For example, in:
2439 /// \code
2440 ///   class A { int a; int b; };
2441 /// \endcode
2442 /// The matcher:
2443 /// \code
2444 ///   cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2445 ///                        has(fieldDecl(hasName("b")).bind("v"))))
2446 /// \endcode
2447 /// will generate two results binding "v", the first of which binds
2448 /// the field declaration of \c a, the second the field declaration of
2449 /// \c b.
2450 ///
2451 /// Usable as: Any Matcher
2452 extern const internal::VariadicOperatorMatcherFunc<
2453     2, std::numeric_limits<unsigned>::max()>
2454     eachOf;
2455
2456 /// Matches if any of the given matchers matches.
2457 ///
2458 /// Usable as: Any Matcher
2459 extern const internal::VariadicOperatorMatcherFunc<
2460     2, std::numeric_limits<unsigned>::max()>
2461     anyOf;
2462
2463 /// Matches if all given matchers match.
2464 ///
2465 /// Usable as: Any Matcher
2466 extern const internal::VariadicOperatorMatcherFunc<
2467     2, std::numeric_limits<unsigned>::max()>
2468     allOf;
2469
2470 /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2471 ///
2472 /// Given
2473 /// \code
2474 ///   Foo x = bar;
2475 ///   int y = sizeof(x) + alignof(x);
2476 /// \endcode
2477 /// unaryExprOrTypeTraitExpr()
2478 ///   matches \c sizeof(x) and \c alignof(x)
2479 extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2480                                                    UnaryExprOrTypeTraitExpr>
2481     unaryExprOrTypeTraitExpr;
2482
2483 /// Matches unary expressions that have a specific type of argument.
2484 ///
2485 /// Given
2486 /// \code
2487 ///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2488 /// \endcode
2489 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2490 ///   matches \c sizeof(a) and \c alignof(c)
2491 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2492               internal::Matcher<QualType>, InnerMatcher) {
2493   const QualType ArgumentType = Node.getTypeOfArgument();
2494   return InnerMatcher.matches(ArgumentType, Finder, Builder);
2495 }
2496
2497 /// Matches unary expressions of a certain kind.
2498 ///
2499 /// Given
2500 /// \code
2501 ///   int x;
2502 ///   int s = sizeof(x) + alignof(x)
2503 /// \endcode
2504 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2505 ///   matches \c sizeof(x)
2506 ///
2507 /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2508 /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2509 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2510   return Node.getKind() == Kind;
2511 }
2512
2513 /// Same as unaryExprOrTypeTraitExpr, but only matching
2514 /// alignof.
2515 inline internal::Matcher<Stmt> alignOfExpr(
2516     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2517   return stmt(unaryExprOrTypeTraitExpr(
2518       allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2519             InnerMatcher)));
2520 }
2521
2522 /// Same as unaryExprOrTypeTraitExpr, but only matching
2523 /// sizeof.
2524 inline internal::Matcher<Stmt> sizeOfExpr(
2525     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2526   return stmt(unaryExprOrTypeTraitExpr(
2527       allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2528 }
2529
2530 /// Matches NamedDecl nodes that have the specified name.
2531 ///
2532 /// Supports specifying enclosing namespaces or classes by prefixing the name
2533 /// with '<enclosing>::'.
2534 /// Does not match typedefs of an underlying type with the given name.
2535 ///
2536 /// Example matches X (Name == "X")
2537 /// \code
2538 ///   class X;
2539 /// \endcode
2540 ///
2541 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2542 /// \code
2543 ///   namespace a { namespace b { class X; } }
2544 /// \endcode
2545 inline internal::Matcher<NamedDecl> hasName(const std::string &Name) {
2546   return internal::Matcher<NamedDecl>(new internal::HasNameMatcher({Name}));
2547 }
2548
2549 /// Matches NamedDecl nodes that have any of the specified names.
2550 ///
2551 /// This matcher is only provided as a performance optimization of hasName.
2552 /// \code
2553 ///     hasAnyName(a, b, c)
2554 /// \endcode
2555 ///  is equivalent to, but faster than
2556 /// \code
2557 ///     anyOf(hasName(a), hasName(b), hasName(c))
2558 /// \endcode
2559 extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2560                                         internal::hasAnyNameFunc>
2561     hasAnyName;
2562
2563 /// Matches NamedDecl nodes whose fully qualified names contain
2564 /// a substring matched by the given RegExp.
2565 ///
2566 /// Supports specifying enclosing namespaces or classes by
2567 /// prefixing the name with '<enclosing>::'.  Does not match typedefs
2568 /// of an underlying type with the given name.
2569 ///
2570 /// Example matches X (regexp == "::X")
2571 /// \code
2572 ///   class X;
2573 /// \endcode
2574 ///
2575 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2576 /// \code
2577 ///   namespace foo { namespace bar { class X; } }
2578 /// \endcode
2579 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
2580   assert(!RegExp.empty());
2581   std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2582   llvm::Regex RE(RegExp);
2583   return RE.match(FullNameString);
2584 }
2585
2586 /// Matches overloaded operator names.
2587 ///
2588 /// Matches overloaded operator names specified in strings without the
2589 /// "operator" prefix: e.g. "<<".
2590 ///
2591 /// Given:
2592 /// \code
2593 ///   class A { int operator*(); };
2594 ///   const A &operator<<(const A &a, const A &b);
2595 ///   A a;
2596 ///   a << a;   // <-- This matches
2597 /// \endcode
2598 ///
2599 /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2600 /// specified line and
2601 /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2602 /// matches the declaration of \c A.
2603 ///
2604 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2605 inline internal::PolymorphicMatcherWithParam1<
2606     internal::HasOverloadedOperatorNameMatcher, StringRef,
2607     AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2608 hasOverloadedOperatorName(StringRef Name) {
2609   return internal::PolymorphicMatcherWithParam1<
2610       internal::HasOverloadedOperatorNameMatcher, StringRef,
2611       AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name);
2612 }
2613
2614 /// Matches C++ classes that are directly or indirectly derived from
2615 /// a class matching \c Base.
2616 ///
2617 /// Note that a class is not considered to be derived from itself.
2618 ///
2619 /// Example matches Y, Z, C (Base == hasName("X"))
2620 /// \code
2621 ///   class X;
2622 ///   class Y : public X {};  // directly derived
2623 ///   class Z : public Y {};  // indirectly derived
2624 ///   typedef X A;
2625 ///   typedef A B;
2626 ///   class C : public B {};  // derived from a typedef of X
2627 /// \endcode
2628 ///
2629 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
2630 /// \code
2631 ///   class Foo;
2632 ///   typedef Foo X;
2633 ///   class Bar : public Foo {};  // derived from a type that X is a typedef of
2634 /// \endcode
2635 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
2636               internal::Matcher<NamedDecl>, Base) {
2637   return Finder->classIsDerivedFrom(&Node, Base, Builder);
2638 }
2639
2640 /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
2641 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) {
2642   assert(!BaseName.empty());
2643   return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2644 }
2645
2646 /// Similar to \c isDerivedFrom(), but also matches classes that directly
2647 /// match \c Base.
2648 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom,
2649                        internal::Matcher<NamedDecl>, Base, 0) {
2650   return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base)))
2651       .matches(Node, Finder, Builder);
2652 }
2653
2654 /// Overloaded method as shortcut for
2655 /// \c isSameOrDerivedFrom(hasName(...)).
2656 AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string,
2657                        BaseName, 1) {
2658   assert(!BaseName.empty());
2659   return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder);
2660 }
2661
2662 /// Matches the first method of a class or struct that satisfies \c
2663 /// InnerMatcher.
2664 ///
2665 /// Given:
2666 /// \code
2667 ///   class A { void func(); };
2668 ///   class B { void member(); };
2669 /// \endcode
2670 ///
2671 /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
2672 /// \c A but not \c B.
2673 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
2674               InnerMatcher) {
2675   return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
2676                                     Node.method_end(), Finder, Builder);
2677 }
2678
2679 /// Matches the generated class of lambda expressions.
2680 ///
2681 /// Given:
2682 /// \code
2683 ///   auto x = []{};
2684 /// \endcode
2685 ///
2686 /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
2687 /// \c decltype(x)
2688 AST_MATCHER(CXXRecordDecl, isLambda) {
2689   return Node.isLambda();
2690 }
2691
2692 /// Matches AST nodes that have child AST nodes that match the
2693 /// provided matcher.
2694 ///
2695 /// Example matches X, Y
2696 ///   (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
2697 /// \code
2698 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
2699 ///   class Y { class X {}; };
2700 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
2701 /// \endcode
2702 ///
2703 /// ChildT must be an AST base type.
2704 ///
2705 /// Usable as: Any Matcher
2706 /// Note that has is direct matcher, so it also matches things like implicit
2707 /// casts and paren casts. If you are matching with expr then you should
2708 /// probably consider using ignoringParenImpCasts like:
2709 /// has(ignoringParenImpCasts(expr())).
2710 extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
2711
2712 /// Matches AST nodes that have descendant AST nodes that match the
2713 /// provided matcher.
2714 ///
2715 /// Example matches X, Y, Z
2716 ///     (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
2717 /// \code
2718 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
2719 ///   class Y { class X {}; };
2720 ///   class Z { class Y { class X {}; }; };
2721 /// \endcode
2722 ///
2723 /// DescendantT must be an AST base type.
2724 ///
2725 /// Usable as: Any Matcher
2726 extern const internal::ArgumentAdaptingMatcherFunc<
2727     internal::HasDescendantMatcher>
2728     hasDescendant;
2729
2730 /// Matches AST nodes that have child AST nodes that match the
2731 /// provided matcher.
2732 ///
2733 /// Example matches X, Y, Y::X, Z::Y, Z::Y::X
2734 ///   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
2735 /// \code
2736 ///   class X {};
2737 ///   class Y { class X {}; };  // Matches Y, because Y::X is a class of name X
2738 ///                             // inside Y.
2739 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
2740 /// \endcode
2741 ///
2742 /// ChildT must be an AST base type.
2743 ///
2744 /// As opposed to 'has', 'forEach' will cause a match for each result that
2745 /// matches instead of only on the first one.
2746 ///
2747 /// Usable as: Any Matcher
2748 extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
2749     forEach;
2750
2751 /// Matches AST nodes that have descendant AST nodes that match the
2752 /// provided matcher.
2753 ///
2754 /// Example matches X, A, A::X, B, B::C, B::C::X
2755 ///   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
2756 /// \code
2757 ///   class X {};
2758 ///   class A { class X {}; };  // Matches A, because A::X is a class of name
2759 ///                             // X inside A.
2760 ///   class B { class C { class X {}; }; };
2761 /// \endcode
2762 ///
2763 /// DescendantT must be an AST base type.
2764 ///
2765 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
2766 /// each result that matches instead of only on the first one.
2767 ///
2768 /// Note: Recursively combined ForEachDescendant can cause many matches:
2769 ///   cxxRecordDecl(forEachDescendant(cxxRecordDecl(
2770 ///     forEachDescendant(cxxRecordDecl())
2771 ///   )))
2772 /// will match 10 times (plus injected class name matches) on:
2773 /// \code
2774 ///   class A { class B { class C { class D { class E {}; }; }; }; };
2775 /// \endcode
2776 ///
2777 /// Usable as: Any Matcher
2778 extern const internal::ArgumentAdaptingMatcherFunc<
2779     internal::ForEachDescendantMatcher>
2780     forEachDescendant;
2781
2782 /// Matches if the node or any descendant matches.
2783 ///
2784 /// Generates results for each match.
2785 ///
2786 /// For example, in:
2787 /// \code
2788 ///   class A { class B {}; class C {}; };
2789 /// \endcode
2790 /// The matcher:
2791 /// \code
2792 ///   cxxRecordDecl(hasName("::A"),
2793 ///                 findAll(cxxRecordDecl(isDefinition()).bind("m")))
2794 /// \endcode
2795 /// will generate results for \c A, \c B and \c C.
2796 ///
2797 /// Usable as: Any Matcher
2798 template <typename T>
2799 internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
2800   return eachOf(Matcher, forEachDescendant(Matcher));
2801 }
2802
2803 /// Matches AST nodes that have a parent that matches the provided
2804 /// matcher.
2805 ///
2806 /// Given
2807 /// \code
2808 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
2809 /// \endcode
2810 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
2811 ///
2812 /// Usable as: Any Matcher
2813 extern const internal::ArgumentAdaptingMatcherFunc<
2814     internal::HasParentMatcher,
2815     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2816     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2817     hasParent;
2818
2819 /// Matches AST nodes that have an ancestor that matches the provided
2820 /// matcher.
2821 ///
2822 /// Given
2823 /// \code
2824 /// void f() { if (true) { int x = 42; } }
2825 /// void g() { for (;;) { int x = 43; } }
2826 /// \endcode
2827 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
2828 ///
2829 /// Usable as: Any Matcher
2830 extern const internal::ArgumentAdaptingMatcherFunc<
2831     internal::HasAncestorMatcher,
2832     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
2833     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
2834     hasAncestor;
2835
2836 /// Matches if the provided matcher does not match.
2837 ///
2838 /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
2839 /// \code
2840 ///   class X {};
2841 ///   class Y {};
2842 /// \endcode
2843 ///
2844 /// Usable as: Any Matcher
2845 extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
2846
2847 /// Matches a node if the declaration associated with that node
2848 /// matches the given matcher.
2849 ///
2850 /// The associated declaration is:
2851 /// - for type nodes, the declaration of the underlying type
2852 /// - for CallExpr, the declaration of the callee
2853 /// - for MemberExpr, the declaration of the referenced member
2854 /// - for CXXConstructExpr, the declaration of the constructor
2855 /// - for CXXNewExpr, the declaration of the operator new
2856 /// - for ObjCIvarExpr, the declaration of the ivar
2857 ///
2858 /// For type nodes, hasDeclaration will generally match the declaration of the
2859 /// sugared type. Given
2860 /// \code
2861 ///   class X {};
2862 ///   typedef X Y;
2863 ///   Y y;
2864 /// \endcode
2865 /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
2866 /// typedefDecl. A common use case is to match the underlying, desugared type.
2867 /// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
2868 /// \code
2869 ///   varDecl(hasType(hasUnqualifiedDesugaredType(
2870 ///       recordType(hasDeclaration(decl())))))
2871 /// \endcode
2872 /// In this matcher, the decl will match the CXXRecordDecl of class X.
2873 ///
2874 /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
2875 ///   Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
2876 ///   Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
2877 ///   Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
2878 ///   Matcher<TagType>, Matcher<TemplateSpecializationType>,
2879 ///   Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
2880 ///   Matcher<UnresolvedUsingType>
2881 inline internal::PolymorphicMatcherWithParam1<
2882     internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2883     void(internal::HasDeclarationSupportedTypes)>
2884 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
2885   return internal::PolymorphicMatcherWithParam1<
2886       internal::HasDeclarationMatcher, internal::Matcher<Decl>,
2887       void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
2888 }
2889
2890 /// Matches a \c NamedDecl whose underlying declaration matches the given
2891 /// matcher.
2892 ///
2893 /// Given
2894 /// \code
2895 ///   namespace N { template<class T> void f(T t); }
2896 ///   template <class T> void g() { using N::f; f(T()); }
2897 /// \endcode
2898 /// \c unresolvedLookupExpr(hasAnyDeclaration(
2899 ///     namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
2900 ///   matches the use of \c f in \c g() .
2901 AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
2902               InnerMatcher) {
2903   const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
2904
2905   return UnderlyingDecl != nullptr &&
2906          InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
2907 }
2908
2909 /// Matches on the implicit object argument of a member call expression, after
2910 /// stripping off any parentheses or implicit casts.
2911 ///
2912 /// Given
2913 /// \code
2914 ///   class Y { public: void m(); };
2915 ///   Y g();
2916 ///   class X : public Y {};
2917 ///   void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
2918 /// \endcode
2919 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
2920 ///   matches `y.m()` and `(g()).m()`.
2921 /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
2922 ///   matches `x.m()`.
2923 /// cxxMemberCallExpr(on(callExpr()))
2924 ///   matches `(g()).m()`.
2925 ///
2926 /// FIXME: Overload to allow directly matching types?
2927 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
2928               InnerMatcher) {
2929   const Expr *ExprNode = Node.getImplicitObjectArgument()
2930                             ->IgnoreParenImpCasts();
2931   return (ExprNode != nullptr &&
2932           InnerMatcher.matches(*ExprNode, Finder, Builder));
2933 }
2934
2935
2936 /// Matches on the receiver of an ObjectiveC Message expression.
2937 ///
2938 /// Example
2939 /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
2940 /// matches the [webView ...] message invocation.
2941 /// \code
2942 ///   NSString *webViewJavaScript = ...
2943 ///   UIWebView *webView = ...
2944 ///   [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
2945 /// \endcode
2946 AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
2947               InnerMatcher) {
2948   const QualType TypeDecl = Node.getReceiverType();
2949   return InnerMatcher.matches(TypeDecl, Finder, Builder);
2950 }
2951
2952 /// Returns true when the Objective-C method declaration is a class method.
2953 ///
2954 /// Example
2955 /// matcher = objcMethodDecl(isClassMethod())
2956 /// matches
2957 /// \code
2958 /// @interface I + (void)foo; @end
2959 /// \endcode
2960 /// but not
2961 /// \code
2962 /// @interface I - (void)bar; @end
2963 /// \endcode
2964 AST_MATCHER(ObjCMethodDecl, isClassMethod) {
2965   return Node.isClassMethod();
2966 }
2967
2968 /// Returns true when the Objective-C method declaration is an instance method.
2969 ///
2970 /// Example
2971 /// matcher = objcMethodDecl(isInstanceMethod())
2972 /// matches
2973 /// \code
2974 /// @interface I - (void)bar; @end
2975 /// \endcode
2976 /// but not
2977 /// \code
2978 /// @interface I + (void)foo; @end
2979 /// \endcode
2980 AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
2981   return Node.isInstanceMethod();
2982 }
2983
2984 /// Returns true when the Objective-C message is sent to a class.
2985 ///
2986 /// Example
2987 /// matcher = objcMessageExpr(isClassMessage())
2988 /// matches
2989 /// \code
2990 ///   [NSString stringWithFormat:@"format"];
2991 /// \endcode
2992 /// but not
2993 /// \code
2994 ///   NSString *x = @"hello";
2995 ///   [x containsString:@"h"];
2996 /// \endcode
2997 AST_MATCHER(ObjCMessageExpr, isClassMessage) {
2998   return Node.isClassMessage();
2999 }
3000
3001 /// Returns true when the Objective-C message is sent to an instance.
3002 ///
3003 /// Example
3004 /// matcher = objcMessageExpr(isInstanceMessage())
3005 /// matches
3006 /// \code
3007 ///   NSString *x = @"hello";
3008 ///   [x containsString:@"h"];
3009 /// \endcode
3010 /// but not
3011 /// \code
3012 ///   [NSString stringWithFormat:@"format"];
3013 /// \endcode
3014 AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3015   return Node.isInstanceMessage();
3016 }
3017
3018 /// Matches if the Objective-C message is sent to an instance,
3019 /// and the inner matcher matches on that instance.
3020 ///
3021 /// For example the method call in
3022 /// \code
3023 ///   NSString *x = @"hello";
3024 ///   [x containsString:@"h"];
3025 /// \endcode
3026 /// is matched by
3027 /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3028 AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3029               InnerMatcher) {
3030   const Expr *ReceiverNode = Node.getInstanceReceiver();
3031   return (ReceiverNode != nullptr &&
3032           InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3033                                Builder));
3034 }
3035
3036 /// Matches when BaseName == Selector.getAsString()
3037 ///
3038 ///  matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3039 ///  matches the outer message expr in the code below, but NOT the message
3040 ///  invocation for self.bodyView.
3041 /// \code
3042 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3043 /// \endcode
3044 AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3045   Selector Sel = Node.getSelector();
3046   return BaseName.compare(Sel.getAsString()) == 0;
3047 }
3048
3049
3050 /// Matches when at least one of the supplied string equals to the
3051 /// Selector.getAsString()
3052 ///
3053 ///  matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3054 ///  matches both of the expressions below:
3055 /// \code
3056 ///     [myObj methodA:argA];
3057 ///     [myObj methodB:argB];
3058 /// \endcode
3059 extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3060                                         StringRef,
3061                                         internal::hasAnySelectorFunc>
3062                                         hasAnySelector;
3063
3064 /// Matches ObjC selectors whose name contains
3065 /// a substring matched by the given RegExp.
3066 ///  matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3067 ///  matches the outer message expr in the code below, but NOT the message
3068 ///  invocation for self.bodyView.
3069 /// \code
3070 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3071 /// \endcode
3072 AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) {
3073   assert(!RegExp.empty());
3074   std::string SelectorString = Node.getSelector().getAsString();
3075   llvm::Regex RE(RegExp);
3076   return RE.match(SelectorString);
3077 }
3078
3079 /// Matches when the selector is the empty selector
3080 ///
3081 /// Matches only when the selector of the objCMessageExpr is NULL. This may
3082 /// represent an error condition in the tree!
3083 AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3084   return Node.getSelector().isNull();
3085 }
3086
3087 /// Matches when the selector is a Unary Selector
3088 ///
3089 ///  matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3090 ///  matches self.bodyView in the code below, but NOT the outer message
3091 ///  invocation of "loadHTMLString:baseURL:".
3092 /// \code
3093 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3094 /// \endcode
3095 AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3096   return Node.getSelector().isUnarySelector();
3097 }
3098
3099 /// Matches when the selector is a keyword selector
3100 ///
3101 /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3102 /// message expression in
3103 ///
3104 /// \code
3105 ///   UIWebView *webView = ...;
3106 ///   CGRect bodyFrame = webView.frame;
3107 ///   bodyFrame.size.height = self.bodyContentHeight;
3108 ///   webView.frame = bodyFrame;
3109 ///   //     ^---- matches here
3110 /// \endcode
3111 AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3112   return Node.getSelector().isKeywordSelector();
3113 }
3114
3115 /// Matches when the selector has the specified number of arguments
3116 ///
3117 ///  matcher = objCMessageExpr(numSelectorArgs(0));
3118 ///  matches self.bodyView in the code below
3119 ///
3120 ///  matcher = objCMessageExpr(numSelectorArgs(2));
3121 ///  matches the invocation of "loadHTMLString:baseURL:" but not that
3122 ///  of self.bodyView
3123 /// \code
3124 ///     [self.bodyView loadHTMLString:html baseURL:NULL];
3125 /// \endcode
3126 AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3127   return Node.getSelector().getNumArgs() == N;
3128 }
3129
3130 /// Matches if the call expression's callee expression matches.
3131 ///
3132 /// Given
3133 /// \code
3134 ///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
3135 ///   void f() { f(); }
3136 /// \endcode
3137 /// callExpr(callee(expr()))
3138 ///   matches this->x(), x(), y.x(), f()
3139 /// with callee(...)
3140 ///   matching this->x, x, y.x, f respectively
3141 ///
3142 /// Note: Callee cannot take the more general internal::Matcher<Expr>
3143 /// because this introduces ambiguous overloads with calls to Callee taking a
3144 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
3145 /// implemented in terms of implicit casts.
3146 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3147               InnerMatcher) {
3148   const Expr *ExprNode = Node.getCallee();
3149   return (ExprNode != nullptr &&
3150           InnerMatcher.matches(*ExprNode, Finder, Builder));
3151 }
3152
3153 /// Matches if the call expression's callee's declaration matches the
3154 /// given matcher.
3155 ///
3156 /// Example matches y.x() (matcher = callExpr(callee(
3157 ///                                    cxxMethodDecl(hasName("x")))))
3158 /// \code
3159 ///   class Y { public: void x(); };
3160 ///   void z() { Y y; y.x(); }
3161 /// \endcode
3162 AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3163                        1) {
3164   return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3165 }
3166
3167 /// Matches if the expression's or declaration's type matches a type
3168 /// matcher.
3169 ///
3170 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3171 ///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3172 ///             and U (matcher = typedefDecl(hasType(asString("int")))
3173 ///             and friend class X (matcher = friendDecl(hasType("X"))
3174 /// \code
3175 ///  class X {};
3176 ///  void y(X &x) { x; X z; }
3177 ///  typedef int U;
3178 ///  class Y { friend class X; };
3179 /// \endcode
3180 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3181     hasType,
3182     AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3183                                     ValueDecl),
3184     internal::Matcher<QualType>, InnerMatcher, 0) {
3185   QualType QT = internal::getUnderlyingType(Node);
3186   if (!QT.isNull())
3187     return InnerMatcher.matches(QT, Finder, Builder);
3188   return false;
3189 }
3190
3191 /// Overloaded to match the declaration of the expression's or value
3192 /// declaration's type.
3193 ///
3194 /// In case of a value declaration (for example a variable declaration),
3195 /// this resolves one layer of indirection. For example, in the value
3196 /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3197 /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3198 /// declaration of x.
3199 ///
3200 /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3201 ///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3202 ///             and friend class X (matcher = friendDecl(hasType("X"))
3203 /// \code
3204 ///  class X {};
3205 ///  void y(X &x) { x; X z; }
3206 ///  class Y { friend class X; };
3207 /// \endcode
3208 ///
3209 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
3210 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3211     hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl),
3212     internal::Matcher<Decl>, InnerMatcher, 1) {
3213   QualType QT = internal::getUnderlyingType(Node);
3214   if (!QT.isNull())
3215     return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3216   return false;
3217 }
3218
3219 /// Matches if the type location of the declarator decl's type matches
3220 /// the inner matcher.
3221 ///
3222 /// Given
3223 /// \code
3224 ///   int x;
3225 /// \endcode
3226 /// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3227 ///   matches int x
3228 AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3229   if (!Node.getTypeSourceInfo())
3230     // This happens for example for implicit destructors.
3231     return false;
3232   return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3233 }
3234
3235 /// Matches if the matched type is represented by the given string.
3236 ///
3237 /// Given
3238 /// \code
3239 ///   class Y { public: void x(); };
3240 ///   void z() { Y* y; y->x(); }
3241 /// \endcode
3242 /// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3243 ///   matches y->x()
3244 AST_MATCHER_P(QualType, asString, std::string, Name) {
3245   return Name == Node.getAsString();
3246 }
3247
3248 /// Matches if the matched type is a pointer type and the pointee type
3249 /// matches the specified matcher.
3250 ///
3251 /// Example matches y->x()
3252 ///   (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3253 ///      cxxRecordDecl(hasName("Y")))))))
3254 /// \code
3255 ///   class Y { public: void x(); };
3256 ///   void z() { Y *y; y->x(); }
3257 /// \endcode
3258 AST_MATCHER_P(
3259     QualType, pointsTo, internal::Matcher<QualType>,
3260     InnerMatcher) {
3261   return (!Node.isNull() && Node->isAnyPointerType() &&
3262           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3263 }
3264
3265 /// Overloaded to match the pointee type's declaration.
3266 AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3267                        InnerMatcher, 1) {
3268   return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3269       .matches(Node, Finder, Builder);
3270 }
3271
3272 /// Matches if the matched type matches the unqualified desugared
3273 /// type of the matched node.
3274 ///
3275 /// For example, in:
3276 /// \code
3277 ///   class A {};
3278 ///   using B = A;
3279 /// \endcode
3280 /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3281 /// both B and A.
3282 AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3283               InnerMatcher) {
3284   return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3285                               Builder);
3286 }
3287
3288 /// Matches if the matched type is a reference type and the referenced
3289 /// type matches the specified matcher.
3290 ///
3291 /// Example matches X &x and const X &y
3292 ///     (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3293 /// \code
3294 ///   class X {
3295 ///     void a(X b) {
3296 ///       X &x = b;
3297 ///       const X &y = b;
3298 ///     }
3299 ///   };
3300 /// \endcode
3301 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3302               InnerMatcher) {
3303   return (!Node.isNull() && Node->isReferenceType() &&
3304           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3305 }
3306
3307 /// Matches QualTypes whose canonical type matches InnerMatcher.
3308 ///
3309 /// Given:
3310 /// \code
3311 ///   typedef int &int_ref;
3312 ///   int a;
3313 ///   int_ref b = a;
3314 /// \endcode
3315 ///
3316 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3317 /// declaration of b but \c
3318 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3319 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3320               InnerMatcher) {
3321   if (Node.isNull())
3322     return false;
3323   return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3324 }
3325
3326 /// Overloaded to match the referenced type's declaration.
3327 AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3328                        InnerMatcher, 1) {
3329   return references(qualType(hasDeclaration(InnerMatcher)))
3330       .matches(Node, Finder, Builder);
3331 }
3332
3333 /// Matches on the implicit object argument of a member call expression. Unlike
3334 /// `on`, matches the argument directly without stripping away anything.
3335 ///
3336 /// Given
3337 /// \code
3338 ///   class Y { public: void m(); };
3339 ///   Y g();
3340 ///   class X : public Y { void g(); };
3341 ///   void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
3342 /// \endcode
3343 /// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
3344 ///     cxxRecordDecl(hasName("Y")))))
3345 ///   matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
3346 /// cxxMemberCallExpr(on(callExpr()))
3347 ///   does not match `(g()).m()`, because the parens are not ignored.
3348 ///
3349 /// FIXME: Overload to allow directly matching types?
3350 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3351               internal::Matcher<Expr>, InnerMatcher) {
3352   const Expr *ExprNode = Node.getImplicitObjectArgument();
3353   return (ExprNode != nullptr &&
3354           InnerMatcher.matches(*ExprNode, Finder, Builder));
3355 }
3356
3357 /// Matches if the type of the expression's implicit object argument either
3358 /// matches the InnerMatcher, or is a pointer to a type that matches the
3359 /// InnerMatcher.
3360 ///
3361 /// Given
3362 /// \code
3363 ///   class Y { public: void m(); };
3364 ///   class X : public Y { void g(); };
3365 ///   void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
3366 /// \endcode
3367 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3368 ///     cxxRecordDecl(hasName("Y")))))
3369 ///   matches `y.m()`, `p->m()` and `x.m()`.
3370 /// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3371 ///     cxxRecordDecl(hasName("X")))))
3372 ///   matches `x.g()`.
3373 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3374                        internal::Matcher<QualType>, InnerMatcher, 0) {
3375   return onImplicitObjectArgument(
3376       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3377       .matches(Node, Finder, Builder);
3378 }
3379
3380 /// Overloaded to match the type's declaration.
3381 AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3382                        internal::Matcher<Decl>, InnerMatcher, 1) {
3383   return onImplicitObjectArgument(
3384       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3385       .matches(Node, Finder, Builder);
3386 }
3387
3388 /// Matches a DeclRefExpr that refers to a declaration that matches the
3389 /// specified matcher.
3390 ///
3391 /// Example matches x in if(x)
3392 ///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
3393 /// \code
3394 ///   bool x;
3395 ///   if (x) {}
3396 /// \endcode
3397 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3398               InnerMatcher) {
3399   const Decl *DeclNode = Node.getDecl();
3400   return (DeclNode != nullptr &&
3401           InnerMatcher.matches(*DeclNode, Finder, Builder));
3402 }
3403
3404 /// Matches a \c DeclRefExpr that refers to a declaration through a
3405 /// specific using shadow declaration.
3406 ///
3407 /// Given
3408 /// \code
3409 ///   namespace a { void f() {} }
3410 ///   using a::f;
3411 ///   void g() {
3412 ///     f();     // Matches this ..
3413 ///     a::f();  // .. but not this.
3414 ///   }
3415 /// \endcode
3416 /// declRefExpr(throughUsingDecl(anything()))
3417 ///   matches \c f()
3418 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
3419               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
3420   const NamedDecl *FoundDecl = Node.getFoundDecl();
3421   if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
3422     return InnerMatcher.matches(*UsingDecl, Finder, Builder);
3423   return false;
3424 }
3425
3426 /// Matches an \c OverloadExpr if any of the declarations in the set of
3427 /// overloads matches the given matcher.
3428 ///
3429 /// Given
3430 /// \code
3431 ///   template <typename T> void foo(T);
3432 ///   template <typename T> void bar(T);
3433 ///   template <typename T> void baz(T t) {
3434 ///     foo(t);
3435 ///     bar(t);
3436 ///   }
3437 /// \endcode
3438 /// unresolvedLookupExpr(hasAnyDeclaration(
3439 ///     functionTemplateDecl(hasName("foo"))))
3440 ///   matches \c foo in \c foo(t); but not \c bar in \c bar(t);
3441 AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
3442               InnerMatcher) {
3443   return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
3444                                     Node.decls_end(), Finder, Builder);
3445 }
3446
3447 /// Matches the Decl of a DeclStmt which has a single declaration.
3448 ///
3449 /// Given
3450 /// \code
3451 ///   int a, b;
3452 ///   int c;
3453 /// \endcode
3454 /// declStmt(hasSingleDecl(anything()))
3455 ///   matches 'int c;' but not 'int a, b;'.
3456 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
3457   if (Node.isSingleDecl()) {
3458     const Decl *FoundDecl = Node.getSingleDecl();
3459     return InnerMatcher.matches(*FoundDecl, Finder, Builder);
3460   }
3461   return false;
3462 }
3463
3464 /// Matches a variable declaration that has an initializer expression
3465 /// that matches the given matcher.
3466 ///
3467 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
3468 /// \code
3469 ///   bool y() { return true; }
3470 ///   bool x = y();
3471 /// \endcode
3472 AST_MATCHER_P(
3473     VarDecl, hasInitializer, internal::Matcher<Expr>,
3474     InnerMatcher) {
3475   const Expr *Initializer = Node.getAnyInitializer();
3476   return (Initializer != nullptr &&
3477           InnerMatcher.matches(*Initializer, Finder, Builder));
3478 }
3479
3480 /// \brief Matches a static variable with local scope.
3481 ///
3482 /// Example matches y (matcher = varDecl(isStaticLocal()))
3483 /// \code
3484 /// void f() {
3485 ///   int x;
3486 ///   static int y;
3487 /// }
3488 /// static int z;
3489 /// \endcode
3490 AST_MATCHER(VarDecl, isStaticLocal) {
3491   return Node.isStaticLocal();
3492 }
3493
3494 /// Matches a variable declaration that has function scope and is a
3495 /// non-static local variable.
3496 ///
3497 /// Example matches x (matcher = varDecl(hasLocalStorage())
3498 /// \code
3499 /// void f() {
3500 ///   int x;
3501 ///   static int y;
3502 /// }
3503 /// int z;
3504 /// \endcode
3505 AST_MATCHER(VarDecl, hasLocalStorage) {
3506   return Node.hasLocalStorage();
3507 }
3508
3509 /// Matches a variable declaration that does not have local storage.
3510 ///
3511 /// Example matches y and z (matcher = varDecl(hasGlobalStorage())
3512 /// \code
3513 /// void f() {
3514 ///   int x;
3515 ///   static int y;
3516 /// }
3517 /// int z;
3518 /// \endcode
3519 AST_MATCHER(VarDecl, hasGlobalStorage) {
3520   return Node.hasGlobalStorage();
3521 }
3522
3523 /// Matches a variable declaration that has automatic storage duration.
3524 ///
3525 /// Example matches x, but not y, z, or a.
3526 /// (matcher = varDecl(hasAutomaticStorageDuration())
3527 /// \code
3528 /// void f() {
3529 ///   int x;
3530 ///   static int y;
3531 ///   thread_local int z;
3532 /// }
3533 /// int a;
3534 /// \endcode
3535 AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
3536   return Node.getStorageDuration() == SD_Automatic;
3537 }
3538
3539 /// Matches a variable declaration that has static storage duration.
3540 /// It includes the variable declared at namespace scope and those declared
3541 /// with "static" and "extern" storage class specifiers.
3542 ///
3543 /// \code
3544 /// void f() {
3545 ///   int x;
3546 ///   static int y;
3547 ///   thread_local int z;
3548 /// }
3549 /// int a;
3550 /// static int b;
3551 /// extern int c;
3552 /// varDecl(hasStaticStorageDuration())
3553 ///   matches the function declaration y, a, b and c.
3554 /// \endcode
3555 AST_MATCHER(VarDecl, hasStaticStorageDuration) {
3556   return Node.getStorageDuration() == SD_Static;
3557 }
3558
3559 /// Matches a variable declaration that has thread storage duration.
3560 ///
3561 /// Example matches z, but not x, z, or a.
3562 /// (matcher = varDecl(hasThreadStorageDuration())
3563 /// \code
3564 /// void f() {
3565 ///   int x;
3566 ///   static int y;
3567 ///   thread_local int z;
3568 /// }
3569 /// int a;
3570 /// \endcode
3571 AST_MATCHER(VarDecl, hasThreadStorageDuration) {
3572   return Node.getStorageDuration() == SD_Thread;
3573 }
3574
3575 /// Matches a variable declaration that is an exception variable from
3576 /// a C++ catch block, or an Objective-C \@catch statement.
3577 ///
3578 /// Example matches x (matcher = varDecl(isExceptionVariable())
3579 /// \code
3580 /// void f(int y) {
3581 ///   try {
3582 ///   } catch (int x) {
3583 ///   }
3584 /// }
3585 /// \endcode
3586 AST_MATCHER(VarDecl, isExceptionVariable) {
3587   return Node.isExceptionVariable();
3588 }
3589
3590 /// Checks that a call expression or a constructor call expression has
3591 /// a specific number of arguments (including absent default arguments).
3592 ///
3593 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
3594 /// \code
3595 ///   void f(int x, int y);
3596 ///   f(0, 0);
3597 /// \endcode
3598 AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
3599                           AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3600                                                           CXXConstructExpr,
3601                                                           ObjCMessageExpr),
3602                           unsigned, N) {
3603   return Node.getNumArgs() == N;
3604 }
3605
3606 /// Matches the n'th argument of a call expression or a constructor
3607 /// call expression.
3608 ///
3609 /// Example matches y in x(y)
3610 ///     (matcher = callExpr(hasArgument(0, declRefExpr())))
3611 /// \code
3612 ///   void x(int) { int y; x(y); }
3613 /// \endcode
3614 AST_POLYMORPHIC_MATCHER_P2(hasArgument,
3615                            AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3616                                                            CXXConstructExpr,
3617                                                            ObjCMessageExpr),
3618                            unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
3619   return (N < Node.getNumArgs() &&
3620           InnerMatcher.matches(
3621               *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
3622 }
3623
3624 /// Matches the n'th item of an initializer list expression.
3625 ///
3626 /// Example matches y.
3627 ///     (matcher = initListExpr(hasInit(0, expr())))
3628 /// \code
3629 ///   int x{y}.
3630 /// \endcode
3631 AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
3632                ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
3633   return N < Node.getNumInits() &&
3634           InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
3635 }
3636
3637 /// Matches declaration statements that contain a specific number of
3638 /// declarations.
3639 ///
3640 /// Example: Given
3641 /// \code
3642 ///   int a, b;
3643 ///   int c;
3644 ///   int d = 2, e;
3645 /// \endcode
3646 /// declCountIs(2)
3647 ///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
3648 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
3649   return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
3650 }
3651
3652 /// Matches the n'th declaration of a declaration statement.
3653 ///
3654 /// Note that this does not work for global declarations because the AST
3655 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
3656 /// DeclStmt's.
3657 /// Example: Given non-global declarations
3658 /// \code
3659 ///   int a, b = 0;
3660 ///   int c;
3661 ///   int d = 2, e;
3662 /// \endcode
3663 /// declStmt(containsDeclaration(
3664 ///       0, varDecl(hasInitializer(anything()))))
3665 ///   matches only 'int d = 2, e;', and
3666 /// declStmt(containsDeclaration(1, varDecl()))
3667 /// \code
3668 ///   matches 'int a, b = 0' as well as 'int d = 2, e;'
3669 ///   but 'int c;' is not matched.
3670 /// \endcode
3671 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
3672                internal::Matcher<Decl>, InnerMatcher) {
3673   const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
3674   if (N >= NumDecls)
3675     return false;
3676   DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
3677   std::advance(Iterator, N);
3678   return InnerMatcher.matches(**Iterator, Finder, Builder);
3679 }
3680
3681 /// Matches a C++ catch statement that has a catch-all handler.
3682 ///
3683 /// Given
3684 /// \code
3685 ///   try {
3686 ///     // ...
3687 ///   } catch (int) {
3688 ///     // ...
3689 ///   } catch (...) {
3690 ///     // ...
3691 ///   }
3692 /// \endcode
3693 /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
3694 AST_MATCHER(CXXCatchStmt, isCatchAll) {
3695   return Node.getExceptionDecl() == nullptr;
3696 }
3697
3698 /// Matches a constructor initializer.
3699 ///
3700 /// Given
3701 /// \code
3702 ///   struct Foo {
3703 ///     Foo() : foo_(1) { }
3704 ///     int foo_;
3705 ///   };
3706 /// \endcode
3707 /// cxxRecordDecl(has(cxxConstructorDecl(
3708 ///   hasAnyConstructorInitializer(anything())
3709 /// )))
3710 ///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
3711 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
3712               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
3713   return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
3714                                     Node.init_end(), Finder, Builder);
3715 }
3716
3717 /// Matches the field declaration of a constructor initializer.
3718 ///
3719 /// Given
3720 /// \code
3721 ///   struct Foo {
3722 ///     Foo() : foo_(1) { }
3723 ///     int foo_;
3724 ///   };
3725 /// \endcode
3726 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3727 ///     forField(hasName("foo_"))))))
3728 ///   matches Foo
3729 /// with forField matching foo_
3730 AST_MATCHER_P(CXXCtorInitializer, forField,
3731               internal::Matcher<FieldDecl>, InnerMatcher) {
3732   const FieldDecl *NodeAsDecl = Node.getAnyMember();
3733   return (NodeAsDecl != nullptr &&
3734       InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
3735 }
3736
3737 /// Matches the initializer expression of a constructor initializer.
3738 ///
3739 /// Given
3740 /// \code
3741 ///   struct Foo {
3742 ///     Foo() : foo_(1) { }
3743 ///     int foo_;
3744 ///   };
3745 /// \endcode
3746 /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
3747 ///     withInitializer(integerLiteral(equals(1)))))))
3748 ///   matches Foo
3749 /// with withInitializer matching (1)
3750 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
3751               internal::Matcher<Expr>, InnerMatcher) {
3752   const Expr* NodeAsExpr = Node.getInit();
3753   return (NodeAsExpr != nullptr &&
3754       InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
3755 }
3756
3757 /// Matches a constructor initializer if it is explicitly written in
3758 /// code (as opposed to implicitly added by the compiler).
3759 ///
3760 /// Given
3761 /// \code
3762 ///   struct Foo {
3763 ///     Foo() { }
3764 ///     Foo(int) : foo_("A") { }
3765 ///     string foo_;
3766 ///   };
3767 /// \endcode
3768 /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
3769 ///   will match Foo(int), but not Foo()
3770 AST_MATCHER(CXXCtorInitializer, isWritten) {
3771   return Node.isWritten();
3772 }
3773
3774 /// Matches a constructor initializer if it is initializing a base, as
3775 /// opposed to a member.
3776 ///
3777 /// Given
3778 /// \code
3779 ///   struct B {};
3780 ///   struct D : B {
3781 ///     int I;
3782 ///     D(int i) : I(i) {}
3783 ///   };
3784 ///   struct E : B {
3785 ///     E() : B() {}
3786 ///   };
3787 /// \endcode
3788 /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
3789 ///   will match E(), but not match D(int).
3790 AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
3791   return Node.isBaseInitializer();
3792 }
3793
3794 /// Matches a constructor initializer if it is initializing a member, as
3795 /// opposed to a base.
3796 ///
3797 /// Given
3798 /// \code
3799 ///   struct B {};
3800 ///   struct D : B {
3801 ///     int I;
3802 ///     D(int i) : I(i) {}
3803 ///   };
3804 ///   struct E : B {
3805 ///     E() : B() {}
3806 ///   };
3807 /// \endcode
3808 /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
3809 ///   will match D(int), but not match E().
3810 AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
3811   return Node.isMemberInitializer();
3812 }
3813
3814 /// Matches any argument of a call expression or a constructor call
3815 /// expression, or an ObjC-message-send expression.
3816 ///
3817 /// Given
3818 /// \code
3819 ///   void x(int, int, int) { int y; x(1, y, 42); }
3820 /// \endcode
3821 /// callExpr(hasAnyArgument(declRefExpr()))
3822 ///   matches x(1, y, 42)
3823 /// with hasAnyArgument(...)
3824 ///   matching y
3825 ///
3826 /// For ObjectiveC, given
3827 /// \code
3828 ///   @interface I - (void) f:(int) y; @end
3829 ///   void foo(I *i) { [i f:12]; }
3830 /// \endcode
3831 /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
3832 ///   matches [i f:12]
3833 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
3834                           AST_POLYMORPHIC_SUPPORTED_TYPES(
3835                               CallExpr, CXXConstructExpr,
3836                               CXXUnresolvedConstructExpr, ObjCMessageExpr),
3837                           internal::Matcher<Expr>, InnerMatcher) {
3838   for (const Expr *Arg : Node.arguments()) {
3839     BoundNodesTreeBuilder Result(*Builder);
3840     if (InnerMatcher.matches(*Arg, Finder, &Result)) {
3841       *Builder = std::move(Result);
3842       return true;
3843     }
3844   }
3845   return false;
3846 }
3847
3848 /// Matches a constructor call expression which uses list initialization.
3849 AST_MATCHER(CXXConstructExpr, isListInitialization) {
3850   return Node.isListInitialization();
3851 }
3852
3853 /// Matches a constructor call expression which requires
3854 /// zero initialization.
3855 ///
3856 /// Given
3857 /// \code
3858 /// void foo() {
3859 ///   struct point { double x; double y; };
3860 ///   point pt[2] = { { 1.0, 2.0 } };
3861 /// }
3862 /// \endcode
3863 /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
3864 /// will match the implicit array filler for pt[1].
3865 AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
3866   return Node.requiresZeroInitialization();
3867 }
3868
3869 /// Matches the n'th parameter of a function or an ObjC method
3870 /// declaration or a block.
3871 ///
3872 /// Given
3873 /// \code
3874 ///   class X { void f(int x) {} };
3875 /// \endcode
3876 /// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
3877 ///   matches f(int x) {}
3878 /// with hasParameter(...)
3879 ///   matching int x
3880 ///
3881 /// For ObjectiveC, given
3882 /// \code
3883 ///   @interface I - (void) f:(int) y; @end
3884 /// \endcode
3885 //
3886 /// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
3887 /// matches the declaration of method f with hasParameter
3888 /// matching y.
3889 AST_POLYMORPHIC_MATCHER_P2(hasParameter,
3890                            AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3891                                                            ObjCMethodDecl,
3892                                                            BlockDecl),
3893                            unsigned, N, internal::Matcher<ParmVarDecl>,
3894                            InnerMatcher) {
3895   return (N < Node.parameters().size()
3896           && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
3897 }
3898
3899 /// Matches all arguments and their respective ParmVarDecl.
3900 ///
3901 /// Given
3902 /// \code
3903 ///   void f(int i);
3904 ///   int y;
3905 ///   f(y);
3906 /// \endcode
3907 /// callExpr(
3908 ///   forEachArgumentWithParam(
3909 ///     declRefExpr(to(varDecl(hasName("y")))),
3910 ///     parmVarDecl(hasType(isInteger()))
3911 /// ))
3912 ///   matches f(y);
3913 /// with declRefExpr(...)
3914 ///   matching int y
3915 /// and parmVarDecl(...)
3916 ///   matching int i
3917 AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
3918                            AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
3919                                                            CXXConstructExpr),
3920                            internal::Matcher<Expr>, ArgMatcher,
3921                            internal::Matcher<ParmVarDecl>, ParamMatcher) {
3922   BoundNodesTreeBuilder Result;
3923   // The first argument of an overloaded member operator is the implicit object
3924   // argument of the method which should not be matched against a parameter, so
3925   // we skip over it here.
3926   BoundNodesTreeBuilder Matches;
3927   unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
3928                               .matches(Node, Finder, &Matches)
3929                           ? 1
3930                           : 0;
3931   int ParamIndex = 0;
3932   bool Matched = false;
3933   for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) {
3934     BoundNodesTreeBuilder ArgMatches(*Builder);
3935     if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
3936                            Finder, &ArgMatches)) {
3937       BoundNodesTreeBuilder ParamMatches(ArgMatches);
3938       if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
3939                          hasParameter(ParamIndex, ParamMatcher)))),
3940                      callExpr(callee(functionDecl(
3941                          hasParameter(ParamIndex, ParamMatcher))))))
3942               .matches(Node, Finder, &ParamMatches)) {
3943         Result.addMatch(ParamMatches);
3944         Matched = true;
3945       }
3946     }
3947     ++ParamIndex;
3948   }
3949   *Builder = std::move(Result);
3950   return Matched;
3951 }
3952
3953 /// Matches any parameter of a function or an ObjC method declaration or a
3954 /// block.
3955 ///
3956 /// Does not match the 'this' parameter of a method.
3957 ///
3958 /// Given
3959 /// \code
3960 ///   class X { void f(int x, int y, int z) {} };
3961 /// \endcode
3962 /// cxxMethodDecl(hasAnyParameter(hasName("y")))
3963 ///   matches f(int x, int y, int z) {}
3964 /// with hasAnyParameter(...)
3965 ///   matching int y
3966 ///
3967 /// For ObjectiveC, given
3968 /// \code
3969 ///   @interface I - (void) f:(int) y; @end
3970 /// \endcode
3971 //
3972 /// the matcher objcMethodDecl(hasAnyParameter(hasName("y")))
3973 /// matches the declaration of method f with hasParameter
3974 /// matching y.
3975 ///
3976 /// For blocks, given
3977 /// \code
3978 ///   b = ^(int y) { printf("%d", y) };
3979 /// \endcode
3980 ///
3981 /// the matcher blockDecl(hasAnyParameter(hasName("y")))
3982 /// matches the declaration of the block b with hasParameter
3983 /// matching y.
3984 AST_POLYMORPHIC_MATCHER_P(hasAnyParameter,
3985                           AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
3986                                                           ObjCMethodDecl,
3987                                                           BlockDecl),
3988                           internal::Matcher<ParmVarDecl>,
3989                           InnerMatcher) {
3990   return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(),
3991                                     Node.param_end(), Finder, Builder);
3992 }
3993
3994 /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a
3995 /// specific parameter count.
3996 ///
3997 /// Given
3998 /// \code
3999 ///   void f(int i) {}
4000 ///   void g(int i, int j) {}
4001 ///   void h(int i, int j);
4002 ///   void j(int i);
4003 ///   void k(int x, int y, int z, ...);
4004 /// \endcode
4005 /// functionDecl(parameterCountIs(2))
4006 ///   matches \c g and \c h
4007 /// functionProtoType(parameterCountIs(2))
4008 ///   matches \c g and \c h
4009 /// functionProtoType(parameterCountIs(3))
4010 ///   matches \c k
4011 AST_POLYMORPHIC_MATCHER_P(parameterCountIs,
4012                           AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4013                                                           FunctionProtoType),
4014                           unsigned, N) {
4015   return Node.getNumParams() == N;
4016 }
4017
4018 /// Matches \c FunctionDecls that have a noreturn attribute.
4019 ///
4020 /// Given
4021 /// \code
4022 ///   void nope();
4023 ///   [[noreturn]] void a();
4024 ///   __attribute__((noreturn)) void b();
4025 ///   struct c { [[noreturn]] c(); };
4026 /// \endcode
4027 /// functionDecl(isNoReturn())
4028 ///   matches all of those except
4029 /// \code
4030 ///   void nope();
4031 /// \endcode
4032 AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); }
4033
4034 /// Matches the return type of a function declaration.
4035 ///
4036 /// Given:
4037 /// \code
4038 ///   class X { int f() { return 1; } };
4039 /// \endcode
4040 /// cxxMethodDecl(returns(asString("int")))
4041 ///   matches int f() { return 1; }
4042 AST_MATCHER_P(FunctionDecl, returns,
4043               internal::Matcher<QualType>, InnerMatcher) {
4044   return InnerMatcher.matches(Node.getReturnType(), Finder, Builder);
4045 }
4046
4047 /// Matches extern "C" function or variable declarations.
4048 ///
4049 /// Given:
4050 /// \code
4051 ///   extern "C" void f() {}
4052 ///   extern "C" { void g() {} }
4053 ///   void h() {}
4054 ///   extern "C" int x = 1;
4055 ///   extern "C" int y = 2;
4056 ///   int z = 3;
4057 /// \endcode
4058 /// functionDecl(isExternC())
4059 ///   matches the declaration of f and g, but not the declaration of h.
4060 /// varDecl(isExternC())
4061 ///   matches the declaration of x and y, but not the declaration of z.
4062 AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4063                                                                    VarDecl)) {
4064   return Node.isExternC();
4065 }
4066
4067 /// Matches variable/function declarations that have "static" storage
4068 /// class specifier ("static" keyword) written in the source.
4069 ///
4070 /// Given:
4071 /// \code
4072 ///   static void f() {}
4073 ///   static int i = 0;
4074 ///   extern int j;
4075 ///   int k;
4076 /// \endcode
4077 /// functionDecl(isStaticStorageClass())
4078 ///   matches the function declaration f.
4079 /// varDecl(isStaticStorageClass())
4080 ///   matches the variable declaration i.
4081 AST_POLYMORPHIC_MATCHER(isStaticStorageClass,
4082                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4083                                                         VarDecl)) {
4084   return Node.getStorageClass() == SC_Static;
4085 }
4086
4087 /// Matches deleted function declarations.
4088 ///
4089 /// Given:
4090 /// \code
4091 ///   void Func();
4092 ///   void DeletedFunc() = delete;
4093 /// \endcode
4094 /// functionDecl(isDeleted())
4095 ///   matches the declaration of DeletedFunc, but not Func.
4096 AST_MATCHER(FunctionDecl, isDeleted) {
4097   return Node.isDeleted();
4098 }
4099
4100 /// Matches defaulted function declarations.
4101 ///
4102 /// Given:
4103 /// \code
4104 ///   class A { ~A(); };
4105 ///   class B { ~B() = default; };
4106 /// \endcode
4107 /// functionDecl(isDefaulted())
4108 ///   matches the declaration of ~B, but not ~A.
4109 AST_MATCHER(FunctionDecl, isDefaulted) {
4110   return Node.isDefaulted();
4111 }
4112
4113 /// Matches functions that have a dynamic exception specification.
4114 ///
4115 /// Given:
4116 /// \code
4117 ///   void f();
4118 ///   void g() noexcept;
4119 ///   void h() noexcept(true);
4120 ///   void i() noexcept(false);
4121 ///   void j() throw();
4122 ///   void k() throw(int);
4123 ///   void l() throw(...);
4124 /// \endcode
4125 /// functionDecl(hasDynamicExceptionSpec()) and
4126 ///   functionProtoType(hasDynamicExceptionSpec())
4127 ///   match the declarations of j, k, and l, but not f, g, h, or i.
4128 AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec,
4129                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4130                                                         FunctionProtoType)) {
4131   if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node))
4132     return FnTy->hasDynamicExceptionSpec();
4133   return false;
4134 }
4135
4136 /// Matches functions that have a non-throwing exception specification.
4137 ///
4138 /// Given:
4139 /// \code
4140 ///   void f();
4141 ///   void g() noexcept;
4142 ///   void h() throw();
4143 ///   void i() throw(int);
4144 ///   void j() noexcept(false);
4145 /// \endcode
4146 /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow())
4147 ///   match the declarations of g, and h, but not f, i or j.
4148 AST_POLYMORPHIC_MATCHER(isNoThrow,
4149                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4150                                                         FunctionProtoType)) {
4151   const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node);
4152
4153   // If the function does not have a prototype, then it is assumed to be a
4154   // throwing function (as it would if the function did not have any exception
4155   // specification).
4156   if (!FnTy)
4157     return false;
4158
4159   // Assume the best for any unresolved exception specification.
4160   if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType()))
4161     return true;
4162
4163   return FnTy->isNothrow();
4164 }
4165
4166 /// Matches constexpr variable and function declarations,
4167 ///        and if constexpr.
4168 ///
4169 /// Given:
4170 /// \code
4171 ///   constexpr int foo = 42;
4172 ///   constexpr int bar();
4173 ///   void baz() { if constexpr(1 > 0) {} }
4174 /// \endcode
4175 /// varDecl(isConstexpr())
4176 ///   matches the declaration of foo.
4177 /// functionDecl(isConstexpr())
4178 ///   matches the declaration of bar.
4179 /// ifStmt(isConstexpr())
4180 ///   matches the if statement in baz.
4181 AST_POLYMORPHIC_MATCHER(isConstexpr,
4182                         AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl,
4183                                                         FunctionDecl,
4184                                                         IfStmt)) {
4185   return Node.isConstexpr();
4186 }
4187
4188 /// Matches the condition expression of an if statement, for loop,
4189 /// switch statement or conditional operator.
4190 ///
4191 /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true))))
4192 /// \code
4193 ///   if (true) {}
4194 /// \endcode
4195 AST_POLYMORPHIC_MATCHER_P(
4196     hasCondition,
4197     AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt,
4198                                     SwitchStmt, AbstractConditionalOperator),
4199     internal::Matcher<Expr>, InnerMatcher) {
4200   const Expr *const Condition = Node.getCond();
4201   return (Condition != nullptr &&
4202           InnerMatcher.matches(*Condition, Finder, Builder));
4203 }
4204
4205 /// Matches the then-statement of an if statement.
4206 ///
4207 /// Examples matches the if statement
4208 ///   (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true)))))
4209 /// \code
4210 ///   if (false) true; else false;
4211 /// \endcode
4212 AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) {
4213   const Stmt *const Then = Node.getThen();
4214   return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder));
4215 }
4216
4217 /// Matches the else-statement of an if statement.
4218 ///
4219 /// Examples matches the if statement
4220 ///   (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true)))))
4221 /// \code
4222 ///   if (false) false; else true;
4223 /// \endcode
4224 AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) {
4225   const Stmt *const Else = Node.getElse();
4226   return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder));
4227 }
4228
4229 /// Matches if a node equals a previously bound node.
4230 ///
4231 /// Matches a node if it equals the node previously bound to \p ID.
4232 ///
4233 /// Given
4234 /// \code
4235 ///   class X { int a; int b; };
4236 /// \endcode
4237 /// cxxRecordDecl(
4238 ///     has(fieldDecl(hasName("a"), hasType(type().bind("t")))),
4239 ///     has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t"))))))
4240 ///   matches the class \c X, as \c a and \c b have the same type.
4241 ///
4242 /// Note that when multiple matches are involved via \c forEach* matchers,
4243 /// \c equalsBoundNodes acts as a filter.
4244 /// For example:
4245 /// compoundStmt(
4246 ///     forEachDescendant(varDecl().bind("d")),
4247 ///     forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d"))))))
4248 /// will trigger a match for each combination of variable declaration
4249 /// and reference to that variable declaration within a compound statement.
4250 AST_POLYMORPHIC_MATCHER_P(equalsBoundNode,
4251                           AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type,
4252                                                           QualType),
4253                           std::string, ID) {
4254   // FIXME: Figure out whether it makes sense to allow this
4255   // on any other node types.
4256   // For *Loc it probably does not make sense, as those seem
4257   // unique. For NestedNameSepcifier it might make sense, as
4258   // those also have pointer identity, but I'm not sure whether
4259   // they're ever reused.
4260   internal::NotEqualsBoundNodePredicate Predicate;
4261   Predicate.ID = ID;
4262   Predicate.Node = ast_type_traits::DynTypedNode::create(Node);
4263   return Builder->removeBindings(Predicate);
4264 }
4265
4266 /// Matches the condition variable statement in an if statement.
4267 ///
4268 /// Given
4269 /// \code
4270 ///   if (A* a = GetAPointer()) {}
4271 /// \endcode
4272 /// hasConditionVariableStatement(...)
4273 ///   matches 'A* a = GetAPointer()'.
4274 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
4275               internal::Matcher<DeclStmt>, InnerMatcher) {
4276   const DeclStmt* const DeclarationStatement =
4277     Node.getConditionVariableDeclStmt();
4278   return DeclarationStatement != nullptr &&
4279          InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
4280 }
4281
4282 /// Matches the index expression of an array subscript expression.
4283 ///
4284 /// Given
4285 /// \code
4286 ///   int i[5];
4287 ///   void f() { i[1] = 42; }
4288 /// \endcode
4289 /// arraySubscriptExpression(hasIndex(integerLiteral()))
4290 ///   matches \c i[1] with the \c integerLiteral() matching \c 1
4291 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
4292               internal::Matcher<Expr>, InnerMatcher) {
4293   if (const Expr* Expression = Node.getIdx())
4294     return InnerMatcher.matches(*Expression, Finder, Builder);
4295   return false;
4296 }
4297
4298 /// Matches the base expression of an array subscript expression.
4299 ///
4300 /// Given
4301 /// \code
4302 ///   int i[5];
4303 ///   void f() { i[1] = 42; }
4304 /// \endcode
4305 /// arraySubscriptExpression(hasBase(implicitCastExpr(
4306 ///     hasSourceExpression(declRefExpr()))))
4307 ///   matches \c i[1] with the \c declRefExpr() matching \c i
4308 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
4309               internal::Matcher<Expr>, InnerMatcher) {
4310   if (const Expr* Expression = Node.getBase())
4311     return InnerMatcher.matches(*Expression, Finder, Builder);
4312   return false;
4313 }
4314
4315 /// Matches a 'for', 'while', 'do while' statement or a function
4316 /// definition that has a given body.
4317 ///
4318 /// Given
4319 /// \code
4320 ///   for (;;) {}
4321 /// \endcode
4322 /// hasBody(compoundStmt())
4323 ///   matches 'for (;;) {}'
4324 /// with compoundStmt()
4325 ///   matching '{}'
4326 AST_POLYMORPHIC_MATCHER_P(hasBody,
4327                           AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt,
4328                                                           WhileStmt,
4329                                                           CXXForRangeStmt,
4330                                                           FunctionDecl),
4331                           internal::Matcher<Stmt>, InnerMatcher) {
4332   const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node);
4333   return (Statement != nullptr &&
4334           InnerMatcher.matches(*Statement, Finder, Builder));
4335 }
4336
4337 /// Matches compound statements where at least one substatement matches
4338 /// a given matcher. Also matches StmtExprs that have CompoundStmt as children.
4339 ///
4340 /// Given
4341 /// \code
4342 ///   { {}; 1+2; }
4343 /// \endcode
4344 /// hasAnySubstatement(compoundStmt())
4345 ///   matches '{ {}; 1+2; }'
4346 /// with compoundStmt()
4347 ///   matching '{}'
4348 AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement,
4349                           AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt,
4350                                                           StmtExpr),
4351                           internal::Matcher<Stmt>, InnerMatcher) {
4352   const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node);
4353   return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(),
4354                                           CS->body_end(), Finder, Builder);
4355 }
4356
4357 /// Checks that a compound statement contains a specific number of
4358 /// child statements.
4359 ///
4360 /// Example: Given
4361 /// \code
4362 ///   { for (;;) {} }
4363 /// \endcode
4364 /// compoundStmt(statementCountIs(0)))
4365 ///   matches '{}'
4366 ///   but does not match the outer compound statement.
4367 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
4368   return Node.size() == N;
4369 }
4370
4371 /// Matches literals that are equal to the given value of type ValueT.
4372 ///
4373 /// Given
4374 /// \code
4375 ///   f('\0', false, 3.14, 42);
4376 /// \endcode
4377 /// characterLiteral(equals(0))
4378 ///   matches '\0'
4379 /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0))
4380 ///   match false
4381 /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2))
4382 ///   match 3.14
4383 /// integerLiteral(equals(42))
4384 ///   matches 42
4385 ///
4386 /// Note that you cannot directly match a negative numeric literal because the
4387 /// minus sign is not part of the literal: It is a unary operator whose operand
4388 /// is the positive numeric literal. Instead, you must use a unaryOperator()
4389 /// matcher to match the minus sign:
4390 ///
4391 /// unaryOperator(hasOperatorName("-"),
4392 ///               hasUnaryOperand(integerLiteral(equals(13))))
4393 ///
4394 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>,
4395 ///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
4396 template <typename ValueT>
4397 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
4398 equals(const ValueT &Value) {
4399   return internal::PolymorphicMatcherWithParam1<
4400     internal::ValueEqualsMatcher,
4401     ValueT>(Value);
4402 }
4403
4404 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4405                           AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4406                                                           CXXBoolLiteralExpr,
4407                                                           IntegerLiteral),
4408                           bool, Value, 0) {
4409   return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4410     .matchesNode(Node);
4411 }
4412
4413 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4414                           AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4415                                                           CXXBoolLiteralExpr,
4416                                                           IntegerLiteral),
4417                           unsigned, Value, 1) {
4418   return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4419     .matchesNode(Node);
4420 }
4421
4422 AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals,
4423                           AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral,
4424                                                           CXXBoolLiteralExpr,
4425                                                           FloatingLiteral,
4426                                                           IntegerLiteral),
4427                           double, Value, 2) {
4428   return internal::ValueEqualsMatcher<NodeType, ParamT>(Value)
4429     .matchesNode(Node);
4430 }
4431
4432 /// Matches the operator Name of operator expressions (binary or
4433 /// unary).
4434 ///
4435 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
4436 /// \code
4437 ///   !(a || b)
4438 /// \endcode
4439 AST_POLYMORPHIC_MATCHER_P(hasOperatorName,
4440                           AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4441                                                           UnaryOperator),
4442                           std::string, Name) {
4443   return Name == Node.getOpcodeStr(Node.getOpcode());
4444 }
4445
4446 /// Matches all kinds of assignment operators.
4447 ///
4448 /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator()))
4449 /// \code
4450 ///   if (a == b)
4451 ///     a += b;
4452 /// \endcode
4453 ///
4454 /// Example 2: matches s1 = s2
4455 ///            (matcher = cxxOperatorCallExpr(isAssignmentOperator()))
4456 /// \code
4457 ///   struct S { S& operator=(const S&); };
4458 ///   void x() { S s1, s2; s1 = s2; })
4459 /// \endcode
4460 AST_POLYMORPHIC_MATCHER(isAssignmentOperator,
4461                         AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4462                                                         CXXOperatorCallExpr)) {
4463   return Node.isAssignmentOp();
4464 }
4465
4466 /// Matches the left hand side of binary operator expressions.
4467 ///
4468 /// Example matches a (matcher = binaryOperator(hasLHS()))
4469 /// \code
4470 ///   a || b
4471 /// \endcode
4472 AST_POLYMORPHIC_MATCHER_P(hasLHS,
4473                           AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4474                                                           ArraySubscriptExpr),
4475                           internal::Matcher<Expr>, InnerMatcher) {
4476   const Expr *LeftHandSide = Node.getLHS();
4477   return (LeftHandSide != nullptr &&
4478           InnerMatcher.matches(*LeftHandSide, Finder, Builder));
4479 }
4480
4481 /// Matches the right hand side of binary operator expressions.
4482 ///
4483 /// Example matches b (matcher = binaryOperator(hasRHS()))
4484 /// \code
4485 ///   a || b
4486 /// \endcode
4487 AST_POLYMORPHIC_MATCHER_P(hasRHS,
4488                           AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator,
4489                                                           ArraySubscriptExpr),
4490                           internal::Matcher<Expr>, InnerMatcher) {
4491   const Expr *RightHandSide = Node.getRHS();
4492   return (RightHandSide != nullptr &&
4493           InnerMatcher.matches(*RightHandSide, Finder, Builder));
4494 }
4495
4496 /// Matches if either the left hand side or the right hand side of a
4497 /// binary operator matches.
4498 inline internal::Matcher<BinaryOperator> hasEitherOperand(
4499     const internal::Matcher<Expr> &InnerMatcher) {
4500   return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
4501 }
4502
4503 /// Matches if the operand of a unary operator matches.
4504 ///
4505 /// Example matches true (matcher = hasUnaryOperand(
4506 ///                                   cxxBoolLiteral(equals(true))))
4507 /// \code
4508 ///   !true
4509 /// \endcode
4510 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
4511               internal::Matcher<Expr>, InnerMatcher) {
4512   const Expr * const Operand = Node.getSubExpr();
4513   return (Operand != nullptr &&
4514           InnerMatcher.matches(*Operand, Finder, Builder));
4515 }
4516
4517 /// Matches if the cast's source expression
4518 /// or opaque value's source expression matches the given matcher.
4519 ///
4520 /// Example 1: matches "a string"
4521 /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr())))
4522 /// \code
4523 /// class URL { URL(string); };
4524 /// URL url = "a string";
4525 /// \endcode
4526 ///
4527 /// Example 2: matches 'b' (matcher =
4528 /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr())))
4529 /// \code
4530 /// int a = b ?: 1;
4531 /// \endcode
4532 AST_POLYMORPHIC_MATCHER_P(hasSourceExpression,
4533                           AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr,
4534                                                           OpaqueValueExpr),
4535                           internal::Matcher<Expr>, InnerMatcher) {
4536   const Expr *const SubExpression =
4537       internal::GetSourceExpressionMatcher<NodeType>::get(Node);
4538   return (SubExpression != nullptr &&
4539           InnerMatcher.matches(*SubExpression, Finder, Builder));
4540 }
4541
4542 /// Matches casts that has a given cast kind.
4543 ///
4544 /// Example: matches the implicit cast around \c 0
4545 /// (matcher = castExpr(hasCastKind(CK_NullToPointer)))
4546 /// \code
4547 ///   int *p = 0;
4548 /// \endcode
4549 ///
4550 /// If the matcher is use from clang-query, CastKind parameter
4551 /// should be passed as a quoted string. e.g., ofKind("CK_NullToPointer").
4552 AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
4553   return Node.getCastKind() == Kind;
4554 }
4555
4556 /// Matches casts whose destination type matches a given matcher.
4557 ///
4558 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
4559 /// actual casts "explicit" casts.)
4560 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
4561               internal::Matcher<QualType>, InnerMatcher) {
4562   const QualType NodeType = Node.getTypeAsWritten();
4563   return InnerMatcher.matches(NodeType, Finder, Builder);
4564 }
4565
4566 /// Matches implicit casts whose destination type matches a given
4567 /// matcher.
4568 ///
4569 /// FIXME: Unit test this matcher
4570 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
4571               internal::Matcher<QualType>, InnerMatcher) {
4572   return InnerMatcher.matches(Node.getType(), Finder, Builder);
4573 }
4574
4575 /// Matches RecordDecl object that are spelled with "struct."
4576 ///
4577 /// Example matches S, but not C or U.
4578 /// \code
4579 ///   struct S {};
4580 ///   class C {};
4581 ///   union U {};
4582 /// \endcode
4583 AST_MATCHER(RecordDecl, isStruct) {
4584   return Node.isStruct();
4585 }
4586
4587 /// Matches RecordDecl object that are spelled with "union."
4588 ///
4589 /// Example matches U, but not C or S.
4590 /// \code
4591 ///   struct S {};
4592 ///   class C {};
4593 ///   union U {};
4594 /// \endcode
4595 AST_MATCHER(RecordDecl, isUnion) {
4596   return Node.isUnion();
4597 }
4598
4599 /// Matches RecordDecl object that are spelled with "class."
4600 ///
4601 /// Example matches C, but not S or U.
4602 /// \code
4603 ///   struct S {};
4604 ///   class C {};
4605 ///   union U {};
4606 /// \endcode
4607 AST_MATCHER(RecordDecl, isClass) {
4608   return Node.isClass();
4609 }
4610
4611 /// Matches the true branch expression of a conditional operator.
4612 ///
4613 /// Example 1 (conditional ternary operator): matches a
4614 /// \code
4615 ///   condition ? a : b
4616 /// \endcode
4617 ///
4618 /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition)
4619 /// \code
4620 ///   condition ?: b
4621 /// \endcode
4622 AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression,
4623               internal::Matcher<Expr>, InnerMatcher) {
4624   const Expr *Expression = Node.getTrueExpr();
4625   return (Expression != nullptr &&
4626           InnerMatcher.matches(*Expression, Finder, Builder));
4627 }
4628
4629 /// Matches the false branch expression of a conditional operator
4630 /// (binary or ternary).
4631 ///
4632 /// Example matches b
4633 /// \code
4634 ///   condition ? a : b
4635 ///   condition ?: b
4636 /// \endcode
4637 AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression,
4638               internal::Matcher<Expr>, InnerMatcher) {
4639   const Expr *Expression = Node.getFalseExpr();
4640   return (Expression != nullptr &&
4641           InnerMatcher.matches(*Expression, Finder, Builder));
4642 }
4643
4644 /// Matches if a declaration has a body attached.
4645 ///
4646 /// Example matches A, va, fa
4647 /// \code
4648 ///   class A {};
4649 ///   class B;  // Doesn't match, as it has no body.
4650 ///   int va;
4651 ///   extern int vb;  // Doesn't match, as it doesn't define the variable.
4652 ///   void fa() {}
4653 ///   void fb();  // Doesn't match, as it has no body.
4654 ///   @interface X
4655 ///   - (void)ma; // Doesn't match, interface is declaration.
4656 ///   @end
4657 ///   @implementation X
4658 ///   - (void)ma {}
4659 ///   @end
4660 /// \endcode
4661 ///
4662 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>,
4663 ///   Matcher<ObjCMethodDecl>
4664 AST_POLYMORPHIC_MATCHER(isDefinition,
4665                         AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl,
4666                                                         ObjCMethodDecl,
4667                                                         FunctionDecl)) {
4668   return Node.isThisDeclarationADefinition();
4669 }
4670
4671 /// Matches if a function declaration is variadic.
4672 ///
4673 /// Example matches f, but not g or h. The function i will not match, even when
4674 /// compiled in C mode.
4675 /// \code
4676 ///   void f(...);
4677 ///   void g(int);
4678 ///   template <typename... Ts> void h(Ts...);
4679 ///   void i();
4680 /// \endcode
4681 AST_MATCHER(FunctionDecl, isVariadic) {
4682   return Node.isVariadic();
4683 }
4684
4685 /// Matches the class declaration that the given method declaration
4686 /// belongs to.
4687 ///
4688 /// FIXME: Generalize this for other kinds of declarations.
4689 /// FIXME: What other kind of declarations would we need to generalize
4690 /// this to?
4691 ///
4692 /// Example matches A() in the last line
4693 ///     (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
4694 ///         ofClass(hasName("A"))))))
4695 /// \code
4696 ///   class A {
4697 ///    public:
4698 ///     A();
4699 ///   };
4700 ///   A a = A();
4701 /// \endcode
4702 AST_MATCHER_P(CXXMethodDecl, ofClass,
4703               internal::Matcher<CXXRecordDecl>, InnerMatcher) {
4704   const CXXRecordDecl *Parent = Node.getParent();
4705   return (Parent != nullptr &&
4706           InnerMatcher.matches(*Parent, Finder, Builder));
4707 }
4708
4709 /// Matches each method overridden by the given method. This matcher may
4710 /// produce multiple matches.
4711 ///
4712 /// Given
4713 /// \code
4714 ///   class A { virtual void f(); };
4715 ///   class B : public A { void f(); };
4716 ///   class C : public B { void f(); };
4717 /// \endcode
4718 /// cxxMethodDecl(ofClass(hasName("C")),
4719 ///               forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4720 ///   matches once, with "b" binding "A::f" and "d" binding "C::f" (Note
4721 ///   that B::f is not overridden by C::f).
4722 ///
4723 /// The check can produce multiple matches in case of multiple inheritance, e.g.
4724 /// \code
4725 ///   class A1 { virtual void f(); };
4726 ///   class A2 { virtual void f(); };
4727 ///   class C : public A1, public A2 { void f(); };
4728 /// \endcode
4729 /// cxxMethodDecl(ofClass(hasName("C")),
4730 ///               forEachOverridden(cxxMethodDecl().bind("b"))).bind("d")
4731 ///   matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and
4732 ///   once with "b" binding "A2::f" and "d" binding "C::f".
4733 AST_MATCHER_P(CXXMethodDecl, forEachOverridden,
4734               internal::Matcher<CXXMethodDecl>, InnerMatcher) {
4735   BoundNodesTreeBuilder Result;
4736   bool Matched = false;
4737   for (const auto *Overridden : Node.overridden_methods()) {
4738     BoundNodesTreeBuilder OverriddenBuilder(*Builder);
4739     const bool OverriddenMatched =
4740         InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder);
4741     if (OverriddenMatched) {
4742       Matched = true;
4743       Result.addMatch(OverriddenBuilder);
4744     }
4745   }
4746   *Builder = std::move(Result);
4747   return Matched;
4748 }
4749
4750 /// Matches if the given method declaration is virtual.
4751 ///
4752 /// Given
4753 /// \code
4754 ///   class A {
4755 ///    public:
4756 ///     virtual void x();
4757 ///   };
4758 /// \endcode
4759 ///   matches A::x
4760 AST_MATCHER(CXXMethodDecl, isVirtual) {
4761   return Node.isVirtual();
4762 }
4763
4764 /// Matches if the given method declaration has an explicit "virtual".
4765 ///
4766 /// Given
4767 /// \code
4768 ///   class A {
4769 ///    public:
4770 ///     virtual void x();
4771 ///   };
4772 ///   class B : public A {
4773 ///    public:
4774 ///     void x();
4775 ///   };
4776 /// \endcode
4777 ///   matches A::x but not B::x
4778 AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) {
4779   return Node.isVirtualAsWritten();
4780 }
4781
4782 /// Matches if the given method or class declaration is final.
4783 ///
4784 /// Given:
4785 /// \code
4786 ///   class A final {};
4787 ///
4788 ///   struct B {
4789 ///     virtual void f();
4790 ///   };
4791 ///
4792 ///   struct C : B {
4793 ///     void f() final;
4794 ///   };
4795 /// \endcode
4796 /// matches A and C::f, but not B, C, or B::f
4797 AST_POLYMORPHIC_MATCHER(isFinal,
4798                         AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl,
4799                                                         CXXMethodDecl)) {
4800   return Node.template hasAttr<FinalAttr>();
4801 }
4802
4803 /// Matches if the given method declaration is pure.
4804 ///
4805 /// Given
4806 /// \code
4807 ///   class A {
4808 ///    public:
4809 ///     virtual void x() = 0;
4810 ///   };
4811 /// \endcode
4812 ///   matches A::x
4813 AST_MATCHER(CXXMethodDecl, isPure) {
4814   return Node.isPure();
4815 }
4816
4817 /// Matches if the given method declaration is const.
4818 ///
4819 /// Given
4820 /// \code
4821 /// struct A {
4822 ///   void foo() const;
4823 ///   void bar();
4824 /// };
4825 /// \endcode
4826 ///
4827 /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar()
4828 AST_MATCHER(CXXMethodDecl, isConst) {
4829   return Node.isConst();
4830 }
4831
4832 /// Matches if the given method declaration declares a copy assignment
4833 /// operator.
4834 ///
4835 /// Given
4836 /// \code
4837 /// struct A {
4838 ///   A &operator=(const A &);
4839 ///   A &operator=(A &&);
4840 /// };
4841 /// \endcode
4842 ///
4843 /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not
4844 /// the second one.
4845 AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) {
4846   return Node.isCopyAssignmentOperator();
4847 }
4848
4849 /// Matches if the given method declaration declares a move assignment
4850 /// operator.
4851 ///
4852 /// Given
4853 /// \code
4854 /// struct A {
4855 ///   A &operator=(const A &);
4856 ///   A &operator=(A &&);
4857 /// };
4858 /// \endcode
4859 ///
4860 /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not
4861 /// the first one.
4862 AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) {
4863   return Node.isMoveAssignmentOperator();
4864 }
4865
4866 /// Matches if the given method declaration overrides another method.
4867 ///
4868 /// Given
4869 /// \code
4870 ///   class A {
4871 ///    public:
4872 ///     virtual void x();
4873 ///   };
4874 ///   class B : public A {
4875 ///    public:
4876 ///     virtual void x();
4877 ///   };
4878 /// \endcode
4879 ///   matches B::x
4880 AST_MATCHER(CXXMethodDecl, isOverride) {
4881   return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>();
4882 }
4883
4884 /// Matches method declarations that are user-provided.
4885 ///
4886 /// Given
4887 /// \code
4888 ///   struct S {
4889 ///     S(); // #1
4890 ///     S(const S &) = default; // #2
4891 ///     S(S &&) = delete; // #3
4892 ///   };
4893 /// \endcode
4894 /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3.
4895 AST_MATCHER(CXXMethodDecl, isUserProvided) {
4896   return Node.isUserProvided();
4897 }
4898
4899 /// Matches member expressions that are called with '->' as opposed
4900 /// to '.'.
4901 ///
4902 /// Member calls on the implicit this pointer match as called with '->'.
4903 ///
4904 /// Given
4905 /// \code
4906 ///   class Y {
4907 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
4908 ///     template <class T> void f() { this->f<T>(); f<T>(); }
4909 ///     int a;
4910 ///     static int b;
4911 ///   };
4912 ///   template <class T>
4913 ///   class Z {
4914 ///     void x() { this->m; }
4915 ///   };
4916 /// \endcode
4917 /// memberExpr(isArrow())
4918 ///   matches this->x, x, y.x, a, this->b
4919 /// cxxDependentScopeMemberExpr(isArrow())
4920 ///   matches this->m
4921 /// unresolvedMemberExpr(isArrow())
4922 ///   matches this->f<T>, f<T>
4923 AST_POLYMORPHIC_MATCHER(
4924     isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
4925                                              CXXDependentScopeMemberExpr)) {
4926   return Node.isArrow();
4927 }
4928
4929 /// Matches QualType nodes that are of integer type.
4930 ///
4931 /// Given
4932 /// \code
4933 ///   void a(int);
4934 ///   void b(long);
4935 ///   void c(double);
4936 /// \endcode
4937 /// functionDecl(hasAnyParameter(hasType(isInteger())))
4938 /// matches "a(int)", "b(long)", but not "c(double)".
4939 AST_MATCHER(QualType, isInteger) {
4940     return Node->isIntegerType();
4941 }
4942
4943 /// Matches QualType nodes that are of unsigned integer type.
4944 ///
4945 /// Given
4946 /// \code
4947 ///   void a(int);
4948 ///   void b(unsigned long);
4949 ///   void c(double);
4950 /// \endcode
4951 /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger())))
4952 /// matches "b(unsigned long)", but not "a(int)" and "c(double)".
4953 AST_MATCHER(QualType, isUnsignedInteger) {
4954     return Node->isUnsignedIntegerType();
4955 }
4956
4957 /// Matches QualType nodes that are of signed integer type.
4958 ///
4959 /// Given
4960 /// \code
4961 ///   void a(int);
4962 ///   void b(unsigned long);
4963 ///   void c(double);
4964 /// \endcode
4965 /// functionDecl(hasAnyParameter(hasType(isSignedInteger())))
4966 /// matches "a(int)", but not "b(unsigned long)" and "c(double)".
4967 AST_MATCHER(QualType, isSignedInteger) {
4968     return Node->isSignedIntegerType();
4969 }
4970
4971 /// Matches QualType nodes that are of character type.
4972 ///
4973 /// Given
4974 /// \code
4975 ///   void a(char);
4976 ///   void b(wchar_t);
4977 ///   void c(double);
4978 /// \endcode
4979 /// functionDecl(hasAnyParameter(hasType(isAnyCharacter())))
4980 /// matches "a(char)", "b(wchar_t)", but not "c(double)".
4981 AST_MATCHER(QualType, isAnyCharacter) {
4982     return Node->isAnyCharacterType();
4983 }
4984
4985 /// Matches QualType nodes that are of any pointer type; this includes
4986 /// the Objective-C object pointer type, which is different despite being
4987 /// syntactically similar.
4988 ///
4989 /// Given
4990 /// \code
4991 ///   int *i = nullptr;
4992 ///
4993 ///   @interface Foo
4994 ///   @end
4995 ///   Foo *f;
4996 ///
4997 ///   int j;
4998 /// \endcode
4999 /// varDecl(hasType(isAnyPointer()))
5000 ///   matches "int *i" and "Foo *f", but not "int j".
5001 AST_MATCHER(QualType, isAnyPointer) {
5002   return Node->isAnyPointerType();
5003 }
5004
5005 /// Matches QualType nodes that are const-qualified, i.e., that
5006 /// include "top-level" const.
5007 ///
5008 /// Given
5009 /// \code
5010 ///   void a(int);
5011 ///   void b(int const);
5012 ///   void c(const int);
5013 ///   void d(const int*);
5014 ///   void e(int const) {};
5015 /// \endcode
5016 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
5017 ///   matches "void b(int const)", "void c(const int)" and
5018 ///   "void e(int const) {}". It does not match d as there
5019 ///   is no top-level const on the parameter type "const int *".
5020 AST_MATCHER(QualType, isConstQualified) {
5021   return Node.isConstQualified();
5022 }
5023
5024 /// Matches QualType nodes that are volatile-qualified, i.e., that
5025 /// include "top-level" volatile.
5026 ///
5027 /// Given
5028 /// \code
5029 ///   void a(int);
5030 ///   void b(int volatile);
5031 ///   void c(volatile int);
5032 ///   void d(volatile int*);
5033 ///   void e(int volatile) {};
5034 /// \endcode
5035 /// functionDecl(hasAnyParameter(hasType(isVolatileQualified())))
5036 ///   matches "void b(int volatile)", "void c(volatile int)" and
5037 ///   "void e(int volatile) {}". It does not match d as there
5038 ///   is no top-level volatile on the parameter type "volatile int *".
5039 AST_MATCHER(QualType, isVolatileQualified) {
5040   return Node.isVolatileQualified();
5041 }
5042
5043 /// Matches QualType nodes that have local CV-qualifiers attached to
5044 /// the node, not hidden within a typedef.
5045 ///
5046 /// Given
5047 /// \code
5048 ///   typedef const int const_int;
5049 ///   const_int i;
5050 ///   int *const j;
5051 ///   int *volatile k;
5052 ///   int m;
5053 /// \endcode
5054 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
5055 /// \c i is const-qualified but the qualifier is not local.
5056 AST_MATCHER(QualType, hasLocalQualifiers) {
5057   return Node.hasLocalQualifiers();
5058 }
5059
5060 /// Matches a member expression where the member is matched by a
5061 /// given matcher.
5062 ///
5063 /// Given
5064 /// \code
5065 ///   struct { int first, second; } first, second;
5066 ///   int i(second.first);
5067 ///   int j(first.second);
5068 /// \endcode
5069 /// memberExpr(member(hasName("first")))
5070 ///   matches second.first
5071 ///   but not first.second (because the member name there is "second").
5072 AST_MATCHER_P(MemberExpr, member,
5073               internal::Matcher<ValueDecl>, InnerMatcher) {
5074   return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
5075 }
5076
5077 /// Matches a member expression where the object expression is matched by a
5078 /// given matcher. Implicit object expressions are included; that is, it matches
5079 /// use of implicit `this`.
5080 ///
5081 /// Given
5082 /// \code
5083 ///   struct X {
5084 ///     int m;
5085 ///     int f(X x) { x.m; return m; }
5086 ///   };
5087 /// \endcode
5088 /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))))
5089 ///   matches `x.m`, but not `m`; however,
5090 /// memberExpr(hasObjectExpression(hasType(pointsTo(
5091 //      cxxRecordDecl(hasName("X"))))))
5092 ///   matches `m` (aka. `this->m`), but not `x.m`.
5093 AST_POLYMORPHIC_MATCHER_P(
5094     hasObjectExpression,
5095     AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr,
5096                                     CXXDependentScopeMemberExpr),
5097     internal::Matcher<Expr>, InnerMatcher) {
5098   if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node))
5099     if (E->isImplicitAccess())
5100       return false;
5101   if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node))
5102     if (E->isImplicitAccess())
5103       return false;
5104   return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
5105 }
5106
5107 /// Matches any using shadow declaration.
5108 ///
5109 /// Given
5110 /// \code
5111 ///   namespace X { void b(); }
5112 ///   using X::b;
5113 /// \endcode
5114 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
5115 ///   matches \code using X::b \endcode
5116 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
5117               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
5118   return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(),
5119                                     Node.shadow_end(), Finder, Builder);
5120 }
5121
5122 /// Matches a using shadow declaration where the target declaration is
5123 /// matched by the given matcher.
5124 ///
5125 /// Given
5126 /// \code
5127 ///   namespace X { int a; void b(); }
5128 ///   using X::a;
5129 ///   using X::b;
5130 /// \endcode
5131 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
5132 ///   matches \code using X::b \endcode
5133 ///   but not \code using X::a \endcode
5134 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
5135               internal::Matcher<NamedDecl>, InnerMatcher) {
5136   return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
5137 }
5138
5139 /// Matches template instantiations of function, class, or static
5140 /// member variable template instantiations.
5141 ///
5142 /// Given
5143 /// \code
5144 ///   template <typename T> class X {}; class A {}; X<A> x;
5145 /// \endcode
5146 /// or
5147 /// \code
5148 ///   template <typename T> class X {}; class A {}; template class X<A>;
5149 /// \endcode
5150 /// or
5151 /// \code
5152 ///   template <typename T> class X {}; class A {}; extern template class X<A>;
5153 /// \endcode
5154 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5155 ///   matches the template instantiation of X<A>.
5156 ///
5157 /// But given
5158 /// \code
5159 ///   template <typename T>  class X {}; class A {};
5160 ///   template <> class X<A> {}; X<A> x;
5161 /// \endcode
5162 /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation())
5163 ///   does not match, as X<A> is an explicit template specialization.
5164 ///
5165 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5166 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation,
5167                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5168                                                         CXXRecordDecl)) {
5169   return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
5170           Node.getTemplateSpecializationKind() ==
5171               TSK_ExplicitInstantiationDefinition ||
5172           Node.getTemplateSpecializationKind() ==
5173               TSK_ExplicitInstantiationDeclaration);
5174 }
5175
5176 /// Matches declarations that are template instantiations or are inside
5177 /// template instantiations.
5178 ///
5179 /// Given
5180 /// \code
5181 ///   template<typename T> void A(T t) { T i; }
5182 ///   A(0);
5183 ///   A(0U);
5184 /// \endcode
5185 /// functionDecl(isInstantiated())
5186 ///   matches 'A(int) {...};' and 'A(unsigned) {...}'.
5187 AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) {
5188   auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5189                                     functionDecl(isTemplateInstantiation())));
5190   return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation)));
5191 }
5192
5193 /// Matches statements inside of a template instantiation.
5194 ///
5195 /// Given
5196 /// \code
5197 ///   int j;
5198 ///   template<typename T> void A(T t) { T i; j += 42;}
5199 ///   A(0);
5200 ///   A(0U);
5201 /// \endcode
5202 /// declStmt(isInTemplateInstantiation())
5203 ///   matches 'int i;' and 'unsigned i'.
5204 /// unless(stmt(isInTemplateInstantiation()))
5205 ///   will NOT match j += 42; as it's shared between the template definition and
5206 ///   instantiation.
5207 AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) {
5208   return stmt(
5209       hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()),
5210                              functionDecl(isTemplateInstantiation())))));
5211 }
5212
5213 /// Matches explicit template specializations of function, class, or
5214 /// static member variable template instantiations.
5215 ///
5216 /// Given
5217 /// \code
5218 ///   template<typename T> void A(T t) { }
5219 ///   template<> void A(int N) { }
5220 /// \endcode
5221 /// functionDecl(isExplicitTemplateSpecialization())
5222 ///   matches the specialization A<int>().
5223 ///
5224 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
5225 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization,
5226                         AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl,
5227                                                         CXXRecordDecl)) {
5228   return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
5229 }
5230
5231 /// Matches \c TypeLocs for which the given inner
5232 /// QualType-matcher matches.
5233 AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc,
5234                                 internal::Matcher<QualType>, InnerMatcher, 0) {
5235   return internal::BindableMatcher<TypeLoc>(
5236       new internal::TypeLocTypeMatcher(InnerMatcher));
5237 }
5238
5239 /// Matches type \c bool.
5240 ///
5241 /// Given
5242 /// \code
5243 ///  struct S { bool func(); };
5244 /// \endcode
5245 /// functionDecl(returns(booleanType()))
5246 ///   matches "bool func();"
5247 AST_MATCHER(Type, booleanType) {
5248   return Node.isBooleanType();
5249 }
5250
5251 /// Matches type \c void.
5252 ///
5253 /// Given
5254 /// \code
5255 ///  struct S { void func(); };
5256 /// \endcode
5257 /// functionDecl(returns(voidType()))
5258 ///   matches "void func();"
5259 AST_MATCHER(Type, voidType) {
5260   return Node.isVoidType();
5261 }
5262
5263 template <typename NodeType>
5264 using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>;
5265
5266 /// Matches builtin Types.
5267 ///
5268 /// Given
5269 /// \code
5270 ///   struct A {};
5271 ///   A a;
5272 ///   int b;
5273 ///   float c;
5274 ///   bool d;
5275 /// \endcode
5276 /// builtinType()
5277 ///   matches "int b", "float c" and "bool d"
5278 extern const AstTypeMatcher<BuiltinType> builtinType;
5279
5280 /// Matches all kinds of arrays.
5281 ///
5282 /// Given
5283 /// \code
5284 ///   int a[] = { 2, 3 };
5285 ///   int b[4];
5286 ///   void f() { int c[a[0]]; }
5287 /// \endcode
5288 /// arrayType()
5289 ///   matches "int a[]", "int b[4]" and "int c[a[0]]";
5290 extern const AstTypeMatcher<ArrayType> arrayType;
5291
5292 /// Matches C99 complex types.
5293 ///
5294 /// Given
5295 /// \code
5296 ///   _Complex float f;
5297 /// \endcode
5298 /// complexType()
5299 ///   matches "_Complex float f"
5300 extern const AstTypeMatcher<ComplexType> complexType;
5301
5302 /// Matches any real floating-point type (float, double, long double).
5303 ///
5304 /// Given
5305 /// \code
5306 ///   int i;
5307 ///   float f;
5308 /// \endcode
5309 /// realFloatingPointType()
5310 ///   matches "float f" but not "int i"
5311 AST_MATCHER(Type, realFloatingPointType) {
5312   return Node.isRealFloatingType();
5313 }
5314
5315 /// Matches arrays and C99 complex types that have a specific element
5316 /// type.
5317 ///
5318 /// Given
5319 /// \code
5320 ///   struct A {};
5321 ///   A a[7];
5322 ///   int b[7];
5323 /// \endcode
5324 /// arrayType(hasElementType(builtinType()))
5325 ///   matches "int b[7]"
5326 ///
5327 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
5328 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement,
5329                                   AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
5330                                                                   ComplexType));
5331
5332 /// Matches C arrays with a specified constant size.
5333 ///
5334 /// Given
5335 /// \code
5336 ///   void() {
5337 ///     int a[2];
5338 ///     int b[] = { 2, 3 };
5339 ///     int c[b[0]];
5340 ///   }
5341 /// \endcode
5342 /// constantArrayType()
5343 ///   matches "int a[2]"
5344 extern const AstTypeMatcher<ConstantArrayType> constantArrayType;
5345
5346 /// Matches nodes that have the specified size.
5347 ///
5348 /// Given
5349 /// \code
5350 ///   int a[42];
5351 ///   int b[2 * 21];
5352 ///   int c[41], d[43];
5353 ///   char *s = "abcd";
5354 ///   wchar_t *ws = L"abcd";
5355 ///   char *w = "a";
5356 /// \endcode
5357 /// constantArrayType(hasSize(42))
5358 ///   matches "int a[42]" and "int b[2 * 21]"
5359 /// stringLiteral(hasSize(4))
5360 ///   matches "abcd", L"abcd"
5361 AST_POLYMORPHIC_MATCHER_P(hasSize,
5362                           AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType,
5363                                                           StringLiteral),
5364                           unsigned, N) {
5365   return internal::HasSizeMatcher<NodeType>::hasSize(Node, N);
5366 }
5367
5368 /// Matches C++ arrays whose size is a value-dependent expression.
5369 ///
5370 /// Given
5371 /// \code
5372 ///   template<typename T, int Size>
5373 ///   class array {
5374 ///     T data[Size];
5375 ///   };
5376 /// \endcode
5377 /// dependentSizedArrayType
5378 ///   matches "T data[Size]"
5379 extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
5380
5381 /// Matches C arrays with unspecified size.
5382 ///
5383 /// Given
5384 /// \code
5385 ///   int a[] = { 2, 3 };
5386 ///   int b[42];
5387 ///   void f(int c[]) { int d[a[0]]; };
5388 /// \endcode
5389 /// incompleteArrayType()
5390 ///   matches "int a[]" and "int c[]"
5391 extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
5392
5393 /// Matches C arrays with a specified size that is not an
5394 /// integer-constant-expression.
5395 ///
5396 /// Given
5397 /// \code
5398 ///   void f() {
5399 ///     int a[] = { 2, 3 }
5400 ///     int b[42];
5401 ///     int c[a[0]];
5402 ///   }
5403 /// \endcode
5404 /// variableArrayType()
5405 ///   matches "int c[a[0]]"
5406 extern const AstTypeMatcher<VariableArrayType> variableArrayType;
5407
5408 /// Matches \c VariableArrayType nodes that have a specific size
5409 /// expression.
5410 ///
5411 /// Given
5412 /// \code
5413 ///   void f(int b) {
5414 ///     int a[b];
5415 ///   }
5416 /// \endcode
5417 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
5418 ///   varDecl(hasName("b")))))))
5419 ///   matches "int a[b]"
5420 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
5421               internal::Matcher<Expr>, InnerMatcher) {
5422   return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
5423 }
5424
5425 /// Matches atomic types.
5426 ///
5427 /// Given
5428 /// \code
5429 ///   _Atomic(int) i;
5430 /// \endcode
5431 /// atomicType()
5432 ///   matches "_Atomic(int) i"
5433 extern const AstTypeMatcher<AtomicType> atomicType;
5434
5435 /// Matches atomic types with a specific value type.
5436 ///
5437 /// Given
5438 /// \code
5439 ///   _Atomic(int) i;
5440 ///   _Atomic(float) f;
5441 /// \endcode
5442 /// atomicType(hasValueType(isInteger()))
5443 ///  matches "_Atomic(int) i"
5444 ///
5445 /// Usable as: Matcher<AtomicType>
5446 AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue,
5447                                   AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
5448
5449 /// Matches types nodes representing C++11 auto types.
5450 ///
5451 /// Given:
5452 /// \code
5453 ///   auto n = 4;
5454 ///   int v[] = { 2, 3 }
5455 ///   for (auto i : v) { }
5456 /// \endcode
5457 /// autoType()
5458 ///   matches "auto n" and "auto i"
5459 extern const AstTypeMatcher<AutoType> autoType;
5460
5461 /// Matches types nodes representing C++11 decltype(<expr>) types.
5462 ///
5463 /// Given:
5464 /// \code
5465 ///   short i = 1;
5466 ///   int j = 42;
5467 ///   decltype(i + j) result = i + j;
5468 /// \endcode
5469 /// decltypeType()
5470 ///   matches "decltype(i + j)"
5471 extern const AstTypeMatcher<DecltypeType> decltypeType;
5472
5473 /// Matches \c AutoType nodes where the deduced type is a specific type.
5474 ///
5475 /// Note: There is no \c TypeLoc for the deduced type and thus no
5476 /// \c getDeducedLoc() matcher.
5477 ///
5478 /// Given
5479 /// \code
5480 ///   auto a = 1;
5481 ///   auto b = 2.0;
5482 /// \endcode
5483 /// autoType(hasDeducedType(isInteger()))
5484 ///   matches "auto a"
5485 ///
5486 /// Usable as: Matcher<AutoType>
5487 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType,
5488                           AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType));
5489
5490 /// Matches \c DecltypeType nodes to find out the underlying type.
5491 ///
5492 /// Given
5493 /// \code
5494 ///   decltype(1) a = 1;
5495 ///   decltype(2.0) b = 2.0;
5496 /// \endcode
5497 /// decltypeType(hasUnderlyingType(isInteger()))
5498 ///   matches the type of "a"
5499 ///
5500 /// Usable as: Matcher<DecltypeType>
5501 AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType,
5502                           AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType));
5503
5504 /// Matches \c FunctionType nodes.
5505 ///
5506 /// Given
5507 /// \code
5508 ///   int (*f)(int);
5509 ///   void g();
5510 /// \endcode
5511 /// functionType()
5512 ///   matches "int (*f)(int)" and the type of "g".
5513 extern const AstTypeMatcher<FunctionType> functionType;
5514
5515 /// Matches \c FunctionProtoType nodes.
5516 ///
5517 /// Given
5518 /// \code
5519 ///   int (*f)(int);
5520 ///   void g();
5521 /// \endcode
5522 /// functionProtoType()
5523 ///   matches "int (*f)(int)" and the type of "g" in C++ mode.
5524 ///   In C mode, "g" is not matched because it does not contain a prototype.
5525 extern const AstTypeMatcher<FunctionProtoType> functionProtoType;
5526
5527 /// Matches \c ParenType nodes.
5528 ///
5529 /// Given
5530 /// \code
5531 ///   int (*ptr_to_array)[4];
5532 ///   int *array_of_ptrs[4];
5533 /// \endcode
5534 ///
5535 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
5536 /// \c array_of_ptrs.
5537 extern const AstTypeMatcher<ParenType> parenType;
5538
5539 /// Matches \c ParenType nodes where the inner type is a specific type.
5540 ///
5541 /// Given
5542 /// \code
5543 ///   int (*ptr_to_array)[4];
5544 ///   int (*ptr_to_func)(int);
5545 /// \endcode
5546 ///
5547 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
5548 /// \c ptr_to_func but not \c ptr_to_array.
5549 ///
5550 /// Usable as: Matcher<ParenType>
5551 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType,
5552                           AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType));
5553
5554 /// Matches block pointer types, i.e. types syntactically represented as
5555 /// "void (^)(int)".
5556 ///
5557 /// The \c pointee is always required to be a \c FunctionType.
5558 extern const AstTypeMatcher<BlockPointerType> blockPointerType;
5559
5560 /// Matches member pointer types.
5561 /// Given
5562 /// \code
5563 ///   struct A { int i; }
5564 ///   A::* ptr = A::i;
5565 /// \endcode
5566 /// memberPointerType()
5567 ///   matches "A::* ptr"
5568 extern const AstTypeMatcher<MemberPointerType> memberPointerType;
5569
5570 /// Matches pointer types, but does not match Objective-C object pointer
5571 /// types.
5572 ///
5573 /// Given
5574 /// \code
5575 ///   int *a;
5576 ///   int &b = *a;
5577 ///   int c = 5;
5578 ///
5579 ///   @interface Foo
5580 ///   @end
5581 ///   Foo *f;
5582 /// \endcode
5583 /// pointerType()
5584 ///   matches "int *a", but does not match "Foo *f".
5585 extern const AstTypeMatcher<PointerType> pointerType;
5586
5587 /// Matches an Objective-C object pointer type, which is different from
5588 /// a pointer type, despite being syntactically similar.
5589 ///
5590 /// Given
5591 /// \code
5592 ///   int *a;
5593 ///
5594 ///   @interface Foo
5595 ///   @end
5596 ///   Foo *f;
5597 /// \endcode
5598 /// pointerType()
5599 ///   matches "Foo *f", but does not match "int *a".
5600 extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
5601
5602 /// Matches both lvalue and rvalue reference types.
5603 ///
5604 /// Given
5605 /// \code
5606 ///   int *a;
5607 ///   int &b = *a;
5608 ///   int &&c = 1;
5609 ///   auto &d = b;
5610 ///   auto &&e = c;
5611 ///   auto &&f = 2;
5612 ///   int g = 5;
5613 /// \endcode
5614 ///
5615 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
5616 extern const AstTypeMatcher<ReferenceType> referenceType;
5617
5618 /// Matches lvalue reference types.
5619 ///
5620 /// Given:
5621 /// \code
5622 ///   int *a;
5623 ///   int &b = *a;
5624 ///   int &&c = 1;
5625 ///   auto &d = b;
5626 ///   auto &&e = c;
5627 ///   auto &&f = 2;
5628 ///   int g = 5;
5629 /// \endcode
5630 ///
5631 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
5632 /// matched since the type is deduced as int& by reference collapsing rules.
5633 extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
5634
5635 /// Matches rvalue reference types.
5636 ///
5637 /// Given:
5638 /// \code
5639 ///   int *a;
5640 ///   int &b = *a;
5641 ///   int &&c = 1;
5642 ///   auto &d = b;
5643 ///   auto &&e = c;
5644 ///   auto &&f = 2;
5645 ///   int g = 5;
5646 /// \endcode
5647 ///
5648 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
5649 /// matched as it is deduced to int& by reference collapsing rules.
5650 extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
5651
5652 /// Narrows PointerType (and similar) matchers to those where the
5653 /// \c pointee matches a given matcher.
5654 ///
5655 /// Given
5656 /// \code
5657 ///   int *a;
5658 ///   int const *b;
5659 ///   float const *f;
5660 /// \endcode
5661 /// pointerType(pointee(isConstQualified(), isInteger()))
5662 ///   matches "int const *b"
5663 ///
5664 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
5665 ///   Matcher<PointerType>, Matcher<ReferenceType>
5666 AST_TYPELOC_TRAVERSE_MATCHER_DECL(
5667     pointee, getPointee,
5668     AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
5669                                     PointerType, ReferenceType));
5670
5671 /// Matches typedef types.
5672 ///
5673 /// Given
5674 /// \code
5675 ///   typedef int X;
5676 /// \endcode
5677 /// typedefType()
5678 ///   matches "typedef int X"
5679 extern const AstTypeMatcher<TypedefType> typedefType;
5680
5681 /// Matches enum types.
5682 ///
5683 /// Given
5684 /// \code
5685 ///   enum C { Green };
5686 ///   enum class S { Red };
5687 ///
5688 ///   C c;
5689 ///   S s;
5690 /// \endcode
5691 //
5692 /// \c enumType() matches the type of the variable declarations of both \c c and
5693 /// \c s.
5694 extern const AstTypeMatcher<EnumType> enumType;
5695
5696 /// Matches template specialization types.
5697 ///
5698 /// Given
5699 /// \code
5700 ///   template <typename T>
5701 ///   class C { };
5702 ///
5703 ///   template class C<int>;  // A
5704 ///   C<char> var;            // B
5705 /// \endcode
5706 ///
5707 /// \c templateSpecializationType() matches the type of the explicit
5708 /// instantiation in \c A and the type of the variable declaration in \c B.
5709 extern const AstTypeMatcher<TemplateSpecializationType>
5710     templateSpecializationType;
5711
5712 /// Matches types nodes representing unary type transformations.
5713 ///
5714 /// Given:
5715 /// \code
5716 ///   typedef __underlying_type(T) type;
5717 /// \endcode
5718 /// unaryTransformType()
5719 ///   matches "__underlying_type(T)"
5720 extern const AstTypeMatcher<UnaryTransformType> unaryTransformType;
5721
5722 /// Matches record types (e.g. structs, classes).
5723 ///
5724 /// Given
5725 /// \code
5726 ///   class C {};
5727 ///   struct S {};
5728 ///
5729 ///   C c;
5730 ///   S s;
5731 /// \endcode
5732 ///
5733 /// \c recordType() matches the type of the variable declarations of both \c c
5734 /// and \c s.
5735 extern const AstTypeMatcher<RecordType> recordType;
5736
5737 /// Matches tag types (record and enum types).
5738 ///
5739 /// Given
5740 /// \code
5741 ///   enum E {};
5742 ///   class C {};
5743 ///
5744 ///   E e;
5745 ///   C c;
5746 /// \endcode
5747 ///
5748 /// \c tagType() matches the type of the variable declarations of both \c e
5749 /// and \c c.
5750 extern const AstTypeMatcher<TagType> tagType;
5751
5752 /// Matches types specified with an elaborated type keyword or with a
5753 /// qualified name.
5754 ///
5755 /// Given
5756 /// \code
5757 ///   namespace N {
5758 ///     namespace M {
5759 ///       class D {};
5760 ///     }
5761 ///   }
5762 ///   class C {};
5763 ///
5764 ///   class C c;
5765 ///   N::M::D d;
5766 /// \endcode
5767 ///
5768 /// \c elaboratedType() matches the type of the variable declarations of both
5769 /// \c c and \c d.
5770 extern const AstTypeMatcher<ElaboratedType> elaboratedType;
5771
5772 /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
5773 /// matches \c InnerMatcher if the qualifier exists.
5774 ///
5775 /// Given
5776 /// \code
5777 ///   namespace N {
5778 ///     namespace M {
5779 ///       class D {};
5780 ///     }
5781 ///   }
5782 ///   N::M::D d;
5783 /// \endcode
5784 ///
5785 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
5786 /// matches the type of the variable declaration of \c d.
5787 AST_MATCHER_P(ElaboratedType, hasQualifier,
5788               internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
5789   if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
5790     return InnerMatcher.matches(*Qualifier, Finder, Builder);
5791
5792   return false;
5793 }
5794
5795 /// Matches ElaboratedTypes whose named type matches \c InnerMatcher.
5796 ///
5797 /// Given
5798 /// \code
5799 ///   namespace N {
5800 ///     namespace M {
5801 ///       class D {};
5802 ///     }
5803 ///   }
5804 ///   N::M::D d;
5805 /// \endcode
5806 ///
5807 /// \c elaboratedType(namesType(recordType(
5808 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
5809 /// declaration of \c d.
5810 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
5811               InnerMatcher) {
5812   return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
5813 }
5814
5815 /// Matches types that represent the result of substituting a type for a
5816 /// template type parameter.
5817 ///
5818 /// Given
5819 /// \code
5820 ///   template <typename T>
5821 ///   void F(T t) {
5822 ///     int i = 1 + t;
5823 ///   }
5824 /// \endcode
5825 ///
5826 /// \c substTemplateTypeParmType() matches the type of 't' but not '1'
5827 extern const AstTypeMatcher<SubstTemplateTypeParmType>
5828     substTemplateTypeParmType;
5829
5830 /// Matches template type parameter substitutions that have a replacement
5831 /// type that matches the provided matcher.
5832 ///
5833 /// Given
5834 /// \code
5835 ///   template <typename T>
5836 ///   double F(T t);
5837 ///   int i;
5838 ///   double j = F(i);
5839 /// \endcode
5840 ///
5841 /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int
5842 AST_TYPE_TRAVERSE_MATCHER(
5843     hasReplacementType, getReplacementType,
5844     AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType));
5845
5846 /// Matches template type parameter types.
5847 ///
5848 /// Example matches T, but not int.
5849 ///     (matcher = templateTypeParmType())
5850 /// \code
5851 ///   template <typename T> void f(int i);
5852 /// \endcode
5853 extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
5854
5855 /// Matches injected class name types.
5856 ///
5857 /// Example matches S s, but not S<T> s.
5858 ///     (matcher = parmVarDecl(hasType(injectedClassNameType())))
5859 /// \code
5860 ///   template <typename T> struct S {
5861 ///     void f(S s);
5862 ///     void g(S<T> s);
5863 ///   };
5864 /// \endcode
5865 extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
5866
5867 /// Matches decayed type
5868 /// Example matches i[] in declaration of f.
5869 ///     (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType())))))
5870 /// Example matches i[1].
5871 ///     (matcher = expr(hasType(decayedType(hasDecayedType(pointerType())))))
5872 /// \code
5873 ///   void f(int i[]) {
5874 ///     i[1] = 0;
5875 ///   }
5876 /// \endcode
5877 extern const AstTypeMatcher<DecayedType> decayedType;
5878
5879 /// Matches the decayed type, whos decayed type matches \c InnerMatcher
5880 AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>,
5881               InnerType) {
5882   return InnerType.matches(Node.getDecayedType(), Finder, Builder);
5883 }
5884
5885 /// Matches declarations whose declaration context, interpreted as a
5886 /// Decl, matches \c InnerMatcher.
5887 ///
5888 /// Given
5889 /// \code
5890 ///   namespace N {
5891 ///     namespace M {
5892 ///       class D {};
5893 ///     }
5894 ///   }
5895 /// \endcode
5896 ///
5897 /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
5898 /// declaration of \c class \c D.
5899 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
5900   const DeclContext *DC = Node.getDeclContext();
5901   if (!DC) return false;
5902   return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder);
5903 }
5904
5905 /// Matches nested name specifiers.
5906 ///
5907 /// Given
5908 /// \code
5909 ///   namespace ns {
5910 ///     struct A { static void f(); };
5911 ///     void A::f() {}
5912 ///     void g() { A::f(); }
5913 ///   }
5914 ///   ns::A a;
5915 /// \endcode
5916 /// nestedNameSpecifier()
5917 ///   matches "ns::" and both "A::"
5918 extern const internal::VariadicAllOfMatcher<NestedNameSpecifier>
5919     nestedNameSpecifier;
5920
5921 /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
5922 extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
5923     nestedNameSpecifierLoc;
5924
5925 /// Matches \c NestedNameSpecifierLocs for which the given inner
5926 /// NestedNameSpecifier-matcher matches.
5927 AST_MATCHER_FUNCTION_P_OVERLOAD(
5928     internal::BindableMatcher<NestedNameSpecifierLoc>, loc,
5929     internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) {
5930   return internal::BindableMatcher<NestedNameSpecifierLoc>(
5931       new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
5932           InnerMatcher));
5933 }
5934
5935 /// Matches nested name specifiers that specify a type matching the
5936 /// given \c QualType matcher without qualifiers.
5937 ///
5938 /// Given
5939 /// \code
5940 ///   struct A { struct B { struct C {}; }; };
5941 ///   A::B::C c;
5942 /// \endcode
5943 /// nestedNameSpecifier(specifiesType(
5944 ///   hasDeclaration(cxxRecordDecl(hasName("A")))
5945 /// ))
5946 ///   matches "A::"
5947 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
5948               internal::Matcher<QualType>, InnerMatcher) {
5949   if (!Node.getAsType())
5950     return false;
5951   return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
5952 }
5953
5954 /// Matches nested name specifier locs that specify a type matching the
5955 /// given \c TypeLoc.
5956 ///
5957 /// Given
5958 /// \code
5959 ///   struct A { struct B { struct C {}; }; };
5960 ///   A::B::C c;
5961 /// \endcode
5962 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
5963 ///   hasDeclaration(cxxRecordDecl(hasName("A")))))))
5964 ///   matches "A::"
5965 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
5966               internal::Matcher<TypeLoc>, InnerMatcher) {
5967   return Node && Node.getNestedNameSpecifier()->getAsType() &&
5968          InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
5969 }
5970
5971 /// Matches on the prefix of a \c NestedNameSpecifier.
5972 ///
5973 /// Given
5974 /// \code
5975 ///   struct A { struct B { struct C {}; }; };
5976 ///   A::B::C c;
5977 /// \endcode
5978 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
5979 ///   matches "A::"
5980 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
5981                        internal::Matcher<NestedNameSpecifier>, InnerMatcher,
5982                        0) {
5983   const NestedNameSpecifier *NextNode = Node.getPrefix();
5984   if (!NextNode)
5985     return false;
5986   return InnerMatcher.matches(*NextNode, Finder, Builder);
5987 }
5988
5989 /// Matches on the prefix of a \c NestedNameSpecifierLoc.
5990 ///
5991 /// Given
5992 /// \code
5993 ///   struct A { struct B { struct C {}; }; };
5994 ///   A::B::C c;
5995 /// \endcode
5996 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
5997 ///   matches "A::"
5998 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
5999                        internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
6000                        1) {
6001   NestedNameSpecifierLoc NextNode = Node.getPrefix();
6002   if (!NextNode)
6003     return false;
6004   return InnerMatcher.matches(NextNode, Finder, Builder);
6005 }
6006
6007 /// Matches nested name specifiers that specify a namespace matching the
6008 /// given namespace matcher.
6009 ///
6010 /// Given
6011 /// \code
6012 ///   namespace ns { struct A {}; }
6013 ///   ns::A a;
6014 /// \endcode
6015 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
6016 ///   matches "ns::"
6017 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
6018               internal::Matcher<NamespaceDecl>, InnerMatcher) {
6019   if (!Node.getAsNamespace())
6020     return false;
6021   return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
6022 }
6023
6024 /// Overloads for the \c equalsNode matcher.
6025 /// FIXME: Implement for other node types.
6026 /// @{
6027
6028 /// Matches if a node equals another node.
6029 ///
6030 /// \c Decl has pointer identity in the AST.
6031 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) {
6032   return &Node == Other;
6033 }
6034 /// Matches if a node equals another node.
6035 ///
6036 /// \c Stmt has pointer identity in the AST.
6037 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) {
6038   return &Node == Other;
6039 }
6040 /// Matches if a node equals another node.
6041 ///
6042 /// \c Type has pointer identity in the AST.
6043 AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) {
6044     return &Node == Other;
6045 }
6046
6047 /// @}
6048
6049 /// Matches each case or default statement belonging to the given switch
6050 /// statement. This matcher may produce multiple matches.
6051 ///
6052 /// Given
6053 /// \code
6054 ///   switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } }
6055 /// \endcode
6056 /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s")
6057 ///   matches four times, with "c" binding each of "case 1:", "case 2:",
6058 /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)",
6059 /// "switch (1)", "switch (2)" and "switch (2)".
6060 AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>,
6061               InnerMatcher) {
6062   BoundNodesTreeBuilder Result;
6063   // FIXME: getSwitchCaseList() does not necessarily guarantee a stable
6064   // iteration order. We should use the more general iterating matchers once
6065   // they are capable of expressing this matcher (for example, it should ignore
6066   // case statements belonging to nested switch statements).
6067   bool Matched = false;
6068   for (const SwitchCase *SC = Node.getSwitchCaseList(); SC;
6069        SC = SC->getNextSwitchCase()) {
6070     BoundNodesTreeBuilder CaseBuilder(*Builder);
6071     bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder);
6072     if (CaseMatched) {
6073       Matched = true;
6074       Result.addMatch(CaseBuilder);
6075     }
6076   }
6077   *Builder = std::move(Result);
6078   return Matched;
6079 }
6080
6081 /// Matches each constructor initializer in a constructor definition.
6082 ///
6083 /// Given
6084 /// \code
6085 ///   class A { A() : i(42), j(42) {} int i; int j; };
6086 /// \endcode
6087 /// cxxConstructorDecl(forEachConstructorInitializer(
6088 ///   forField(decl().bind("x"))
6089 /// ))
6090 ///   will trigger two matches, binding for 'i' and 'j' respectively.
6091 AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer,
6092               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
6093   BoundNodesTreeBuilder Result;
6094   bool Matched = false;
6095   for (const auto *I : Node.inits()) {
6096     BoundNodesTreeBuilder InitBuilder(*Builder);
6097     if (InnerMatcher.matches(*I, Finder, &InitBuilder)) {
6098       Matched = true;
6099       Result.addMatch(InitBuilder);
6100     }
6101   }
6102   *Builder = std::move(Result);
6103   return Matched;
6104 }
6105
6106 /// Matches constructor declarations that are copy constructors.
6107 ///
6108 /// Given
6109 /// \code
6110 ///   struct S {
6111 ///     S(); // #1
6112 ///     S(const S &); // #2
6113 ///     S(S &&); // #3
6114 ///   };
6115 /// \endcode
6116 /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3.
6117 AST_MATCHER(CXXConstructorDecl, isCopyConstructor) {
6118   return Node.isCopyConstructor();
6119 }
6120
6121 /// Matches constructor declarations that are move constructors.
6122 ///
6123 /// Given
6124 /// \code
6125 ///   struct S {
6126 ///     S(); // #1
6127 ///     S(const S &); // #2
6128 ///     S(S &&); // #3
6129 ///   };
6130 /// \endcode
6131 /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2.
6132 AST_MATCHER(CXXConstructorDecl, isMoveConstructor) {
6133   return Node.isMoveConstructor();
6134 }
6135
6136 /// Matches constructor declarations that are default constructors.
6137 ///
6138 /// Given
6139 /// \code
6140 ///   struct S {
6141 ///     S(); // #1
6142 ///     S(const S &); // #2
6143 ///     S(S &&); // #3
6144 ///   };
6145 /// \endcode
6146 /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3.
6147 AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) {
6148   return Node.isDefaultConstructor();
6149 }
6150
6151 /// Matches constructors that delegate to another constructor.
6152 ///
6153 /// Given
6154 /// \code
6155 ///   struct S {
6156 ///     S(); // #1
6157 ///     S(int) {} // #2
6158 ///     S(S &&) : S() {} // #3
6159 ///   };
6160 ///   S::S() : S(0) {} // #4
6161 /// \endcode
6162 /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not
6163 /// #1 or #2.
6164 AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) {
6165   return Node.isDelegatingConstructor();
6166 }
6167
6168 /// Matches constructor, conversion function, and deduction guide declarations
6169 /// that have an explicit specifier if this explicit specifier is resolved to
6170 /// true.
6171 ///
6172 /// Given
6173 /// \code
6174 ///   template<bool b>
6175 ///   struct S {
6176 ///     S(int); // #1
6177 ///     explicit S(double); // #2
6178 ///     operator int(); // #3
6179 ///     explicit operator bool(); // #4
6180 ///     explicit(false) S(bool) // # 7
6181 ///     explicit(true) S(char) // # 8
6182 ///     explicit(b) S(S) // # 9
6183 ///   };
6184 ///   S(int) -> S<true> // #5
6185 ///   explicit S(double) -> S<false> // #6
6186 /// \endcode
6187 /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9.
6188 /// cxxConversionDecl(isExplicit()) will match #4, but not #3.
6189 /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5.
6190 AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES(
6191                                         CXXConstructorDecl, CXXConversionDecl,
6192                                         CXXDeductionGuideDecl)) {
6193   return Node.isExplicit();
6194 }
6195
6196 /// Matches the expression in an explicit specifier if present in the given
6197 /// declaration.
6198 ///
6199 /// Given
6200 /// \code
6201 ///   template<bool b>
6202 ///   struct S {
6203 ///     S(int); // #1
6204 ///     explicit S(double); // #2
6205 ///     operator int(); // #3
6206 ///     explicit operator bool(); // #4
6207 ///     explicit(false) S(bool) // # 7
6208 ///     explicit(true) S(char) // # 8
6209 ///     explicit(b) S(S) // # 9
6210 ///   };
6211 ///   S(int) -> S<true> // #5
6212 ///   explicit S(double) -> S<false> // #6
6213 /// \endcode
6214 /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2.
6215 /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4.
6216 /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6.
6217 AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>,
6218               InnerMatcher) {
6219   ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node);
6220   if (!ES.getExpr())
6221     return false;
6222   return InnerMatcher.matches(*ES.getExpr(), Finder, Builder);
6223 }
6224
6225 /// Matches function and namespace declarations that are marked with
6226 /// the inline keyword.
6227 ///
6228 /// Given
6229 /// \code
6230 ///   inline void f();
6231 ///   void g();
6232 ///   namespace n {
6233 ///   inline namespace m {}
6234 ///   }
6235 /// \endcode
6236 /// functionDecl(isInline()) will match ::f().
6237 /// namespaceDecl(isInline()) will match n::m.
6238 AST_POLYMORPHIC_MATCHER(isInline,
6239                         AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl,
6240                                                         FunctionDecl)) {
6241   // This is required because the spelling of the function used to determine
6242   // whether inline is specified or not differs between the polymorphic types.
6243   if (const auto *FD = dyn_cast<FunctionDecl>(&Node))
6244     return FD->isInlineSpecified();
6245   else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node))
6246     return NSD->isInline();
6247   llvm_unreachable("Not a valid polymorphic type");
6248 }
6249
6250 /// Matches anonymous namespace declarations.
6251 ///
6252 /// Given
6253 /// \code
6254 ///   namespace n {
6255 ///   namespace {} // #1
6256 ///   }
6257 /// \endcode
6258 /// namespaceDecl(isAnonymous()) will match #1 but not ::n.
6259 AST_MATCHER(NamespaceDecl, isAnonymous) {
6260   return Node.isAnonymousNamespace();
6261 }
6262
6263 /// Matches declarations in the namespace `std`, but not in nested namespaces.
6264 ///
6265 /// Given
6266 /// \code
6267 ///   class vector {};
6268 ///   namespace foo {
6269 ///     class vector {};
6270 ///     namespace std {
6271 ///       class vector {};
6272 ///     }
6273 ///   }
6274 ///   namespace std {
6275 ///     inline namespace __1 {
6276 ///       class vector {}; // #1
6277 ///       namespace experimental {
6278 ///         class vector {};
6279 ///       }
6280 ///     }
6281 ///   }
6282 /// \endcode
6283 /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1.
6284 AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); }
6285
6286 /// If the given case statement does not use the GNU case range
6287 /// extension, matches the constant given in the statement.
6288 ///
6289 /// Given
6290 /// \code
6291 ///   switch (1) { case 1: case 1+1: case 3 ... 4: ; }
6292 /// \endcode
6293 /// caseStmt(hasCaseConstant(integerLiteral()))
6294 ///   matches "case 1:"
6295 AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>,
6296               InnerMatcher) {
6297   if (Node.getRHS())
6298     return false;
6299
6300   return InnerMatcher.matches(*Node.getLHS(), Finder, Builder);
6301 }
6302
6303 /// Matches declaration that has a given attribute.
6304 ///
6305 /// Given
6306 /// \code
6307 ///   __attribute__((device)) void f() { ... }
6308 /// \endcode
6309 /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of
6310 /// f. If the matcher is used from clang-query, attr::Kind parameter should be
6311 /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice").
6312 AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) {
6313   for (const auto *Attr : Node.attrs()) {
6314     if (Attr->getKind() == AttrKind)
6315       return true;
6316   }
6317   return false;
6318 }
6319
6320 /// Matches the return value expression of a return statement
6321 ///
6322 /// Given
6323 /// \code
6324 ///   return a + b;
6325 /// \endcode
6326 /// hasReturnValue(binaryOperator())
6327 ///   matches 'return a + b'
6328 /// with binaryOperator()
6329 ///   matching 'a + b'
6330 AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>,
6331               InnerMatcher) {
6332   if (const auto *RetValue = Node.getRetValue())
6333     return InnerMatcher.matches(*RetValue, Finder, Builder);
6334   return false;
6335 }
6336
6337 /// Matches CUDA kernel call expression.
6338 ///
6339 /// Example matches,
6340 /// \code
6341 ///   kernel<<<i,j>>>();
6342 /// \endcode
6343 extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
6344     cudaKernelCallExpr;
6345
6346 /// Matches expressions that resolve to a null pointer constant, such as
6347 /// GNU's __null, C++11's nullptr, or C's NULL macro.
6348 ///
6349 /// Given:
6350 /// \code
6351 ///   void *v1 = NULL;
6352 ///   void *v2 = nullptr;
6353 ///   void *v3 = __null; // GNU extension
6354 ///   char *cp = (char *)0;
6355 ///   int *ip = 0;
6356 ///   int i = 0;
6357 /// \endcode
6358 /// expr(nullPointerConstant())
6359 ///   matches the initializer for v1, v2, v3, cp, and ip. Does not match the
6360 ///   initializer for i.
6361 AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) {
6362   return anyOf(
6363       gnuNullExpr(), cxxNullPtrLiteralExpr(),
6364       integerLiteral(equals(0), hasParent(expr(hasType(pointerType())))));
6365 }
6366
6367 /// Matches declaration of the function the statement belongs to
6368 ///
6369 /// Given:
6370 /// \code
6371 /// F& operator=(const F& o) {
6372 ///   std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; });
6373 ///   return *this;
6374 /// }
6375 /// \endcode
6376 /// returnStmt(forFunction(hasName("operator=")))
6377 ///   matches 'return *this'
6378 ///   but does match 'return > 0'
6379 AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>,
6380               InnerMatcher) {
6381   const auto &Parents = Finder->getASTContext().getParents(Node);
6382
6383   llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(),
6384                                                             Parents.end());
6385   while(!Stack.empty()) {
6386     const auto &CurNode = Stack.back();
6387     Stack.pop_back();
6388     if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) {
6389       if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) {
6390         return true;
6391       }
6392     } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) {
6393       if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(),
6394                               Finder, Builder)) {
6395         return true;
6396       }
6397     } else {
6398       for(const auto &Parent: Finder->getASTContext().getParents(CurNode))
6399         Stack.push_back(Parent);
6400     }
6401   }
6402   return false;
6403 }
6404
6405 /// Matches a declaration that has external formal linkage.
6406 ///
6407 /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage()))
6408 /// \code
6409 /// void f() {
6410 ///   int x;
6411 ///   static int y;
6412 /// }
6413 /// int z;
6414 /// \endcode
6415 ///
6416 /// Example matches f() because it has external formal linkage despite being
6417 /// unique to the translation unit as though it has internal likage
6418 /// (matcher = functionDecl(hasExternalFormalLinkage()))
6419 ///
6420 /// \code
6421 /// namespace {
6422 /// void f() {}
6423 /// }
6424 /// \endcode
6425 AST_MATCHER(NamedDecl, hasExternalFormalLinkage) {
6426   return Node.hasExternalFormalLinkage();
6427 }
6428
6429 /// Matches a declaration that has default arguments.
6430 ///
6431 /// Example matches y (matcher = parmVarDecl(hasDefaultArgument()))
6432 /// \code
6433 /// void x(int val) {}
6434 /// void y(int val = 0) {}
6435 /// \endcode
6436 AST_MATCHER(ParmVarDecl, hasDefaultArgument) {
6437   return Node.hasDefaultArg();
6438 }
6439
6440 /// Matches array new expressions.
6441 ///
6442 /// Given:
6443 /// \code
6444 ///   MyClass *p1 = new MyClass[10];
6445 /// \endcode
6446 /// cxxNewExpr(isArray())
6447 ///   matches the expression 'new MyClass[10]'.
6448 AST_MATCHER(CXXNewExpr, isArray) {
6449   return Node.isArray();
6450 }
6451
6452 /// Matches array new expressions with a given array size.
6453 ///
6454 /// Given:
6455 /// \code
6456 ///   MyClass *p1 = new MyClass[10];
6457 /// \endcode
6458 /// cxxNewExpr(hasArraySize(intgerLiteral(equals(10))))
6459 ///   matches the expression 'new MyClass[10]'.
6460 AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) {
6461   return Node.isArray() && *Node.getArraySize() &&
6462          InnerMatcher.matches(**Node.getArraySize(), Finder, Builder);
6463 }
6464
6465 /// Matches a class declaration that is defined.
6466 ///
6467 /// Example matches x (matcher = cxxRecordDecl(hasDefinition()))
6468 /// \code
6469 /// class x {};
6470 /// class y;
6471 /// \endcode
6472 AST_MATCHER(CXXRecordDecl, hasDefinition) {
6473   return Node.hasDefinition();
6474 }
6475
6476 /// Matches C++11 scoped enum declaration.
6477 ///
6478 /// Example matches Y (matcher = enumDecl(isScoped()))
6479 /// \code
6480 /// enum X {};
6481 /// enum class Y {};
6482 /// \endcode
6483 AST_MATCHER(EnumDecl, isScoped) {
6484   return Node.isScoped();
6485 }
6486
6487 /// Matches a function declared with a trailing return type.
6488 ///
6489 /// Example matches Y (matcher = functionDecl(hasTrailingReturn()))
6490 /// \code
6491 /// int X() {}
6492 /// auto Y() -> int {}
6493 /// \endcode
6494 AST_MATCHER(FunctionDecl, hasTrailingReturn) {
6495   if (const auto *F = Node.getType()->getAs<FunctionProtoType>())
6496     return F->hasTrailingReturn();
6497   return false;
6498 }
6499
6500 /// Matches expressions that match InnerMatcher that are possibly wrapped in an
6501 /// elidable constructor.
6502 ///
6503 /// In C++17 copy elidable constructors are no longer being
6504 /// generated in the AST as it is not permitted by the standard. They are
6505 /// however part of the AST in C++14 and earlier. Therefore, to write a matcher
6506 /// that works in all language modes, the matcher has to skip elidable
6507 /// constructor AST nodes if they appear in the AST. This matcher can be used to
6508 /// skip those elidable constructors.
6509 ///
6510 /// Given
6511 ///
6512 /// \code
6513 /// struct H {};
6514 /// H G();
6515 /// void f() {
6516 ///   H D = G();
6517 /// }
6518 /// \endcode
6519 ///
6520 /// ``varDecl(hasInitializer(any(
6521 ///       ignoringElidableConstructorCall(callExpr()),
6522 ///       exprWithCleanups(ignoringElidableConstructorCall(callExpr()))))``
6523 /// matches ``H D = G()``
6524 AST_MATCHER_P(Expr, ignoringElidableConstructorCall,
6525               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
6526   if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(&Node)) {
6527     if (CtorExpr->isElidable()) {
6528       if (const auto *MaterializeTemp =
6529               dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) {
6530         return InnerMatcher.matches(*MaterializeTemp->GetTemporaryExpr(),
6531                                     Finder, Builder);
6532       }
6533     }
6534   }
6535   return InnerMatcher.matches(Node, Finder, Builder);
6536 }
6537
6538 //----------------------------------------------------------------------------//
6539 // OpenMP handling.
6540 //----------------------------------------------------------------------------//
6541
6542 /// Matches any ``#pragma omp`` executable directive.
6543 ///
6544 /// Given
6545 ///
6546 /// \code
6547 ///   #pragma omp parallel
6548 ///   #pragma omp parallel default(none)
6549 ///   #pragma omp taskyield
6550 /// \endcode
6551 ///
6552 /// ``ompExecutableDirective()`` matches ``omp parallel``,
6553 /// ``omp parallel default(none)`` and ``omp taskyield``.
6554 extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
6555     ompExecutableDirective;
6556
6557 /// Matches standalone OpenMP directives,
6558 /// i.e., directives that can't have a structured block.
6559 ///
6560 /// Given
6561 ///
6562 /// \code
6563 ///   #pragma omp parallel
6564 ///   {}
6565 ///   #pragma omp taskyield
6566 /// \endcode
6567 ///
6568 /// ``ompExecutableDirective(isStandaloneDirective()))`` matches
6569 /// ``omp taskyield``.
6570 AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) {
6571   return Node.isStandaloneDirective();
6572 }
6573
6574 /// Matches the Stmt AST node that is marked as being the structured-block
6575 /// of an OpenMP executable directive.
6576 ///
6577 /// Given
6578 ///
6579 /// \code
6580 ///    #pragma omp parallel
6581 ///    {}
6582 /// \endcode
6583 ///
6584 /// ``stmt(isOMPStructuredBlock()))`` matches ``{}``.
6585 AST_MATCHER(Stmt, isOMPStructuredBlock) { return Node.isOMPStructuredBlock(); }
6586
6587 /// Matches the structured-block of the OpenMP executable directive
6588 ///
6589 /// Prerequisite: the executable directive must not be standalone directive.
6590 /// If it is, it will never match.
6591 ///
6592 /// Given
6593 ///
6594 /// \code
6595 ///    #pragma omp parallel
6596 ///    ;
6597 ///    #pragma omp parallel
6598 ///    {}
6599 /// \endcode
6600 ///
6601 /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;``
6602 AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock,
6603               internal::Matcher<Stmt>, InnerMatcher) {
6604   if (Node.isStandaloneDirective())
6605     return false; // Standalone directives have no structured blocks.
6606   return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder);
6607 }
6608
6609 /// Matches any clause in an OpenMP directive.
6610 ///
6611 /// Given
6612 ///
6613 /// \code
6614 ///   #pragma omp parallel
6615 ///   #pragma omp parallel default(none)
6616 /// \endcode
6617 ///
6618 /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches
6619 /// ``omp parallel default(none)``.
6620 AST_MATCHER_P(OMPExecutableDirective, hasAnyClause,
6621               internal::Matcher<OMPClause>, InnerMatcher) {
6622   ArrayRef<OMPClause *> Clauses = Node.clauses();
6623   return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(),
6624                                     Clauses.end(), Finder, Builder);
6625 }
6626
6627 /// Matches OpenMP ``default`` clause.
6628 ///
6629 /// Given
6630 ///
6631 /// \code
6632 ///   #pragma omp parallel default(none)
6633 ///   #pragma omp parallel default(shared)
6634 ///   #pragma omp parallel
6635 /// \endcode
6636 ///
6637 /// ``ompDefaultClause()`` matches ``default(none)`` and ``default(shared)``.
6638 extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
6639     ompDefaultClause;
6640
6641 /// Matches if the OpenMP ``default`` clause has ``none`` kind specified.
6642 ///
6643 /// Given
6644 ///
6645 /// \code
6646 ///   #pragma omp parallel
6647 ///   #pragma omp parallel default(none)
6648 ///   #pragma omp parallel default(shared)
6649 /// \endcode
6650 ///
6651 /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``.
6652 AST_MATCHER(OMPDefaultClause, isNoneKind) {
6653   return Node.getDefaultKind() == OMPC_DEFAULT_none;
6654 }
6655
6656 /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified.
6657 ///
6658 /// Given
6659 ///
6660 /// \code
6661 ///   #pragma omp parallel
6662 ///   #pragma omp parallel default(none)
6663 ///   #pragma omp parallel default(shared)
6664 /// \endcode
6665 ///
6666 /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``.
6667 AST_MATCHER(OMPDefaultClause, isSharedKind) {
6668   return Node.getDefaultKind() == OMPC_DEFAULT_shared;
6669 }
6670
6671 /// Matches if the OpenMP directive is allowed to contain the specified OpenMP
6672 /// clause kind.
6673 ///
6674 /// Given
6675 ///
6676 /// \code
6677 ///   #pragma omp parallel
6678 ///   #pragma omp parallel for
6679 ///   #pragma omp          for
6680 /// \endcode
6681 ///
6682 /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches
6683 /// ``omp parallel`` and ``omp parallel for``.
6684 ///
6685 /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter
6686 /// should be passed as a quoted string. e.g.,
6687 /// ``isAllowedToContainClauseKind("OMPC_default").``
6688 AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind,
6689               OpenMPClauseKind, CKind) {
6690   return isAllowedClauseForDirective(Node.getDirectiveKind(), CKind);
6691 }
6692
6693 //----------------------------------------------------------------------------//
6694 // End OpenMP handling.
6695 //----------------------------------------------------------------------------//
6696
6697 } // namespace ast_matchers
6698 } // namespace clang
6699
6700 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H