Coverage Report

Created: 2021-01-19 06:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/ASTMatchers/ASTMatchers.h
Line
Count
Source (jump to first uncovered line)
1
//===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements matchers to be used together with the MatchFinder to
10
//  match AST nodes.
11
//
12
//  Matchers are created by generator functions, which can be combined in
13
//  a functional in-language DSL to express queries over the C++ AST.
14
//
15
//  For example, to match a class with a certain name, one would call:
16
//    cxxRecordDecl(hasName("MyClass"))
17
//  which returns a matcher that can be used to find all AST nodes that declare
18
//  a class named 'MyClass'.
19
//
20
//  For more complicated match expressions we're often interested in accessing
21
//  multiple parts of the matched AST nodes once a match is found. In that case,
22
//  call `.bind("name")` on match expressions that match the nodes you want to
23
//  access.
24
//
25
//  For example, when we're interested in child classes of a certain class, we
26
//  would write:
27
//    cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child")))
28
//  When the match is found via the MatchFinder, a user provided callback will
29
//  be called with a BoundNodes instance that contains a mapping from the
30
//  strings that we provided for the `.bind()` calls to the nodes that were
31
//  matched.
32
//  In the given example, each time our matcher finds a match we get a callback
33
//  where "child" is bound to the RecordDecl node of the matching child
34
//  class declaration.
35
//
36
//  See ASTMatchersInternal.h for a more in-depth explanation of the
37
//  implementation details of the matcher framework.
38
//
39
//  See ASTMatchFinder.h for how to use the generated matchers to run over
40
//  an AST.
41
//
42
//===----------------------------------------------------------------------===//
43
44
#ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
45
#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
46
47
#include "clang/AST/ASTContext.h"
48
#include "clang/AST/ASTTypeTraits.h"
49
#include "clang/AST/Attr.h"
50
#include "clang/AST/CXXInheritance.h"
51
#include "clang/AST/Decl.h"
52
#include "clang/AST/DeclCXX.h"
53
#include "clang/AST/DeclFriend.h"
54
#include "clang/AST/DeclObjC.h"
55
#include "clang/AST/DeclTemplate.h"
56
#include "clang/AST/Expr.h"
57
#include "clang/AST/ExprCXX.h"
58
#include "clang/AST/ExprObjC.h"
59
#include "clang/AST/LambdaCapture.h"
60
#include "clang/AST/NestedNameSpecifier.h"
61
#include "clang/AST/OpenMPClause.h"
62
#include "clang/AST/OperationKinds.h"
63
#include "clang/AST/ParentMapContext.h"
64
#include "clang/AST/Stmt.h"
65
#include "clang/AST/StmtCXX.h"
66
#include "clang/AST/StmtObjC.h"
67
#include "clang/AST/StmtOpenMP.h"
68
#include "clang/AST/TemplateBase.h"
69
#include "clang/AST/TemplateName.h"
70
#include "clang/AST/Type.h"
71
#include "clang/AST/TypeLoc.h"
72
#include "clang/ASTMatchers/ASTMatchersInternal.h"
73
#include "clang/ASTMatchers/ASTMatchersMacros.h"
74
#include "clang/Basic/AttrKinds.h"
75
#include "clang/Basic/ExceptionSpecificationType.h"
76
#include "clang/Basic/FileManager.h"
77
#include "clang/Basic/IdentifierTable.h"
78
#include "clang/Basic/LLVM.h"
79
#include "clang/Basic/SourceManager.h"
80
#include "clang/Basic/Specifiers.h"
81
#include "clang/Basic/TypeTraits.h"
82
#include "llvm/ADT/ArrayRef.h"
83
#include "llvm/ADT/SmallVector.h"
84
#include "llvm/ADT/StringRef.h"
85
#include "llvm/Support/Casting.h"
86
#include "llvm/Support/Compiler.h"
87
#include "llvm/Support/ErrorHandling.h"
88
#include "llvm/Support/Regex.h"
89
#include <cassert>
90
#include <cstddef>
91
#include <iterator>
92
#include <limits>
93
#include <string>
94
#include <utility>
95
#include <vector>
96
97
namespace clang {
98
namespace ast_matchers {
99
100
/// Maps string IDs to AST nodes matched by parts of a matcher.
101
///
102
/// The bound nodes are generated by calling \c bind("id") on the node matchers
103
/// of the nodes we want to access later.
104
///
105
/// The instances of BoundNodes are created by \c MatchFinder when the user's
106
/// callbacks are executed every time a match is found.
107
class BoundNodes {
108
public:
109
  /// Returns the AST node bound to \c ID.
110
  ///
111
  /// Returns NULL if there was no node bound to \c ID or if there is a node but
112
  /// it cannot be converted to the specified type.
113
  template <typename T>
114
8.70k
  const T *getNodeAs(StringRef ID) const {
115
8.70k
    return MyBoundNodes.getNodeAs<T>(ID);
116
8.70k
  }
clang::CallExpr const* clang::ast_matchers::BoundNodes::getNodeAs<clang::CallExpr>(llvm::StringRef) const
Line
Count
Source
114
93
  const T *getNodeAs(StringRef ID) const {
115
93
    return MyBoundNodes.getNodeAs<T>(ID);
116
93
  }
clang::Decl const* clang::ast_matchers::BoundNodes::getNodeAs<clang::Decl>(llvm::StringRef) const
Line
Count
Source
114
1.55k
  const T *getNodeAs(StringRef ID) const {
115
1.55k
    return MyBoundNodes.getNodeAs<T>(ID);
116
1.55k
  }
clang::QualType const* clang::ast_matchers::BoundNodes::getNodeAs<clang::QualType>(llvm::StringRef) const
Line
Count
Source
114
445
  const T *getNodeAs(StringRef ID) const {
115
445
    return MyBoundNodes.getNodeAs<T>(ID);
116
445
  }
clang::ParmVarDecl const* clang::ast_matchers::BoundNodes::getNodeAs<clang::ParmVarDecl>(llvm::StringRef) const
Line
Count
Source
114
76
  const T *getNodeAs(StringRef ID) const {
115
76
    return MyBoundNodes.getNodeAs<T>(ID);
116
76
  }
clang::Expr const* clang::ast_matchers::BoundNodes::getNodeAs<clang::Expr>(llvm::StringRef) const
Line
Count
Source
114
1.09k
  const T *getNodeAs(StringRef ID) const {
115
1.09k
    return MyBoundNodes.getNodeAs<T>(ID);
116
1.09k
  }
clang::ObjCMethodDecl const* clang::ast_matchers::BoundNodes::getNodeAs<clang::ObjCMethodDecl>(llvm::StringRef) const
Line
Count
Source
114
31
  const T *getNodeAs(StringRef ID) const {
115
31
    return MyBoundNodes.getNodeAs<T>(ID);
116
31
  }
clang::ObjCAutoreleasePoolStmt const* clang::ast_matchers::BoundNodes::getNodeAs<clang::ObjCAutoreleasePoolStmt>(llvm::StringRef) const
Line
Count
Source
114
43
  const T *getNodeAs(StringRef ID) const {
115
43
    return MyBoundNodes.getNodeAs<T>(ID);
116
43
  }
clang::CastExpr const* clang::ast_matchers::BoundNodes::getNodeAs<clang::CastExpr>(llvm::StringRef) const
Line
Count
Source
114
1
  const T *getNodeAs(StringRef ID) const {
115
1
    return MyBoundNodes.getNodeAs<T>(ID);
116
1
  }
clang::CXXRecordDecl const* clang::ast_matchers::BoundNodes::getNodeAs<clang::CXXRecordDecl>(llvm::StringRef) const
Line
Count
Source
114
837
  const T *getNodeAs(StringRef ID) const {
115
837
    return MyBoundNodes.getNodeAs<T>(ID);
116
837
  }
clang::Stmt const* clang::ast_matchers::BoundNodes::getNodeAs<clang::Stmt>(llvm::StringRef) const
Line
Count
Source
114
1.08k
  const T *getNodeAs(StringRef ID) const {
115
1.08k
    return MyBoundNodes.getNodeAs<T>(ID);
116
1.08k
  }
clang::ObjCMessageExpr const* clang::ast_matchers::BoundNodes::getNodeAs<clang::ObjCMessageExpr>(llvm::StringRef) const
Line
Count
Source
114
20
  const T *getNodeAs(StringRef ID) const {
115
20
    return MyBoundNodes.getNodeAs<T>(ID);
116
20
  }
clang::MemberExpr const* clang::ast_matchers::BoundNodes::getNodeAs<clang::MemberExpr>(llvm::StringRef) const
Line
Count
Source
114
19
  const T *getNodeAs(StringRef ID) const {
115
19
    return MyBoundNodes.getNodeAs<T>(ID);
116
19
  }
clang::ObjCIvarRefExpr const* clang::ast_matchers::BoundNodes::getNodeAs<clang::ObjCIvarRefExpr>(llvm::StringRef) const
Line
Count
Source
114
2
  const T *getNodeAs(StringRef ID) const {
115
2
    return MyBoundNodes.getNodeAs<T>(ID);
116
2
  }
clang::IntegerLiteral const* clang::ast_matchers::BoundNodes::getNodeAs<clang::IntegerLiteral>(llvm::StringRef) const
Line
Count
Source
114
245
  const T *getNodeAs(StringRef ID) const {
115
245
    return MyBoundNodes.getNodeAs<T>(ID);
116
245
  }
clang::BinaryOperator const* clang::ast_matchers::BoundNodes::getNodeAs<clang::BinaryOperator>(llvm::StringRef) const
Line
Count
Source
114
114
  const T *getNodeAs(StringRef ID) const {
115
114
    return MyBoundNodes.getNodeAs<T>(ID);
116
114
  }
clang::VarDecl const* clang::ast_matchers::BoundNodes::getNodeAs<clang::VarDecl>(llvm::StringRef) const
Line
Count
Source
114
1.23k
  const T *getNodeAs(StringRef ID) const {
115
1.23k
    return MyBoundNodes.getNodeAs<T>(ID);
116
1.23k
  }
clang::FunctionDecl const* clang::ast_matchers::BoundNodes::getNodeAs<clang::FunctionDecl>(llvm::StringRef) const
Line
Count
Source
114
1.66k
  const T *getNodeAs(StringRef ID) const {
115
1.66k
    return MyBoundNodes.getNodeAs<T>(ID);
116
1.66k
  }
clang::IfStmt const* clang::ast_matchers::BoundNodes::getNodeAs<clang::IfStmt>(llvm::StringRef) const
Line
Count
Source
114
138
  const T *getNodeAs(StringRef ID) const {
115
138
    return MyBoundNodes.getNodeAs<T>(ID);
116
138
  }
117
118
  /// Type of mapping from binding identifiers to bound nodes. This type
119
  /// is an associative container with a key type of \c std::string and a value
120
  /// type of \c clang::DynTypedNode
121
  using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap;
122
123
  /// Retrieve mapping from binding identifiers to bound nodes.
124
1.41k
  const IDToNodeMap &getMap() const {
125
1.41k
    return MyBoundNodes.getMap();
126
1.41k
  }
127
128
private:
129
  friend class internal::BoundNodesTreeBuilder;
130
131
  /// Create BoundNodes from a pre-filled map of bindings.
132
  BoundNodes(internal::BoundNodesMap &MyBoundNodes)
133
32.1k
      : MyBoundNodes(MyBoundNodes) {}
134
135
  internal::BoundNodesMap MyBoundNodes;
136
};
137
138
/// Types of matchers for the top-level classes in the AST class
139
/// hierarchy.
140
/// @{
141
using DeclarationMatcher = internal::Matcher<Decl>;
142
using StatementMatcher = internal::Matcher<Stmt>;
143
using TypeMatcher = internal::Matcher<QualType>;
144
using TypeLocMatcher = internal::Matcher<TypeLoc>;
145
using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>;
146
using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>;
147
using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>;
148
using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>;
149
using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>;
150
/// @}
151
152
/// Matches any node.
153
///
154
/// Useful when another matcher requires a child matcher, but there's no
155
/// additional constraint. This will often be used with an explicit conversion
156
/// to an \c internal::Matcher<> type such as \c TypeMatcher.
157
///
158
/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
159
/// \code
160
/// "int* p" and "void f()" in
161
///   int* p;
162
///   void f();
163
/// \endcode
164
///
165
/// Usable as: Any Matcher
166
376
inline internal::TrueMatcher anything() { return internal::TrueMatcher(); }
167
168
/// Matches the top declaration context.
169
///
170
/// Given
171
/// \code
172
///   int X;
173
///   namespace NS {
174
///   int Y;
175
///   }  // namespace NS
176
/// \endcode
177
/// decl(hasDeclContext(translationUnitDecl()))
178
///   matches "int X", but not "int Y".
179
extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
180
    translationUnitDecl;
181
182
/// Matches typedef declarations.
183
///
184
/// Given
185
/// \code
186
///   typedef int X;
187
///   using Y = int;
188
/// \endcode
189
/// typedefDecl()
190
///   matches "typedef int X", but not "using Y = int"
191
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl>
192
    typedefDecl;
193
194
/// Matches typedef name declarations.
195
///
196
/// Given
197
/// \code
198
///   typedef int X;
199
///   using Y = int;
200
/// \endcode
201
/// typedefNameDecl()
202
///   matches "typedef int X" and "using Y = int"
203
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
204
    typedefNameDecl;
205
206
/// Matches type alias declarations.
207
///
208
/// Given
209
/// \code
210
///   typedef int X;
211
///   using Y = int;
212
/// \endcode
213
/// typeAliasDecl()
214
///   matches "using Y = int", but not "typedef int X"
215
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl>
216
    typeAliasDecl;
217
218
/// Matches type alias template declarations.
219
///
220
/// typeAliasTemplateDecl() matches
221
/// \code
222
///   template <typename T>
223
///   using Y = X<T>;
224
/// \endcode
225
extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
226
    typeAliasTemplateDecl;
227
228
/// Matches AST nodes that were expanded within the main-file.
229
///
230
/// Example matches X but not Y
231
///   (matcher = cxxRecordDecl(isExpansionInMainFile())
232
/// \code
233
///   #include <Y.h>
234
///   class X {};
235
/// \endcode
236
/// Y.h:
237
/// \code
238
///   class Y {};
239
/// \endcode
240
///
241
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
242
AST_POLYMORPHIC_MATCHER(isExpansionInMainFile,
243
0
                        AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
244
0
  auto &SourceManager = Finder->getASTContext().getSourceManager();
245
0
  return SourceManager.isInMainFile(
246
0
      SourceManager.getExpansionLoc(Node.getBeginLoc()));
247
0
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInMainFileMatcher<clang::Decl>::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInMainFileMatcher<clang::Stmt>::matches(clang::Stmt const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInMainFileMatcher<clang::TypeLoc>::matches(clang::TypeLoc const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
248
249
/// Matches AST nodes that were expanded within system-header-files.
250
///
251
/// Example matches Y but not X
252
///     (matcher = cxxRecordDecl(isExpansionInSystemHeader())
253
/// \code
254
///   #include <SystemHeader.h>
255
///   class X {};
256
/// \endcode
257
/// SystemHeader.h:
258
/// \code
259
///   class Y {};
260
/// \endcode
261
///
262
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
263
AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader,
264
0
                        AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) {
265
0
  auto &SourceManager = Finder->getASTContext().getSourceManager();
266
0
  auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
267
0
  if (ExpansionLoc.isInvalid()) {
268
0
    return false;
269
0
  }
270
0
  return SourceManager.isInSystemHeader(ExpansionLoc);
271
0
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInSystemHeaderMatcher<clang::Decl>::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInSystemHeaderMatcher<clang::Stmt>::matches(clang::Stmt const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInSystemHeaderMatcher<clang::TypeLoc>::matches(clang::TypeLoc const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
272
273
/// Matches AST nodes that were expanded within files whose name is
274
/// partially matching a given regex.
275
///
276
/// Example matches Y but not X
277
///     (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*"))
278
/// \code
279
///   #include "ASTMatcher.h"
280
///   class X {};
281
/// \endcode
282
/// ASTMatcher.h:
283
/// \code
284
///   class Y {};
285
/// \endcode
286
///
287
/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc>
288
AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching,
289
                              AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt,
290
                                                              TypeLoc),
291
0
                              RegExp) {
292
0
  auto &SourceManager = Finder->getASTContext().getSourceManager();
293
0
  auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc());
294
0
  if (ExpansionLoc.isInvalid()) {
295
0
    return false;
296
0
  }
297
0
  auto FileEntry =
298
0
      SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc));
299
0
  if (!FileEntry) {
300
0
    return false;
301
0
  }
302
303
0
  auto Filename = FileEntry->getName();
304
0
  return RegExp->match(Filename);
305
0
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInFileMatching0Matcher<clang::Decl, std::__1::shared_ptr<llvm::Regex> >::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInFileMatching0Matcher<clang::Stmt, std::__1::shared_ptr<llvm::Regex> >::matches(clang::Stmt const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpansionInFileMatching0Matcher<clang::TypeLoc, std::__1::shared_ptr<llvm::Regex> >::matches(clang::TypeLoc const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
306
307
/// Matches statements that are (transitively) expanded from the named macro.
308
/// Does not match if only part of the statement is expanded from that macro or
309
/// if different parts of the the statement are expanded from different
310
/// appearances of the macro.
311
AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro,
312
                          AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc),
313
32
                          std::string, MacroName) {
314
  // Verifies that the statement' beginning and ending are both expanded from
315
  // the same instance of the given macro.
316
32
  auto& Context = Finder->getASTContext();
317
32
  llvm::Optional<SourceLocation> B =
318
32
      internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
319
32
  if (!B) 
return false14
;
320
18
  llvm::Optional<SourceLocation> E =
321
18
      internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
322
18
  if (!E) 
return false0
;
323
18
  return *B == *E;
324
18
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpandedFromMacro0Matcher<clang::Decl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isExpandedFromMacro0Matcher<clang::Stmt, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::Stmt const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
clang::ast_matchers::internal::matcher_isExpandedFromMacro0Matcher<clang::TypeLoc, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::TypeLoc const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
313
12
                          std::string, MacroName) {
314
  // Verifies that the statement' beginning and ending are both expanded from
315
  // the same instance of the given macro.
316
12
  auto& Context = Finder->getASTContext();
317
12
  llvm::Optional<SourceLocation> B =
318
12
      internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
319
12
  if (!B) 
return false10
;
320
2
  llvm::Optional<SourceLocation> E =
321
2
      internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
322
2
  if (!E) 
return false0
;
323
2
  return *B == *E;
324
2
}
clang::ast_matchers::internal::matcher_isExpandedFromMacro0Matcher<clang::CallExpr, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::CallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
313
20
                          std::string, MacroName) {
314
  // Verifies that the statement' beginning and ending are both expanded from
315
  // the same instance of the given macro.
316
20
  auto& Context = Finder->getASTContext();
317
20
  llvm::Optional<SourceLocation> B =
318
20
      internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context);
319
20
  if (!B) 
return false4
;
320
16
  llvm::Optional<SourceLocation> E =
321
16
      internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context);
322
16
  if (!E) 
return false0
;
323
16
  return *B == *E;
324
16
}
325
326
/// Matches declarations.
327
///
328
/// Examples matches \c X, \c C, and the friend declaration inside \c C;
329
/// \code
330
///   void X();
331
///   class C {
332
///     friend X;
333
///   };
334
/// \endcode
335
extern const internal::VariadicAllOfMatcher<Decl> decl;
336
337
/// Matches decomposition-declarations.
338
///
339
/// Examples matches the declaration node with \c foo and \c bar, but not
340
/// \c number.
341
/// (matcher = declStmt(has(decompositionDecl())))
342
///
343
/// \code
344
///   int number = 42;
345
///   auto [foo, bar] = std::make_pair{42, 42};
346
/// \endcode
347
extern const internal::VariadicAllOfMatcher<DecompositionDecl>
348
    decompositionDecl;
349
350
/// Matches a declaration of a linkage specification.
351
///
352
/// Given
353
/// \code
354
///   extern "C" {}
355
/// \endcode
356
/// linkageSpecDecl()
357
///   matches "extern "C" {}"
358
extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
359
    linkageSpecDecl;
360
361
/// Matches a declaration of anything that could have a name.
362
///
363
/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
364
/// \code
365
///   typedef int X;
366
///   struct S {
367
///     union {
368
///       int i;
369
///     } U;
370
///   };
371
/// \endcode
372
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
373
374
/// Matches a declaration of label.
375
///
376
/// Given
377
/// \code
378
///   goto FOO;
379
///   FOO: bar();
380
/// \endcode
381
/// labelDecl()
382
///   matches 'FOO:'
383
extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
384
385
/// Matches a declaration of a namespace.
386
///
387
/// Given
388
/// \code
389
///   namespace {}
390
///   namespace test {}
391
/// \endcode
392
/// namespaceDecl()
393
///   matches "namespace {}" and "namespace test {}"
394
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl>
395
    namespaceDecl;
396
397
/// Matches a declaration of a namespace alias.
398
///
399
/// Given
400
/// \code
401
///   namespace test {}
402
///   namespace alias = ::test;
403
/// \endcode
404
/// namespaceAliasDecl()
405
///   matches "namespace alias" but not "namespace test"
406
extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
407
    namespaceAliasDecl;
408
409
/// Matches class, struct, and union declarations.
410
///
411
/// Example matches \c X, \c Z, \c U, and \c S
412
/// \code
413
///   class X;
414
///   template<class T> class Z {};
415
///   struct S {};
416
///   union U {};
417
/// \endcode
418
extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
419
420
/// Matches C++ class declarations.
421
///
422
/// Example matches \c X, \c Z
423
/// \code
424
///   class X;
425
///   template<class T> class Z {};
426
/// \endcode
427
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl>
428
    cxxRecordDecl;
429
430
/// Matches C++ class template declarations.
431
///
432
/// Example matches \c Z
433
/// \code
434
///   template<class T> class Z {};
435
/// \endcode
436
extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
437
    classTemplateDecl;
438
439
/// Matches C++ class template specializations.
440
///
441
/// Given
442
/// \code
443
///   template<typename T> class A {};
444
///   template<> class A<double> {};
445
///   A<int> a;
446
/// \endcode
447
/// classTemplateSpecializationDecl()
448
///   matches the specializations \c A<int> and \c A<double>
449
extern const internal::VariadicDynCastAllOfMatcher<
450
    Decl, ClassTemplateSpecializationDecl>
451
    classTemplateSpecializationDecl;
452
453
/// Matches C++ class template partial specializations.
454
///
455
/// Given
456
/// \code
457
///   template<class T1, class T2, int I>
458
///   class A {};
459
///
460
///   template<class T, int I>
461
///   class A<T, T*, I> {};
462
///
463
///   template<>
464
///   class A<int, int, 1> {};
465
/// \endcode
466
/// classTemplatePartialSpecializationDecl()
467
///   matches the specialization \c A<T,T*,I> but not \c A<int,int,1>
468
extern const internal::VariadicDynCastAllOfMatcher<
469
    Decl, ClassTemplatePartialSpecializationDecl>
470
    classTemplatePartialSpecializationDecl;
471
472
/// Matches declarator declarations (field, variable, function
473
/// and non-type template parameter declarations).
474
///
475
/// Given
476
/// \code
477
///   class X { int y; };
478
/// \endcode
479
/// declaratorDecl()
480
///   matches \c int y.
481
extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
482
    declaratorDecl;
483
484
/// Matches parameter variable declarations.
485
///
486
/// Given
487
/// \code
488
///   void f(int x);
489
/// \endcode
490
/// parmVarDecl()
491
///   matches \c int x.
492
extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl>
493
    parmVarDecl;
494
495
/// Matches C++ access specifier declarations.
496
///
497
/// Given
498
/// \code
499
///   class C {
500
///   public:
501
///     int a;
502
///   };
503
/// \endcode
504
/// accessSpecDecl()
505
///   matches 'public:'
506
extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
507
    accessSpecDecl;
508
509
/// Matches constructor initializers.
510
///
511
/// Examples matches \c i(42).
512
/// \code
513
///   class C {
514
///     C() : i(42) {}
515
///     int i;
516
///   };
517
/// \endcode
518
extern const internal::VariadicAllOfMatcher<CXXCtorInitializer>
519
    cxxCtorInitializer;
