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