Coverage Report

Created: 2019-02-20 07:29

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