520
521
/// Matches template arguments.
522
///
523
/// Given
524
/// \code
525
///   template <typename T> struct C {};
526
///   C<int> c;
527
/// \endcode
528
/// templateArgument()
529
///   matches 'int' in C<int>.
530
extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
531
532
/// Matches template arguments (with location info).
533
///
534
/// Given
535
/// \code
536
///   template <typename T> struct C {};
537
///   C<int> c;
538
/// \endcode
539
/// templateArgumentLoc()
540
///   matches 'int' in C<int>.
541
extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc>
542
    templateArgumentLoc;
543
544
/// Matches template name.
545
///
546
/// Given
547
/// \code
548
///   template <typename T> class X { };
549
///   X<int> xi;
550
/// \endcode
551
/// templateName()
552
///   matches 'X' in X<int>.
553
extern const internal::VariadicAllOfMatcher<TemplateName> templateName;
554
555
/// Matches non-type template parameter declarations.
556
///
557
/// Given
558
/// \code
559
///   template <typename T, int N> struct C {};
560
/// \endcode
561
/// nonTypeTemplateParmDecl()
562
///   matches 'N', but not 'T'.
563
extern const internal::VariadicDynCastAllOfMatcher<Decl,
564
                                                   NonTypeTemplateParmDecl>
565
    nonTypeTemplateParmDecl;
566
567
/// Matches template type parameter declarations.
568
///
569
/// Given
570
/// \code
571
///   template <typename T, int N> struct C {};
572
/// \endcode
573
/// templateTypeParmDecl()
574
///   matches 'T', but not 'N'.
575
extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
576
    templateTypeParmDecl;
577
578
/// Matches template template parameter declarations.
579
///
580
/// Given
581
/// \code
582
///   template <template <typename> class Z, int N> struct C {};
583
/// \endcode
584
/// templateTypeParmDecl()
585
///   matches 'Z', but not 'N'.
586
extern const internal::VariadicDynCastAllOfMatcher<Decl,
587
                                                   TemplateTemplateParmDecl>
588
    templateTemplateParmDecl;
589
590
/// Matches public C++ declarations and C++ base specifers that specify public
591
/// inheritance.
592
///
593
/// Examples:
594
/// \code
595
///   class C {
596
///   public:    int a; // fieldDecl(isPublic()) matches 'a'
597
///   protected: int b;
598
///   private:   int c;
599
///   };
600
/// \endcode
601
///
602
/// \code
603
///   class Base {};
604
///   class Derived1 : public Base {}; // matches 'Base'
605
///   struct Derived2 : Base {}; // matches 'Base'
606
/// \endcode
607
AST_POLYMORPHIC_MATCHER(isPublic,
608
                        AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
609
100
                                                        CXXBaseSpecifier)) {
610
100
  return getAccessSpecifier(Node) == AS_public;
611
100
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isPublicMatcher<clang::Decl>::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
clang::ast_matchers::internal::matcher_isPublicMatcher<clang::CXXBaseSpecifier>::matches(clang::CXXBaseSpecifier const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
609
100
                                                        CXXBaseSpecifier)) {
610
100
  return getAccessSpecifier(Node) == AS_public;
611
100
}
612
613
/// Matches protected C++ declarations and C++ base specifers that specify
614
/// protected inheritance.
615
///
616
/// Examples:
617
/// \code
618
///   class C {
619
///   public:    int a;
620
///   protected: int b; // fieldDecl(isProtected()) matches 'b'
621
///   private:   int c;
622
///   };
623
/// \endcode
624
///
625
/// \code
626
///   class Base {};
627
///   class Derived : protected Base {}; // matches 'Base'
628
/// \endcode
629
AST_POLYMORPHIC_MATCHER(isProtected,
630
                        AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
631
60
                                                        CXXBaseSpecifier)) {
632
60
  return getAccessSpecifier(Node) == AS_protected;
633
60
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isProtectedMatcher<clang::Decl>::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
clang::ast_matchers::internal::matcher_isProtectedMatcher<clang::CXXBaseSpecifier>::matches(clang::CXXBaseSpecifier const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
631
60
                                                        CXXBaseSpecifier)) {
632
60
  return getAccessSpecifier(Node) == AS_protected;
633
60
}
634
635
/// Matches private C++ declarations and C++ base specifers that specify private
636
/// inheritance.
637
///
638
/// Examples:
639
/// \code
640
///   class C {
641
///   public:    int a;
642
///   protected: int b;
643
///   private:   int c; // fieldDecl(isPrivate()) matches 'c'
644
///   };
645
/// \endcode
646
///
647
/// \code
648
///   struct Base {};
649
///   struct Derived1 : private Base {}; // matches 'Base'
650
///   class Derived2 : Base {}; // matches 'Base'
651
/// \endcode
652
AST_POLYMORPHIC_MATCHER(isPrivate,
653
                        AST_POLYMORPHIC_SUPPORTED_TYPES(Decl,
654
100
                                                        CXXBaseSpecifier)) {
655
100
  return getAccessSpecifier(Node) == AS_private;
656
100
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_isPrivateMatcher<clang::Decl>::matches(clang::Decl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
clang::ast_matchers::internal::matcher_isPrivateMatcher<clang::CXXBaseSpecifier>::matches(clang::CXXBaseSpecifier const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
654
100
                                                        CXXBaseSpecifier)) {
655
100
  return getAccessSpecifier(Node) == AS_private;
656
100
}
657
658
/// Matches non-static data members that are bit-fields.
659
///
660
/// Given
661
/// \code
662
///   class C {
663
///     int a : 2;
664
///     int b;
665
///   };
666
/// \endcode
667
/// fieldDecl(isBitField())
668
///   matches 'int a;' but not 'int b;'.
669
168
AST_MATCHER(FieldDecl, isBitField) {
670
168
  return Node.isBitField();
671
168
}
672
673
/// Matches non-static data members that are bit-fields of the specified
674
/// bit width.
675
///
676
/// Given
677
/// \code
678
///   class C {
679
///     int a : 2;
680
///     int b : 4;
681
///     int c : 2;
682
///   };
683
/// \endcode
684
/// fieldDecl(hasBitWidth(2))
685
///   matches 'int a;' and 'int c;' but not 'int b;'.
686
56
AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) {
687
56
  return Node.isBitField() &&
688
56
         Node.getBitWidthValue(Finder->getASTContext()) == Width;
689
56
}
690
691
/// Matches non-static data members that have an in-class initializer.
692
///
693
/// Given
694
/// \code
695
///   class C {
696
///     int a = 2;
697
///     int b = 3;
698
///     int c;
699
///   };
700
/// \endcode
701
/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2))))
702
///   matches 'int a;' but not 'int b;'.
703
/// fieldDecl(hasInClassInitializer(anything()))
704
///   matches 'int a;' and 'int b;' but not 'int c;'.
705
AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>,
706
80
              InnerMatcher) {
707
80
  const Expr *Initializer = Node.getInClassInitializer();
708
80
  return (Initializer != nullptr &&
709
40
          InnerMatcher.matches(*Initializer, Finder, Builder));
710
80
}
711
712
/// Determines whether the function is "main", which is the entry point
713
/// into an executable program.
714
247
AST_MATCHER(FunctionDecl, isMain) {
715
247
  return Node.isMain();
716
247
}
717
718
/// Matches the specialized template of a specialization declaration.
719
///
720
/// Given
721
/// \code
722
///   template<typename T> class A {}; #1
723
///   template<> class A<int> {}; #2
724
/// \endcode
725
/// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl()))
726
///   matches '#2' with classTemplateDecl() matching the class template
727
///   declaration of 'A' at #1.
728
AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate,
729
10
              internal::Matcher<ClassTemplateDecl>, InnerMatcher) {
730
10
  const ClassTemplateDecl* Decl = Node.getSpecializedTemplate();
731
10
  return (Decl != nullptr &&
732
10
          InnerMatcher.matches(*Decl, Finder, Builder));
733
10
}
734
735
/// Matches a declaration that has been implicitly added
736
/// by the compiler (eg. implicit default/copy constructors).
737
3.89k
AST_MATCHER(Decl, isImplicit) {
738
3.89k
  return Node.isImplicit();
739
3.89k
}
740
741
/// Matches classTemplateSpecializations, templateSpecializationType and
742
/// functionDecl that have at least one TemplateArgument matching the given
743
/// InnerMatcher.
744
///
745
/// Given
746
/// \code
747
///   template<typename T> class A {};
748
///   template<> class A<double> {};
749
///   A<int> a;
750
///
751
///   template<typename T> f() {};
752
///   void func() { f<int>(); };
753
/// \endcode
754
///
755
/// \endcode
756
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
757
///     refersToType(asString("int"))))
758
///   matches the specialization \c A<int>
759
///
760
/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int"))))
761
///   matches the specialization \c f<int>
762
AST_POLYMORPHIC_MATCHER_P(
763
    hasAnyTemplateArgument,
764
    AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
765
                                    TemplateSpecializationType,
766
                                    FunctionDecl),
767
172
    internal::Matcher<TemplateArgument>, InnerMatcher) {
768
172
  ArrayRef<TemplateArgument> List =
769
172
      internal::getTemplateSpecializationArgs(Node);
770
172
  return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
771
172
                             Builder) != List.end();
772
172
}
clang::ast_matchers::internal::matcher_hasAnyTemplateArgument0Matcher<clang::ClassTemplateSpecializationDecl, clang::ast_matchers::internal::Matcher<clang::TemplateArgument> >::matches(clang::ClassTemplateSpecializationDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
767
160
    internal::Matcher<TemplateArgument>, InnerMatcher) {
768
160
  ArrayRef<TemplateArgument> List =
769
160
      internal::getTemplateSpecializationArgs(Node);
770
160
  return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
771
160
                             Builder) != List.end();
772
160
}
clang::ast_matchers::internal::matcher_hasAnyTemplateArgument0Matcher<clang::TemplateSpecializationType, clang::ast_matchers::internal::Matcher<clang::TemplateArgument> >::matches(clang::TemplateSpecializationType const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
767
6
    internal::Matcher<TemplateArgument>, InnerMatcher) {
768
6
  ArrayRef<TemplateArgument> List =
769
6
      internal::getTemplateSpecializationArgs(Node);
770
6
  return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
771
6
                             Builder) != List.end();
772
6
}
clang::ast_matchers::internal::matcher_hasAnyTemplateArgument0Matcher<clang::FunctionDecl, clang::ast_matchers::internal::Matcher<clang::TemplateArgument> >::matches(clang::FunctionDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
767
6
    internal::Matcher<TemplateArgument>, InnerMatcher) {
768
6
  ArrayRef<TemplateArgument> List =
769
6
      internal::getTemplateSpecializationArgs(Node);
770
6
  return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder,
771
6
                             Builder) != List.end();
772
6
}
773
774
/// Causes all nested matchers to be matched with the specified traversal kind.
775
///
776
/// Given
777
/// \code
778
///   void foo()
779
///   {
780
///       int i = 3.0;
781
///   }
782
/// \endcode
783
/// The matcher
784
/// \code
785
///   traverse(TK_IgnoreUnlessSpelledInSource,
786
///     varDecl(hasInitializer(floatLiteral().bind("init")))
787
///   )
788
/// \endcode
789
/// matches the variable declaration with "init" bound to the "3.0".
790
template <typename T>
791
internal::Matcher<T> traverse(TraversalKind TK,
792
481
                              const internal::Matcher<T> &InnerMatcher) {
793
481
  return internal::DynTypedMatcher::constructRestrictedWrapper(
794
481
             new internal::TraversalMatcher<T>(TK, InnerMatcher),
795
481
             InnerMatcher.getID().first)
796
481
      .template unconditionalConvertTo<T>();
797
481
}
798
799
template <typename T>
800
internal::BindableMatcher<T>
801
822
traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) {
802
822
  return internal::BindableMatcher<T>(
803
822
      internal::DynTypedMatcher::constructRestrictedWrapper(
804
822
          new internal::TraversalMatcher<T>(TK, InnerMatcher),
805
822
          InnerMatcher.getID().first)
806
822
          .template unconditionalConvertTo<T>());
807
822
}
808
809
template <typename... T>
810
internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>
811
traverse(TraversalKind TK,
812
         const internal::VariadicOperatorMatcher<T...> &InnerMatcher) {
813
  return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>(
814
      TK, InnerMatcher);
815
}
816
817
template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
818
          typename T, typename ToTypes>
819
internal::TraversalWrapper<
820
    internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>
821
traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor<
822
                               ArgumentAdapterT, T, ToTypes> &InnerMatcher) {
823
  return internal::TraversalWrapper<
824
      internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T,
825
                                                   ToTypes>>(TK, InnerMatcher);
826
}
827
828
template <template <typename T, typename P1> class MatcherT, typename P1,
829
          typename ReturnTypesF>
830
internal::TraversalWrapper<
831
    internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>
832
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam1<
833
                               MatcherT, P1, ReturnTypesF> &InnerMatcher) {
834
  return internal::TraversalWrapper<
835
      internal::PolymorphicMatcherWithParam1<MatcherT, P1, ReturnTypesF>>(
836
      TK, InnerMatcher);
837
}
838
839
template <template <typename T, typename P1, typename P2> class MatcherT,
840
          typename P1, typename P2, typename ReturnTypesF>
841
internal::TraversalWrapper<
842
    internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>
843
traverse(TraversalKind TK, const internal::PolymorphicMatcherWithParam2<
844
                               MatcherT, P1, P2, ReturnTypesF> &InnerMatcher) {
845
  return internal::TraversalWrapper<
846
      internal::PolymorphicMatcherWithParam2<MatcherT, P1, P2, ReturnTypesF>>(
847
      TK, InnerMatcher);
848
}
849
850
template <typename... T>
851
internal::Matcher<typename internal::GetClade<T...>::Type>
852
traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) {
853
  return traverse(TK, InnerMatcher.with());
854
}
855
856
/// Matches expressions that match InnerMatcher after any implicit AST
857
/// nodes are stripped off.
858
///
859
/// Parentheses and explicit casts are not discarded.
860
/// Given
861
/// \code
862
///   class C {};
863
///   C a = C();
864
///   C b;
865
///   C c = b;
866
/// \endcode
867
/// The matchers
868
/// \code
869
///    varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr())))
870
/// \endcode
871
/// would match the declarations for a, b, and c.
872
/// While
873
/// \code
874
///    varDecl(hasInitializer(cxxConstructExpr()))
875
/// \endcode
876
/// only match the declarations for b and c.
877
AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>,
878
133
              InnerMatcher) {
879
133
  return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder);
880
133
}
881
882
/// Matches expressions that match InnerMatcher after any implicit casts
883
/// are stripped off.
884
///
885
/// Parentheses and explicit casts are not discarded.
886
/// Given
887
/// \code
888
///   int arr[5];
889
///   int a = 0;
890
///   char b = 0;
891
///   const int c = a;
892
///   int *d = arr;
893
///   long e = (long) 0l;
894
/// \endcode
895
/// The matchers
896
/// \code
897
///    varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
898
///    varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
899
/// \endcode
900
/// would match the declarations for a, b, c, and d, but not e.
901
/// While
902
/// \code
903
///    varDecl(hasInitializer(integerLiteral()))
904
///    varDecl(hasInitializer(declRefExpr()))
905
/// \endcode
906
/// only match the declarations for b, c, and d.
907
AST_MATCHER_P(Expr, ignoringImpCasts,
908
355
              internal::Matcher<Expr>, InnerMatcher) {
909
355
  return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
910
355
}
911
912
/// Matches expressions that match InnerMatcher after parentheses and
913
/// casts are stripped off.
914
///
915
/// Implicit and non-C Style casts are also discarded.
916
/// Given
917
/// \code
918
///   int a = 0;
919
///   char b = (0);
920
///   void* c = reinterpret_cast<char*>(0);
921
///   char d = char(0);
922
/// \endcode
923
/// The matcher
924
///    varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
925
/// would match the declarations for a, b, c, and d.
926
/// while
927
///    varDecl(hasInitializer(integerLiteral()))
928
/// only match the declaration for a.
929
90
AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
930
90
  return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
931
90
}
932
933
/// Matches expressions that match InnerMatcher after implicit casts and
934
/// parentheses are stripped off.
935
///
936
/// Explicit casts are not discarded.
937
/// Given
938
/// \code
939
///   int arr[5];
940
///   int a = 0;
941
///   char b = (0);
942
///   const int c = a;
943
///   int *d = (arr);
944
///   long e = ((long) 0l);
945
/// \endcode
946
/// The matchers
947
///    varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
948
///    varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
949
/// would match the declarations for a, b, c, and d, but not e.
950
/// while
951
///    varDecl(hasInitializer(integerLiteral()))
952
///    varDecl(hasInitializer(declRefExpr()))
953
/// would only match the declaration for a.
954
AST_MATCHER_P(Expr, ignoringParenImpCasts,
955
2.89k
              internal::Matcher<Expr>, InnerMatcher) {
956
2.89k
  return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
957
2.89k
}
958
959
/// Matches types that match InnerMatcher after any parens are stripped.
960
///
961
/// Given
962
/// \code
963
///   void (*fp)(void);
964
/// \endcode
965
/// The matcher
966
/// \code
967
///   varDecl(hasType(pointerType(pointee(ignoringParens(functionType())))))
968
/// \endcode
969
/// would match the declaration for fp.
970
AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>,
971
70
                       InnerMatcher, 0) {
972
70
  return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder);
973
70
}
974
975
/// Overload \c ignoringParens for \c Expr.
976
///
977
/// Given
978
/// \code
979
///   const char* str = ("my-string");
980
/// \endcode
981
/// The matcher
982
/// \code
983
///   implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral())))
984
/// \endcode
985
/// would match the implicit cast resulting from the assignment.
986
AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>,
987
17.2k
                       InnerMatcher, 1) {
988
17.2k
  const Expr *E = Node.IgnoreParens();
989
17.2k
  return InnerMatcher.matches(*E, Finder, Builder);
990
17.2k
}
991
992
/// Matches expressions that are instantiation-dependent even if it is
993
/// neither type- nor value-dependent.
994
///
995
/// In the following example, the expression sizeof(sizeof(T() + T()))
996
/// is instantiation-dependent (since it involves a template parameter T),
997
/// but is neither type- nor value-dependent, since the type of the inner
998
/// sizeof is known (std::size_t) and therefore the size of the outer
999
/// sizeof is known.
1000
/// \code
1001
///   template<typename T>
1002
///   void f(T x, T y) { sizeof(sizeof(T() + T()); }
1003
/// \endcode
1004
/// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T())
1005
100
AST_MATCHER(Expr, isInstantiationDependent) {
1006
100
  return Node.isInstantiationDependent();
1007
100
}
1008
1009
/// Matches expressions that are type-dependent because the template type
1010
/// is not yet instantiated.
1011
///
1012
/// For example, the expressions "x" and "x + y" are type-dependent in
1013
/// the following code, but "y" is not type-dependent:
1014
/// \code
1015
///   template<typename T>
1016
///   void add(T x, int y) {
1017
///     x + y;
1018
///   }
1019
/// \endcode
1020
/// expr(isTypeDependent()) matches x + y
1021
321
AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); }
1022
1023
/// Matches expression that are value-dependent because they contain a
1024
/// non-type template parameter.
1025
///
1026
/// For example, the array bound of "Chars" in the following example is
1027
/// value-dependent.
1028
/// \code
1029
///   template<int Size> int f() { return Size; }
1030
/// \endcode
1031
/// expr(isValueDependent()) matches return Size
1032
100
AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); }
1033
1034
/// Matches classTemplateSpecializations, templateSpecializationType and
1035
/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher.
1036
///
1037
/// Given
1038
/// \code
1039
///   template<typename T, typename U> class A {};
1040
///   A<bool, int> b;
1041
///   A<int, bool> c;
1042
///
1043
///   template<typename T> void f() {}
1044
///   void func() { f<int>(); };
1045
/// \endcode
1046
/// classTemplateSpecializationDecl(hasTemplateArgument(
1047
///     1, refersToType(asString("int"))))
1048
///   matches the specialization \c A<bool, int>
1049
///
1050
/// functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))
1051
///   matches the specialization \c f<int>
1052
AST_POLYMORPHIC_MATCHER_P2(
1053
    hasTemplateArgument,
1054
    AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
1055
                                    TemplateSpecializationType,
1056
                                    FunctionDecl),
1057
104
    unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1058
104
  ArrayRef<TemplateArgument> List =
1059
104
      internal::getTemplateSpecializationArgs(Node);
1060
104
  if (List.size() <= N)
1061
10
    return false;
1062
94
  return InnerMatcher.matches(List[N], Finder, Builder);
1063
94
}
clang::ast_matchers::internal::matcher_hasTemplateArgument0Matcher<clang::ClassTemplateSpecializationDecl, unsigned int, clang::ast_matchers::internal::Matcher<clang::TemplateArgument> >::matches(clang::ClassTemplateSpecializationDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
1057
78
    unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1058
78
  ArrayRef<TemplateArgument> List =
1059
78
      internal::getTemplateSpecializationArgs(Node);
1060
78
  if (List.size() <= N)
1061
0
    return false;
1062
78
  return InnerMatcher.matches(List[N], Finder, Builder);
1063
78
}
clang::ast_matchers::internal::matcher_hasTemplateArgument0Matcher<clang::TemplateSpecializationType, unsigned int, clang::ast_matchers::internal::Matcher<clang::TemplateArgument> >::matches(clang::TemplateSpecializationType const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
1057
4
    unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1058
4
  ArrayRef<TemplateArgument> List =
1059
4
      internal::getTemplateSpecializationArgs(Node);
1060
4
  if (List.size() <= N)
1061
0
    return false;
1062
4
  return InnerMatcher.matches(List[N], Finder, Builder);
1063
4
}
clang::ast_matchers::internal::matcher_hasTemplateArgument0Matcher<clang::FunctionDecl, unsigned int, clang::ast_matchers::internal::Matcher<clang::TemplateArgument> >::matches(clang::FunctionDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
1057
22
    unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
1058
22
  ArrayRef<TemplateArgument> List =
1059
22
      internal::getTemplateSpecializationArgs(Node);
1060
22
  if (List.size() <= N)
1061
10
    return false;
1062
12
  return InnerMatcher.matches(List[N], Finder, Builder);
1063
12
}
1064
1065
/// Matches if the number of template arguments equals \p N.
1066
///
1067
/// Given
1068
/// \code
1069
///   template<typename T> struct C {};
1070
///   C<int> c;
1071
/// \endcode
1072
/// classTemplateSpecializationDecl(templateArgumentCountIs(1))
1073
///   matches C<int>.
1074
AST_POLYMORPHIC_MATCHER_P(
1075
    templateArgumentCountIs,
1076
    AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
1077
                                    TemplateSpecializationType),
1078
80
    unsigned, N) {
1079
80
  return internal::getTemplateSpecializationArgs(Node).size() == N;
1080
80
}
clang::ast_matchers::internal::matcher_templateArgumentCountIs0Matcher<clang::ClassTemplateSpecializationDecl, unsigned int>::matches(clang::ClassTemplateSpecializationDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
1078
40
    unsigned, N) {
1079
40
  return internal::getTemplateSpecializationArgs(Node).size() == N;
1080
40
}
clang::ast_matchers::internal::matcher_templateArgumentCountIs0Matcher<clang::TemplateSpecializationType, unsigned int>::matches(clang::TemplateSpecializationType const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
1078
40
    unsigned, N) {
1079
40
  return internal::getTemplateSpecializationArgs(Node).size() == N;
1080
40
}
1081
1082
/// Matches a TemplateArgument that refers to a certain type.
1083
///
1084
/// Given
1085
/// \code
1086
///   struct X {};
1087
///   template<typename T> struct A {};
1088
///   A<X> a;
1089
/// \endcode
1090
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1091
///     refersToType(class(hasName("X")))))
1092
///   matches the specialization \c A<X>
1093
AST_MATCHER_P(TemplateArgument, refersToType,
1094
104
              internal::Matcher<QualType>, InnerMatcher) {
1095
104
  if (Node.getKind() != TemplateArgument::Type)
1096
0
    return false;
1097
104
  return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
1098
104
}
1099
1100
/// Matches a TemplateArgument that refers to a certain template.
1101
///
1102
/// Given
1103
/// \code
1104
///   template<template <typename> class S> class X {};
1105
///   template<typename T> class Y {};
1106
///   X<Y> xi;
1107
/// \endcode
1108
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1109
///     refersToTemplate(templateName())))
1110
///   matches the specialization \c X<Y>
1111
AST_MATCHER_P(TemplateArgument, refersToTemplate,
1112
2
              internal::Matcher<TemplateName>, InnerMatcher) {
1113
2
  if (Node.getKind() != TemplateArgument::Template)
1114
0
    return false;
1115
2
  return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder);
