Coverage Report

Created: 2018-07-19 20:53

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