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