1116
2
}
1117
1118
/// Matches a canonical TemplateArgument that refers to a certain
1119
/// declaration.
1120
///
1121
/// Given
1122
/// \code
1123
///   struct B { int next; };
1124
///   template<int(B::*next_ptr)> struct A {};
1125
///   A<&B::next> a;
1126
/// \endcode
1127
/// classTemplateSpecializationDecl(hasAnyTemplateArgument(
1128
///     refersToDeclaration(fieldDecl(hasName("next")))))
1129
///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1130
///     \c B::next
1131
AST_MATCHER_P(TemplateArgument, refersToDeclaration,
1132
6
              internal::Matcher<Decl>, InnerMatcher) {
1133
6
  if (Node.getKind() == TemplateArgument::Declaration)
1134
2
    return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
1135
4
  return false;
1136
4
}
1137
1138
/// Matches a sugar TemplateArgument that refers to a certain expression.
1139
///
1140
/// Given
1141
/// \code
1142
///   struct B { int next; };
1143
///   template<int(B::*next_ptr)> struct A {};
1144
///   A<&B::next> a;
1145
/// \endcode
1146
/// templateSpecializationType(hasAnyTemplateArgument(
1147
///   isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))
1148
///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
1149
///     \c B::next
1150
2
AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) {
1151
2
  if (Node.getKind() == TemplateArgument::Expression)
1152
2
    return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder);
1153
0
  return false;
1154
0
}
1155
1156
/// Matches a TemplateArgument that is an integral value.
1157
///
1158
/// Given
1159
/// \code
1160
///   template<int T> struct C {};
1161
///   C<42> c;
1162
/// \endcode
1163
/// classTemplateSpecializationDecl(
1164
///   hasAnyTemplateArgument(isIntegral()))
1165
///   matches the implicit instantiation of C in C<42>
1166
///   with isIntegral() matching 42.
1167
40
AST_MATCHER(TemplateArgument, isIntegral) {
1168
40
  return Node.getKind() == TemplateArgument::Integral;
1169
40
}
1170
1171
/// Matches a TemplateArgument that refers to an integral type.
1172
///
1173
/// Given
1174
/// \code
1175
///   template<int T> struct C {};
1176
///   C<42> c;
1177
/// \endcode
1178
/// classTemplateSpecializationDecl(
1179
///   hasAnyTemplateArgument(refersToIntegralType(asString("int"))))
1180
///   matches the implicit instantiation of C in C<42>.
1181
AST_MATCHER_P(TemplateArgument, refersToIntegralType,
1182
4
              internal::Matcher<QualType>, InnerMatcher) {
1183
4
  if (Node.getKind() != TemplateArgument::Integral)
1184
0
    return false;
1185
4
  return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder);
1186
4
}
1187
1188
/// Matches a TemplateArgument of integral type with a given value.
1189
///
1190
/// Note that 'Value' is a string as the template argument's value is
1191
/// an arbitrary precision integer. 'Value' must be euqal to the canonical
1192
/// representation of that integral value in base 10.
1193
///
1194
/// Given
1195
/// \code
1196
///   template<int T> struct C {};
1197
///   C<42> c;
1198
/// \endcode
1199
/// classTemplateSpecializationDecl(
1200
///   hasAnyTemplateArgument(equalsIntegralValue("42")))
1201
///   matches the implicit instantiation of C in C<42>.
1202
AST_MATCHER_P(TemplateArgument, equalsIntegralValue,
1203
80
              std::string, Value) {
1204
80
  if (Node.getKind() != TemplateArgument::Integral)
1205
0
    return false;
1206
80
  return Node.getAsIntegral().toString(10) == Value;
1207
80
}
1208
1209
/// Matches an Objective-C autorelease pool statement.
1210
///
1211
/// Given
1212
/// \code
1213
///   @autoreleasepool {
1214
///     int x = 0;
1215
///   }
1216
/// \endcode
1217
/// autoreleasePoolStmt(stmt()) matches the declaration of "x"
1218
/// inside the autorelease pool.
1219
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1220
       ObjCAutoreleasePoolStmt> autoreleasePoolStmt;
1221
1222
/// Matches any value declaration.
1223
///
1224
/// Example matches A, B, C and F
1225
/// \code
1226
///   enum X { A, B, C };
1227
///   void F();
1228
/// \endcode
1229
extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
1230
1231
/// Matches C++ constructor declarations.
1232
///
1233
/// Example matches Foo::Foo() and Foo::Foo(int)
1234
/// \code
1235
///   class Foo {
1236
///    public:
1237
///     Foo();
1238
///     Foo(int);
1239
///     int DoSomething();
1240
///   };
1241
/// \endcode
1242
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
1243
    cxxConstructorDecl;
1244
1245
/// Matches explicit C++ destructor declarations.
1246
///
1247
/// Example matches Foo::~Foo()
1248
/// \code
1249
///   class Foo {
1250
///    public:
1251
///     virtual ~Foo();
1252
///   };
1253
/// \endcode
1254
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
1255
    cxxDestructorDecl;
1256
1257
/// Matches enum declarations.
1258
///
1259
/// Example matches X
1260
/// \code
1261
///   enum X {
1262
///     A, B, C
1263
///   };
1264
/// \endcode
1265
extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
1266
1267
/// Matches enum constants.
1268
///
1269
/// Example matches A, B, C
1270
/// \code
1271
///   enum X {
1272
///     A, B, C
1273
///   };
1274
/// \endcode
1275
extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
1276
    enumConstantDecl;
1277
1278
/// Matches tag declarations.
1279
///
1280
/// Example matches X, Z, U, S, E
1281
/// \code
1282
///   class X;
1283
///   template<class T> class Z {};
1284
///   struct S {};
1285
///   union U {};
1286
///   enum E {
1287
///     A, B, C
1288
///   };
1289
/// \endcode
1290
extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
1291
1292
/// Matches method declarations.
1293
///
1294
/// Example matches y
1295
/// \code
1296
///   class X { void y(); };
1297
/// \endcode
1298
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl>
1299
    cxxMethodDecl;
1300
1301
/// Matches conversion operator declarations.
1302
///
1303
/// Example matches the operator.
1304
/// \code
1305
///   class X { operator int() const; };
1306
/// \endcode
1307
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
1308
    cxxConversionDecl;
1309
1310
/// Matches user-defined and implicitly generated deduction guide.
1311
///
1312
/// Example matches the deduction guide.
1313
/// \code
1314
///   template<typename T>
1315
///   class X { X(int) };
1316
///   X(int) -> X<int>;
1317
/// \endcode
1318
extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
1319
    cxxDeductionGuideDecl;
1320
1321
/// Matches variable declarations.
1322
///
1323
/// Note: this does not match declarations of member variables, which are
1324
/// "field" declarations in Clang parlance.
1325
///
1326
/// Example matches a
1327
/// \code
1328
///   int a;
1329
/// \endcode
1330
extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
1331
1332
/// Matches field declarations.
1333
///
1334
/// Given
1335
/// \code
1336
///   class X { int m; };
1337
/// \endcode
1338
/// fieldDecl()
1339
///   matches 'm'.
1340
extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
1341
1342
/// Matches indirect field declarations.
1343
///
1344
/// Given
1345
/// \code
1346
///   struct X { struct { int a; }; };
1347
/// \endcode
1348
/// indirectFieldDecl()
1349
///   matches 'a'.
1350
extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
1351
    indirectFieldDecl;
1352
1353
/// Matches function declarations.
1354
///
1355
/// Example matches f
1356
/// \code
1357
///   void f();
1358
/// \endcode
1359
extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl>
1360
    functionDecl;
1361
1362
/// Matches C++ function template declarations.
1363
///
1364
/// Example matches f
1365
/// \code
1366
///   template<class T> void f(T t) {}
1367
/// \endcode
1368
extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
1369
    functionTemplateDecl;
1370
1371
/// Matches friend declarations.
1372
///
1373
/// Given
1374
/// \code
1375
///   class X { friend void foo(); };
1376
/// \endcode
1377
/// friendDecl()
1378
///   matches 'friend void foo()'.
1379
extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
1380
1381
/// Matches statements.
1382
///
1383
/// Given
1384
/// \code
1385
///   { ++a; }
1386
/// \endcode
1387
/// stmt()
1388
///   matches both the compound statement '{ ++a; }' and '++a'.
1389
extern const internal::VariadicAllOfMatcher<Stmt> stmt;
1390
1391
/// Matches declaration statements.
1392
///
1393
/// Given
1394
/// \code
1395
///   int a;
1396
/// \endcode
1397
/// declStmt()
1398
///   matches 'int a'.
1399
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
1400
1401
/// Matches member expressions.
1402
///
1403
/// Given
1404
/// \code
1405
///   class Y {
1406
///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
1407
///     int a; static int b;
1408
///   };
1409
/// \endcode
1410
/// memberExpr()
1411
///   matches this->x, x, y.x, a, this->b
1412
extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
1413
1414
/// Matches unresolved member expressions.
1415
///
1416
/// Given
1417
/// \code
1418
///   struct X {
1419
///     template <class T> void f();
1420
///     void g();
1421
///   };
1422
///   template <class T> void h() { X x; x.f<T>(); x.g(); }
1423
/// \endcode
1424
/// unresolvedMemberExpr()
1425
///   matches x.f<T>
1426
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
1427
    unresolvedMemberExpr;
1428
1429
/// Matches member expressions where the actual member referenced could not be
1430
/// resolved because the base expression or the member name was dependent.
1431
///
1432
/// Given
1433
/// \code
1434
///   template <class T> void f() { T t; t.g(); }
1435
/// \endcode
1436
/// cxxDependentScopeMemberExpr()
1437
///   matches t.g
1438
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1439
                                                   CXXDependentScopeMemberExpr>
1440
    cxxDependentScopeMemberExpr;
1441
1442
/// Matches call expressions.
1443
///
1444
/// Example matches x.y() and y()
1445
/// \code
1446
///   X x;
1447
///   x.y();
1448
///   y();
1449
/// \endcode
1450
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
1451
1452
/// Matches call expressions which were resolved using ADL.
1453
///
1454
/// Example matches y(x) but not y(42) or NS::y(x).
1455
/// \code
1456
///   namespace NS {
1457
///     struct X {};
1458
///     void y(X);
1459
///   }
1460
///
1461
///   void y(...);
1462
///
1463
///   void test() {
1464
///     NS::X x;
1465
///     y(x); // Matches
1466
///     NS::y(x); // Doesn't match
1467
///     y(42); // Doesn't match
1468
///     using NS::y;
1469
///     y(x); // Found by both unqualified lookup and ADL, doesn't match
1470
//    }
1471
/// \endcode
1472
200
AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); }
1473
1474
/// Matches lambda expressions.
1475
///
1476
/// Example matches [&](){return 5;}
1477
/// \code
1478
///   [&](){return 5;}
1479
/// \endcode
1480
extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
1481
1482
/// Matches member call expressions.
1483
///
1484
/// Example matches x.y()
1485
/// \code
1486
///   X x;
1487
///   x.y();
1488
/// \endcode
1489
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
1490
    cxxMemberCallExpr;
1491
1492
/// Matches ObjectiveC Message invocation expressions.
1493
///
1494
/// The innermost message send invokes the "alloc" class method on the
1495
/// NSString class, while the outermost message send invokes the
1496
/// "initWithString" instance method on the object returned from
1497
/// NSString's "alloc". This matcher should match both message sends.
1498
/// \code
1499
///   [[NSString alloc] initWithString:@"Hello"]
1500
/// \endcode
1501
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
1502
    objcMessageExpr;
1503
1504
/// Matches Objective-C interface declarations.
1505
///
1506
/// Example matches Foo
1507
/// \code
1508
///   @interface Foo
1509
///   @end
1510
/// \endcode
1511
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
1512
    objcInterfaceDecl;
1513
1514
/// Matches Objective-C implementation declarations.
1515
///
1516
/// Example matches Foo
1517
/// \code
1518
///   @implementation Foo
1519
///   @end
1520
/// \endcode
1521
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
1522
    objcImplementationDecl;
1523
1524
/// Matches Objective-C protocol declarations.
1525
///
1526
/// Example matches FooDelegate
1527
/// \code
1528
///   @protocol FooDelegate
1529
///   @end
1530
/// \endcode
1531
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
1532
    objcProtocolDecl;
1533
1534
/// Matches Objective-C category declarations.
1535
///
1536
/// Example matches Foo (Additions)
1537
/// \code
1538
///   @interface Foo (Additions)
1539
///   @end
1540
/// \endcode
1541
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
1542
    objcCategoryDecl;
1543
1544
/// Matches Objective-C category definitions.
1545
///
1546
/// Example matches Foo (Additions)
1547
/// \code
1548
///   @implementation Foo (Additions)
1549
///   @end
1550
/// \endcode
1551
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
1552
    objcCategoryImplDecl;
1553
1554
/// Matches Objective-C method declarations.
1555
///
1556
/// Example matches both declaration and definition of -[Foo method]
1557
/// \code
1558
///   @interface Foo
1559
///   - (void)method;
1560
///   @end
1561
///
1562
///   @implementation Foo
1563
///   - (void)method {}
1564
///   @end
1565
/// \endcode
1566
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
1567
    objcMethodDecl;
1568
1569
/// Matches block declarations.
1570
///
1571
/// Example matches the declaration of the nameless block printing an input
1572
/// integer.
1573
///
1574
/// \code
1575
///   myFunc(^(int p) {
1576
///     printf("%d", p);
1577
///   })
1578
/// \endcode
1579
extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
1580
    blockDecl;
1581
1582
/// Matches Objective-C instance variable declarations.
1583
///
1584
/// Example matches _enabled
1585
/// \code
1586
///   @implementation Foo {
1587
///     BOOL _enabled;
1588
///   }
1589
///   @end
1590
/// \endcode
1591
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl>
1592
    objcIvarDecl;
1593
1594
/// Matches Objective-C property declarations.
1595
///
1596
/// Example matches enabled
1597
/// \code
1598
///   @interface Foo
1599
///   @property BOOL enabled;
1600
///   @end
1601
/// \endcode
1602
extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
1603
    objcPropertyDecl;
1604
1605
/// Matches Objective-C \@throw statements.
1606
///
1607
/// Example matches \@throw
1608
/// \code
1609
///   @throw obj;
1610
/// \endcode
1611
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
1612
    objcThrowStmt;
1613
1614
/// Matches Objective-C @try statements.
1615
///
1616
/// Example matches @try
1617
/// \code
1618
///   @try {}
1619
///   @catch (...) {}
1620
/// \endcode
1621
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt>
1622
    objcTryStmt;
1623
1624
/// Matches Objective-C @catch statements.
1625
///
1626
/// Example matches @catch
1627
/// \code
1628
///   @try {}
1629
///   @catch (...) {}
1630
/// \endcode
1631
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
1632
    objcCatchStmt;
1633
1634
/// Matches Objective-C @finally statements.
1635
///
1636
/// Example matches @finally
1637
/// \code
1638
///   @try {}
1639
///   @finally {}
1640
/// \endcode
1641
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
1642
    objcFinallyStmt;
1643
1644
/// Matches expressions that introduce cleanups to be run at the end
1645
/// of the sub-expression's evaluation.
1646
///
1647
/// Example matches std::string()
1648
/// \code
1649
///   const std::string str = std::string();
1650
/// \endcode
1651
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
1652
    exprWithCleanups;
1653
1654
/// Matches init list expressions.
1655
///
1656
/// Given
1657
/// \code
1658
///   int a[] = { 1, 2 };
1659
///   struct B { int x, y; };
1660
///   B b = { 5, 6 };
1661
/// \endcode
1662
/// initListExpr()
1663
///   matches "{ 1, 2 }" and "{ 5, 6 }"
1664
extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr>
1665
    initListExpr;
1666
1667
/// Matches the syntactic form of init list expressions
1668
/// (if expression have it).
1669
AST_MATCHER_P(InitListExpr, hasSyntacticForm,
1670
12
              internal::Matcher<Expr>, InnerMatcher) {
1671
12
  const Expr *SyntForm = Node.getSyntacticForm();
1672
12
  return (SyntForm != nullptr &&
1673
4
          InnerMatcher.matches(*SyntForm, Finder, Builder));
1674
12
}
1675
1676
/// Matches C++ initializer list expressions.
1677
///
1678
/// Given
1679
/// \code
1680
///   std::vector<int> a({ 1, 2, 3 });
1681
///   std::vector<int> b = { 4, 5 };
1682
///   int c[] = { 6, 7 };
1683
///   std::pair<int, int> d = { 8, 9 };
1684
/// \endcode
1685
/// cxxStdInitializerListExpr()
1686
///   matches "{ 1, 2, 3 }" and "{ 4, 5 }"
1687
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1688
                                                   CXXStdInitializerListExpr>
1689
    cxxStdInitializerListExpr;
1690
1691
/// Matches implicit initializers of init list expressions.
1692
///
1693
/// Given
1694
/// \code
1695
///   point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
1696
/// \endcode
1697
/// implicitValueInitExpr()
1698
///   matches "[0].y" (implicitly)
1699
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
1700
    implicitValueInitExpr;
1701
1702
/// Matches paren list expressions.
1703
/// ParenListExprs don't have a predefined type and are used for late parsing.
1704
/// In the final AST, they can be met in template declarations.
1705
///
1706
/// Given
1707
/// \code
1708
///   template<typename T> class X {
1709
///     void f() {
1710
///       X x(*this);
1711
///       int a = 0, b = 1; int i = (a, b);
1712
///     }
1713
///   };
1714
/// \endcode
1715
/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b)
1716
/// has a predefined type and is a ParenExpr, not a ParenListExpr.
1717
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr>
1718
    parenListExpr;
1719
1720
/// Matches substitutions of non-type template parameters.
1721
///
1722
/// Given
1723
/// \code
1724
///   template <int N>
1725
///   struct A { static const int n = N; };
1726
///   struct B : public A<42> {};
1727
/// \endcode
1728
/// substNonTypeTemplateParmExpr()
1729
///   matches "N" in the right-hand side of "static const int n = N;"
1730
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1731
                                                   SubstNonTypeTemplateParmExpr>
1732
    substNonTypeTemplateParmExpr;
1733
1734
/// Matches using declarations.
1735
///
1736
/// Given
1737
/// \code
1738
///   namespace X { int x; }
1739
///   using X::x;
1740
/// \endcode
1741
/// usingDecl()
1742
///   matches \code using X::x \endcode
1743
extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
1744
1745
/// Matches using namespace declarations.
1746
///
1747
/// Given
1748
/// \code
1749
///   namespace X { int x; }
1750
///   using namespace X;
1751
/// \endcode
1752
/// usingDirectiveDecl()
1753
///   matches \code using namespace X \endcode
1754
extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
1755
    usingDirectiveDecl;
1756
1757
/// Matches reference to a name that can be looked up during parsing
1758
/// but could not be resolved to a specific declaration.
1759
///
1760
/// Given
1761
/// \code
1762
///   template<typename T>
1763
///   T foo() { T a; return a; }
1764
///   template<typename T>
1765
///   void bar() {
1766
///     foo<T>();
1767
///   }
1768
/// \endcode
1769
/// unresolvedLookupExpr()
1770
///   matches \code foo<T>() \endcode
1771
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
1772
    unresolvedLookupExpr;
1773
1774
/// Matches unresolved using value declarations.
1775
///
1776
/// Given
1777
/// \code
1778
///   template<typename X>
1779
///   class C : private X {
1780
///     using X::x;
1781
///   };
1782
/// \endcode
1783
/// unresolvedUsingValueDecl()
1784
///   matches \code using X::x \endcode
1785
extern const internal::VariadicDynCastAllOfMatcher<Decl,
1786
                                                   UnresolvedUsingValueDecl>
1787
    unresolvedUsingValueDecl;
1788
1789
/// Matches unresolved using value declarations that involve the
1790
/// typename.
1791
///
1792
/// Given
1793
/// \code
1794
///   template <typename T>
1795
///   struct Base { typedef T Foo; };
1796
///
1797
///   template<typename T>
1798
///   struct S : private Base<T> {
1799
///     using typename Base<T>::Foo;
1800
///   };
1801
/// \endcode
1802
/// unresolvedUsingTypenameDecl()
1803
///   matches \code using Base<T>::Foo \endcode
1804
extern const internal::VariadicDynCastAllOfMatcher<Decl,
1805
                                                   UnresolvedUsingTypenameDecl>
1806
    unresolvedUsingTypenameDecl;
1807
1808
/// Matches a constant expression wrapper.
1809
///
1810
/// Example matches the constant in the case statement:
1811
///     (matcher = constantExpr())
1812
/// \code
1813
///   switch (a) {
1814
///   case 37: break;
1815
///   }
1816
/// \endcode
1817
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr>
1818
    constantExpr;
1819
1820
/// Matches parentheses used in expressions.
1821
///
1822
/// Example matches (foo() + 1)
1823
/// \code
1824
///   int foo() { return 1; }
1825
///   int a = (foo() + 1);
1826
/// \endcode
1827
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
1828
1829
/// Matches constructor call expressions (including implicit ones).
1830
///
1831
/// Example matches string(ptr, n) and ptr within arguments of f
1832
///     (matcher = cxxConstructExpr())
1833
/// \code
1834
///   void f(const string &a, const string &b);
1835
///   char *ptr;
1836
///   int n;
1837
///   f(string(ptr, n), ptr);
1838
/// \endcode
1839
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
1840
    cxxConstructExpr;
1841
1842
/// Matches unresolved constructor call expressions.
1843
///
1844
/// Example matches T(t) in return statement of f
1845
///     (matcher = cxxUnresolvedConstructExpr())
1846
/// \code
1847
///   template <typename T>
1848
///   void f(const T& t) { return T(t); }
1849
/// \endcode
1850
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1851
                                                   CXXUnresolvedConstructExpr>
1852
    cxxUnresolvedConstructExpr;
1853
1854
/// Matches implicit and explicit this expressions.
1855
///
1856
/// Example matches the implicit this expression in "return i".
1857
///     (matcher = cxxThisExpr())
1858
/// \code
1859
/// struct foo {
1860
///   int i;
1861
///   int f() { return i; }
1862
/// };
1863
/// \endcode
1864
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr>
1865
    cxxThisExpr;
1866
1867
/// Matches nodes where temporaries are created.
1868
///
1869
/// Example matches FunctionTakesString(GetStringByValue())
1870
///     (matcher = cxxBindTemporaryExpr())
1871
/// \code
1872
///   FunctionTakesString(GetStringByValue());
1873
///   FunctionTakesStringByPointer(GetStringPointer());
1874
/// \endcode
1875
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
1876
    cxxBindTemporaryExpr;
1877
1878
/// Matches nodes where temporaries are materialized.
1879
///
1880
/// Example: Given
1881
/// \code
1882
///   struct T {void func();};
1883
///   T f();
1884
///   void g(T);
1885
/// \endcode
1886
/// materializeTemporaryExpr() matches 'f()' in these statements
1887
/// \code
1888
///   T u(f());
1889
///   g(f());
1890
///   f().func();
1891
/// \endcode
1892
/// but does not match
1893
/// \code
1894
///   f();
1895
/// \endcode
1896
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1897
                                                   MaterializeTemporaryExpr>
1898
    materializeTemporaryExpr;
1899
1900
/// Matches new expressions.
1901
///
1902
/// Given
1903
/// \code
1904
///   new X;
1905
/// \endcode
1906
/// cxxNewExpr()
1907
///   matches 'new X'.
1908
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
1909
1910
/// Matches delete expressions.
1911
///
1912
/// Given
1913
/// \code
1914
///   delete X;
1915
/// \endcode
1916
/// cxxDeleteExpr()
1917
///   matches 'delete X'.
1918
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr>
1919
    cxxDeleteExpr;
1920
1921
/// Matches noexcept expressions.
1922
///
1923
/// Given
1924
/// \code
1925
///   bool a() noexcept;
1926
///   bool b() noexcept(true);
1927
///   bool c() noexcept(false);
1928
///   bool d() noexcept(noexcept(a()));
1929
///   bool e = noexcept(b()) || noexcept(c());
1930
/// \endcode
1931
/// cxxNoexceptExpr()
1932
///   matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`.
1933
///   doesn't match the noexcept specifier in the declarations a, b, c or d.
1934
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
1935
    cxxNoexceptExpr;
