Coverage Report

Created: 2018-11-16 02:38

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