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