1936
1937
/// Matches array subscript expressions.
1938
///
1939
/// Given
1940
/// \code
1941
///   int i = a[1];
1942
/// \endcode
1943
/// arraySubscriptExpr()
1944
///   matches "a[1]"
1945
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
1946
    arraySubscriptExpr;
1947
1948
/// Matches the value of a default argument at the call site.
1949
///
1950
/// Example matches the CXXDefaultArgExpr placeholder inserted for the
1951
///     default value of the second parameter in the call expression f(42)
1952
///     (matcher = cxxDefaultArgExpr())
1953
/// \code
1954
///   void f(int x, int y = 0);
1955
///   f(42);
1956
/// \endcode
1957
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
1958
    cxxDefaultArgExpr;
1959
1960
/// Matches overloaded operator calls.
1961
///
1962
/// Note that if an operator isn't overloaded, it won't match. Instead, use
1963
/// binaryOperator matcher.
1964
/// Currently it does not match operators such as new delete.
1965
/// FIXME: figure out why these do not match?
1966
///
1967
/// Example matches both operator<<((o << b), c) and operator<<(o, b)
1968
///     (matcher = cxxOperatorCallExpr())
1969
/// \code
1970
///   ostream &operator<< (ostream &out, int i) { };
1971
///   ostream &o; int b = 1, c = 1;
1972
///   o << b << c;
1973
/// \endcode
1974
/// See also the binaryOperation() matcher for more-general matching of binary
1975
/// uses of this AST node.
1976
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
1977
    cxxOperatorCallExpr;
1978
1979
/// Matches rewritten binary operators
1980
///
1981
/// Example matches use of "<":
1982
/// \code
1983
///   #include <compare>
1984
///   struct HasSpaceshipMem {
1985
///     int a;
1986
///     constexpr auto operator<=>(const HasSpaceshipMem&) const = default;
1987
///   };
1988
///   void compare() {
1989
///     HasSpaceshipMem hs1, hs2;
1990
///     if (hs1 < hs2)
1991
///         return;
1992
///   }
1993
/// \endcode
1994
/// See also the binaryOperation() matcher for more-general matching
1995
/// of this AST node.
1996
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
1997
                                                   CXXRewrittenBinaryOperator>
1998
    cxxRewrittenBinaryOperator;
1999
2000
/// Matches expressions.
2001
///
2002
/// Example matches x()
2003
/// \code
2004
///   void f() { x(); }
2005
/// \endcode
2006
extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
2007
2008
/// Matches expressions that refer to declarations.
2009
///
2010
/// Example matches x in if (x)
2011
/// \code
2012
///   bool x;
2013
///   if (x) {}
2014
/// \endcode
2015
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr>
2016
    declRefExpr;
2017
2018
/// Matches a reference to an ObjCIvar.
2019
///
2020
/// Example: matches "a" in "init" method:
2021
/// \code
2022
/// @implementation A {
2023
///   NSString *a;
2024
/// }
2025
/// - (void) init {
2026
///   a = @"hello";
2027
/// }
2028
/// \endcode
2029
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr>
2030
    objcIvarRefExpr;
2031
2032
/// Matches a reference to a block.
2033
///
2034
/// Example: matches "^{}":
2035
/// \code
2036
///   void f() { ^{}(); }
2037
/// \endcode
2038
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
2039
2040
/// Matches if statements.
2041
///
2042
/// Example matches 'if (x) {}'
2043
/// \code
2044
///   if (x) {}
2045
/// \endcode
2046
extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
2047
2048
/// Matches for statements.
2049
///
2050
/// Example matches 'for (;;) {}'
2051
/// \code
2052
///   for (;;) {}
2053
///   int i[] =  {1, 2, 3}; for (auto a : i);
2054
/// \endcode
2055
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
2056
2057
/// Matches the increment statement of a for loop.
2058
///
2059
/// Example:
2060
///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
2061
/// matches '++x' in
2062
/// \code
2063
///     for (x; x < N; ++x) { }
2064
/// \endcode
2065
AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
2066
157
              InnerMatcher) {
2067
157
  const Stmt *const Increment = Node.getInc();
2068
157
  return (Increment != nullptr &&
2069
157
          InnerMatcher.matches(*Increment, Finder, Builder));
2070
157
}
2071
2072
/// Matches the initialization statement of a for loop.
2073
///
2074
/// Example:
2075
///     forStmt(hasLoopInit(declStmt()))
2076
/// matches 'int x = 0' in
2077
/// \code
2078
///     for (int x = 0; x < N; ++x) { }
2079
/// \endcode
2080
AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
2081
161
              InnerMatcher) {
2082
161
  const Stmt *const Init = Node.getInit();
2083
161
  return (Init != nullptr && 
InnerMatcher.matches(*Init, Finder, Builder)159
);
2084
161
}
2085
2086
/// Matches range-based for statements.
2087
///
2088
/// cxxForRangeStmt() matches 'for (auto a : i)'
2089
/// \code
2090
///   int i[] =  {1, 2, 3}; for (auto a : i);
2091
///   for(int j = 0; j < 5; ++j);
2092
/// \endcode
2093
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
2094
    cxxForRangeStmt;
2095
2096
/// Matches the initialization statement of a for loop.
2097
///
2098
/// Example:
2099
///     forStmt(hasLoopVariable(anything()))
2100
/// matches 'int x' in
2101
/// \code
2102
///     for (int x : a) { }
2103
/// \endcode
2104
AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>,
2105
37
              InnerMatcher) {
2106
37
  const VarDecl *const Var = Node.getLoopVariable();
2107
37
  return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder));
2108
37
}
2109
2110
/// Matches the range initialization statement of a for loop.
2111
///
2112
/// Example:
2113
///     forStmt(hasRangeInit(anything()))
2114
/// matches 'a' in
2115
/// \code
2116
///     for (int x : a) { }
2117
/// \endcode
2118
AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>,
2119
33
              InnerMatcher) {
2120
33
  const Expr *const Init = Node.getRangeInit();
2121
33
  return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder));
2122
33
}
2123
2124
/// Matches while statements.
2125
///
2126
/// Given
2127
/// \code
2128
///   while (true) {}
2129
/// \endcode
2130
/// whileStmt()
2131
///   matches 'while (true) {}'.
2132
extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
2133
2134
/// Matches do statements.
2135
///
2136
/// Given
2137
/// \code
2138
///   do {} while (true);
2139
/// \endcode
2140
/// doStmt()
2141
///   matches 'do {} while(true)'
2142
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
2143
2144
/// Matches break statements.
2145
///
2146
/// Given
2147
/// \code
2148
///   while (true) { break; }
2149
/// \endcode
2150
/// breakStmt()
2151
///   matches 'break'
2152
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
2153
2154
/// Matches continue statements.
2155
///
2156
/// Given
2157
/// \code
2158
///   while (true) { continue; }
2159
/// \endcode
2160
/// continueStmt()
2161
///   matches 'continue'
2162
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt>
2163
    continueStmt;
2164
2165
/// Matches return statements.
2166
///
2167
/// Given
2168
/// \code
2169
///   return 1;
2170
/// \endcode
2171
/// returnStmt()
2172
///   matches 'return 1'
2173
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
2174
2175
/// Matches goto statements.
2176
///
2177
/// Given
2178
/// \code
2179
///   goto FOO;
2180
///   FOO: bar();
2181
/// \endcode
2182
/// gotoStmt()
2183
///   matches 'goto FOO'
2184
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
2185
2186
/// Matches label statements.
2187
///
2188
/// Given
2189
/// \code
2190
///   goto FOO;
2191
///   FOO: bar();
2192
/// \endcode
2193
/// labelStmt()
2194
///   matches 'FOO:'
2195
extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
2196
2197
/// Matches address of label statements (GNU extension).
2198
///
2199
/// Given
2200
/// \code
2201
///   FOO: bar();
2202
///   void *ptr = &&FOO;
2203
///   goto *bar;
2204
/// \endcode
2205
/// addrLabelExpr()
2206
///   matches '&&FOO'
2207
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr>
2208
    addrLabelExpr;
2209
2210
/// Matches switch statements.
2211
///
2212
/// Given
2213
/// \code
2214
///   switch(a) { case 42: break; default: break; }
2215
/// \endcode
2216
/// switchStmt()
2217
///   matches 'switch(a)'.
2218
extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
2219
2220
/// Matches case and default statements inside switch statements.
2221
///
2222
/// Given
2223
/// \code
2224
///   switch(a) { case 42: break; default: break; }
2225
/// \endcode
2226
/// switchCase()
2227
///   matches 'case 42:' and 'default:'.
2228
extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
2229
2230
/// Matches case statements inside switch statements.
2231
///
2232
/// Given
2233
/// \code
2234
///   switch(a) { case 42: break; default: break; }
2235
/// \endcode
2236
/// caseStmt()
2237
///   matches 'case 42:'.
2238
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
2239
2240
/// Matches default statements inside switch statements.
2241
///
2242
/// Given
2243
/// \code
2244
///   switch(a) { case 42: break; default: break; }
2245
/// \endcode
2246
/// defaultStmt()
2247
///   matches 'default:'.
2248
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt>
2249
    defaultStmt;
2250
2251
/// Matches compound statements.
2252
///
2253
/// Example matches '{}' and '{{}}' in 'for (;;) {{}}'
2254
/// \code
2255
///   for (;;) {{}}
2256
/// \endcode
2257
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt>
2258
    compoundStmt;
2259
2260
/// Matches catch statements.
2261
///
2262
/// \code
2263
///   try {} catch(int i) {}
2264
/// \endcode
2265
/// cxxCatchStmt()
2266
///   matches 'catch(int i)'
2267
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt>
2268
    cxxCatchStmt;
2269
2270
/// Matches try statements.
2271
///
2272
/// \code
2273
///   try {} catch(int i) {}
2274
/// \endcode
2275
/// cxxTryStmt()
2276
///   matches 'try {}'
2277
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
2278
2279
/// Matches throw expressions.
2280
///
2281
/// \code
2282
///   try { throw 5; } catch(int i) {}
2283
/// \endcode
2284
/// cxxThrowExpr()
2285
///   matches 'throw 5'
2286
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr>
2287
    cxxThrowExpr;
2288
2289
/// Matches null statements.
2290
///
2291
/// \code
2292
///   foo();;
2293
/// \endcode
2294
/// nullStmt()
2295
///   matches the second ';'
2296
extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
2297
2298
/// Matches asm statements.
2299
///
2300
/// \code
2301
///  int i = 100;
2302
///   __asm("mov al, 2");
2303
/// \endcode
2304
/// asmStmt()
2305
///   matches '__asm("mov al, 2")'
2306
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
2307
2308
/// Matches bool literals.
2309
///
2310
/// Example matches true
2311
/// \code
2312
///   true
2313
/// \endcode
2314
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
2315
    cxxBoolLiteral;
2316
2317
/// Matches string literals (also matches wide string literals).
2318
///
2319
/// Example matches "abcd", L"abcd"
2320
/// \code
2321
///   char *s = "abcd";
2322
///   wchar_t *ws = L"abcd";
2323
/// \endcode
2324
extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral>
2325
    stringLiteral;
2326
2327
/// Matches character literals (also matches wchar_t).
2328
///
2329
/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
2330
/// though.
2331
///
2332
/// Example matches 'a', L'a'
2333
/// \code
2334
///   char ch = 'a';
2335
///   wchar_t chw = L'a';
2336
/// \endcode
2337
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
2338
    characterLiteral;
2339
2340
/// Matches integer literals of all sizes / encodings, e.g.
2341
/// 1, 1L, 0x1 and 1U.
2342
///
2343
/// Does not match character-encoded integers such as L'a'.
2344
extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
2345
    integerLiteral;
2346
2347
/// Matches float literals of all sizes / encodings, e.g.
2348
/// 1.0, 1.0f, 1.0L and 1e10.
2349
///
2350
/// Does not match implicit conversions such as
2351
/// \code
2352
///   float a = 10;
2353
/// \endcode
2354
extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral>
2355
    floatLiteral;
2356
2357
/// Matches imaginary literals, which are based on integer and floating
2358
/// point literals e.g.: 1i, 1.0i
2359
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral>
2360
    imaginaryLiteral;
2361
2362
/// Matches fixed point literals
2363
extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral>
2364
    fixedPointLiteral;
2365
2366
/// Matches user defined literal operator call.
2367
///
2368
/// Example match: "foo"_suffix
2369
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
2370
    userDefinedLiteral;
2371
2372
/// Matches compound (i.e. non-scalar) literals
2373
///
2374
/// Example match: {1}, (1, 2)
2375
/// \code
2376
///   int array[4] = {1};
2377
///   vector int myvec = (vector int)(1, 2);
2378
/// \endcode
2379
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
2380
    compoundLiteralExpr;
2381
2382
/// Matches nullptr literal.
2383
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
2384
    cxxNullPtrLiteralExpr;
2385
2386
/// Matches GNU __builtin_choose_expr.
2387
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr>
2388
    chooseExpr;
2389
2390
/// Matches GNU __null expression.
2391
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr>
2392
    gnuNullExpr;
2393
2394
/// Matches C11 _Generic expression.
2395
extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr>
2396
    genericSelectionExpr;
2397
2398
/// Matches atomic builtins.
2399
/// Example matches __atomic_load_n(ptr, 1)
2400
/// \code
2401
///   void foo() { int *ptr; __atomic_load_n(ptr, 1); }
2402
/// \endcode
2403
extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
2404
2405
/// Matches statement expression (GNU extension).
2406
///
2407
/// Example match: ({ int X = 4; X; })
2408
/// \code
2409
///   int C = ({ int X = 4; X; });
2410
/// \endcode
2411
extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
2412
2413
/// Matches binary operator expressions.
2414
///
2415
/// Example matches a || b
2416
/// \code
2417
///   !(a || b)
2418
/// \endcode
2419
/// See also the binaryOperation() matcher for more-general matching.
2420
extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
2421
    binaryOperator;
2422
2423
/// Matches unary operator expressions.
2424
///
2425
/// Example matches !a
2426
/// \code
2427
///   !a || b
2428
/// \endcode
2429
extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator>
2430
    unaryOperator;
2431
2432
/// Matches conditional operator expressions.
2433
///
2434
/// Example matches a ? b : c
2435
/// \code
2436
///   (a ? b : c) + 42
2437
/// \endcode
2438
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
2439
    conditionalOperator;
2440
2441
/// Matches binary conditional operator expressions (GNU extension).
2442
///
2443
/// Example matches a ?: b
2444
/// \code
2445
///   (a ?: b) + 42;
2446
/// \endcode
2447
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2448
                                                   BinaryConditionalOperator>
2449
    binaryConditionalOperator;
2450
2451
/// Matches opaque value expressions. They are used as helpers
2452
/// to reference another expressions and can be met
2453
/// in BinaryConditionalOperators, for example.
2454
///
2455
/// Example matches 'a'
2456
/// \code
2457
///   (a ?: c) + 42;
2458
/// \endcode
2459
extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
2460
    opaqueValueExpr;
2461
2462
/// Matches a C++ static_assert declaration.
2463
///
2464
/// Example:
2465
///   staticAssertExpr()
2466
/// matches
2467
///   static_assert(sizeof(S) == sizeof(int))
2468
/// in
2469
/// \code
2470
///   struct S {
2471
///     int x;
2472
///   };
2473
///   static_assert(sizeof(S) == sizeof(int));
2474
/// \endcode
2475
extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
2476
    staticAssertDecl;
2477
2478
/// Matches a reinterpret_cast expression.
2479
///
2480
/// Either the source expression or the destination type can be matched
2481
/// using has(), but hasDestinationType() is more specific and can be
2482
/// more readable.
2483
///
2484
/// Example matches reinterpret_cast<char*>(&p) in
2485
/// \code
2486
///   void* p = reinterpret_cast<char*>(&p);
2487
/// \endcode
2488
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
2489
    cxxReinterpretCastExpr;
2490
2491
/// Matches a C++ static_cast expression.
2492
///
2493
/// \see hasDestinationType
2494
/// \see reinterpretCast
2495
///
2496
/// Example:
2497
///   cxxStaticCastExpr()
2498
/// matches
2499
///   static_cast<long>(8)
2500
/// in
2501
/// \code
2502
///   long eight(static_cast<long>(8));
2503
/// \endcode
2504
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
2505
    cxxStaticCastExpr;
2506
2507
/// Matches a dynamic_cast expression.
2508
///
2509
/// Example:
2510
///   cxxDynamicCastExpr()
2511
/// matches
2512
///   dynamic_cast<D*>(&b);
2513
/// in
2514
/// \code
2515
///   struct B { virtual ~B() {} }; struct D : B {};
2516
///   B b;
2517
///   D* p = dynamic_cast<D*>(&b);
2518
/// \endcode
2519
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
2520
    cxxDynamicCastExpr;
2521
2522
/// Matches a const_cast expression.
2523
///
2524
/// Example: Matches const_cast<int*>(&r) in
2525
/// \code
2526
///   int n = 42;
2527
///   const int &r(n);
2528
///   int* p = const_cast<int*>(&r);
2529
/// \endcode
2530
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
2531
    cxxConstCastExpr;
2532
2533
/// Matches a C-style cast expression.
2534
///
2535
/// Example: Matches (int) 2.2f in
2536
/// \code
2537
///   int i = (int) 2.2f;
2538
/// \endcode
2539
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
2540
    cStyleCastExpr;
2541
2542
/// Matches explicit cast expressions.
2543
///
2544
/// Matches any cast expression written in user code, whether it be a
2545
/// C-style cast, a functional-style cast, or a keyword cast.
2546
///
2547
/// Does not match implicit conversions.
2548
///
2549
/// Note: the name "explicitCast" is chosen to match Clang's terminology, as
2550
/// Clang uses the term "cast" to apply to implicit conversions as well as to
2551
/// actual cast expressions.
2552
///
2553
/// \see hasDestinationType.
2554
///
2555
/// Example: matches all five of the casts in
2556
/// \code
2557
///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
2558
/// \endcode
2559
/// but does not match the implicit conversion in
2560
/// \code
2561
///   long ell = 42;
2562
/// \endcode
2563
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
2564
    explicitCastExpr;
2565
2566
/// Matches the implicit cast nodes of Clang's AST.
2567
///
2568
/// This matches many different places, including function call return value
2569
/// eliding, as well as any type conversions.
2570
extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
2571
    implicitCastExpr;
2572
2573
/// Matches any cast nodes of Clang's AST.
2574
///
2575
/// Example: castExpr() matches each of the following:
2576
/// \code
2577
///   (int) 3;
2578
///   const_cast<Expr *>(SubExpr);
2579
///   char c = 0;
2580
/// \endcode
2581
/// but does not match
2582
/// \code
2583
///   int i = (0);
2584
///   int k = 0;
2585
/// \endcode
2586
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
2587
2588
/// Matches functional cast expressions
2589
///
2590
/// Example: Matches Foo(bar);
2591
/// \code
2592
///   Foo f = bar;
2593
///   Foo g = (Foo) bar;
2594
///   Foo h = Foo(bar);
2595
/// \endcode
2596
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
2597
    cxxFunctionalCastExpr;
2598
2599
/// Matches functional cast expressions having N != 1 arguments
2600
///
2601
/// Example: Matches Foo(bar, bar)
2602
/// \code
2603
///   Foo h = Foo(bar, bar);
2604
/// \endcode
2605
extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
2606
    cxxTemporaryObjectExpr;
2607
2608
/// Matches predefined identifier expressions [C99 6.4.2.2].
2609
///
2610
/// Example: Matches __func__
2611
/// \code
2612
///   printf("%s", __func__);
2613
/// \endcode
2614
extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
2615
    predefinedExpr;
2616
2617
/// Matches C99 designated initializer expressions [C99 6.7.8].
2618
///
2619
/// Example: Matches { [2].y = 1.0, [0].x = 1.0 }
2620
/// \code
2621
///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2622
/// \endcode
2623
extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
2624
    designatedInitExpr;
2625
2626
/// Matches designated initializer expressions that contain
2627
/// a specific number of designators.
2628
///
2629
/// Example: Given
2630
/// \code
2631
///   point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 };
2632
///   point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 };
2633
/// \endcode
2634
/// designatorCountIs(2)
2635
///   matches '{ [2].y = 1.0, [0].x = 1.0 }',
2636
///   but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'.
2637
60
AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) {
2638
60
  return Node.size() == N;
2639
60
}
2640
2641
/// Matches \c QualTypes in the clang AST.
2642
extern const internal::VariadicAllOfMatcher<QualType> qualType;
2643
2644
/// Matches \c Types in the clang AST.
2645
extern const internal::VariadicAllOfMatcher<Type> type;
2646
2647
/// Matches \c TypeLocs in the clang AST.
2648
extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
2649
2650
/// Matches if any of the given matchers matches.
2651
///
2652
/// Unlike \c anyOf, \c eachOf will generate a match result for each
2653
/// matching submatcher.
2654
///
2655
/// For example, in:
2656
/// \code
2657
///   class A { int a; int b; };
2658
/// \endcode
2659
/// The matcher:
2660
/// \code
2661
///   cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
2662
///                        has(fieldDecl(hasName("b")).bind("v"))))
2663
/// \endcode
2664
/// will generate two results binding "v", the first of which binds
2665
/// the field declaration of \c a, the second the field declaration of
2666
/// \c b.
2667
///
2668
/// Usable as: Any Matcher
2669
extern const internal::VariadicOperatorMatcherFunc<
2670
    2, std::numeric_limits<unsigned>::max()>
2671
    eachOf;
2672
2673
/// Matches if any of the given matchers matches.
2674
///
2675
/// Usable as: Any Matcher
2676
extern const internal::VariadicOperatorMatcherFunc<
2677
    2, std::numeric_limits<unsigned>::max()>
2678
    anyOf;
2679
2680
/// Matches if all given matchers match.
2681
///
2682
/// Usable as: Any Matcher
2683
extern const internal::VariadicOperatorMatcherFunc<
2684
    2, std::numeric_limits<unsigned>::max()>
2685
    allOf;
2686
2687
/// Matches any node regardless of the submatcher.
2688
///
2689
/// However, \c optionally will retain any bindings generated by the submatcher.
2690
/// Useful when additional information which may or may not present about a main
2691
/// matching node is desired.
2692
///
2693
/// For example, in:
2694
/// \code
2695
///   class Foo {
2696
///     int bar;
2697
///   }
2698
/// \endcode
2699
/// The matcher:
2700
/// \code
2701
///   cxxRecordDecl(
2702
///     optionally(has(
2703
///       fieldDecl(hasName("bar")).bind("var")
2704
///   ))).bind("record")
2705
/// \endcode
2706
/// will produce a result binding for both "record" and "var".
2707
/// The matcher will produce a "record" binding for even if there is no data
2708
/// member named "bar" in that class.
2709
///
2710
/// Usable as: Any Matcher
2711
extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally;
2712
2713
/// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
2714
///
2715
/// Given
2716
/// \code
2717
///   Foo x = bar;
2718
///   int y = sizeof(x) + alignof(x);
2719
/// \endcode
2720
/// unaryExprOrTypeTraitExpr()
2721
///   matches \c sizeof(x) and \c alignof(x)
2722
extern const internal::VariadicDynCastAllOfMatcher<Stmt,
2723
                                                   UnaryExprOrTypeTraitExpr>
2724
    unaryExprOrTypeTraitExpr;
