Coverage Report

Created: 2019-07-24 05:18

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