Subversion Repositories QNX 8.QNX8 LLVM/Clang compiler suite

Rev

Blame | Last modification | View Log | Download | RSS feed

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