2725
2726
/// Matches any of the \p NodeMatchers with InnerMatchers nested within
2727
///
2728
/// Given
2729
/// \code
2730
///   if (true);
2731
///   for (; true; );
2732
/// \endcode
2733
/// with the matcher
2734
/// \code
2735
///   mapAnyOf(ifStmt, forStmt).with(
2736
///     hasCondition(cxxBoolLiteralExpr(equals(true)))
2737
///     ).bind("trueCond")
2738
/// \endcode
2739
/// matches the \c if and the \c for. It is equivalent to:
2740
/// \code
2741
///   auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true)));
2742
///   anyOf(
2743
///     ifStmt(trueCond).bind("trueCond"),
2744
///     forStmt(trueCond).bind("trueCond")
2745
///     );
2746
/// \endcode
2747
///
2748
/// The with() chain-call accepts zero or more matchers which are combined
2749
/// as-if with allOf() in each of the node matchers.
2750
/// Usable as: Any Matcher
2751
template <typename T, typename... U>
2752
auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) {
2753
  return internal::MapAnyOfHelper<U...>();
2754
}
2755
2756
/// Matches nodes which can be used with binary operators.
2757
///
2758
/// The code
2759
/// \code
2760
///   var1 != var2;
2761
/// \endcode
2762
/// might be represented in the clang AST as a binaryOperator, a
2763
/// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on
2764
///
2765
/// * whether the types of var1 and var2 are fundamental (binaryOperator) or at
2766
///   least one is a class type (cxxOperatorCallExpr)
2767
/// * whether the code appears in a template declaration, if at least one of the
2768
///   vars is a dependent-type (binaryOperator)
2769
/// * whether the code relies on a rewritten binary operator, such as a
2770
/// spaceship operator or an inverted equality operator
2771
/// (cxxRewrittenBinaryOperator)
2772
///
2773
/// This matcher elides details in places where the matchers for the nodes are
2774
/// compatible.
2775
///
2776
/// Given
2777
/// \code
2778
///   binaryOperation(
2779
///     hasOperatorName("!="),
2780
///     hasLHS(expr().bind("lhs")),
2781
///     hasRHS(expr().bind("rhs"))
2782
///   )
2783
/// \endcode
2784
/// matches each use of "!=" in:
2785
/// \code
2786
///   struct S{
2787
///       bool operator!=(const S&) const;
2788
///   };
2789
///
2790
///   void foo()
2791
///   {
2792
///      1 != 2;
2793
///      S() != S();
2794
///   }
2795
///
2796
///   template<typename T>
2797
///   void templ()
2798
///   {
2799
///      1 != 2;
2800
///      T() != S();
2801
///   }
2802
///   struct HasOpEq
2803
///   {
2804
///       bool operator==(const HasOpEq &) const;
2805
///   };
2806
///
2807
///   void inverse()
2808
///   {
2809
///       HasOpEq s1;
2810
///       HasOpEq s2;
2811
///       if (s1 != s2)
2812
///           return;
2813
///   }
2814
///
2815
///   struct HasSpaceship
2816
///   {
2817
///       bool operator<=>(const HasOpEq &) const;
2818
///   };
2819
///
2820
///   void use_spaceship()
2821
///   {
2822
///       HasSpaceship s1;
2823
///       HasSpaceship s2;
2824
///       if (s1 != s2)
2825
///           return;
2826
///   }
2827
/// \endcode
2828
extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr,
2829
                                       CXXRewrittenBinaryOperator>
2830
    binaryOperation;
2831
2832
/// Matches unary expressions that have a specific type of argument.
2833
///
2834
/// Given
2835
/// \code
2836
///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
2837
/// \endcode
2838
/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
2839
///   matches \c sizeof(a) and \c alignof(c)
2840
AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
2841
115
              internal::Matcher<QualType>, InnerMatcher) {
2842
115
  const QualType ArgumentType = Node.getTypeOfArgument();
2843
115
  return InnerMatcher.matches(ArgumentType, Finder, Builder);
2844
115
}
2845
2846
/// Matches unary expressions of a certain kind.
2847
///
2848
/// Given
2849
/// \code
2850
///   int x;
2851
///   int s = sizeof(x) + alignof(x)
2852
/// \endcode
2853
/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
2854
///   matches \c sizeof(x)
2855
///
2856
/// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter
2857
/// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf").
2858
176
AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
2859
176
  return Node.getKind() == Kind;
2860
176
}
2861
2862
/// Same as unaryExprOrTypeTraitExpr, but only matching
2863
/// alignof.
2864
inline internal::BindableMatcher<Stmt> alignOfExpr(
2865
14
    const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2866
14
  return stmt(unaryExprOrTypeTraitExpr(
2867
14
      allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)),
2868
14
            InnerMatcher)));
2869
14
}
2870
2871
/// Same as unaryExprOrTypeTraitExpr, but only matching
2872
/// sizeof.
2873
inline internal::BindableMatcher<Stmt> sizeOfExpr(
2874
394
    const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
2875
394
  return stmt(unaryExprOrTypeTraitExpr(
2876
394
      allOf(ofKind(UETT_SizeOf), InnerMatcher)));
2877
394
}
2878
2879
/// Matches NamedDecl nodes that have the specified name.
2880
///
2881
/// Supports specifying enclosing namespaces or classes by prefixing the name
2882
/// with '<enclosing>::'.
2883
/// Does not match typedefs of an underlying type with the given name.
2884
///
2885
/// Example matches X (Name == "X")
2886
/// \code
2887
///   class X;
2888
/// \endcode
2889
///
2890
/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
2891
/// \code
2892
///   namespace a { namespace b { class X; } }
2893
/// \endcode
2894
20.3k
inline internal::Matcher<NamedDecl> hasName(StringRef Name) {
2895
20.3k
  return internal::Matcher<NamedDecl>(
2896
20.3k
      new internal::HasNameMatcher({std::string(Name)}));
2897
20.3k
}
2898
2899
/// Matches NamedDecl nodes that have any of the specified names.
2900
///
2901
/// This matcher is only provided as a performance optimization of hasName.
2902
/// \code
2903
///     hasAnyName(a, b, c)
2904
/// \endcode
2905
///  is equivalent to, but faster than
2906
/// \code
2907
///     anyOf(hasName(a), hasName(b), hasName(c))
2908
/// \endcode
2909
extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
2910
                                        internal::hasAnyNameFunc>
2911
    hasAnyName;
2912
2913
/// Matches NamedDecl nodes whose fully qualified names contain
2914
/// a substring matched by the given RegExp.
2915
///
2916
/// Supports specifying enclosing namespaces or classes by
2917
/// prefixing the name with '<enclosing>::'.  Does not match typedefs
2918
/// of an underlying type with the given name.
2919
///
2920
/// Example matches X (regexp == "::X")
2921
/// \code
2922
///   class X;
2923
/// \endcode
2924
///
2925
/// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
2926
/// \code
2927
///   namespace foo { namespace bar { class X; } }
2928
/// \endcode
2929
3.75k
AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) {
2930
3.75k
  std::string FullNameString = "::" + Node.getQualifiedNameAsString();
2931
3.75k
  return RegExp->match(FullNameString);
2932
3.75k
}
2933
2934
/// Matches overloaded operator names.
2935
///
2936
/// Matches overloaded operator names specified in strings without the
2937
/// "operator" prefix: e.g. "<<".
2938
///
2939
/// Given:
2940
/// \code
2941
///   class A { int operator*(); };
2942
///   const A &operator<<(const A &a, const A &b);
2943
///   A a;
2944
///   a << a;   // <-- This matches
2945
/// \endcode
2946
///
2947
/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the
2948
/// specified line and
2949
/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")))
2950
/// matches the declaration of \c A.
2951
///
2952
/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl>
2953
inline internal::PolymorphicMatcherWithParam1<
2954
    internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
2955
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>
2956
575
hasOverloadedOperatorName(StringRef Name) {
2957
575
  return internal::PolymorphicMatcherWithParam1<
2958
575
      internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
2959
575
      AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(
2960
575
      {std::string(Name)});
2961
575
}
2962
2963
/// Matches overloaded operator names.
2964
///
2965
/// Matches overloaded operator names specified in strings without the
2966
/// "operator" prefix: e.g. "<<".
2967
///
2968
///   hasAnyOverloadedOperatorName("+", "-")
2969
/// Is equivalent to
2970
///   anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-"))
2971
extern const internal::VariadicFunction<
2972
    internal::PolymorphicMatcherWithParam1<
2973
        internal::HasOverloadedOperatorNameMatcher, std::vector<std::string>,
2974
        AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>,
2975
    StringRef, internal::hasAnyOverloadedOperatorNameFunc>
2976
    hasAnyOverloadedOperatorName;
2977
2978
/// Matches template-dependent, but known, member names.
2979
///
2980
/// In template declarations, dependent members are not resolved and so can
2981
/// not be matched to particular named declarations.
2982
///
2983
/// This matcher allows to match on the known name of members.
2984
///
2985
/// Given
2986
/// \code
2987
///   template <typename T>
2988
///   struct S {
2989
///       void mem();
2990
///   };
2991
///   template <typename T>
2992
///   void x() {
2993
///       S<T> s;
2994
///       s.mem();
2995
///   }
2996
/// \endcode
2997
/// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()`
2998
8
AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) {
2999
8
  return Node.getMember().getAsString() == N;
3000
8
}
3001
3002
/// Matches template-dependent, but known, member names against an already-bound
3003
/// node
3004
///
3005
/// In template declarations, dependent members are not resolved and so can
3006
/// not be matched to particular named declarations.
3007
///
3008
/// This matcher allows to match on the name of already-bound VarDecl, FieldDecl
3009
/// and CXXMethodDecl nodes.
3010
///
3011
/// Given
3012
/// \code
3013
///   template <typename T>
3014
///   struct S {
3015
///       void mem();
3016
///   };
3017
///   template <typename T>
3018
///   void x() {
3019
///       S<T> s;
3020
///       s.mem();
3021
///   }
3022
/// \endcode
3023
/// The matcher
3024
/// @code
3025
/// \c cxxDependentScopeMemberExpr(
3026
///   hasObjectExpression(declRefExpr(hasType(templateSpecializationType(
3027
///       hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has(
3028
///           cxxMethodDecl(hasName("mem")).bind("templMem")
3029
///           )))))
3030
///       )))),
3031
///   memberHasSameNameAsBoundNode("templMem")
3032
///   )
3033
/// @endcode
3034
/// first matches and binds the @c mem member of the @c S template, then
3035
/// compares its name to the usage in @c s.mem() in the @c x function template
3036
AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode,
3037
7
              std::string, BindingID) {
3038
7
  auto MemberName = Node.getMember().getAsString();
3039
3040
7
  return Builder->removeBindings(
3041
7
      [this, MemberName](const BoundNodesMap &Nodes) {
3042
7
        const auto &BN = Nodes.getNode(this->BindingID);
3043
7
        if (const auto *ND = BN.get<NamedDecl>()) {
3044
7
          if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND))
3045
1
            return true;
3046
6
          return ND->getName() != MemberName;
3047
6
        }
3048
0
        return true;
3049
0
      });
3050
7
}
3051
3052
/// Matches C++ classes that are directly or indirectly derived from a class
3053
/// matching \c Base, or Objective-C classes that directly or indirectly
3054
/// subclass a class matching \c Base.
3055
///
3056
/// Note that a class is not considered to be derived from itself.
3057
///
3058
/// Example matches Y, Z, C (Base == hasName("X"))
3059
/// \code
3060
///   class X;
3061
///   class Y : public X {};  // directly derived
3062
///   class Z : public Y {};  // indirectly derived
3063
///   typedef X A;
3064
///   typedef A B;
3065
///   class C : public B {};  // derived from a typedef of X
3066
/// \endcode
3067
///
3068
/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3069
/// \code
3070
///   class Foo;
3071
///   typedef Foo X;
3072
///   class Bar : public Foo {};  // derived from a type that X is a typedef of
3073
/// \endcode
3074
///
3075
/// In the following example, Bar matches isDerivedFrom(hasName("NSObject"))
3076
/// \code
3077
///   @interface NSObject @end
3078
///   @interface Bar : NSObject @end
3079
/// \endcode
3080
///
3081
/// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl>
3082
AST_POLYMORPHIC_MATCHER_P(
3083
    isDerivedFrom,
3084
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3085
5.81k
    internal::Matcher<NamedDecl>, Base) {
3086
  // Check if the node is a C++ struct/union/class.
3087
5.81k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3088
4.69k
    return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3089
3090
  // The node must be an Objective-C class.
3091
1.12k
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3092
1.12k
  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3093
1.12k
                                        /*Directly=*/false);
3094
1.12k
}
clang::ast_matchers::internal::matcher_isDerivedFrom0Matcher<clang::CXXRecordDecl, clang::ast_matchers::internal::Matcher<clang::NamedDecl> >::matches(clang::CXXRecordDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3085
4.69k
    internal::Matcher<NamedDecl>, Base) {
3086
  // Check if the node is a C++ struct/union/class.
3087
4.69k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3088
4.69k
    return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3089
3090
  // The node must be an Objective-C class.
3091
0
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3092
0
  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3093
0
                                        /*Directly=*/false);
3094
0
}
clang::ast_matchers::internal::matcher_isDerivedFrom0Matcher<clang::ObjCInterfaceDecl, clang::ast_matchers::internal::Matcher<clang::NamedDecl> >::matches(clang::ObjCInterfaceDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3085
1.12k
    internal::Matcher<NamedDecl>, Base) {
3086
  // Check if the node is a C++ struct/union/class.
3087
1.12k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3088
0
    return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false);
3089
3090
  // The node must be an Objective-C class.
3091
1.12k
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3092
1.12k
  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3093
1.12k
                                        /*Directly=*/false);
3094
1.12k
}
3095
3096
/// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
3097
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3098
    isDerivedFrom,
3099
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3100
4.24k
    std::string, BaseName, 1) {
3101
4.24k
  if (BaseName.empty())
3102
100
    return false;
3103
3104
4.14k
  const auto M = isDerivedFrom(hasName(BaseName));
3105
3106
4.14k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3107
3.25k
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3108
3109
896
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3110
896
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3111
896
}
clang::ast_matchers::internal::matcher_isDerivedFrom1Matcher<clang::CXXRecordDecl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::CXXRecordDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3100
3.35k
    std::string, BaseName, 1) {
3101
3.35k
  if (BaseName.empty())
3102
100
    return false;
3103
3104
3.25k
  const auto M = isDerivedFrom(hasName(BaseName));
3105
3106
3.25k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3107
3.25k
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3108
3109
0
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3110
0
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3111
0
}
clang::ast_matchers::internal::matcher_isDerivedFrom1Matcher<clang::ObjCInterfaceDecl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::ObjCInterfaceDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3100
896
    std::string, BaseName, 1) {
3101
896
  if (BaseName.empty())
3102
0
    return false;
3103
3104
896
  const auto M = isDerivedFrom(hasName(BaseName));
3105
3106
896
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3107
0
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3108
3109
896
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3110
896
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3111
896
}
3112
3113
/// Matches C++ classes that have a direct or indirect base matching \p
3114
/// BaseSpecMatcher.
3115
///
3116
/// Example:
3117
/// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3118
/// \code
3119
///   class Foo;
3120
///   class Bar : Foo {};
3121
///   class Baz : Bar {};
3122
///   class SpecialBase;
3123
///   class Proxy : SpecialBase {};  // matches Proxy
3124
///   class IndirectlyDerived : Proxy {};  //matches IndirectlyDerived
3125
/// \endcode
3126
///
3127
// FIXME: Refactor this and isDerivedFrom to reuse implementation.
3128
AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>,
3129
1.72k
              BaseSpecMatcher) {
3130
1.72k
  return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder);
3131
1.72k
}
3132
3133
/// Matches C++ classes that have a direct base matching \p BaseSpecMatcher.
3134
///
3135
/// Example:
3136
/// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase"))))
3137
/// \code
3138
///   class Foo;
3139
///   class Bar : Foo {};
3140
///   class Baz : Bar {};
3141
///   class SpecialBase;
3142
///   class Proxy : SpecialBase {};  // matches Proxy
3143
///   class IndirectlyDerived : Proxy {};  // doesn't match
3144
/// \endcode
3145
AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>,
3146
200
              BaseSpecMatcher) {
3147
200
  return Node.hasDefinition() &&
3148
120
         
llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) 100
{
3149
120
           return BaseSpecMatcher.matches(Base, Finder, Builder);
3150
120
         });
3151
200
}
3152
3153
/// Similar to \c isDerivedFrom(), but also matches classes that directly
3154
/// match \c Base.
3155
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3156
    isSameOrDerivedFrom,
3157
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3158
1.62k
    internal::Matcher<NamedDecl>, Base, 0) {
3159
1.62k
  const auto M = anyOf(Base, isDerivedFrom(Base));
3160
3161
1.62k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3162
1.31k
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3163
3164
308
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3165
308
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3166
308
}
clang::ast_matchers::internal::matcher_isSameOrDerivedFrom0Matcher<clang::CXXRecordDecl, clang::ast_matchers::internal::Matcher<clang::NamedDecl> >::matches(clang::CXXRecordDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3158
1.31k
    internal::Matcher<NamedDecl>, Base, 0) {
3159
1.31k
  const auto M = anyOf(Base, isDerivedFrom(Base));
3160
3161
1.31k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3162
1.31k
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3163
3164
0
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3165
0
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3166
0
}
clang::ast_matchers::internal::matcher_isSameOrDerivedFrom0Matcher<clang::ObjCInterfaceDecl, clang::ast_matchers::internal::Matcher<clang::NamedDecl> >::matches(clang::ObjCInterfaceDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3158
308
    internal::Matcher<NamedDecl>, Base, 0) {
3159
308
  const auto M = anyOf(Base, isDerivedFrom(Base));
3160
3161
308
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3162
0
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3163
3164
308
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3165
308
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3166
308
}
3167
3168
/// Overloaded method as shortcut for
3169
/// \c isSameOrDerivedFrom(hasName(...)).
3170
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3171
    isSameOrDerivedFrom,
3172
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3173
1.71k
    std::string, BaseName, 1) {
3174
1.71k
  if (BaseName.empty())
3175
100
    return false;
3176
3177
1.61k
  const auto M = isSameOrDerivedFrom(hasName(BaseName));
3178
3179
1.61k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3180
1.30k
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3181
3182
308
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3183
308
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3184
308
}
clang::ast_matchers::internal::matcher_isSameOrDerivedFrom1Matcher<clang::CXXRecordDecl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::CXXRecordDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3173
1.40k
    std::string, BaseName, 1) {
3174
1.40k
  if (BaseName.empty())
3175
100
    return false;
3176
3177
1.30k
  const auto M = isSameOrDerivedFrom(hasName(BaseName));
3178
3179
1.30k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3180
1.30k
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3181
3182
0
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3183
0
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3184
0
}
clang::ast_matchers::internal::matcher_isSameOrDerivedFrom1Matcher<clang::ObjCInterfaceDecl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::ObjCInterfaceDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3173
308
    std::string, BaseName, 1) {
3174
308
  if (BaseName.empty())
3175
0
    return false;
3176
3177
308
  const auto M = isSameOrDerivedFrom(hasName(BaseName));
3178
3179
308
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3180
0
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3181
3182
308
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3183
308
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3184
308
}
3185
3186
/// Matches C++ or Objective-C classes that are directly derived from a class
3187
/// matching \c Base.
3188
///
3189
/// Note that a class is not considered to be derived from itself.
3190
///
3191
/// Example matches Y, C (Base == hasName("X"))
3192
/// \code
3193
///   class X;
3194
///   class Y : public X {};  // directly derived
3195
///   class Z : public Y {};  // indirectly derived
3196
///   typedef X A;
3197
///   typedef A B;
3198
///   class C : public B {};  // derived from a typedef of X
3199
/// \endcode
3200
///
3201
/// In the following example, Bar matches isDerivedFrom(hasName("X")):
3202
/// \code
3203
///   class Foo;
3204
///   typedef Foo X;
3205
///   class Bar : public Foo {};  // derived from a type that X is a typedef of
3206
/// \endcode
3207
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3208
    isDirectlyDerivedFrom,
3209
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3210
1.26k
    internal::Matcher<NamedDecl>, Base, 0) {
3211
  // Check if the node is a C++ struct/union/class.
3212
1.26k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3213
420
    return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3214
3215
  // The node must be an Objective-C class.
3216
840
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3217
840
  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3218
840
                                        /*Directly=*/true);
3219
840
}
clang::ast_matchers::internal::matcher_isDirectlyDerivedFrom0Matcher<clang::CXXRecordDecl, clang::ast_matchers::internal::Matcher<clang::NamedDecl> >::matches(clang::CXXRecordDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3210
420
    internal::Matcher<NamedDecl>, Base, 0) {
3211
  // Check if the node is a C++ struct/union/class.
3212
420
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3213
420
    return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3214
3215
  // The node must be an Objective-C class.
3216
0
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3217
0
  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3218
0
                                        /*Directly=*/true);
3219
0
}
clang::ast_matchers::internal::matcher_isDirectlyDerivedFrom0Matcher<clang::ObjCInterfaceDecl, clang::ast_matchers::internal::Matcher<clang::NamedDecl> >::matches(clang::ObjCInterfaceDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3210
840
    internal::Matcher<NamedDecl>, Base, 0) {
3211
  // Check if the node is a C++ struct/union/class.
3212
840
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3213
0
    return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true);
3214
3215
  // The node must be an Objective-C class.
3216
840
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3217
840
  return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder,
3218
840
                                        /*Directly=*/true);
3219
840
}
3220
3221
/// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)).
3222
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3223
    isDirectlyDerivedFrom,
3224
    AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl),
3225
1.32k
    std::string, BaseName, 1) {
3226
1.32k
  if (BaseName.empty())
3227
100
    return false;
3228
1.22k
  const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3229
3230
1.22k
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3231
380
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3232
3233
840
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3234
840
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3235
840
}
clang::ast_matchers::internal::matcher_isDirectlyDerivedFrom1Matcher<clang::CXXRecordDecl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::CXXRecordDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3225
480
    std::string, BaseName, 1) {
3226
480
  if (BaseName.empty())
3227
100
    return false;
3228
380
  const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3229
3230
380
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3231
380
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3232
3233
0
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3234
0
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3235
0
}
clang::ast_matchers::internal::matcher_isDirectlyDerivedFrom1Matcher<clang::ObjCInterfaceDecl, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >::matches(clang::ObjCInterfaceDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3225
840
    std::string, BaseName, 1) {
3226
840
  if (BaseName.empty())
3227
0
    return false;
3228
840
  const auto M = isDirectlyDerivedFrom(hasName(BaseName));
3229
3230
840
  if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node))
3231
0
    return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder);
3232
3233
840
  const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node);
3234
840
  return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder);
3235
840
}
3236
/// Matches the first method of a class or struct that satisfies \c
3237
/// InnerMatcher.
3238
///
3239
/// Given:
3240
/// \code
3241
///   class A { void func(); };
3242
///   class B { void member(); };
3243
/// \endcode
3244
///
3245
/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of
3246
/// \c A but not \c B.
3247
AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
3248
217
              InnerMatcher) {
3249
217
  BoundNodesTreeBuilder Result(*Builder);
3250
217
  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(),
3251
217
                                            Node.method_end(), Finder, &Result);
3252
217
  if (MatchIt == Node.method_end())
3253
139
    return false;
3254
3255
78
  if (Finder->isTraversalIgnoringImplicitNodes() && 
(*MatchIt)->isImplicit()8
)
3256
8
    return false;
3257
70
  *Builder = std::move(Result);
3258
70
  return true;
3259
70
}
3260
3261
/// Matches the generated class of lambda expressions.
3262
///
3263
/// Given:
3264
/// \code
3265
///   auto x = []{};
3266
/// \endcode
3267
///
3268
/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of
3269
/// \c decltype(x)
3270
200
AST_MATCHER(CXXRecordDecl, isLambda) {
3271
200
  return Node.isLambda();
3272
200
}
3273
3274
/// Matches AST nodes that have child AST nodes that match the
3275
/// provided matcher.
3276
///
3277
/// Example matches X, Y
3278
///   (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X")))
3279
/// \code
3280
///   class X {};  // Matches X, because X::X is a class of name X inside X.
3281
///   class Y { class X {}; };
3282
///   class Z { class Y { class X {}; }; };  // Does not match Z.
3283
/// \endcode
3284
///
3285
/// ChildT must be an AST base type.
3286
///
3287
/// Usable as: Any Matcher
3288
/// Note that has is direct matcher, so it also matches things like implicit
3289
/// casts and paren casts. If you are matching with expr then you should
3290
/// probably consider using ignoringParenImpCasts like:
3291
/// has(ignoringParenImpCasts(expr())).
3292
extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has;
3293
3294
/// Matches AST nodes that have descendant AST nodes that match the
3295
/// provided matcher.
3296
///
3297
/// Example matches X, Y, Z
3298
///     (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X")))))
3299
/// \code
3300
///   class X {};  // Matches X, because X::X is a class of name X inside X.
3301
///   class Y { class X {}; };
3302
///   class Z { class Y { class X {}; }; };
3303
/// \endcode
3304
///
3305
/// DescendantT must be an AST base type.
3306
///
3307
/// Usable as: Any Matcher
3308
extern const internal::ArgumentAdaptingMatcherFunc<
3309
    internal::HasDescendantMatcher>
3310
    hasDescendant;
3311
3312
/// Matches AST nodes that have child AST nodes that match the
3313
/// provided matcher.
3314
///
3315
/// Example matches X, Y, Y::X, Z::Y, Z::Y::X
3316
///   (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X")))
3317
/// \code
3318
///   class X {};
3319
///   class Y { class X {}; };  // Matches Y, because Y::X is a class of name X
3320
///                             // inside Y.
3321
///   class Z { class Y { class X {}; }; };  // Does not match Z.
3322
/// \endcode
3323
///
3324
/// ChildT must be an AST base type.
3325
///
3326
/// As opposed to 'has', 'forEach' will cause a match for each result that
3327
/// matches instead of only on the first one.
3328
///
3329
/// Usable as: Any Matcher
3330
extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher>
3331
    forEach;
3332
3333
/// Matches AST nodes that have descendant AST nodes that match the
3334
/// provided matcher.
3335
///
3336
/// Example matches X, A, A::X, B, B::C, B::C::X
3337
///   (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X")))))
3338
/// \code
3339
///   class X {};
3340
///   class A { class X {}; };  // Matches A, because A::X is a class of name
3341
///                             // X inside A.
3342
///   class B { class C { class X {}; }; };
3343
/// \endcode
3344
///
3345
/// DescendantT must be an AST base type.
3346
///
3347
/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
3348
/// each result that matches instead of only on the first one.
3349
///
3350
/// Note: Recursively combined ForEachDescendant can cause many matches:
3351
///   cxxRecordDecl(forEachDescendant(cxxRecordDecl(
3352
///     forEachDescendant(cxxRecordDecl())
3353
///   )))
3354
/// will match 10 times (plus injected class name matches) on:
3355
/// \code
3356
///   class A { class B { class C { class D { class E {}; }; }; }; };
3357
/// \endcode
3358
///
3359
/// Usable as: Any Matcher
3360
extern const internal::ArgumentAdaptingMatcherFunc<
3361
    internal::ForEachDescendantMatcher>
3362
    forEachDescendant;
3363
3364
/// Matches if the node or any descendant matches.
3365
///
3366
/// Generates results for each match.
3367
///
3368
/// For example, in:
3369
/// \code
3370
///   class A { class B {}; class C {}; };
3371
/// \endcode
3372
/// The matcher:
3373
/// \code
3374
///   cxxRecordDecl(hasName("::A"),
3375
///                 findAll(cxxRecordDecl(isDefinition()).bind("m")))
3376
/// \endcode
3377
/// will generate results for \c A, \c B and \c C.
3378
///
3379
/// Usable as: Any Matcher
3380
template <typename T>
3381
2.25k
internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) {
3382
2.25k
  return eachOf(Matcher, forEachDescendant(Matcher));
3383
2.25k
}
3384
3385
/// Matches AST nodes that have a parent that matches the provided
3386
/// matcher.
3387
///
3388
/// Given
3389
/// \code
3390
/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
3391
/// \endcode
3392
/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
3393
///
3394
/// Usable as: Any Matcher
3395
extern const internal::ArgumentAdaptingMatcherFunc<
3396
    internal::HasParentMatcher,
3397
    internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
3398
    internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
3399
    hasParent;
3400
3401
/// Matches AST nodes that have an ancestor that matches the provided
3402
/// matcher.
3403
///
3404
/// Given
3405
/// \code
3406
/// void f() { if (true) { int x = 42; } }
3407
/// void g() { for (;;) { int x = 43; } }
3408
/// \endcode
3409
/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
3410
///
3411
/// Usable as: Any Matcher
3412
extern const internal::ArgumentAdaptingMatcherFunc<
3413
    internal::HasAncestorMatcher,
3414
    internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
3415
    internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
3416
    hasAncestor;
3417
3418
/// Matches if the provided matcher does not match.
3419
///
3420
/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X"))))
3421
/// \code
3422
///   class X {};
3423
///   class Y {};
3424
/// \endcode
3425
///
3426
/// Usable as: Any Matcher
3427
extern const internal::VariadicOperatorMatcherFunc<1, 1> unless;
3428
3429
/// Matches a node if the declaration associated with that node
3430
/// matches the given matcher.
3431
///
3432
/// The associated declaration is:
3433
/// - for type nodes, the declaration of the underlying type
3434
/// - for CallExpr, the declaration of the callee
3435
/// - for MemberExpr, the declaration of the referenced member
3436
/// - for CXXConstructExpr, the declaration of the constructor
3437
/// - for CXXNewExpr, the declaration of the operator new
3438
/// - for ObjCIvarExpr, the declaration of the ivar
3439
///
3440
/// For type nodes, hasDeclaration will generally match the declaration of the
3441
/// sugared type. Given
3442
/// \code
3443
///   class X {};
3444
///   typedef X Y;
3445
///   Y y;
3446
/// \endcode
3447
/// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the
3448
/// typedefDecl. A common use case is to match the underlying, desugared type.
3449
/// This can be achieved by using the hasUnqualifiedDesugaredType matcher:
3450
/// \code
3451
///   varDecl(hasType(hasUnqualifiedDesugaredType(
3452
///       recordType(hasDeclaration(decl())))))
3453
/// \endcode
3454
/// In this matcher, the decl will match the CXXRecordDecl of class X.
3455
///
3456
/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>,
3457
///   Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>,
3458
///   Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>,
3459
///   Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>,
3460
///   Matcher<TagType>, Matcher<TemplateSpecializationType>,
3461
///   Matcher<TemplateTypeParmType>, Matcher<TypedefType>,
3462
///   Matcher<UnresolvedUsingType>
3463
inline internal::PolymorphicMatcherWithParam1<
3464
    internal::HasDeclarationMatcher, internal::Matcher<Decl>,
3465
    void(internal::HasDeclarationSupportedTypes)>
3466
22.0k
hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
3467
22.0k
  return internal::PolymorphicMatcherWithParam1<
3468
22.0k
      internal::HasDeclarationMatcher, internal::Matcher<Decl>,
3469
22.0k
      void(internal::HasDeclarationSupportedTypes)>(InnerMatcher);
3470
22.0k
}
3471
3472
/// Matches a \c NamedDecl whose underlying declaration matches the given
3473
/// matcher.
3474
///
3475
/// Given
3476
/// \code
3477
///   namespace N { template<class T> void f(T t); }
3478
///   template <class T> void g() { using N::f; f(T()); }
3479
/// \endcode
3480
/// \c unresolvedLookupExpr(hasAnyDeclaration(
3481
///     namedDecl(hasUnderlyingDecl(hasName("::N::f")))))
3482
///   matches the use of \c f in \c g() .
3483
AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>,
3484
2
              InnerMatcher) {
3485
2
  const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl();
3486
3487
2
  return UnderlyingDecl != nullptr &&
3488
2
         InnerMatcher.matches(*UnderlyingDecl, Finder, Builder);
3489
2
}
3490
3491
/// Matches on the implicit object argument of a member call expression, after
3492
/// stripping off any parentheses or implicit casts.
3493
///
3494
/// Given
3495
/// \code
3496
///   class Y { public: void m(); };
3497
///   Y g();
3498
///   class X : public Y {};
3499
///   void z(Y y, X x) { y.m(); (g()).m(); x.m(); }
3500
/// \endcode
3501
/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))
3502
///   matches `y.m()` and `(g()).m()`.
3503
/// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))))
3504
///   matches `x.m()`.
3505
/// cxxMemberCallExpr(on(callExpr()))
3506
///   matches `(g()).m()`.
3507
///
3508
/// FIXME: Overload to allow directly matching types?
3509
AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
3510
416
              InnerMatcher) {
3511
416
  const Expr *ExprNode = Node.getImplicitObjectArgument()
3512
416
                            ->IgnoreParenImpCasts();
3513
416
  return (ExprNode != nullptr &&
3514
416
          InnerMatcher.matches(*ExprNode, Finder, Builder));
3515
416
}
3516
3517
3518
/// Matches on the receiver of an ObjectiveC Message expression.
3519
///
3520
/// Example
3521
/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *")));
3522
/// matches the [webView ...] message invocation.
3523
/// \code
3524
///   NSString *webViewJavaScript = ...
3525
///   UIWebView *webView = ...
3526
///   [webView stringByEvaluatingJavaScriptFromString:webViewJavascript];
3527
/// \endcode
3528
AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>,
3529
11
              InnerMatcher) {
3530
11
  const QualType TypeDecl = Node.getReceiverType();
3531
11
  return InnerMatcher.matches(TypeDecl, Finder, Builder);
3532
11
}
3533
3534
/// Returns true when the Objective-C method declaration is a class method.
3535
///
3536
/// Example
3537
/// matcher = objcMethodDecl(isClassMethod())
3538
/// matches
3539
/// \code
3540
/// @interface I + (void)foo; @end
3541
/// \endcode
3542
/// but not
3543
/// \code
3544
/// @interface I - (void)bar; @end
3545
/// \endcode
3546
8
AST_MATCHER(ObjCMethodDecl, isClassMethod) {
3547
8
  return Node.isClassMethod();
3548
8
}
3549
3550
/// Returns true when the Objective-C method declaration is an instance method.
3551
///
3552
/// Example
3553
/// matcher = objcMethodDecl(isInstanceMethod())
3554
/// matches
3555
/// \code
3556
/// @interface I - (void)bar; @end
3557
/// \endcode
3558
/// but not
3559
/// \code
3560
/// @interface I + (void)foo; @end
3561
/// \endcode
3562
8
AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
3563
8
  return Node.isInstanceMethod();
3564
8
}
3565
3566
/// Returns true when the Objective-C message is sent to a class.
3567
///
3568
/// Example
3569
/// matcher = objcMessageExpr(isClassMessage())
3570
/// matches
3571
/// \code
3572
///   [NSString stringWithFormat:@"format"];
3573
/// \endcode
3574
/// but not
3575
/// \code
3576
///   NSString *x = @"hello";
3577
///   [x containsString:@"h"];
3578
/// \endcode
3579
4
AST_MATCHER(ObjCMessageExpr, isClassMessage) {
3580
4
  return Node.isClassMessage();
3581
4
}
3582
3583
/// Returns true when the Objective-C message is sent to an instance.
3584
///
3585
/// Example
3586
/// matcher = objcMessageExpr(isInstanceMessage())
3587
/// matches
3588
/// \code
3589
///   NSString *x = @"hello";
3590
///   [x containsString:@"h"];
3591
/// \endcode
3592
/// but not
3593
/// \code
3594
///   [NSString stringWithFormat:@"format"];
3595
/// \endcode
3596
4
AST_MATCHER(ObjCMessageExpr, isInstanceMessage) {
3597
4
  return Node.isInstanceMessage();
3598
4
}
3599
3600
/// Matches if the Objective-C message is sent to an instance,
3601
/// and the inner matcher matches on that instance.
3602
///
3603
/// For example the method call in
3604
/// \code
3605
///   NSString *x = @"hello";
3606
///   [x containsString:@"h"];
3607
/// \endcode
3608
/// is matched by
3609
/// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))
3610
AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>,
3611
15
              InnerMatcher) {
3612
15
  const Expr *ReceiverNode = Node.getInstanceReceiver();
3613
15
  return (ReceiverNode != nullptr &&
3614
13
          InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder,
3615
13
                               Builder));
3616
15
}
3617
3618
/// Matches when BaseName == Selector.getAsString()
3619
///
3620
///  matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:"));
3621
///  matches the outer message expr in the code below, but NOT the message
3622
///  invocation for self.bodyView.
3623
/// \code
3624
///     [self.bodyView loadHTMLString:html baseURL:NULL];
3625
/// \endcode
3626
53
AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) {
3627
53
  Selector Sel = Node.getSelector();
3628
53
  return BaseName.compare(Sel.getAsString()) == 0;
3629
53
}
3630
3631
3632
/// Matches when at least one of the supplied string equals to the
3633
/// Selector.getAsString()
3634
///
3635
///  matcher = objCMessageExpr(hasSelector("methodA:", "methodB:"));
3636
///  matches both of the expressions below:
3637
/// \code
3638
///     [myObj methodA:argA];
3639
///     [myObj methodB:argB];
3640
/// \endcode
3641
extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>,
3642
                                        StringRef,
3643
                                        internal::hasAnySelectorFunc>
3644
                                        hasAnySelector;
3645
3646
/// Matches ObjC selectors whose name contains
3647
/// a substring matched by the given RegExp.
3648
///  matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?"));
3649
///  matches the outer message expr in the code below, but NOT the message
3650
///  invocation for self.bodyView.
3651
/// \code
3652
///     [self.bodyView loadHTMLString:html baseURL:NULL];
3653
/// \endcode
3654
12
AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) {
3655
12
  std::string SelectorString = Node.getSelector().getAsString();
3656
12
  return RegExp->match(SelectorString);
3657
12
}
3658
3659
/// Matches when the selector is the empty selector
3660
///
3661
/// Matches only when the selector of the objCMessageExpr is NULL. This may
3662
/// represent an error condition in the tree!
3663
2
AST_MATCHER(ObjCMessageExpr, hasNullSelector) {
3664
2
  return Node.getSelector().isNull();
3665
2
}
3666
3667
/// Matches when the selector is a Unary Selector
3668
///
3669
///  matcher = objCMessageExpr(matchesSelector(hasUnarySelector());
3670
///  matches self.bodyView in the code below, but NOT the outer message
3671
///  invocation of "loadHTMLString:baseURL:".
3672
/// \code
3673
///     [self.bodyView loadHTMLString:html baseURL:NULL];
3674
/// \endcode
3675
2
AST_MATCHER(ObjCMessageExpr, hasUnarySelector) {
3676
2
  return Node.getSelector().isUnarySelector();
3677
2
}
3678
3679
/// Matches when the selector is a keyword selector
3680
///
3681
/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame
3682
/// message expression in
3683
///
3684
/// \code
3685
///   UIWebView *webView = ...;
3686
///   CGRect bodyFrame = webView.frame;
3687
///   bodyFrame.size.height = self.bodyContentHeight;
3688
///   webView.frame = bodyFrame;
3689
///   //     ^---- matches here
3690
/// \endcode
3691
0
AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) {
3692
0
  return Node.getSelector().isKeywordSelector();
3693
0
}
3694
3695
/// Matches when the selector has the specified number of arguments
3696
///
3697
///  matcher = objCMessageExpr(numSelectorArgs(0));
3698
///  matches self.bodyView in the code below
3699
///
3700
///  matcher = objCMessageExpr(numSelectorArgs(2));
3701
///  matches the invocation of "loadHTMLString:baseURL:" but not that
3702
///  of self.bodyView
3703
/// \code
3704
///     [self.bodyView loadHTMLString:html baseURL:NULL];
3705
/// \endcode
3706
2
AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) {
3707
2
  return Node.getSelector().getNumArgs() == N;
3708
2
}
3709
3710
/// Matches if the call expression's callee expression matches.
3711
///
3712
/// Given
3713
/// \code
3714
///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
3715
///   void f() { f(); }
3716
/// \endcode
3717
/// callExpr(callee(expr()))
3718
///   matches this->x(), x(), y.x(), f()
3719
/// with callee(...)
3720
///   matching this->x, x, y.x, f respectively
3721
///
3722
/// Note: Callee cannot take the more general internal::Matcher<Expr>
3723
/// because this introduces ambiguous overloads with calls to Callee taking a
3724
/// internal::Matcher<Decl>, as the matcher hierarchy is purely
3725
/// implemented in terms of implicit casts.
3726
AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
3727
299
              InnerMatcher) {
3728
299
  const Expr *ExprNode = Node.getCallee();
3729
299
  return (ExprNode != nullptr &&
3730
299
          InnerMatcher.matches(*ExprNode, Finder, Builder));
3731
299
}
3732
3733
/// Matches if the call expression's callee's declaration matches the
3734
/// given matcher.
3735
///
3736
/// Example matches y.x() (matcher = callExpr(callee(
3737
///                                    cxxMethodDecl(hasName("x")))))
3738
/// \code
3739
///   class Y { public: void x(); };
3740
///   void z() { Y y; y.x(); }
3741
/// \endcode
3742
AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher,
3743
1.44k
                       1) {
3744
1.44k
  return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder);
3745
1.44k
}
3746
3747
/// Matches if the expression's or declaration's type matches a type
3748
/// matcher.
3749
///
3750
/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3751
///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3752
///             and U (matcher = typedefDecl(hasType(asString("int")))
3753
///             and friend class X (matcher = friendDecl(hasType("X"))
3754
/// \code
3755
///  class X {};
3756
///  void y(X &x) { x; X z; }
3757
///  typedef int U;
3758
///  class Y { friend class X; };
3759
/// \endcode
3760
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3761
    hasType,
3762
    AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl,
3763
                                    ValueDecl),
3764
7.25k
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
7.25k
  QualType QT = internal::getUnderlyingType(Node);
3766
7.25k
  if (!QT.isNull())
3767
7.23k
    return InnerMatcher.matches(QT, Finder, Builder);
3768
20
  return false;
3769
20
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::ExplicitCastExpr, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::ExplicitCastExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
228
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
228
  QualType QT = internal::getUnderlyingType(Node);
3766
228
  if (!QT.isNull())
3767
228
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::CStyleCastExpr, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::CStyleCastExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
3
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
3
  QualType QT = internal::getUnderlyingType(Node);
3766
3
  if (!QT.isNull())
3767
3
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::FieldDecl, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::FieldDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
239
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
239
  QualType QT = internal::getUnderlyingType(Node);
3766
239
  if (!QT.isNull())
3767
239
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::VarDecl, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::VarDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
3.05k
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
3.05k
  QualType QT = internal::getUnderlyingType(Node);
3766
3.05k
  if (!QT.isNull())
3767
3.05k
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::ParmVarDecl, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::ParmVarDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
483
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
483
  QualType QT = internal::getUnderlyingType(Node);
3766
483
  if (!QT.isNull())
3767
483
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::Expr, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::Expr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
3.07k
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
3.07k
  QualType QT = internal::getUnderlyingType(Node);
3766
3.07k
  if (!QT.isNull())
3767
3.05k
    return InnerMatcher.matches(QT, Finder, Builder);
3768
20
  return false;
3769
20
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::FriendDecl, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::FriendDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
20
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
20
  QualType QT = internal::getUnderlyingType(Node);
3766
20
  if (!QT.isNull())
3767
20
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::TypedefNameDecl, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::TypedefNameDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
26
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
26
  QualType QT = internal::getUnderlyingType(Node);
3766
26
  if (!QT.isNull())
3767
26
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::ValueDecl, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::ValueDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
96
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
96
  QualType QT = internal::getUnderlyingType(Node);
3766
96
  if (!QT.isNull())
3767
96
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
clang::ast_matchers::internal::matcher_hasType0Matcher<clang::DeclRefExpr, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::DeclRefExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3764
33
    internal::Matcher<QualType>, InnerMatcher, 0) {
3765
33
  QualType QT = internal::getUnderlyingType(Node);
3766
33
  if (!QT.isNull())
3767
33
    return InnerMatcher.matches(QT, Finder, Builder);
3768
0
  return false;
3769
0
}
3770
3771
/// Overloaded to match the declaration of the expression's or value
3772
/// declaration's type.
3773
///
3774
/// In case of a value declaration (for example a variable declaration),
3775
/// this resolves one layer of indirection. For example, in the value
3776
/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of
3777
/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the
3778
/// declaration of x.
3779
///
3780
/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X")))))
3781
///             and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X")))))
3782
///             and friend class X (matcher = friendDecl(hasType("X"))
3783
/// \code
3784
///  class X {};
3785
///  void y(X &x) { x; X z; }
3786
///  class Y { friend class X; };
3787
/// \endcode
3788
///
3789
/// Example matches class Derived
3790
/// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base"))))))
3791
/// \code
3792
/// class Base {};
3793
/// class Derived : Base {};
3794
/// \endcode
3795
///
3796
/// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>,
3797
/// Matcher<CXXBaseSpecifier>
3798
AST_POLYMORPHIC_MATCHER_P_OVERLOAD(
3799
    hasType,
3800
    AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl,
3801
                                    CXXBaseSpecifier),
3802
781
    internal::Matcher<Decl>, InnerMatcher, 1) {
3803
781
  QualType QT = internal::getUnderlyingType(Node);
3804
781
  if (!QT.isNull())
3805
781
    return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3806
0
  return false;
3807
0
}
clang::ast_matchers::internal::matcher_hasType1Matcher<clang::VarDecl, clang::ast_matchers::internal::Matcher<clang::Decl> >::matches(clang::VarDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3802
102
    internal::Matcher<Decl>, InnerMatcher, 1) {
3803
102
  QualType QT = internal::getUnderlyingType(Node);
3804
102
  if (!QT.isNull())
3805
102
    return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3806
0
  return false;
3807
0
}
clang::ast_matchers::internal::matcher_hasType1Matcher<clang::Expr, clang::ast_matchers::internal::Matcher<clang::Decl> >::matches(clang::Expr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3802
479
    internal::Matcher<Decl>, InnerMatcher, 1) {
3803
479
  QualType QT = internal::getUnderlyingType(Node);
3804
479
  if (!QT.isNull())
3805
479
    return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3806
0
  return false;
3807
0
}
clang::ast_matchers::internal::matcher_hasType1Matcher<clang::FriendDecl, clang::ast_matchers::internal::Matcher<clang::Decl> >::matches(clang::FriendDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3802
20
    internal::Matcher<Decl>, InnerMatcher, 1) {
3803
20
  QualType QT = internal::getUnderlyingType(Node);
3804
20
  if (!QT.isNull())
3805
20
    return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3806
0
  return false;
3807
0
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_hasType1Matcher<clang::ValueDecl, clang::ast_matchers::internal::Matcher<clang::Decl> >::matches(clang::ValueDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
clang::ast_matchers::internal::matcher_hasType1Matcher<clang::CXXBaseSpecifier, clang::ast_matchers::internal::Matcher<clang::Decl> >::matches(clang::CXXBaseSpecifier const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
3802
180
    internal::Matcher<Decl>, InnerMatcher, 1) {
3803
180
  QualType QT = internal::getUnderlyingType(Node);
3804
180
  if (!QT.isNull())
3805
180
    return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder);
3806
0
  return false;
3807
0
}
3808
3809
/// Matches if the type location of the declarator decl's type matches
3810
/// the inner matcher.
3811
///
3812
/// Given
3813
/// \code
3814
///   int x;
3815
/// \endcode
3816
/// declaratorDecl(hasTypeLoc(loc(asString("int"))))
3817
///   matches int x
3818
30
AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) {
3819
30
  if (!Node.getTypeSourceInfo())
3820
    // This happens for example for implicit destructors.
3821
20
    return false;
3822
10
  return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder);
3823
10
}
3824
3825
/// Matches if the matched type is represented by the given string.
3826
///
3827
/// Given
3828
/// \code
3829
///   class Y { public: void x(); };
3830
///   void z() { Y* y; y->x(); }
3831
/// \endcode
3832
/// cxxMemberCallExpr(on(hasType(asString("class Y *"))))
3833
///   matches y->x()
3834
889
AST_MATCHER_P(QualType, asString, std::string, Name) {
3835
889
  return Name == Node.getAsString();
3836
889
}
3837
3838
/// Matches if the matched type is a pointer type and the pointee type
3839
/// matches the specified matcher.
3840
///
3841
/// Example matches y->x()
3842
///   (matcher = cxxMemberCallExpr(on(hasType(pointsTo
3843
///      cxxRecordDecl(hasName("Y")))))))
3844
/// \code
3845
///   class Y { public: void x(); };
3846
///   void z() { Y *y; y->x(); }
3847
/// \endcode
3848
AST_MATCHER_P(
3849
    QualType, pointsTo, internal::Matcher<QualType>,
3850
636
    InnerMatcher) {
3851
636
  return (!Node.isNull() && Node->isAnyPointerType() &&
3852
438
          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3853
636
}
3854
3855
/// Overloaded to match the pointee type's declaration.
3856
AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>,
3857
388
                       InnerMatcher, 1) {
3858
388
  return pointsTo(qualType(hasDeclaration(InnerMatcher)))
3859
388
      .matches(Node, Finder, Builder);
3860
388
}
3861
3862
/// Matches if the matched type matches the unqualified desugared
3863
/// type of the matched node.
3864
///
3865
/// For example, in:
3866
/// \code
3867
///   class A {};
3868
///   using B = A;
3869
/// \endcode
3870
/// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches
3871
/// both B and A.
3872
AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>,
3873
617
              InnerMatcher) {
3874
617
  return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder,
3875
617
                              Builder);
3876
617
}
3877
3878
/// Matches if the matched type is a reference type and the referenced
3879
/// type matches the specified matcher.
3880
///
3881
/// Example matches X &x and const X &y
3882
///     (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X"))))))
3883
/// \code
3884
///   class X {
3885
///     void a(X b) {
3886
///       X &x = b;
3887
///       const X &y = b;
3888
///     }
3889
///   };
3890
/// \endcode
3891
AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
3892
324
              InnerMatcher) {
3893
324
  return (!Node.isNull() && Node->isReferenceType() &&
3894
104
          InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
3895
324
}
3896
3897
/// Matches QualTypes whose canonical type matches InnerMatcher.
3898
///
3899
/// Given:
3900
/// \code
3901
///   typedef int &int_ref;
3902
///   int a;
3903
///   int_ref b = a;
3904
/// \endcode
3905
///
3906
/// \c varDecl(hasType(qualType(referenceType()))))) will not match the
3907
/// declaration of b but \c
3908
/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
3909
AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
3910
2.46k
              InnerMatcher) {
3911
2.46k
  if (Node.isNull())
3912
0
    return false;
3913
2.46k
  return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
3914
2.46k
}
3915
3916
/// Overloaded to match the referenced type's declaration.
3917
AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>,
3918
218
                       InnerMatcher, 1) {
3919
218
  return references(qualType(hasDeclaration(InnerMatcher)))
3920
218
      .matches(Node, Finder, Builder);
3921
218
}
3922
3923
/// Matches on the implicit object argument of a member call expression. Unlike
3924
/// `on`, matches the argument directly without stripping away anything.
3925
///
3926
/// Given
3927
/// \code
3928
///   class Y { public: void m(); };
3929
///   Y g();
3930
///   class X : public Y { void g(); };
3931
///   void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); }
3932
/// \endcode
3933
/// cxxMemberCallExpr(onImplicitObjectArgument(hasType(
3934
///     cxxRecordDecl(hasName("Y")))))
3935
///   matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`.
3936
/// cxxMemberCallExpr(on(callExpr()))
3937
///   does not match `(g()).m()`, because the parens are not ignored.
3938
///
3939
/// FIXME: Overload to allow directly matching types?
3940
AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
3941
149
              internal::Matcher<Expr>, InnerMatcher) {
3942
149
  const Expr *ExprNode = Node.getImplicitObjectArgument();
3943
149
  return (ExprNode != nullptr &&
3944
149
          InnerMatcher.matches(*ExprNode, Finder, Builder));
3945
149
}
3946
3947
/// Matches if the type of the expression's implicit object argument either
3948
/// matches the InnerMatcher, or is a pointer to a type that matches the
3949
/// InnerMatcher.
3950
///
3951
/// Given
3952
/// \code
3953
///   class Y { public: void m(); };
3954
///   class X : public Y { void g(); };
3955
///   void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); }
3956
/// \endcode
3957
/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3958
///     cxxRecordDecl(hasName("Y")))))
3959
///   matches `y.m()`, `p->m()` and `x.m()`.
3960
/// cxxMemberCallExpr(thisPointerType(hasDeclaration(
3961
///     cxxRecordDecl(hasName("X")))))
3962
///   matches `x.g()`.
3963
AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3964
0
                       internal::Matcher<QualType>, InnerMatcher, 0) {
3965
0
  return onImplicitObjectArgument(
3966
0
      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3967
0
      .matches(Node, Finder, Builder);
3968
0
}
3969
3970
/// Overloaded to match the type's declaration.
3971
AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType,
3972
140
                       internal::Matcher<Decl>, InnerMatcher, 1) {
3973
140
  return onImplicitObjectArgument(
3974
140
      anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))))
3975
140
      .matches(Node, Finder, Builder);
3976
140
}
3977
3978
/// Matches a DeclRefExpr that refers to a declaration that matches the
3979
/// specified matcher.
3980
///
3981
/// Example matches x in if(x)
3982
///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
3983
/// \code
3984
///   bool x;
3985
///   if (x) {}
3986
/// \endcode
3987
AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
3988
3.22k
              InnerMatcher) {
3989
3.22k
  const Decl *DeclNode = Node.getDecl();
3990
3.22k
  return (DeclNode != nullptr &&
3991
3.22k
          InnerMatcher.matches(*DeclNode, Finder, Builder));
3992
3.22k
}
3993
3994
/// Matches a \c DeclRefExpr that refers to a declaration through a
3995
/// specific using shadow declaration.
3996
///
3997
/// Given
3998
/// \code
3999
///   namespace a { void f() {} }
4000
///   using a::f;
4001
///   void g() {
4002
///     f();     // Matches this ..
4003
///     a::f();  // .. but not this.
4004
///   }
4005
/// \endcode
4006
/// declRefExpr(throughUsingDecl(anything()))
4007
///   matches \c f()
4008
AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
4009
4
              internal::Matcher<UsingShadowDecl>, InnerMatcher) {
4010
4
  const NamedDecl *FoundDecl = Node.getFoundDecl();
4011
4
  if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
4012
2
    return InnerMatcher.matches(*UsingDecl, Finder, Builder);
4013
2
  return false;
4014
2
}
4015
4016
/// Matches an \c OverloadExpr if any of the declarations in the set of
4017
/// overloads matches the given matcher.
4018
///
4019
/// Given
4020
/// \code
4021
///   template <typename T> void foo(T);
4022
///   template <typename T> void bar(T);
4023
///   template <typename T> void baz(T t) {
4024
///     foo(t);
4025
///     bar(t);
4026
///   }
4027
/// \endcode
4028
/// unresolvedLookupExpr(hasAnyDeclaration(
4029
///     functionTemplateDecl(hasName("foo"))))
4030
///   matches \c foo in \c foo(t); but not \c bar in \c bar(t);
4031
AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>,
4032
14
              InnerMatcher) {
4033
14
  return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(),
4034
14
                                    Node.decls_end(), Finder,
4035
14
                                    Builder) != Node.decls_end();
4036
14
}
4037
4038
/// Matches the Decl of a DeclStmt which has a single declaration.
4039
///
4040
/// Given
4041
/// \code
4042
///   int a, b;
4043
///   int c;
4044
/// \endcode
4045
/// declStmt(hasSingleDecl(anything()))
4046
///   matches 'int c;' but not 'int a, b;'.
4047
409
AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
4048
409
  if (Node.isSingleDecl()) {
4049
407
    const Decl *FoundDecl = Node.getSingleDecl();
4050
407
    return InnerMatcher.matches(*FoundDecl, Finder, Builder);
4051
407
  }
4052
2
  return false;
4053
2
}
4054
4055
/// Matches a variable declaration that has an initializer expression
4056
/// that matches the given matcher.
4057
///
4058
/// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
4059
/// \code
4060
///   bool y() { return true; }
4061
///   bool x = y();
4062
/// \endcode
4063
AST_MATCHER_P(
4064
    VarDecl, hasInitializer, internal::Matcher<Expr>,
4065
1.38k
    InnerMatcher) {
4066
1.38k
  const Expr *Initializer = Node.getAnyInitializer();
4067
1.38k
  return (Initializer != nullptr &&
4068
1.13k
          InnerMatcher.matches(*Initializer, Finder, Builder));
4069
1.38k
}
4070
4071
/// \brief Matches a static variable with local scope.
4072
///
4073
/// Example matches y (matcher = varDecl(isStaticLocal()))
4074
/// \code
4075
/// void f() {
4076
///   int x;
4077
///   static int y;
4078
/// }
4079
/// static int z;
4080
/// \endcode
4081
112
AST_MATCHER(VarDecl, isStaticLocal) {
4082
112
  return Node.isStaticLocal();
4083
112
}
4084
4085
/// Matches a variable declaration that has function scope and is a
4086
/// non-static local variable.
4087
///
4088
/// Example matches x (matcher = varDecl(hasLocalStorage())
4089
/// \code
4090
/// void f() {
4091
///   int x;
4092
///   static int y;
4093
/// }
4094
/// int z;
4095
/// \endcode
4096
84
AST_MATCHER(VarDecl, hasLocalStorage) {
4097
84
  return Node.hasLocalStorage();
4098
84
}
4099
4100
/// Matches a variable declaration that does not have local storage.
4101
///
4102
/// Example matches y and z (matcher = varDecl(hasGlobalStorage())
4103
/// \code
4104
/// void f() {
4105
///   int x;
4106
///   static int y;
4107
/// }
4108
/// int z;
4109
/// \endcode
4110
84
AST_MATCHER(VarDecl, hasGlobalStorage) {
4111
84
  return Node.hasGlobalStorage();
4112
84
}
4113
4114
/// Matches a variable declaration that has automatic storage duration.
4115
///
4116
/// Example matches x, but not y, z, or a.
4117
/// (matcher = varDecl(hasAutomaticStorageDuration())
4118
/// \code
4119
/// void f() {
4120
///   int x;
4121
///   static int y;
4122
///   thread_local int z;
4123
/// }
4124
/// int a;
4125
/// \endcode
4126
84
AST_MATCHER(VarDecl, hasAutomaticStorageDuration) {
4127
84
  return Node.getStorageDuration() == SD_Automatic;
4128
84
}
4129
4130
/// Matches a variable declaration that has static storage duration.
4131
/// It includes the variable declared at namespace scope and those declared
4132
/// with "static" and "extern" storage class specifiers.
4133
///
4134
/// \code
4135
/// void f() {
4136
///   int x;
4137
///   static int y;
4138
///   thread_local int z;
4139
/// }
4140
/// int a;
4141
/// static int b;
4142
/// extern int c;
4143
/// varDecl(hasStaticStorageDuration())
4144
///   matches the function declaration y, a, b and c.
4145
/// \endcode
4146
144
AST_MATCHER(VarDecl, hasStaticStorageDuration) {
4147
144
  return Node.getStorageDuration() == SD_Static;
4148
144
}
4149
4150
/// Matches a variable declaration that has thread storage duration.
4151
///
4152
/// Example matches z, but not x, z, or a.
4153
/// (matcher = varDecl(hasThreadStorageDuration())
4154
/// \code
4155
/// void f() {
4156
///   int x;
4157
///   static int y;
4158
///   thread_local int z;
4159
/// }
4160
/// int a;
4161
/// \endcode
4162
84
AST_MATCHER(VarDecl, hasThreadStorageDuration) {
4163
84
  return Node.getStorageDuration() == SD_Thread;
4164
84
}
4165
4166
/// Matches a variable declaration that is an exception variable from
4167
/// a C++ catch block, or an Objective-C \@catch statement.
4168
///
4169
/// Example matches x (matcher = varDecl(isExceptionVariable())
4170
/// \code
4171
/// void f(int y) {
4172
///   try {
4173
///   } catch (int x) {
4174
///   }
4175
/// }
4176
/// \endcode
4177
40
AST_MATCHER(VarDecl, isExceptionVariable) {
4178
40
  return Node.isExceptionVariable();
4179
40
}
4180
4181
/// Checks that a call expression or a constructor call expression has
4182
/// a specific number of arguments (including absent default arguments).
4183
///
4184
/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
4185
/// \code
4186
///   void f(int x, int y);
4187
///   f(0, 0);
4188
/// \endcode
4189
AST_POLYMORPHIC_MATCHER_P(argumentCountIs,
4190
                          AST_POLYMORPHIC_SUPPORTED_TYPES(
4191
                              CallExpr, CXXConstructExpr,
4192
                              CXXUnresolvedConstructExpr, ObjCMessageExpr),
4193
202
                          unsigned, N) {
4194
202
  unsigned NumArgs = Node.getNumArgs();
4195
202
  if (!Finder->isTraversalIgnoringImplicitNodes())
4196
198
    return NumArgs == N;
4197
8
  
while (4
NumArgs) {
4198
8
    if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4199
4
      break;
4200
4
    --NumArgs;
4201
4
  }
4202
4
  return NumArgs == N;
4203
4
}
clang::ast_matchers::internal::matcher_argumentCountIs0Matcher<clang::CallExpr, unsigned int>::matches(clang::CallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4193
87
                          unsigned, N) {
4194
87
  unsigned NumArgs = Node.getNumArgs();
4195
87
  if (!Finder->isTraversalIgnoringImplicitNodes())
4196
83
    return NumArgs == N;
4197
8
  
while (4
NumArgs) {
4198
8
    if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4199
4
      break;
4200
4
    --NumArgs;
4201
4
  }
4202
4
  return NumArgs == N;
4203
4
}
clang::ast_matchers::internal::matcher_argumentCountIs0Matcher<clang::CXXConstructExpr, unsigned int>::matches(clang::CXXConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4193
104
                          unsigned, N) {
4194
104
  unsigned NumArgs = Node.getNumArgs();
4195
104
  if (!Finder->isTraversalIgnoringImplicitNodes())
4196
104
    return NumArgs == N;
4197
0
  while (NumArgs) {
4198
0
    if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4199
0
      break;
4200
0
    --NumArgs;
4201
0
  }
4202
0
  return NumArgs == N;
4203
0
}
clang::ast_matchers::internal::matcher_argumentCountIs0Matcher<clang::CXXUnresolvedConstructExpr, unsigned int>::matches(clang::CXXUnresolvedConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4193
4
                          unsigned, N) {
4194
4
  unsigned NumArgs = Node.getNumArgs();
4195
4
  if (!Finder->isTraversalIgnoringImplicitNodes())
4196
4
    return NumArgs == N;
4197
0
  while (NumArgs) {
4198
0
    if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4199
0
      break;
4200
0
    --NumArgs;
4201
0
  }
4202
0
  return NumArgs == N;
4203
0
}
clang::ast_matchers::internal::matcher_argumentCountIs0Matcher<clang::ObjCMessageExpr, unsigned int>::matches(clang::ObjCMessageExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4193
2
                          unsigned, N) {
4194
2
  unsigned NumArgs = Node.getNumArgs();
4195
2
  if (!Finder->isTraversalIgnoringImplicitNodes())
4196
2
    return NumArgs == N;
4197
0
  while (NumArgs) {
4198
0
    if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4199
0
      break;
4200
0
    --NumArgs;
4201
0
  }
4202
0
  return NumArgs == N;
4203
0
}
clang::ast_matchers::internal::matcher_argumentCountIs0Matcher<clang::CXXOperatorCallExpr, unsigned int>::matches(clang::CXXOperatorCallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4193
5
                          unsigned, N) {
4194
5
  unsigned NumArgs = Node.getNumArgs();
4195
5
  if (!Finder->isTraversalIgnoringImplicitNodes())
4196
5
    return NumArgs == N;
4197
0
  while (NumArgs) {
4198
0
    if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1)))
4199
0
      break;
4200
0
    --NumArgs;
4201
0
  }
4202
0
  return NumArgs == N;
4203
0
}
4204
4205
/// Matches the n'th argument of a call expression or a constructor
4206
/// call expression.
4207
///
4208
/// Example matches y in x(y)
4209
///     (matcher = callExpr(hasArgument(0, declRefExpr())))
4210
/// \code
4211
///   void x(int) { int y; x(y); }
4212
/// \endcode
4213
AST_POLYMORPHIC_MATCHER_P2(hasArgument,
4214
                           AST_POLYMORPHIC_SUPPORTED_TYPES(
4215
                               CallExpr, CXXConstructExpr,
4216
                               CXXUnresolvedConstructExpr, ObjCMessageExpr),
4217
779
                           unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4218
779
  if (N >= Node.getNumArgs())
4219
22
    return false;
4220
757
  const Expr *Arg = Node.getArg(N);
4221
757
  if (Finder->isTraversalIgnoringImplicitNodes() && 
isa<CXXDefaultArgExpr>(Arg)71
)
4222
2
    return false;
4223
755
  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4224
755
}
clang::ast_matchers::internal::matcher_hasArgument0Matcher<clang::CallExpr, unsigned int, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4217
558
                           unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4218
558
  if (N >= Node.getNumArgs())
4219
2
    return false;
4220
556
  const Expr *Arg = Node.getArg(N);
4221
556
  if (Finder->isTraversalIgnoringImplicitNodes() && 
isa<CXXDefaultArgExpr>(Arg)34
)
4222
2
    return false;
4223
554
  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4224
554
}
clang::ast_matchers::internal::matcher_hasArgument0Matcher<clang::CXXConstructExpr, unsigned int, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CXXConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4217
160
                           unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4218
160
  if (N >= Node.getNumArgs())
4219
20
    return false;
4220
140
  const Expr *Arg = Node.getArg(N);
4221
140
  if (Finder->isTraversalIgnoringImplicitNodes() && 
isa<CXXDefaultArgExpr>(Arg)32
)
4222
0
    return false;
4223
140
  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4224
140
}
clang::ast_matchers::internal::matcher_hasArgument0Matcher<clang::CXXUnresolvedConstructExpr, unsigned int, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CXXUnresolvedConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4217
4
                           unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4218
4
  if (N >= Node.getNumArgs())
4219
0
    return false;
4220
4
  const Expr *Arg = Node.getArg(N);
4221
4
  if (Finder->isTraversalIgnoringImplicitNodes() && 
isa<CXXDefaultArgExpr>(Arg)0
)
4222
0
    return false;
4223
4
  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4224
4
}
Unexecuted instantiation: clang::ast_matchers::internal::matcher_hasArgument0Matcher<clang::ObjCMessageExpr, unsigned int, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::ObjCMessageExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
clang::ast_matchers::internal::matcher_hasArgument0Matcher<clang::CXXOperatorCallExpr, unsigned int, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CXXOperatorCallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4217
57
                           unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
4218
57
  if (N >= Node.getNumArgs())
4219
0
    return false;
4220
57
  const Expr *Arg = Node.getArg(N);
4221
57
  if (Finder->isTraversalIgnoringImplicitNodes() && 
isa<CXXDefaultArgExpr>(Arg)5
)
4222
0
    return false;
4223
57
  return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder);
4224
57
}
4225
4226
/// Matches the n'th item of an initializer list expression.
4227
///
4228
/// Example matches y.
4229
///     (matcher = initListExpr(hasInit(0, expr())))
4230
/// \code
4231
///   int x{y}.
4232
/// \endcode
4233
AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N,
4234
32
               ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
4235
32
  return N < Node.getNumInits() &&
4236
16
          InnerMatcher.matches(*Node.getInit(N), Finder, Builder);
4237
32
}
4238
4239
/// Matches declaration statements that contain a specific number of
4240
/// declarations.
4241
///
4242
/// Example: Given
4243
/// \code
4244
///   int a, b;
4245
///   int c;
4246
///   int d = 2, e;
4247
/// \endcode
4248
/// declCountIs(2)
4249
///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
4250
112
AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
4251
112
  return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
4252
112
}
4253
4254
/// Matches the n'th declaration of a declaration statement.
4255
///
4256
/// Note that this does not work for global declarations because the AST
4257
/// breaks up multiple-declaration DeclStmt's into multiple single-declaration
4258
/// DeclStmt's.
4259
/// Example: Given non-global declarations
4260
/// \code
4261
///   int a, b = 0;
4262
///   int c;
4263
///   int d = 2, e;
4264
/// \endcode
4265
/// declStmt(containsDeclaration(
4266
///       0, varDecl(hasInitializer(anything()))))
4267
///   matches only 'int d = 2, e;', and
4268
/// declStmt(containsDeclaration(1, varDecl()))
4269
/// \code
4270
///   matches 'int a, b = 0' as well as 'int d = 2, e;'
4271
///   but 'int c;' is not matched.
4272
/// \endcode
4273
AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
4274
9
               internal::Matcher<Decl>, InnerMatcher) {
4275
9
  const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
4276
9
  if (N >= NumDecls)
4277
2
    return false;
4278
7
  DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
4279
7
  std::advance(Iterator, N);
4280
7
  return InnerMatcher.matches(**Iterator, Finder, Builder);
4281
7
}
4282
4283
/// Matches a C++ catch statement that has a catch-all handler.
4284
///
4285
/// Given
4286
/// \code
4287
///   try {
4288
///     // ...
4289
///   } catch (int) {
4290
///     // ...
4291
///   } catch (...) {
4292
///     // ...
4293
///   }
4294
/// \endcode
4295
/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int).
4296
60
AST_MATCHER(CXXCatchStmt, isCatchAll) {
4297
60
  return Node.getExceptionDecl() == nullptr;
4298
60
}
4299
4300
/// Matches a constructor initializer.
4301
///
4302
/// Given
4303
/// \code
4304
///   struct Foo {
4305
///     Foo() : foo_(1) { }
4306
///     int foo_;
4307
///   };
4308
/// \endcode
4309
/// cxxRecordDecl(has(cxxConstructorDecl(
4310
///   hasAnyConstructorInitializer(anything())
4311
/// )))
4312
///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
4313
AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
4314
128
              internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
4315
128
  auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(),
4316
128
                                            Node.init_end(), Finder, Builder);
4317
128
  if (MatchIt == Node.init_end())
4318
96
    return false;
4319
32
  return (*MatchIt)->isWritten() || 
!Finder->isTraversalIgnoringImplicitNodes()8
;
4320
32
}
4321
4322
/// Matches the field declaration of a constructor initializer.
4323
///
4324
/// Given
4325
/// \code
4326
///   struct Foo {
4327
///     Foo() : foo_(1) { }
4328
///     int foo_;
4329
///   };
4330
/// \endcode
4331
/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4332
///     forField(hasName("foo_"))))))
4333
///   matches Foo
4334
/// with forField matching foo_
4335
AST_MATCHER_P(CXXCtorInitializer, forField,
4336
121
              internal::Matcher<FieldDecl>, InnerMatcher) {
4337
121
  const FieldDecl *NodeAsDecl = Node.getAnyMember();
4338
121
  return (NodeAsDecl != nullptr &&
4339
91
      InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
4340
121
}
4341
4342
/// Matches the initializer expression of a constructor initializer.
4343
///
4344
/// Given
4345
/// \code
4346
///   struct Foo {
4347
///     Foo() : foo_(1) { }
4348
///     int foo_;
4349
///   };
4350
/// \endcode
4351
/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer(
4352
///     withInitializer(integerLiteral(equals(1)))))))
4353
///   matches Foo
4354
/// with withInitializer matching (1)
4355
AST_MATCHER_P(CXXCtorInitializer, withInitializer,
4356
11
              internal::Matcher<Expr>, InnerMatcher) {
4357
11
  const Expr* NodeAsExpr = Node.getInit();
4358
11
  return (NodeAsExpr != nullptr &&
4359
11
      InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
4360
11
}
4361
4362
/// Matches a constructor initializer if it is explicitly written in
4363
/// code (as opposed to implicitly added by the compiler).
4364
///
4365
/// Given
4366
/// \code
4367
///   struct Foo {
4368
///     Foo() { }
4369
///     Foo(int) : foo_("A") { }
4370
///     string foo_;
4371
///   };
4372
/// \endcode
4373
/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten()))
4374
///   will match Foo(int), but not Foo()
4375
18
AST_MATCHER(CXXCtorInitializer, isWritten) {
4376
18
  return Node.isWritten();
4377
18
}
4378
4379
/// Matches a constructor initializer if it is initializing a base, as
4380
/// opposed to a member.
4381
///
4382
/// Given
4383
/// \code
4384
///   struct B {};
4385
///   struct D : B {
4386
///     int I;
4387
///     D(int i) : I(i) {}
4388
///   };
4389
///   struct E : B {
4390
///     E() : B() {}
4391
///   };
4392
/// \endcode
4393
/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer()))
4394
///   will match E(), but not match D(int).
4395
16
AST_MATCHER(CXXCtorInitializer, isBaseInitializer) {
4396
16
  return Node.isBaseInitializer();
4397
16
}
4398
4399
/// Matches a constructor initializer if it is initializing a member, as
4400
/// opposed to a base.
4401
///
4402
/// Given
4403
/// \code
4404
///   struct B {};
4405
///   struct D : B {
4406
///     int I;
4407
///     D(int i) : I(i) {}
4408
///   };
4409
///   struct E : B {
4410
///     E() : B() {}
4411
///   };
4412
/// \endcode
4413
/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer()))
4414
///   will match D(int), but not match E().
4415
12
AST_MATCHER(CXXCtorInitializer, isMemberInitializer) {
4416
12
  return Node.isMemberInitializer();
4417
12
}
4418
4419
/// Matches any argument of a call expression or a constructor call
4420
/// expression, or an ObjC-message-send expression.
4421
///
4422
/// Given
4423
/// \code
4424
///   void x(int, int, int) { int y; x(1, y, 42); }
4425
/// \endcode
4426
/// callExpr(hasAnyArgument(declRefExpr()))
4427
///   matches x(1, y, 42)
4428
/// with hasAnyArgument(...)
4429
///   matching y
4430
///
4431
/// For ObjectiveC, given
4432
/// \code
4433
///   @interface I - (void) f:(int) y; @end
4434
///   void foo(I *i) { [i f:12]; }
4435
/// \endcode
4436
/// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12))))
4437
///   matches [i f:12]
4438
AST_POLYMORPHIC_MATCHER_P(hasAnyArgument,
4439
                          AST_POLYMORPHIC_SUPPORTED_TYPES(
4440
                              CallExpr, CXXConstructExpr,
4441
                              CXXUnresolvedConstructExpr, ObjCMessageExpr),
4442
514
                          internal::Matcher<Expr>, InnerMatcher) {
4443
471
  for (const Expr *Arg : Node.arguments()) {
4444
471
    if (Finder->isTraversalIgnoringImplicitNodes() &&
4445
6
        isa<CXXDefaultArgExpr>(Arg))
4446
2
      break;
4447
469
    BoundNodesTreeBuilder Result(*Builder);
4448
469
    if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4449
118
      *Builder = std::move(Result);
4450
118
      return true;
4451
118
    }
4452
469
  }
4453
396
  return false;
4454
514
}
clang::ast_matchers::internal::matcher_hasAnyArgument0Matcher<clang::CallExpr, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4442
439
                          internal::Matcher<Expr>, InnerMatcher) {
4443
386
  for (const Expr *Arg : Node.arguments()) {
4444
386
    if (Finder->isTraversalIgnoringImplicitNodes() &&
4445
6
        isa<CXXDefaultArgExpr>(Arg))
4446
2
      break;
4447
384
    BoundNodesTreeBuilder Result(*Builder);
4448
384
    if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4449
79
      *Builder = std::move(Result);
4450
79
      return true;
4451
79
    }
4452
384
  }
4453
360
  return false;
4454
439
}
clang::ast_matchers::internal::matcher_hasAnyArgument0Matcher<clang::ObjCMessageExpr, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::ObjCMessageExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4442
61
                          internal::Matcher<Expr>, InnerMatcher) {
4443
64
  for (const Expr *Arg : Node.arguments()) {
4444
64
    if (Finder->isTraversalIgnoringImplicitNodes() &&
4445
0
        isa<CXXDefaultArgExpr>(Arg))
4446
0
      break;
4447
64
    BoundNodesTreeBuilder Result(*Builder);
4448
64
    if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4449
30
      *Builder = std::move(Result);
4450
30
      return true;
4451
30
    }
4452
64
  }
4453
31
  return false;
4454
61
}
clang::ast_matchers::internal::matcher_hasAnyArgument0Matcher<clang::CXXConstructExpr, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CXXConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4442
6
                          internal::Matcher<Expr>, InnerMatcher) {
4443
10
  for (const Expr *Arg : Node.arguments()) {
4444
10
    if (Finder->isTraversalIgnoringImplicitNodes() &&
4445
0
        isa<CXXDefaultArgExpr>(Arg))
4446
0
      break;
4447
10
    BoundNodesTreeBuilder Result(*Builder);
4448
10
    if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4449
4
      *Builder = std::move(Result);
4450
4
      return true;
4451
4
    }
4452
10
  }
4453
2
  return false;
4454
6
}
clang::ast_matchers::internal::matcher_hasAnyArgument0Matcher<clang::CXXUnresolvedConstructExpr, clang::ast_matchers::internal::Matcher<clang::Expr> >::matches(clang::CXXUnresolvedConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4442
8
                          internal::Matcher<Expr>, InnerMatcher) {
4443
11
  for (const Expr *Arg : Node.arguments()) {
4444
11
    if (Finder->isTraversalIgnoringImplicitNodes() &&
4445
0
        isa<CXXDefaultArgExpr>(Arg))
4446
0
      break;
4447
11
    BoundNodesTreeBuilder Result(*Builder);
4448
11
    if (InnerMatcher.matches(*Arg, Finder, &Result)) {
4449
5
      *Builder = std::move(Result);
4450
5
      return true;
4451
5
    }
4452
11
  }
4453
3
  return false;
4454
8
}
4455
4456
/// Matches any capture of a lambda expression.
4457
///
4458
/// Given
4459
/// \code
4460
///   void foo() {
4461
///     int x;
4462
///     auto f = [x](){};
4463
///   }
4464
/// \endcode
4465
/// lambdaExpr(hasAnyCapture(anything()))
4466
///   matches [x](){};
4467
AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>,
4468
10
                       InnerMatcher, 0) {
4469
8
  for (const LambdaCapture &Capture : Node.captures()) {
4470
8
    if (Capture.capturesVariable()) {
4471
6
      BoundNodesTreeBuilder Result(*Builder);
4472
6
      if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) {
4473
4
        *Builder = std::move(Result);
4474
4
        return true;
4475
4
      }
4476
6
    }
4477
8
  }
4478
6
  return false;
4479
10
}
4480
4481
/// Matches any capture of 'this' in a lambda expression.
4482
///
4483
/// Given
4484
/// \code
4485
///   struct foo {
4486
///     void bar() {
4487
///       auto f = [this](){};
4488
///     }
4489
///   }
4490
/// \endcode
4491
/// lambdaExpr(hasAnyCapture(cxxThisExpr()))
4492
///   matches [this](){};
4493
AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture,
4494
10
                       internal::Matcher<CXXThisExpr>, InnerMatcher, 1) {
4495
8
  return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) {
4496
8
    return LC.capturesThis();
4497
8
  });
4498
10
}
4499
4500
/// Matches a constructor call expression which uses list initialization.
4501
16
AST_MATCHER(CXXConstructExpr, isListInitialization) {
4502
16
  return Node.isListInitialization();
4503
16
}
4504
4505
/// Matches a constructor call expression which requires
4506
/// zero initialization.
4507
///
4508
/// Given
4509
/// \code
4510
/// void foo() {
4511
///   struct point { double x; double y; };
4512
///   point pt[2] = { { 1.0, 2.0 } };
4513
/// }
4514
/// \endcode
4515
/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization()))
4516
/// will match the implicit array filler for pt[1].
4517
10
AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) {
4518
10
  return Node.requiresZeroInitialization();
4519
10
}
4520
4521
/// Matches the n'th parameter of a function or an ObjC method
4522
/// declaration or a block.
4523
///
4524
/// Given
4525
/// \code
4526
///   class X { void f(int x) {} };
4527
/// \endcode
4528
/// cxxMethodDecl(hasParameter(0, hasType(varDecl())))
4529
///   matches f(int x) {}
4530
/// with hasParameter(...)
4531
///   matching int x
4532
///
4533
/// For ObjectiveC, given
4534
/// \code
4535
///   @interface I - (void) f:(int) y; @end
4536
/// \endcode
4537
//
4538
/// the matcher objcMethodDecl(hasParameter(0, hasName("y")))
4539
/// matches the declaration of method f with hasParameter
4540
/// matching y.
4541
AST_POLYMORPHIC_MATCHER_P2(hasParameter,
4542
                           AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
4543
                                                           ObjCMethodDecl,
4544
                                                           BlockDecl),
4545
                           unsigned, N, internal::Matcher<ParmVarDecl>,
4546
539
                           InnerMatcher) {
4547
539
  return (N < Node.parameters().size()
4548
476
          && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4549
539
}
clang::ast_matchers::internal::matcher_hasParameter0Matcher<clang::CXXConstructorDecl, unsigned int, clang::ast_matchers::internal::Matcher<clang::ParmVarDecl> >::matches(clang::CXXConstructorDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4546
96
                           InnerMatcher) {
4547
96
  return (N < Node.parameters().size()
4548
95
          && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4549
96
}
clang::ast_matchers::internal::matcher_hasParameter0Matcher<clang::FunctionDecl, unsigned int, clang::ast_matchers::internal::Matcher<clang::ParmVarDecl> >::matches(clang::FunctionDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4546
439
                           InnerMatcher) {
4547
439
  return (N < Node.parameters().size()
4548
377
          && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4549
439
}
clang::ast_matchers::internal::matcher_hasParameter0Matcher<clang::ObjCMethodDecl, unsigned int, clang::ast_matchers::internal::Matcher<clang::ParmVarDecl> >::matches(clang::ObjCMethodDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4546
2
                           InnerMatcher) {
4547
2
  return (N < Node.parameters().size()
4548
2
          && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4549
2
}
clang::ast_matchers::internal::matcher_hasParameter0Matcher<clang::BlockDecl, unsigned int, clang::ast_matchers::internal::Matcher<clang::ParmVarDecl> >::matches(clang::BlockDecl const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4546
2
                           InnerMatcher) {
4547
2
  return (N < Node.parameters().size()
4548
2
          && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder));
4549
2
}
4550
4551
/// Matches all arguments and their respective ParmVarDecl.
4552
///
4553
/// Given
4554
/// \code
4555
///   void f(int i);
4556
///   int y;
4557
///   f(y);
4558
/// \endcode
4559
/// callExpr(
4560
///   forEachArgumentWithParam(
4561
///     declRefExpr(to(varDecl(hasName("y")))),
4562
///     parmVarDecl(hasType(isInteger()))
4563
/// ))
4564
///   matches f(y);
4565
/// with declRefExpr(...)
4566
///   matching int y
4567
/// and parmVarDecl(...)
4568
///   matching int i
4569
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam,
4570
                           AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
4571
                                                           CXXConstructExpr),
4572
                           internal::Matcher<Expr>, ArgMatcher,
4573
1.24k
                           internal::Matcher<ParmVarDecl>, ParamMatcher) {
4574
1.24k
  BoundNodesTreeBuilder Result;
4575
  // The first argument of an overloaded member operator is the implicit object
4576
  // argument of the method which should not be matched against a parameter, so
4577
  // we skip over it here.
4578
1.24k
  BoundNodesTreeBuilder Matches;
4579
1.24k
  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4580
1.24k
                              .matches(Node, Finder, &Matches)
4581
17
                          ? 1
4582
1.22k
                          : 0;
4583
1.24k
  int ParamIndex = 0;
4584
1.24k
  bool Matched = false;
4585
1.39k
  for (; ArgIndex < Node.getNumArgs(); 
++ArgIndex154
) {
4586
154
    BoundNodesTreeBuilder ArgMatches(*Builder);
4587
154
    if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4588
94
                           Finder, &ArgMatches)) {
4589
94
      BoundNodesTreeBuilder ParamMatches(ArgMatches);
4590
94
      if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4591
94
                         hasParameter(ParamIndex, ParamMatcher)))),
4592
94
                     callExpr(callee(functionDecl(
4593
94
                         hasParameter(ParamIndex, ParamMatcher))))))
4594
62
              .matches(Node, Finder, &ParamMatches)) {
4595
62
        Result.addMatch(ParamMatches);
4596
62
        Matched = true;
4597
62
      }
4598
94
    }
4599
154
    ++ParamIndex;
4600
154
  }
4601
1.24k
  *Builder = std::move(Result);
4602
1.24k
  return Matched;
4603
1.24k
}
clang::ast_matchers::internal::matcher_forEachArgumentWithParam0Matcher<clang::CallExpr, clang::ast_matchers::internal::Matcher<clang::Expr>, clang::ast_matchers::internal::Matcher<clang::ParmVarDecl> >::matches(clang::CallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4573
1.16k
                           internal::Matcher<ParmVarDecl>, ParamMatcher) {
4574
1.16k
  BoundNodesTreeBuilder Result;
4575
  // The first argument of an overloaded member operator is the implicit object
4576
  // argument of the method which should not be matched against a parameter, so
4577
  // we skip over it here.
4578
1.16k
  BoundNodesTreeBuilder Matches;
4579
1.16k
  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4580
1.16k
                              .matches(Node, Finder, &Matches)
4581
17
                          ? 1
4582
1.15k
                          : 0;
4583
1.16k
  int ParamIndex = 0;
4584
1.16k
  bool Matched = false;
4585
1.30k
  for (; ArgIndex < Node.getNumArgs(); 
++ArgIndex132
) {
4586
132
    BoundNodesTreeBuilder ArgMatches(*Builder);
4587
132
    if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4588
76
                           Finder, &ArgMatches)) {
4589
76
      BoundNodesTreeBuilder ParamMatches(ArgMatches);
4590
76
      if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4591
76
                         hasParameter(ParamIndex, ParamMatcher)))),
4592
76
                     callExpr(callee(functionDecl(
4593
76
                         hasParameter(ParamIndex, ParamMatcher))))))
4594
53
              .matches(Node, Finder, &ParamMatches)) {
4595
53
        Result.addMatch(ParamMatches);
4596
53
        Matched = true;
4597
53
      }
4598
76
    }
4599
132
    ++ParamIndex;
4600
132
  }
4601
1.16k
  *Builder = std::move(Result);
4602
1.16k
  return Matched;
4603
1.16k
}
clang::ast_matchers::internal::matcher_forEachArgumentWithParam0Matcher<clang::CXXConstructExpr, clang::ast_matchers::internal::Matcher<clang::Expr>, clang::ast_matchers::internal::Matcher<clang::ParmVarDecl> >::matches(clang::CXXConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4573
73
                           internal::Matcher<ParmVarDecl>, ParamMatcher) {
4574
73
  BoundNodesTreeBuilder Result;
4575
  // The first argument of an overloaded member operator is the implicit object
4576
  // argument of the method which should not be matched against a parameter, so
4577
  // we skip over it here.
4578
73
  BoundNodesTreeBuilder Matches;
4579
73
  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4580
73
                              .matches(Node, Finder, &Matches)
4581
0
                          ? 1
4582
73
                          : 0;
4583
73
  int ParamIndex = 0;
4584
73
  bool Matched = false;
4585
95
  for (; ArgIndex < Node.getNumArgs(); 
++ArgIndex22
) {
4586
22
    BoundNodesTreeBuilder ArgMatches(*Builder);
4587
22
    if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()),
4588
18
                           Finder, &ArgMatches)) {
4589
18
      BoundNodesTreeBuilder ParamMatches(ArgMatches);
4590
18
      if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4591
18
                         hasParameter(ParamIndex, ParamMatcher)))),
4592
18
                     callExpr(callee(functionDecl(
4593
18
                         hasParameter(ParamIndex, ParamMatcher))))))
4594
9
              .matches(Node, Finder, &ParamMatches)) {
4595
9
        Result.addMatch(ParamMatches);
4596
9
        Matched = true;
4597
9
      }
4598
18
    }
4599
22
    ++ParamIndex;
4600
22
  }
4601
73
  *Builder = std::move(Result);
4602
73
  return Matched;
4603
73
}
4604
4605
/// Matches all arguments and their respective types for a \c CallExpr or
4606
/// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but
4607
/// it works on calls through function pointers as well.
4608
///
4609
/// The difference is, that function pointers do not provide access to a
4610
/// \c ParmVarDecl, but only the \c QualType for each argument.
4611
///
4612
/// Given
4613
/// \code
4614
///   void f(int i);
4615
///   int y;
4616
///   f(y);
4617
///   void (*f_ptr)(int) = f;
4618
///   f_ptr(y);
4619
/// \endcode
4620
/// callExpr(
4621
///   forEachArgumentWithParamType(
4622
///     declRefExpr(to(varDecl(hasName("y")))),
4623
///     qualType(isInteger()).bind("type)
4624
/// ))
4625
///   matches f(y) and f_ptr(y)
4626
/// with declRefExpr(...)
4627
///   matching int y
4628
/// and qualType(...)
4629
///   matching int
4630
AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType,
4631
                           AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr,
4632
                                                           CXXConstructExpr),
4633
                           internal::Matcher<Expr>, ArgMatcher,
4634
321
                           internal::Matcher<QualType>, ParamMatcher) {
4635
321
  BoundNodesTreeBuilder Result;
4636
  // The first argument of an overloaded member operator is the implicit object
4637
  // argument of the method which should not be matched against a parameter, so
4638
  // we skip over it here.
4639
321
  BoundNodesTreeBuilder Matches;
4640
321
  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4641
321
                              .matches(Node, Finder, &Matches)
4642
27
                          ? 1
4643
294
                          : 0;
4644
4645
321
  const FunctionProtoType *FProto = nullptr;
4646
4647
321
  if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4648
178
    if (const auto *Value =
4649
169
            dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4650
169
      QualType QT = Value->getType().getCanonicalType();
4651
4652
      // This does not necessarily lead to a `FunctionProtoType`,
4653
      // e.g. K&R functions do not have a function prototype.
4654
169
      if (QT->isFunctionPointerType())
4655
4
        FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4656
4657
169
      if (QT->isMemberFunctionPointerType()) {
4658
4
        const auto *MP = QT->getAs<MemberPointerType>();
4659
4
        assert(MP && "Must be member-pointer if its a memberfunctionpointer");
4660
4
        FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
4661
4
        assert(FProto &&
4662
4
               "The call must have happened through a member function "
4663
4
               "pointer");
4664
4
      }
4665
169
    }
4666
178
  }
4667
4668
321
  int ParamIndex = 0;
4669
321
  bool Matched = false;
4670
4671
544
  for (; ArgIndex < Node.getNumArgs(); 
++ArgIndex, ++ParamIndex223
) {
4672
223
    BoundNodesTreeBuilder ArgMatches(*Builder);
4673
223
    if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
4674
151
                           &ArgMatches)) {
4675
151
      BoundNodesTreeBuilder ParamMatches(ArgMatches);
4676
4677
      // This test is cheaper compared to the big matcher in the next if.
4678
      // Therefore, please keep this order.
4679
151
      if (FProto) {
4680
8
        QualType ParamType = FProto->getParamType(ParamIndex);
4681
8
        if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
4682
8
          Result.addMatch(ParamMatches);
4683
8
          Matched = true;
4684
8
          continue;
4685
8
        }
4686
143
      }
4687
143
      if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4688
143
                         hasParameter(ParamIndex, hasType(ParamMatcher))))),
4689
143
                     callExpr(callee(functionDecl(
4690
143
                         hasParameter(ParamIndex, hasType(ParamMatcher)))))))
4691
91
              .matches(Node, Finder, &ParamMatches)) {
4692
91
        Result.addMatch(ParamMatches);
4693
91
        Matched = true;
4694
91
        continue;
4695
91
      }
4696
143
    }
4697
223
  }
4698
321
  *Builder = std::move(Result);
4699
321
  return Matched;
4700
321
}
clang::ast_matchers::internal::matcher_forEachArgumentWithParamType0Matcher<clang::CallExpr, clang::ast_matchers::internal::Matcher<clang::Expr>, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::CallExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4634
178
                           internal::Matcher<QualType>, ParamMatcher) {
4635
178
  BoundNodesTreeBuilder Result;
4636
  // The first argument of an overloaded member operator is the implicit object
4637
  // argument of the method which should not be matched against a parameter, so
4638
  // we skip over it here.
4639
178
  BoundNodesTreeBuilder Matches;
4640
178
  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4641
178
                              .matches(Node, Finder, &Matches)
4642
27
                          ? 1
4643
151
                          : 0;
4644
4645
178
  const FunctionProtoType *FProto = nullptr;
4646
4647
178
  if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4648
178
    if (const auto *Value =
4649
169
            dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4650
169
      QualType QT = Value->getType().getCanonicalType();
4651
4652
      // This does not necessarily lead to a `FunctionProtoType`,
4653
      // e.g. K&R functions do not have a function prototype.
4654
169
      if (QT->isFunctionPointerType())
4655
4
        FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4656
4657
169
      if (QT->isMemberFunctionPointerType()) {
4658
4
        const auto *MP = QT->getAs<MemberPointerType>();
4659
4
        assert(MP && "Must be member-pointer if its a memberfunctionpointer");
4660
4
        FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
4661
4
        assert(FProto &&
4662
4
               "The call must have happened through a member function "
4663
4
               "pointer");
4664
4
      }
4665
169
    }
4666
178
  }
4667
4668
178
  int ParamIndex = 0;
4669
178
  bool Matched = false;
4670
4671
369
  for (; ArgIndex < Node.getNumArgs(); 
++ArgIndex, ++ParamIndex191
) {
4672
191
    BoundNodesTreeBuilder ArgMatches(*Builder);
4673
191
    if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
4674
124
                           &ArgMatches)) {
4675
124
      BoundNodesTreeBuilder ParamMatches(ArgMatches);
4676
4677
      // This test is cheaper compared to the big matcher in the next if.
4678
      // Therefore, please keep this order.
4679
124
      if (FProto) {
4680
8
        QualType ParamType = FProto->getParamType(ParamIndex);
4681
8
        if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) {
4682
8
          Result.addMatch(ParamMatches);
4683
8
          Matched = true;
4684
8
          continue;
4685
8
        }
4686
116
      }
4687
116
      if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl(
4688
116
                         hasParameter(ParamIndex, hasType(ParamMatcher))))),
4689
116
                     callExpr(callee(functionDecl(
4690
116
                         hasParameter(ParamIndex, hasType(ParamMatcher)))))))
4691
75
              .matches(Node, Finder, &ParamMatches)) {
4692
75
        Result.addMatch(ParamMatches);
4693
75
        Matched = true;
4694
75
        continue;
4695
75
      }
4696
116
    }
4697
191
  }
4698
178
  *Builder = std::move(Result);
4699
178
  return Matched;
4700
178
}
clang::ast_matchers::internal::matcher_forEachArgumentWithParamType0Matcher<clang::CXXConstructExpr, clang::ast_matchers::internal::Matcher<clang::Expr>, clang::ast_matchers::internal::Matcher<clang::QualType> >::matches(clang::CXXConstructExpr const&, clang::ast_matchers::internal::ASTMatchFinder*, clang::ast_matchers::internal::BoundNodesTreeBuilder*) const
Line
Count
Source
4634
143
                           internal::Matcher<QualType>, ParamMatcher) {
4635
143
  BoundNodesTreeBuilder Result;
4636
  // The first argument of an overloaded member operator is the implicit object
4637
  // argument of the method which should not be matched against a parameter, so
4638
  // we skip over it here.
4639
143
  BoundNodesTreeBuilder Matches;
4640
143
  unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl()))
4641
143
                              .matches(Node, Finder, &Matches)
4642
0
                          ? 1
4643
143
                          : 0;
4644
4645
143
  const FunctionProtoType *FProto = nullptr;
4646
4647
143
  if (const auto *Call = dyn_cast<CallExpr>(&Node)) {
4648
0
    if (const auto *Value =
4649
0
            dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) {
4650
0
      QualType QT = Value->getType().getCanonicalType();
4651
4652
      // This does not necessarily lead to a `FunctionProtoType`,
4653
      // e.g. K&R functions do not have a function prototype.
4654
0
      if (QT->isFunctionPointerType())
4655
0
        FProto = QT->getPointeeType()->getAs<FunctionProtoType>();
4656
4657
0
      if (QT->isMemberFunctionPointerType()) {
4658
0
        const auto *MP = QT->getAs<MemberPointerType>();
4659
0
        assert(MP && "Must be member-pointer if its a memberfunctionpointer");
4660
0
        FProto = MP->getPointeeType()->getAs<FunctionProtoType>();
4661
0
        assert(FProto &&
4662
0
               "The call must have happened through a member function "
4663
0
               "pointer");
4664
0
      }
4665
0
    }
4666
0
  }
4667
4668
143
  int ParamIndex = 0;
4669
143
  bool Matched = false;
4670
4671
175
  for (; ArgIndex < Node.getNumArgs(); 
++ArgIndex, ++ParamIndex32
) {
4672
32
    BoundNodesTreeBuilder ArgMatches(*Builder);
4673
32
    if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder,
4674
27
                           &ArgMatches)) {
4675
27
      BoundNodesTreeBuilder ParamMatches(ArgMatches);
4676