]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/include/clang/ASTMatchers/ASTMatchers.h
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / include / clang / ASTMatchers / ASTMatchers.h
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 //    recordDecl(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 //    recordDecl(hasName("MyClass"), hasChild(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 CXXRecordDecl 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_AST_MATCHERS_AST_MATCHERS_H
46 #define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H
47
48 #include "clang/AST/DeclTemplate.h"
49 #include "clang/ASTMatchers/ASTMatchersInternal.h"
50 #include "clang/ASTMatchers/ASTMatchersMacros.h"
51 #include "llvm/ADT/Twine.h"
52 #include "llvm/Support/Regex.h"
53 #include <iterator>
54
55 namespace clang {
56 namespace ast_matchers {
57
58 /// \brief Maps string IDs to AST nodes matched by parts of a matcher.
59 ///
60 /// The bound nodes are generated by calling \c bind("id") on the node matchers
61 /// of the nodes we want to access later.
62 ///
63 /// The instances of BoundNodes are created by \c MatchFinder when the user's
64 /// callbacks are executed every time a match is found.
65 class BoundNodes {
66 public:
67   /// \brief Returns the AST node bound to \c ID.
68   ///
69   /// Returns NULL if there was no node bound to \c ID or if there is a node but
70   /// it cannot be converted to the specified type.
71   template <typename T>
72   const T *getNodeAs(StringRef ID) const {
73     return MyBoundNodes.getNodeAs<T>(ID);
74   }
75
76   /// \brief Deprecated. Please use \c getNodeAs instead.
77   /// @{
78   template <typename T>
79   const T *getDeclAs(StringRef ID) const {
80     return getNodeAs<T>(ID);
81   }
82   template <typename T>
83   const T *getStmtAs(StringRef ID) const {
84     return getNodeAs<T>(ID);
85   }
86   /// @}
87
88 private:
89   /// \brief Create BoundNodes from a pre-filled map of bindings.
90   BoundNodes(internal::BoundNodesMap &MyBoundNodes)
91       : MyBoundNodes(MyBoundNodes) {}
92
93   internal::BoundNodesMap MyBoundNodes;
94
95   friend class internal::BoundNodesTree;
96 };
97
98 /// \brief If the provided matcher matches a node, binds the node to \c ID.
99 ///
100 /// FIXME: Do we want to support this now that we have bind()?
101 template <typename T>
102 internal::Matcher<T> id(const std::string &ID,
103                         const internal::BindableMatcher<T> &InnerMatcher) {
104   return InnerMatcher.bind(ID);
105 }
106
107 /// \brief Types of matchers for the top-level classes in the AST class
108 /// hierarchy.
109 /// @{
110 typedef internal::Matcher<Decl> DeclarationMatcher;
111 typedef internal::Matcher<Stmt> StatementMatcher;
112 typedef internal::Matcher<QualType> TypeMatcher;
113 typedef internal::Matcher<TypeLoc> TypeLocMatcher;
114 typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher;
115 typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher;
116 /// @}
117
118 /// \brief Matches any node.
119 ///
120 /// Useful when another matcher requires a child matcher, but there's no
121 /// additional constraint. This will often be used with an explicit conversion
122 /// to an \c internal::Matcher<> type such as \c TypeMatcher.
123 ///
124 /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g.,
125 /// \code
126 /// "int* p" and "void f()" in
127 ///   int* p;
128 ///   void f();
129 /// \endcode
130 ///
131 /// Usable as: Any Matcher
132 inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>
133 anything() {
134   return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>();
135 }
136
137 /// \brief Matches declarations.
138 ///
139 /// Examples matches \c X, \c C, and the friend declaration inside \c C;
140 /// \code
141 ///   void X();
142 ///   class C {
143 ///     friend X;
144 ///   };
145 /// \endcode
146 const internal::VariadicAllOfMatcher<Decl> decl;
147
148 /// \brief Matches a declaration of anything that could have a name.
149 ///
150 /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U;
151 /// \code
152 ///   typedef int X;
153 ///   struct S {
154 ///     union {
155 ///       int i;
156 ///     } U;
157 ///   };
158 /// \endcode
159 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
160
161 /// \brief Matches a declaration of a namespace.
162 ///
163 /// Given
164 /// \code
165 ///   namespace {}
166 ///   namespace test {}
167 /// \endcode
168 /// namespaceDecl()
169 ///   matches "namespace {}" and "namespace test {}"
170 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
171
172 /// \brief Matches C++ class declarations.
173 ///
174 /// Example matches \c X, \c Z
175 /// \code
176 ///   class X;
177 ///   template<class T> class Z {};
178 /// \endcode
179 const internal::VariadicDynCastAllOfMatcher<
180   Decl,
181   CXXRecordDecl> recordDecl;
182
183 /// \brief Matches C++ class template declarations.
184 ///
185 /// Example matches \c Z
186 /// \code
187 ///   template<class T> class Z {};
188 /// \endcode
189 const internal::VariadicDynCastAllOfMatcher<
190   Decl,
191   ClassTemplateDecl> classTemplateDecl;
192
193 /// \brief Matches C++ class template specializations.
194 ///
195 /// Given
196 /// \code
197 ///   template<typename T> class A {};
198 ///   template<> class A<double> {};
199 ///   A<int> a;
200 /// \endcode
201 /// classTemplateSpecializationDecl()
202 ///   matches the specializations \c A<int> and \c A<double>
203 const internal::VariadicDynCastAllOfMatcher<
204   Decl,
205   ClassTemplateSpecializationDecl> classTemplateSpecializationDecl;
206
207 /// \brief Matches C++ access specifier declarations.
208 ///
209 /// Given
210 /// \code
211 ///   class C {
212 ///   public:
213 ///     int a;
214 ///   };
215 /// \endcode
216 /// accessSpecDecl()
217 ///   matches 'public:'
218 const internal::VariadicDynCastAllOfMatcher<
219   Decl,
220   AccessSpecDecl> accessSpecDecl;
221
222 /// \brief Matches public C++ declarations.
223 ///
224 /// Given
225 /// \code
226 ///   class C {
227 ///   public:    int a;
228 ///   protected: int b;
229 ///   private:   int c;
230 ///   };
231 /// \endcode
232 /// fieldDecl(isPublic())
233 ///   matches 'int a;' 
234 AST_MATCHER(Decl, isPublic) {
235   return Node.getAccess() == AS_public;
236 }
237
238 /// \brief Matches protected C++ declarations.
239 ///
240 /// Given
241 /// \code
242 ///   class C {
243 ///   public:    int a;
244 ///   protected: int b;
245 ///   private:   int c;
246 ///   };
247 /// \endcode
248 /// fieldDecl(isProtected())
249 ///   matches 'int b;' 
250 AST_MATCHER(Decl, isProtected) {
251   return Node.getAccess() == AS_protected;
252 }
253
254 /// \brief Matches private C++ declarations.
255 ///
256 /// Given
257 /// \code
258 ///   class C {
259 ///   public:    int a;
260 ///   protected: int b;
261 ///   private:   int c;
262 ///   };
263 /// \endcode
264 /// fieldDecl(isPrivate())
265 ///   matches 'int c;' 
266 AST_MATCHER(Decl, isPrivate) {
267   return Node.getAccess() == AS_private;
268 }
269
270 /// \brief Matches classTemplateSpecializations that have at least one
271 /// TemplateArgument matching the given InnerMatcher.
272 ///
273 /// Given
274 /// \code
275 ///   template<typename T> class A {};
276 ///   template<> class A<double> {};
277 ///   A<int> a;
278 /// \endcode
279 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
280 ///     refersToType(asString("int"))))
281 ///   matches the specialization \c A<int>
282 AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument,
283               internal::Matcher<TemplateArgument>, InnerMatcher) {
284   const TemplateArgumentList &List = Node.getTemplateArgs();
285   for (unsigned i = 0; i < List.size(); ++i) {
286     if (InnerMatcher.matches(List.get(i), Finder, Builder))
287       return true;
288   }
289   return false;
290 }
291
292 /// \brief Matches expressions that match InnerMatcher after any implicit casts
293 /// are stripped off.
294 ///
295 /// Parentheses and explicit casts are not discarded.
296 /// Given
297 /// \code
298 ///   int arr[5];
299 ///   int a = 0;
300 ///   char b = 0;
301 ///   const int c = a;
302 ///   int *d = arr;
303 ///   long e = (long) 0l;
304 /// \endcode
305 /// The matchers
306 /// \code
307 ///    varDecl(hasInitializer(ignoringImpCasts(integerLiteral())))
308 ///    varDecl(hasInitializer(ignoringImpCasts(declRefExpr())))
309 /// \endcode
310 /// would match the declarations for a, b, c, and d, but not e.
311 /// While
312 /// \code
313 ///    varDecl(hasInitializer(integerLiteral()))
314 ///    varDecl(hasInitializer(declRefExpr()))
315 /// \endcode
316 /// only match the declarations for b, c, and d.
317 AST_MATCHER_P(Expr, ignoringImpCasts,
318               internal::Matcher<Expr>, InnerMatcher) {
319   return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder);
320 }
321
322 /// \brief Matches expressions that match InnerMatcher after parentheses and
323 /// casts are stripped off.
324 ///
325 /// Implicit and non-C Style casts are also discarded.
326 /// Given
327 /// \code
328 ///   int a = 0;
329 ///   char b = (0);
330 ///   void* c = reinterpret_cast<char*>(0);
331 ///   char d = char(0);
332 /// \endcode
333 /// The matcher
334 ///    varDecl(hasInitializer(ignoringParenCasts(integerLiteral())))
335 /// would match the declarations for a, b, c, and d.
336 /// while
337 ///    varDecl(hasInitializer(integerLiteral()))
338 /// only match the declaration for a.
339 AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) {
340   return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder);
341 }
342
343 /// \brief Matches expressions that match InnerMatcher after implicit casts and
344 /// parentheses are stripped off.
345 ///
346 /// Explicit casts are not discarded.
347 /// Given
348 /// \code
349 ///   int arr[5];
350 ///   int a = 0;
351 ///   char b = (0);
352 ///   const int c = a;
353 ///   int *d = (arr);
354 ///   long e = ((long) 0l);
355 /// \endcode
356 /// The matchers
357 ///    varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral())))
358 ///    varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr())))
359 /// would match the declarations for a, b, c, and d, but not e.
360 /// while
361 ///    varDecl(hasInitializer(integerLiteral()))
362 ///    varDecl(hasInitializer(declRefExpr()))
363 /// would only match the declaration for a.
364 AST_MATCHER_P(Expr, ignoringParenImpCasts,
365               internal::Matcher<Expr>, InnerMatcher) {
366   return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder);
367 }
368
369 /// \brief Matches classTemplateSpecializations where the n'th TemplateArgument
370 /// matches the given InnerMatcher.
371 ///
372 /// Given
373 /// \code
374 ///   template<typename T, typename U> class A {};
375 ///   A<bool, int> b;
376 ///   A<int, bool> c;
377 /// \endcode
378 /// classTemplateSpecializationDecl(hasTemplateArgument(
379 ///     1, refersToType(asString("int"))))
380 ///   matches the specialization \c A<bool, int>
381 AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument,
382                unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) {
383   const TemplateArgumentList &List = Node.getTemplateArgs();
384   if (List.size() <= N)
385     return false;
386   return InnerMatcher.matches(List.get(N), Finder, Builder);
387 }
388
389 /// \brief Matches a TemplateArgument that refers to a certain type.
390 ///
391 /// Given
392 /// \code
393 ///   struct X {};
394 ///   template<typename T> struct A {};
395 ///   A<X> a;
396 /// \endcode
397 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
398 ///     refersToType(class(hasName("X")))))
399 ///   matches the specialization \c A<X>
400 AST_MATCHER_P(TemplateArgument, refersToType,
401               internal::Matcher<QualType>, InnerMatcher) {
402   if (Node.getKind() != TemplateArgument::Type)
403     return false;
404   return InnerMatcher.matches(Node.getAsType(), Finder, Builder);
405 }
406
407 /// \brief Matches a TemplateArgument that refers to a certain declaration.
408 ///
409 /// Given
410 /// \code
411 ///   template<typename T> struct A {};
412 ///   struct B { B* next; };
413 ///   A<&B::next> a;
414 /// \endcode
415 /// classTemplateSpecializationDecl(hasAnyTemplateArgument(
416 ///     refersToDeclaration(fieldDecl(hasName("next"))))
417 ///   matches the specialization \c A<&B::next> with \c fieldDecl(...) matching
418 ///     \c B::next
419 AST_MATCHER_P(TemplateArgument, refersToDeclaration,
420               internal::Matcher<Decl>, InnerMatcher) {
421   if (Node.getKind() == TemplateArgument::Declaration)
422     return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder);
423   return false;
424 }
425
426 /// \brief Matches C++ constructor declarations.
427 ///
428 /// Example matches Foo::Foo() and Foo::Foo(int)
429 /// \code
430 ///   class Foo {
431 ///    public:
432 ///     Foo();
433 ///     Foo(int);
434 ///     int DoSomething();
435 ///   };
436 /// \endcode
437 const internal::VariadicDynCastAllOfMatcher<
438   Decl,
439   CXXConstructorDecl> constructorDecl;
440
441 /// \brief Matches explicit C++ destructor declarations.
442 ///
443 /// Example matches Foo::~Foo()
444 /// \code
445 ///   class Foo {
446 ///    public:
447 ///     virtual ~Foo();
448 ///   };
449 /// \endcode
450 const internal::VariadicDynCastAllOfMatcher<
451   Decl,
452   CXXDestructorDecl> destructorDecl;
453
454 /// \brief Matches enum declarations.
455 ///
456 /// Example matches X
457 /// \code
458 ///   enum X {
459 ///     A, B, C
460 ///   };
461 /// \endcode
462 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
463
464 /// \brief Matches enum constants.
465 ///
466 /// Example matches A, B, C
467 /// \code
468 ///   enum X {
469 ///     A, B, C
470 ///   };
471 /// \endcode
472 const internal::VariadicDynCastAllOfMatcher<
473   Decl,
474   EnumConstantDecl> enumConstantDecl;
475
476 /// \brief Matches method declarations.
477 ///
478 /// Example matches y
479 /// \code
480 ///   class X { void y() };
481 /// \endcode
482 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl;
483
484 /// \brief Matches variable declarations.
485 ///
486 /// Note: this does not match declarations of member variables, which are
487 /// "field" declarations in Clang parlance.
488 ///
489 /// Example matches a
490 /// \code
491 ///   int a;
492 /// \endcode
493 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
494
495 /// \brief Matches field declarations.
496 ///
497 /// Given
498 /// \code
499 ///   class X { int m; };
500 /// \endcode
501 /// fieldDecl()
502 ///   matches 'm'.
503 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
504
505 /// \brief Matches function declarations.
506 ///
507 /// Example matches f
508 /// \code
509 ///   void f();
510 /// \endcode
511 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
512
513 /// \brief Matches C++ function template declarations.
514 ///
515 /// Example matches f
516 /// \code
517 ///   template<class T> void f(T t) {}
518 /// \endcode
519 const internal::VariadicDynCastAllOfMatcher<
520   Decl,
521   FunctionTemplateDecl> functionTemplateDecl;
522
523 /// \brief Matches statements.
524 ///
525 /// Given
526 /// \code
527 ///   { ++a; }
528 /// \endcode
529 /// stmt()
530 ///   matches both the compound statement '{ ++a; }' and '++a'.
531 const internal::VariadicAllOfMatcher<Stmt> stmt;
532
533 /// \brief Matches declaration statements.
534 ///
535 /// Given
536 /// \code
537 ///   int a;
538 /// \endcode
539 /// declStmt()
540 ///   matches 'int a'.
541 const internal::VariadicDynCastAllOfMatcher<
542   Stmt,
543   DeclStmt> declStmt;
544
545 /// \brief Matches member expressions.
546 ///
547 /// Given
548 /// \code
549 ///   class Y {
550 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
551 ///     int a; static int b;
552 ///   };
553 /// \endcode
554 /// memberExpr()
555 ///   matches this->x, x, y.x, a, this->b
556 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
557
558 /// \brief Matches call expressions.
559 ///
560 /// Example matches x.y() and y()
561 /// \code
562 ///   X x;
563 ///   x.y();
564 ///   y();
565 /// \endcode
566 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
567
568 /// \brief Matches lambda expressions.
569 ///
570 /// Example matches [&](){return 5;}
571 /// \code
572 ///   [&](){return 5;}
573 /// \endcode
574 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
575
576 /// \brief Matches member call expressions.
577 ///
578 /// Example matches x.y()
579 /// \code
580 ///   X x;
581 ///   x.y();
582 /// \endcode
583 const internal::VariadicDynCastAllOfMatcher<
584   Stmt,
585   CXXMemberCallExpr> memberCallExpr;
586
587 /// \brief Matches init list expressions.
588 ///
589 /// Given
590 /// \code
591 ///   int a[] = { 1, 2 };
592 ///   struct B { int x, y; };
593 ///   B b = { 5, 6 };
594 /// \endcode
595 /// initList()
596 ///   matches "{ 1, 2 }" and "{ 5, 6 }"
597 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
598
599 /// \brief Matches using declarations.
600 ///
601 /// Given
602 /// \code
603 ///   namespace X { int x; }
604 ///   using X::x;
605 /// \endcode
606 /// usingDecl()
607 ///   matches \code using X::x \endcode
608 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
609
610 /// \brief Matches constructor call expressions (including implicit ones).
611 ///
612 /// Example matches string(ptr, n) and ptr within arguments of f
613 ///     (matcher = constructExpr())
614 /// \code
615 ///   void f(const string &a, const string &b);
616 ///   char *ptr;
617 ///   int n;
618 ///   f(string(ptr, n), ptr);
619 /// \endcode
620 const internal::VariadicDynCastAllOfMatcher<
621   Stmt,
622   CXXConstructExpr> constructExpr;
623
624 /// \brief Matches implicit and explicit this expressions.
625 ///
626 /// Example matches the implicit this expression in "return i".
627 ///     (matcher = thisExpr())
628 /// \code
629 /// struct foo {
630 ///   int i;
631 ///   int f() { return i; }
632 /// };
633 /// \endcode
634 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr;
635
636 /// \brief Matches nodes where temporaries are created.
637 ///
638 /// Example matches FunctionTakesString(GetStringByValue())
639 ///     (matcher = bindTemporaryExpr())
640 /// \code
641 ///   FunctionTakesString(GetStringByValue());
642 ///   FunctionTakesStringByPointer(GetStringPointer());
643 /// \endcode
644 const internal::VariadicDynCastAllOfMatcher<
645   Stmt,
646   CXXBindTemporaryExpr> bindTemporaryExpr;
647
648 /// \brief Matches nodes where temporaries are materialized.
649 ///
650 /// Example: Given
651 /// \code
652 ///   struct T {void func()};
653 ///   T f();
654 ///   void g(T);
655 /// \endcode
656 /// materializeTemporaryExpr() matches 'f()' in these statements
657 /// \code
658 ///   T u(f());
659 ///   g(f());
660 /// \endcode
661 /// but does not match
662 /// \code
663 ///   f();
664 ///   f().func();
665 /// \endcode
666 const internal::VariadicDynCastAllOfMatcher<
667   Stmt,
668   MaterializeTemporaryExpr> materializeTemporaryExpr;
669
670 /// \brief Matches new expressions.
671 ///
672 /// Given
673 /// \code
674 ///   new X;
675 /// \endcode
676 /// newExpr()
677 ///   matches 'new X'.
678 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr;
679
680 /// \brief Matches delete expressions.
681 ///
682 /// Given
683 /// \code
684 ///   delete X;
685 /// \endcode
686 /// deleteExpr()
687 ///   matches 'delete X'.
688 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr;
689
690 /// \brief Matches array subscript expressions.
691 ///
692 /// Given
693 /// \code
694 ///   int i = a[1];
695 /// \endcode
696 /// arraySubscriptExpr()
697 ///   matches "a[1]"
698 const internal::VariadicDynCastAllOfMatcher<
699   Stmt,
700   ArraySubscriptExpr> arraySubscriptExpr;
701
702 /// \brief Matches the value of a default argument at the call site.
703 ///
704 /// Example matches the CXXDefaultArgExpr placeholder inserted for the
705 ///     default value of the second parameter in the call expression f(42)
706 ///     (matcher = defaultArgExpr())
707 /// \code
708 ///   void f(int x, int y = 0);
709 ///   f(42);
710 /// \endcode
711 const internal::VariadicDynCastAllOfMatcher<
712   Stmt,
713   CXXDefaultArgExpr> defaultArgExpr;
714
715 /// \brief Matches overloaded operator calls.
716 ///
717 /// Note that if an operator isn't overloaded, it won't match. Instead, use
718 /// binaryOperator matcher.
719 /// Currently it does not match operators such as new delete.
720 /// FIXME: figure out why these do not match?
721 ///
722 /// Example matches both operator<<((o << b), c) and operator<<(o, b)
723 ///     (matcher = operatorCallExpr())
724 /// \code
725 ///   ostream &operator<< (ostream &out, int i) { };
726 ///   ostream &o; int b = 1, c = 1;
727 ///   o << b << c;
728 /// \endcode
729 const internal::VariadicDynCastAllOfMatcher<
730   Stmt,
731   CXXOperatorCallExpr> operatorCallExpr;
732
733 /// \brief Matches expressions.
734 ///
735 /// Example matches x()
736 /// \code
737 ///   void f() { x(); }
738 /// \endcode
739 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
740
741 /// \brief Matches expressions that refer to declarations.
742 ///
743 /// Example matches x in if (x)
744 /// \code
745 ///   bool x;
746 ///   if (x) {}
747 /// \endcode
748 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
749
750 /// \brief Matches if statements.
751 ///
752 /// Example matches 'if (x) {}'
753 /// \code
754 ///   if (x) {}
755 /// \endcode
756 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
757
758 /// \brief Matches for statements.
759 ///
760 /// Example matches 'for (;;) {}'
761 /// \code
762 ///   for (;;) {}
763 ///   int i[] =  {1, 2, 3}; for (auto a : i);
764 /// \endcode
765 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
766
767 /// \brief Matches range-based for statements.
768 ///
769 /// forRangeStmt() matches 'for (auto a : i)'
770 /// \code
771 ///   int i[] =  {1, 2, 3}; for (auto a : i);
772 ///   for(int j = 0; j < 5; ++j);
773 /// \endcode
774 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt;
775
776 /// \brief Matches the increment statement of a for loop.
777 ///
778 /// Example:
779 ///     forStmt(hasIncrement(unaryOperator(hasOperatorName("++"))))
780 /// matches '++x' in
781 /// \code
782 ///     for (x; x < N; ++x) { }
783 /// \endcode
784 AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>,
785               InnerMatcher) {
786   const Stmt *const Increment = Node.getInc();
787   return (Increment != NULL &&
788           InnerMatcher.matches(*Increment, Finder, Builder));
789 }
790
791 /// \brief Matches the initialization statement of a for loop.
792 ///
793 /// Example:
794 ///     forStmt(hasLoopInit(declStmt()))
795 /// matches 'int x = 0' in
796 /// \code
797 ///     for (int x = 0; x < N; ++x) { }
798 /// \endcode
799 AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>,
800               InnerMatcher) {
801   const Stmt *const Init = Node.getInit();
802   return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder));
803 }
804
805 /// \brief Matches while statements.
806 ///
807 /// Given
808 /// \code
809 ///   while (true) {}
810 /// \endcode
811 /// whileStmt()
812 ///   matches 'while (true) {}'.
813 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
814
815 /// \brief Matches do statements.
816 ///
817 /// Given
818 /// \code
819 ///   do {} while (true);
820 /// \endcode
821 /// doStmt()
822 ///   matches 'do {} while(true)'
823 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
824
825 /// \brief Matches break statements.
826 ///
827 /// Given
828 /// \code
829 ///   while (true) { break; }
830 /// \endcode
831 /// breakStmt()
832 ///   matches 'break'
833 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
834
835 /// \brief Matches continue statements.
836 ///
837 /// Given
838 /// \code
839 ///   while (true) { continue; }
840 /// \endcode
841 /// continueStmt()
842 ///   matches 'continue'
843 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
844
845 /// \brief Matches return statements.
846 ///
847 /// Given
848 /// \code
849 ///   return 1;
850 /// \endcode
851 /// returnStmt()
852 ///   matches 'return 1'
853 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
854
855 /// \brief Matches goto statements.
856 ///
857 /// Given
858 /// \code
859 ///   goto FOO;
860 ///   FOO: bar();
861 /// \endcode
862 /// gotoStmt()
863 ///   matches 'goto FOO'
864 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
865
866 /// \brief Matches label statements.
867 ///
868 /// Given
869 /// \code
870 ///   goto FOO;
871 ///   FOO: bar();
872 /// \endcode
873 /// labelStmt()
874 ///   matches 'FOO:'
875 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
876
877 /// \brief Matches switch statements.
878 ///
879 /// Given
880 /// \code
881 ///   switch(a) { case 42: break; default: break; }
882 /// \endcode
883 /// switchStmt()
884 ///   matches 'switch(a)'.
885 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
886
887 /// \brief Matches case and default statements inside switch statements.
888 ///
889 /// Given
890 /// \code
891 ///   switch(a) { case 42: break; default: break; }
892 /// \endcode
893 /// switchCase()
894 ///   matches 'case 42: break;' and 'default: break;'.
895 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
896
897 /// \brief Matches compound statements.
898 ///
899 /// Example matches '{}' and '{{}}'in 'for (;;) {{}}'
900 /// \code
901 ///   for (;;) {{}}
902 /// \endcode
903 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
904
905 /// \brief Matches catch statements.
906 ///
907 /// \code
908 ///   try {} catch(int i) {}
909 /// \endcode
910 /// catchStmt()
911 ///   matches 'catch(int i)'
912 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt;
913
914 /// \brief Matches try statements.
915 ///
916 /// \code
917 ///   try {} catch(int i) {}
918 /// \endcode
919 /// tryStmt()
920 ///   matches 'try {}'
921 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt;
922
923 /// \brief Matches throw expressions.
924 ///
925 /// \code
926 ///   try { throw 5; } catch(int i) {}
927 /// \endcode
928 /// throwExpr()
929 ///   matches 'throw 5'
930 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr;
931
932 /// \brief Matches null statements.
933 ///
934 /// \code
935 ///   foo();;
936 /// \endcode
937 /// nullStmt()
938 ///   matches the second ';'
939 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
940
941 /// \brief Matches asm statements.
942 ///
943 /// \code
944 ///  int i = 100;
945 ///   __asm("mov al, 2");
946 /// \endcode
947 /// asmStmt()
948 ///   matches '__asm("mov al, 2")'
949 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
950
951 /// \brief Matches bool literals.
952 ///
953 /// Example matches true
954 /// \code
955 ///   true
956 /// \endcode
957 const internal::VariadicDynCastAllOfMatcher<
958   Stmt,
959   CXXBoolLiteralExpr> boolLiteral;
960
961 /// \brief Matches string literals (also matches wide string literals).
962 ///
963 /// Example matches "abcd", L"abcd"
964 /// \code
965 ///   char *s = "abcd"; wchar_t *ws = L"abcd"
966 /// \endcode
967 const internal::VariadicDynCastAllOfMatcher<
968   Stmt,
969   StringLiteral> stringLiteral;
970
971 /// \brief Matches character literals (also matches wchar_t).
972 ///
973 /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral),
974 /// though.
975 ///
976 /// Example matches 'a', L'a'
977 /// \code
978 ///   char ch = 'a'; wchar_t chw = L'a';
979 /// \endcode
980 const internal::VariadicDynCastAllOfMatcher<
981   Stmt,
982   CharacterLiteral> characterLiteral;
983
984 /// \brief Matches integer literals of all sizes / encodings.
985 ///
986 /// Not matching character-encoded integers such as L'a'.
987 ///
988 /// Example matches 1, 1L, 0x1, 1U
989 const internal::VariadicDynCastAllOfMatcher<
990   Stmt,
991   IntegerLiteral> integerLiteral;
992
993 /// \brief Matches user defined literal operator call.
994 ///
995 /// Example match: "foo"_suffix
996 const internal::VariadicDynCastAllOfMatcher<
997   Stmt,
998   UserDefinedLiteral> userDefinedLiteral;
999
1000 /// \brief Matches compound (i.e. non-scalar) literals
1001 ///
1002 /// Example match: {1}, (1, 2)
1003 /// \code
1004 ///   int array[4] = {1}; vector int myvec = (vector int)(1, 2);
1005 /// \endcode
1006 const internal::VariadicDynCastAllOfMatcher<
1007   Stmt,
1008   CompoundLiteralExpr> compoundLiteralExpr;
1009
1010 /// \brief Matches nullptr literal.
1011 const internal::VariadicDynCastAllOfMatcher<
1012   Stmt,
1013   CXXNullPtrLiteralExpr> nullPtrLiteralExpr;
1014
1015 /// \brief Matches binary operator expressions.
1016 ///
1017 /// Example matches a || b
1018 /// \code
1019 ///   !(a || b)
1020 /// \endcode
1021 const internal::VariadicDynCastAllOfMatcher<
1022   Stmt,
1023   BinaryOperator> binaryOperator;
1024
1025 /// \brief Matches unary operator expressions.
1026 ///
1027 /// Example matches !a
1028 /// \code
1029 ///   !a || b
1030 /// \endcode
1031 const internal::VariadicDynCastAllOfMatcher<
1032   Stmt,
1033   UnaryOperator> unaryOperator;
1034
1035 /// \brief Matches conditional operator expressions.
1036 ///
1037 /// Example matches a ? b : c
1038 /// \code
1039 ///   (a ? b : c) + 42
1040 /// \endcode
1041 const internal::VariadicDynCastAllOfMatcher<
1042   Stmt,
1043   ConditionalOperator> conditionalOperator;
1044
1045 /// \brief Matches a reinterpret_cast expression.
1046 ///
1047 /// Either the source expression or the destination type can be matched
1048 /// using has(), but hasDestinationType() is more specific and can be
1049 /// more readable.
1050 ///
1051 /// Example matches reinterpret_cast<char*>(&p) in
1052 /// \code
1053 ///   void* p = reinterpret_cast<char*>(&p);
1054 /// \endcode
1055 const internal::VariadicDynCastAllOfMatcher<
1056   Stmt,
1057   CXXReinterpretCastExpr> reinterpretCastExpr;
1058
1059 /// \brief Matches a C++ static_cast expression.
1060 ///
1061 /// \see hasDestinationType
1062 /// \see reinterpretCast
1063 ///
1064 /// Example:
1065 ///   staticCastExpr()
1066 /// matches
1067 ///   static_cast<long>(8)
1068 /// in
1069 /// \code
1070 ///   long eight(static_cast<long>(8));
1071 /// \endcode
1072 const internal::VariadicDynCastAllOfMatcher<
1073   Stmt,
1074   CXXStaticCastExpr> staticCastExpr;
1075
1076 /// \brief Matches a dynamic_cast expression.
1077 ///
1078 /// Example:
1079 ///   dynamicCastExpr()
1080 /// matches
1081 ///   dynamic_cast<D*>(&b);
1082 /// in
1083 /// \code
1084 ///   struct B { virtual ~B() {} }; struct D : B {};
1085 ///   B b;
1086 ///   D* p = dynamic_cast<D*>(&b);
1087 /// \endcode
1088 const internal::VariadicDynCastAllOfMatcher<
1089   Stmt,
1090   CXXDynamicCastExpr> dynamicCastExpr;
1091
1092 /// \brief Matches a const_cast expression.
1093 ///
1094 /// Example: Matches const_cast<int*>(&r) in
1095 /// \code
1096 ///   int n = 42;
1097 ///   const int &r(n);
1098 ///   int* p = const_cast<int*>(&r);
1099 /// \endcode
1100 const internal::VariadicDynCastAllOfMatcher<
1101   Stmt,
1102   CXXConstCastExpr> constCastExpr;
1103
1104 /// \brief Matches a C-style cast expression.
1105 ///
1106 /// Example: Matches (int*) 2.2f in
1107 /// \code
1108 ///   int i = (int) 2.2f;
1109 /// \endcode
1110 const internal::VariadicDynCastAllOfMatcher<
1111   Stmt,
1112   CStyleCastExpr> cStyleCastExpr;
1113
1114 /// \brief Matches explicit cast expressions.
1115 ///
1116 /// Matches any cast expression written in user code, whether it be a
1117 /// C-style cast, a functional-style cast, or a keyword cast.
1118 ///
1119 /// Does not match implicit conversions.
1120 ///
1121 /// Note: the name "explicitCast" is chosen to match Clang's terminology, as
1122 /// Clang uses the term "cast" to apply to implicit conversions as well as to
1123 /// actual cast expressions.
1124 ///
1125 /// \see hasDestinationType.
1126 ///
1127 /// Example: matches all five of the casts in
1128 /// \code
1129 ///   int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42)))))
1130 /// \endcode
1131 /// but does not match the implicit conversion in
1132 /// \code
1133 ///   long ell = 42;
1134 /// \endcode
1135 const internal::VariadicDynCastAllOfMatcher<
1136   Stmt,
1137   ExplicitCastExpr> explicitCastExpr;
1138
1139 /// \brief Matches the implicit cast nodes of Clang's AST.
1140 ///
1141 /// This matches many different places, including function call return value
1142 /// eliding, as well as any type conversions.
1143 const internal::VariadicDynCastAllOfMatcher<
1144   Stmt,
1145   ImplicitCastExpr> implicitCastExpr;
1146
1147 /// \brief Matches any cast nodes of Clang's AST.
1148 ///
1149 /// Example: castExpr() matches each of the following:
1150 /// \code
1151 ///   (int) 3;
1152 ///   const_cast<Expr *>(SubExpr);
1153 ///   char c = 0;
1154 /// \endcode
1155 /// but does not match
1156 /// \code
1157 ///   int i = (0);
1158 ///   int k = 0;
1159 /// \endcode
1160 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
1161
1162 /// \brief Matches functional cast expressions
1163 ///
1164 /// Example: Matches Foo(bar);
1165 /// \code
1166 ///   Foo f = bar;
1167 ///   Foo g = (Foo) bar;
1168 ///   Foo h = Foo(bar);
1169 /// \endcode
1170 const internal::VariadicDynCastAllOfMatcher<
1171   Stmt,
1172   CXXFunctionalCastExpr> functionalCastExpr;
1173
1174 /// \brief Matches \c QualTypes in the clang AST.
1175 const internal::VariadicAllOfMatcher<QualType> qualType;
1176
1177 /// \brief Matches \c Types in the clang AST.
1178 const internal::VariadicAllOfMatcher<Type> type;
1179
1180 /// \brief Matches \c TypeLocs in the clang AST.
1181 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
1182
1183 /// \brief Matches if any of the given matchers matches.
1184 ///
1185 /// Unlike \c anyOf, \c eachOf will generate a match result for each
1186 /// matching submatcher.
1187 ///
1188 /// For example, in:
1189 /// \code
1190 ///   class A { int a; int b; };
1191 /// \endcode
1192 /// The matcher:
1193 /// \code
1194 ///   recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
1195 ///                     has(fieldDecl(hasName("b")).bind("v"))))
1196 /// \endcode
1197 /// will generate two results binding "v", the first of which binds
1198 /// the field declaration of \c a, the second the field declaration of
1199 /// \c b.
1200 ///
1201 /// Usable as: Any Matcher
1202 template <typename M1, typename M2>
1203 internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, M2>
1204 eachOf(const M1 &P1, const M2 &P2) {
1205   return internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1,
1206                                                 M2>(P1, P2);
1207 }
1208
1209 /// \brief Various overloads for the anyOf matcher.
1210 /// @{
1211
1212 /// \brief Matches if any of the given matchers matches.
1213 ///
1214 /// Usable as: Any Matcher
1215 template<typename M1, typename M2>
1216 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2>
1217 anyOf(const M1 &P1, const M2 &P2) {
1218   return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1219                                                 M1, M2 >(P1, P2);
1220 }
1221 template<typename M1, typename M2, typename M3>
1222 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1223     internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> >
1224 anyOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1225   return anyOf(P1, anyOf(P2, P3));
1226 }
1227 template<typename M1, typename M2, typename M3, typename M4>
1228 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1229     internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1230         internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1231                                                M3, M4> > >
1232 anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1233   return anyOf(P1, anyOf(P2, anyOf(P3, P4)));
1234 }
1235 template<typename M1, typename M2, typename M3, typename M4, typename M5>
1236 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1,
1237     internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2,
1238         internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3,
1239             internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher,
1240                                                    M4, M5> > > >
1241 anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1242   return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5))));
1243 }
1244
1245 /// @}
1246
1247 /// \brief Various overloads for the allOf matcher.
1248 /// @{
1249
1250 /// \brief Matches if all given matchers match.
1251 ///
1252 /// Usable as: Any Matcher
1253 template <typename M1, typename M2>
1254 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>
1255 allOf(const M1 &P1, const M2 &P2) {
1256   return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>(
1257       P1, P2);
1258 }
1259 template <typename M1, typename M2, typename M3>
1260 internal::PolymorphicMatcherWithParam2<
1261     internal::AllOfMatcher, M1,
1262     internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> >
1263 allOf(const M1 &P1, const M2 &P2, const M3 &P3) {
1264   return allOf(P1, allOf(P2, P3));
1265 }
1266 template <typename M1, typename M2, typename M3, typename M4>
1267 internal::PolymorphicMatcherWithParam2<
1268     internal::AllOfMatcher, M1,
1269     internal::PolymorphicMatcherWithParam2<
1270         internal::AllOfMatcher, M2, internal::PolymorphicMatcherWithParam2<
1271                                         internal::AllOfMatcher, M3, M4> > >
1272 allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) {
1273   return allOf(P1, allOf(P2, P3, P4));
1274 }
1275 template <typename M1, typename M2, typename M3, typename M4, typename M5>
1276 internal::PolymorphicMatcherWithParam2<
1277     internal::AllOfMatcher, M1,
1278     internal::PolymorphicMatcherWithParam2<
1279         internal::AllOfMatcher, M2,
1280         internal::PolymorphicMatcherWithParam2<
1281             internal::AllOfMatcher, M3,
1282             internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M4,
1283                                                    M5> > > >
1284 allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) {
1285   return allOf(P1, allOf(P2, P3, P4, P5));
1286 }
1287
1288 /// @}
1289
1290 /// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL)
1291 ///
1292 /// Given
1293 /// \code
1294 ///   Foo x = bar;
1295 ///   int y = sizeof(x) + alignof(x);
1296 /// \endcode
1297 /// unaryExprOrTypeTraitExpr()
1298 ///   matches \c sizeof(x) and \c alignof(x)
1299 const internal::VariadicDynCastAllOfMatcher<
1300   Stmt,
1301   UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr;
1302
1303 /// \brief Matches unary expressions that have a specific type of argument.
1304 ///
1305 /// Given
1306 /// \code
1307 ///   int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c);
1308 /// \endcode
1309 /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int"))
1310 ///   matches \c sizeof(a) and \c alignof(c)
1311 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType,
1312               internal::Matcher<QualType>, InnerMatcher) {
1313   const QualType ArgumentType = Node.getTypeOfArgument();
1314   return InnerMatcher.matches(ArgumentType, Finder, Builder);
1315 }
1316
1317 /// \brief Matches unary expressions of a certain kind.
1318 ///
1319 /// Given
1320 /// \code
1321 ///   int x;
1322 ///   int s = sizeof(x) + alignof(x)
1323 /// \endcode
1324 /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf))
1325 ///   matches \c sizeof(x)
1326 AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) {
1327   return Node.getKind() == Kind;
1328 }
1329
1330 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1331 /// alignof.
1332 inline internal::Matcher<Stmt> alignOfExpr(
1333     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1334   return stmt(unaryExprOrTypeTraitExpr(allOf(
1335       ofKind(UETT_AlignOf), InnerMatcher)));
1336 }
1337
1338 /// \brief Same as unaryExprOrTypeTraitExpr, but only matching
1339 /// sizeof.
1340 inline internal::Matcher<Stmt> sizeOfExpr(
1341     const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) {
1342   return stmt(unaryExprOrTypeTraitExpr(
1343       allOf(ofKind(UETT_SizeOf), InnerMatcher)));
1344 }
1345
1346 /// \brief Matches NamedDecl nodes that have the specified name.
1347 ///
1348 /// Supports specifying enclosing namespaces or classes by prefixing the name
1349 /// with '<enclosing>::'.
1350 /// Does not match typedefs of an underlying type with the given name.
1351 ///
1352 /// Example matches X (Name == "X")
1353 /// \code
1354 ///   class X;
1355 /// \endcode
1356 ///
1357 /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X")
1358 /// \code
1359 ///   namespace a { namespace b { class X; } }
1360 /// \endcode
1361 AST_MATCHER_P(NamedDecl, hasName, std::string, Name) {
1362   assert(!Name.empty());
1363   const std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1364   const StringRef FullName = FullNameString;
1365   const StringRef Pattern = Name;
1366   if (Pattern.startswith("::")) {
1367     return FullName == Pattern;
1368   } else {
1369     return FullName.endswith(("::" + Pattern).str());
1370   }
1371 }
1372
1373 /// \brief Matches NamedDecl nodes whose fully qualified names contain
1374 /// a substring matched by the given RegExp.
1375 ///
1376 /// Supports specifying enclosing namespaces or classes by
1377 /// prefixing the name with '<enclosing>::'.  Does not match typedefs
1378 /// of an underlying type with the given name.
1379 ///
1380 /// Example matches X (regexp == "::X")
1381 /// \code
1382 ///   class X;
1383 /// \endcode
1384 ///
1385 /// Example matches X (regexp is one of "::X", "^foo::.*X", among others)
1386 /// \code
1387 ///   namespace foo { namespace bar { class X; } }
1388 /// \endcode
1389 AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) {
1390   assert(!RegExp.empty());
1391   std::string FullNameString = "::" + Node.getQualifiedNameAsString();
1392   llvm::Regex RE(RegExp);
1393   return RE.match(FullNameString);
1394 }
1395
1396 /// \brief Matches overloaded operator names.
1397 ///
1398 /// Matches overloaded operator names specified in strings without the
1399 /// "operator" prefix: e.g. "<<".
1400 ///
1401 /// Given:
1402 /// \code
1403 ///   class A { int operator*(); };
1404 ///   const A &operator<<(const A &a, const A &b);
1405 ///   A a;
1406 ///   a << a;   // <-- This matches
1407 /// \endcode
1408 ///
1409 /// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified
1410 /// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches
1411 /// the declaration of \c A.
1412 ///
1413 /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl>
1414 inline internal::PolymorphicMatcherWithParam1<
1415     internal::HasOverloadedOperatorNameMatcher, StringRef>
1416 hasOverloadedOperatorName(const StringRef Name) {
1417   return internal::PolymorphicMatcherWithParam1<
1418       internal::HasOverloadedOperatorNameMatcher, StringRef>(Name);
1419 }
1420
1421 /// \brief Matches C++ classes that are directly or indirectly derived from
1422 /// a class matching \c Base.
1423 ///
1424 /// Note that a class is not considered to be derived from itself.
1425 ///
1426 /// Example matches Y, Z, C (Base == hasName("X"))
1427 /// \code
1428 ///   class X;
1429 ///   class Y : public X {};  // directly derived
1430 ///   class Z : public Y {};  // indirectly derived
1431 ///   typedef X A;
1432 ///   typedef A B;
1433 ///   class C : public B {};  // derived from a typedef of X
1434 /// \endcode
1435 ///
1436 /// In the following example, Bar matches isDerivedFrom(hasName("X")):
1437 /// \code
1438 ///   class Foo;
1439 ///   typedef Foo X;
1440 ///   class Bar : public Foo {};  // derived from a type that X is a typedef of
1441 /// \endcode
1442 AST_MATCHER_P(CXXRecordDecl, isDerivedFrom,
1443               internal::Matcher<NamedDecl>, Base) {
1444   return Finder->classIsDerivedFrom(&Node, Base, Builder);
1445 }
1446
1447 /// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)).
1448 inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) {
1449   assert(!BaseName.empty());
1450   return isDerivedFrom(hasName(BaseName));
1451 }
1452
1453 /// \brief Similar to \c isDerivedFrom(), but also matches classes that directly
1454 /// match \c Base.
1455 inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1456     internal::Matcher<NamedDecl> Base) {
1457   return anyOf(Base, isDerivedFrom(Base));
1458 }
1459
1460 /// \brief Overloaded method as shortcut for
1461 /// \c isSameOrDerivedFrom(hasName(...)).
1462 inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom(
1463     StringRef BaseName) {
1464   assert(!BaseName.empty());
1465   return isSameOrDerivedFrom(hasName(BaseName));
1466 }
1467
1468 /// \brief Matches the first method of a class or struct that satisfies \c
1469 /// InnerMatcher.
1470 ///
1471 /// Given:
1472 /// \code
1473 ///   class A { void func(); };
1474 ///   class B { void member(); };
1475 /// \code
1476 ///
1477 /// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A
1478 /// but not \c B.
1479 AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>,
1480               InnerMatcher) {
1481   for (CXXRecordDecl::method_iterator I = Node.method_begin(),
1482                                       E = Node.method_end();
1483        I != E; ++I)
1484     if (InnerMatcher.matches(**I, Finder, Builder))
1485       return true;
1486   return false;
1487 }
1488
1489 /// \brief Matches AST nodes that have child AST nodes that match the
1490 /// provided matcher.
1491 ///
1492 /// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X")))
1493 /// \code
1494 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
1495 ///   class Y { class X {}; };
1496 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
1497 /// \endcode
1498 ///
1499 /// ChildT must be an AST base type.
1500 ///
1501 /// Usable as: Any Matcher
1502 template <typename ChildT>
1503 internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has(
1504     const internal::Matcher<ChildT> &ChildMatcher) {
1505   return internal::ArgumentAdaptingMatcher<internal::HasMatcher,
1506                                            ChildT>(ChildMatcher);
1507 }
1508
1509 /// \brief Matches AST nodes that have descendant AST nodes that match the
1510 /// provided matcher.
1511 ///
1512 /// Example matches X, Y, Z
1513 ///     (matcher = recordDecl(hasDescendant(recordDecl(hasName("X")))))
1514 /// \code
1515 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
1516 ///   class Y { class X {}; };
1517 ///   class Z { class Y { class X {}; }; };
1518 /// \endcode
1519 ///
1520 /// DescendantT must be an AST base type.
1521 ///
1522 /// Usable as: Any Matcher
1523 template <typename DescendantT>
1524 internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT>
1525 hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) {
1526   return internal::ArgumentAdaptingMatcher<
1527     internal::HasDescendantMatcher,
1528     DescendantT>(DescendantMatcher);
1529 }
1530
1531 /// \brief Matches AST nodes that have child AST nodes that match the
1532 /// provided matcher.
1533 ///
1534 /// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X")))
1535 /// \code
1536 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
1537 ///   class Y { class X {}; };
1538 ///   class Z { class Y { class X {}; }; };  // Does not match Z.
1539 /// \endcode
1540 ///
1541 /// ChildT must be an AST base type.
1542 ///
1543 /// As opposed to 'has', 'forEach' will cause a match for each result that
1544 /// matches instead of only on the first one.
1545 ///
1546 /// Usable as: Any Matcher
1547 template <typename ChildT>
1548 internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach(
1549     const internal::Matcher<ChildT> &ChildMatcher) {
1550   return internal::ArgumentAdaptingMatcher<
1551     internal::ForEachMatcher,
1552     ChildT>(ChildMatcher);
1553 }
1554
1555 /// \brief Matches AST nodes that have descendant AST nodes that match the
1556 /// provided matcher.
1557 ///
1558 /// Example matches X, A, B, C
1559 ///     (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X")))))
1560 /// \code
1561 ///   class X {};  // Matches X, because X::X is a class of name X inside X.
1562 ///   class A { class X {}; };
1563 ///   class B { class C { class X {}; }; };
1564 /// \endcode
1565 ///
1566 /// DescendantT must be an AST base type.
1567 ///
1568 /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for
1569 /// each result that matches instead of only on the first one.
1570 ///
1571 /// Note: Recursively combined ForEachDescendant can cause many matches:
1572 ///   recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl()))))
1573 /// will match 10 times (plus injected class name matches) on:
1574 /// \code
1575 ///   class A { class B { class C { class D { class E {}; }; }; }; };
1576 /// \endcode
1577 ///
1578 /// Usable as: Any Matcher
1579 template <typename DescendantT>
1580 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher,
1581                                   DescendantT>
1582 forEachDescendant(
1583     const internal::Matcher<DescendantT> &DescendantMatcher) {
1584   return internal::ArgumentAdaptingMatcher<
1585     internal::ForEachDescendantMatcher,
1586     DescendantT>(DescendantMatcher);
1587 }
1588
1589 /// \brief Matches if the node or any descendant matches.
1590 ///
1591 /// Generates results for each match.
1592 ///
1593 /// For example, in:
1594 /// \code
1595 ///   class A { class B {}; class C {}; };
1596 /// \endcode
1597 /// The matcher:
1598 /// \code
1599 ///   recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m")))
1600 /// \endcode
1601 /// will generate results for \c A, \c B and \c C.
1602 ///
1603 /// Usable as: Any Matcher
1604 template <typename T>
1605 internal::PolymorphicMatcherWithParam2<
1606     internal::EachOfMatcher, internal::Matcher<T>,
1607     internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> >
1608 findAll(const internal::Matcher<T> &Matcher) {
1609   return eachOf(Matcher, forEachDescendant(Matcher));
1610 }
1611
1612 /// \brief Matches AST nodes that have a parent that matches the provided
1613 /// matcher.
1614 ///
1615 /// Given
1616 /// \code
1617 /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } }
1618 /// \endcode
1619 /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }".
1620 ///
1621 /// Usable as: Any Matcher
1622 template <typename ParentT>
1623 internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT>
1624 hasParent(const internal::Matcher<ParentT> &ParentMatcher) {
1625   return internal::ArgumentAdaptingMatcher<
1626     internal::HasParentMatcher,
1627     ParentT>(ParentMatcher);
1628 }
1629
1630 /// \brief Matches AST nodes that have an ancestor that matches the provided
1631 /// matcher.
1632 ///
1633 /// Given
1634 /// \code
1635 /// void f() { if (true) { int x = 42; } }
1636 /// void g() { for (;;) { int x = 43; } }
1637 /// \endcode
1638 /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43.
1639 ///
1640 /// Usable as: Any Matcher
1641 template <typename AncestorT>
1642 internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT>
1643 hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) {
1644   return internal::ArgumentAdaptingMatcher<
1645     internal::HasAncestorMatcher,
1646     AncestorT>(AncestorMatcher);
1647 }
1648
1649 /// \brief Matches if the provided matcher does not match.
1650 ///
1651 /// Example matches Y (matcher = recordDecl(unless(hasName("X"))))
1652 /// \code
1653 ///   class X {};
1654 ///   class Y {};
1655 /// \endcode
1656 ///
1657 /// Usable as: Any Matcher
1658 template <typename M>
1659 internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M>
1660 unless(const M &InnerMatcher) {
1661   return internal::PolymorphicMatcherWithParam1<
1662     internal::NotMatcher, M>(InnerMatcher);
1663 }
1664
1665 /// \brief Matches a type if the declaration of the type matches the given
1666 /// matcher.
1667 ///
1668 /// In addition to being usable as Matcher<TypedefType>, also usable as
1669 /// Matcher<T> for any T supporting the getDecl() member function. e.g. various
1670 /// subtypes of clang::Type.
1671 ///
1672 /// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>,
1673 ///   Matcher<MemberExpr>, Matcher<TypedefType>,
1674 ///   Matcher<TemplateSpecializationType>
1675 inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher,
1676                                      internal::Matcher<Decl> >
1677     hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) {
1678   return internal::PolymorphicMatcherWithParam1<
1679     internal::HasDeclarationMatcher,
1680     internal::Matcher<Decl> >(InnerMatcher);
1681 }
1682
1683 /// \brief Matches on the implicit object argument of a member call expression.
1684 ///
1685 /// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y"))))))
1686 /// \code
1687 ///   class Y { public: void x(); };
1688 ///   void z() { Y y; y.x(); }",
1689 /// \endcode
1690 ///
1691 /// FIXME: Overload to allow directly matching types?
1692 AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>,
1693               InnerMatcher) {
1694   const Expr *ExprNode = Node.getImplicitObjectArgument()
1695                             ->IgnoreParenImpCasts();
1696   return (ExprNode != NULL &&
1697           InnerMatcher.matches(*ExprNode, Finder, Builder));
1698 }
1699
1700 /// \brief Matches if the call expression's callee expression matches.
1701 ///
1702 /// Given
1703 /// \code
1704 ///   class Y { void x() { this->x(); x(); Y y; y.x(); } };
1705 ///   void f() { f(); }
1706 /// \endcode
1707 /// callExpr(callee(expr()))
1708 ///   matches this->x(), x(), y.x(), f()
1709 /// with callee(...)
1710 ///   matching this->x, x, y.x, f respectively
1711 ///
1712 /// Note: Callee cannot take the more general internal::Matcher<Expr>
1713 /// because this introduces ambiguous overloads with calls to Callee taking a
1714 /// internal::Matcher<Decl>, as the matcher hierarchy is purely
1715 /// implemented in terms of implicit casts.
1716 AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>,
1717               InnerMatcher) {
1718   const Expr *ExprNode = Node.getCallee();
1719   return (ExprNode != NULL &&
1720           InnerMatcher.matches(*ExprNode, Finder, Builder));
1721 }
1722
1723 /// \brief Matches if the call expression's callee's declaration matches the
1724 /// given matcher.
1725 ///
1726 /// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x")))))
1727 /// \code
1728 ///   class Y { public: void x(); };
1729 ///   void z() { Y y; y.x();
1730 /// \endcode
1731 inline internal::Matcher<CallExpr> callee(
1732     const internal::Matcher<Decl> &InnerMatcher) {
1733   return callExpr(hasDeclaration(InnerMatcher));
1734 }
1735
1736 /// \brief Matches if the expression's or declaration's type matches a type
1737 /// matcher.
1738 ///
1739 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1740 ///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1741 /// \code
1742 ///  class X {};
1743 ///  void y(X &x) { x; X z; }
1744 /// \endcode
1745 AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>,
1746                           InnerMatcher) {
1747   TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value ||
1748                           llvm::is_base_of<ValueDecl, NodeType>::value),
1749                          instantiated_with_wrong_types);
1750   return InnerMatcher.matches(Node.getType(), Finder, Builder);
1751 }
1752
1753 /// \brief Overloaded to match the declaration of the expression's or value
1754 /// declaration's type.
1755 ///
1756 /// In case of a value declaration (for example a variable declaration),
1757 /// this resolves one layer of indirection. For example, in the value
1758 /// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X,
1759 /// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration
1760 /// of x."
1761 ///
1762 /// Example matches x (matcher = expr(hasType(recordDecl(hasName("X")))))
1763 ///             and z (matcher = varDecl(hasType(recordDecl(hasName("X")))))
1764 /// \code
1765 ///  class X {};
1766 ///  void y(X &x) { x; X z; }
1767 /// \endcode
1768 ///
1769 /// Usable as: Matcher<Expr>, Matcher<ValueDecl>
1770 inline internal::PolymorphicMatcherWithParam1<
1771   internal::matcher_hasType0Matcher,
1772   internal::Matcher<QualType> >
1773 hasType(const internal::Matcher<Decl> &InnerMatcher) {
1774   return hasType(qualType(hasDeclaration(InnerMatcher)));
1775 }
1776
1777 /// \brief Matches if the matched type is represented by the given string.
1778 ///
1779 /// Given
1780 /// \code
1781 ///   class Y { public: void x(); };
1782 ///   void z() { Y* y; y->x(); }
1783 /// \endcode
1784 /// callExpr(on(hasType(asString("class Y *"))))
1785 ///   matches y->x()
1786 AST_MATCHER_P(QualType, asString, std::string, Name) {
1787   return Name == Node.getAsString();
1788 }
1789
1790 /// \brief Matches if the matched type is a pointer type and the pointee type
1791 /// matches the specified matcher.
1792 ///
1793 /// Example matches y->x()
1794 ///     (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y")))))))
1795 /// \code
1796 ///   class Y { public: void x(); };
1797 ///   void z() { Y *y; y->x(); }
1798 /// \endcode
1799 AST_MATCHER_P(
1800     QualType, pointsTo, internal::Matcher<QualType>,
1801     InnerMatcher) {
1802   return (!Node.isNull() && Node->isPointerType() &&
1803           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1804 }
1805
1806 /// \brief Overloaded to match the pointee type's declaration.
1807 inline internal::Matcher<QualType> pointsTo(
1808     const internal::Matcher<Decl> &InnerMatcher) {
1809   return pointsTo(qualType(hasDeclaration(InnerMatcher)));
1810 }
1811
1812 /// \brief Matches if the matched type is a reference type and the referenced
1813 /// type matches the specified matcher.
1814 ///
1815 /// Example matches X &x and const X &y
1816 ///     (matcher = varDecl(hasType(references(recordDecl(hasName("X"))))))
1817 /// \code
1818 ///   class X {
1819 ///     void a(X b) {
1820 ///       X &x = b;
1821 ///       const X &y = b;
1822 ///   };
1823 /// \endcode
1824 AST_MATCHER_P(QualType, references, internal::Matcher<QualType>,
1825               InnerMatcher) {
1826   return (!Node.isNull() && Node->isReferenceType() &&
1827           InnerMatcher.matches(Node->getPointeeType(), Finder, Builder));
1828 }
1829
1830 /// \brief Matches QualTypes whose canonical type matches InnerMatcher.
1831 ///
1832 /// Given:
1833 /// \code
1834 ///   typedef int &int_ref;
1835 ///   int a;
1836 ///   int_ref b = a;
1837 /// \code
1838 ///
1839 /// \c varDecl(hasType(qualType(referenceType()))))) will not match the
1840 /// declaration of b but \c
1841 /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does.
1842 AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>,
1843               InnerMatcher) {
1844   return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder);
1845 }
1846
1847 /// \brief Overloaded to match the referenced type's declaration.
1848 inline internal::Matcher<QualType> references(
1849     const internal::Matcher<Decl> &InnerMatcher) {
1850   return references(qualType(hasDeclaration(InnerMatcher)));
1851 }
1852
1853 AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument,
1854               internal::Matcher<Expr>, InnerMatcher) {
1855   const Expr *ExprNode = Node.getImplicitObjectArgument();
1856   return (ExprNode != NULL &&
1857           InnerMatcher.matches(*ExprNode, Finder, Builder));
1858 }
1859
1860 /// \brief Matches if the expression's type either matches the specified
1861 /// matcher, or is a pointer to a type that matches the InnerMatcher.
1862 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1863     const internal::Matcher<QualType> &InnerMatcher) {
1864   return onImplicitObjectArgument(
1865       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1866 }
1867
1868 /// \brief Overloaded to match the type's declaration.
1869 inline internal::Matcher<CXXMemberCallExpr> thisPointerType(
1870     const internal::Matcher<Decl> &InnerMatcher) {
1871   return onImplicitObjectArgument(
1872       anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher))));
1873 }
1874
1875 /// \brief Matches a DeclRefExpr that refers to a declaration that matches the
1876 /// specified matcher.
1877 ///
1878 /// Example matches x in if(x)
1879 ///     (matcher = declRefExpr(to(varDecl(hasName("x")))))
1880 /// \code
1881 ///   bool x;
1882 ///   if (x) {}
1883 /// \endcode
1884 AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>,
1885               InnerMatcher) {
1886   const Decl *DeclNode = Node.getDecl();
1887   return (DeclNode != NULL &&
1888           InnerMatcher.matches(*DeclNode, Finder, Builder));
1889 }
1890
1891 /// \brief Matches a \c DeclRefExpr that refers to a declaration through a
1892 /// specific using shadow declaration.
1893 ///
1894 /// FIXME: This currently only works for functions. Fix.
1895 ///
1896 /// Given
1897 /// \code
1898 ///   namespace a { void f() {} }
1899 ///   using a::f;
1900 ///   void g() {
1901 ///     f();     // Matches this ..
1902 ///     a::f();  // .. but not this.
1903 ///   }
1904 /// \endcode
1905 /// declRefExpr(throughUsingDeclaration(anything()))
1906 ///   matches \c f()
1907 AST_MATCHER_P(DeclRefExpr, throughUsingDecl,
1908               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
1909   const NamedDecl *FoundDecl = Node.getFoundDecl();
1910   if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl))
1911     return InnerMatcher.matches(*UsingDecl, Finder, Builder);
1912   return false;
1913 }
1914
1915 /// \brief Matches the Decl of a DeclStmt which has a single declaration.
1916 ///
1917 /// Given
1918 /// \code
1919 ///   int a, b;
1920 ///   int c;
1921 /// \endcode
1922 /// declStmt(hasSingleDecl(anything()))
1923 ///   matches 'int c;' but not 'int a, b;'.
1924 AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) {
1925   if (Node.isSingleDecl()) {
1926     const Decl *FoundDecl = Node.getSingleDecl();
1927     return InnerMatcher.matches(*FoundDecl, Finder, Builder);
1928   }
1929   return false;
1930 }
1931
1932 /// \brief Matches a variable declaration that has an initializer expression
1933 /// that matches the given matcher.
1934 ///
1935 /// Example matches x (matcher = varDecl(hasInitializer(callExpr())))
1936 /// \code
1937 ///   bool y() { return true; }
1938 ///   bool x = y();
1939 /// \endcode
1940 AST_MATCHER_P(
1941     VarDecl, hasInitializer, internal::Matcher<Expr>,
1942     InnerMatcher) {
1943   const Expr *Initializer = Node.getAnyInitializer();
1944   return (Initializer != NULL &&
1945           InnerMatcher.matches(*Initializer, Finder, Builder));
1946 }
1947
1948 /// \brief Checks that a call expression or a constructor call expression has
1949 /// a specific number of arguments (including absent default arguments).
1950 ///
1951 /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2)))
1952 /// \code
1953 ///   void f(int x, int y);
1954 ///   f(0, 0);
1955 /// \endcode
1956 AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) {
1957   TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1958                           llvm::is_base_of<CXXConstructExpr,
1959                                            NodeType>::value),
1960                          instantiated_with_wrong_types);
1961   return Node.getNumArgs() == N;
1962 }
1963
1964 /// \brief Matches the n'th argument of a call expression or a constructor
1965 /// call expression.
1966 ///
1967 /// Example matches y in x(y)
1968 ///     (matcher = callExpr(hasArgument(0, declRefExpr())))
1969 /// \code
1970 ///   void x(int) { int y; x(y); }
1971 /// \endcode
1972 AST_POLYMORPHIC_MATCHER_P2(
1973     hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) {
1974   TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
1975                          llvm::is_base_of<CXXConstructExpr,
1976                                           NodeType>::value),
1977                          instantiated_with_wrong_types);
1978   return (N < Node.getNumArgs() &&
1979           InnerMatcher.matches(
1980               *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder));
1981 }
1982
1983 /// \brief Matches declaration statements that contain a specific number of
1984 /// declarations.
1985 ///
1986 /// Example: Given
1987 /// \code
1988 ///   int a, b;
1989 ///   int c;
1990 ///   int d = 2, e;
1991 /// \endcode
1992 /// declCountIs(2)
1993 ///   matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'.
1994 AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) {
1995   return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N;
1996 }
1997
1998 /// \brief Matches the n'th declaration of a declaration statement.
1999 ///
2000 /// Note that this does not work for global declarations because the AST
2001 /// breaks up multiple-declaration DeclStmt's into multiple single-declaration
2002 /// DeclStmt's.
2003 /// Example: Given non-global declarations
2004 /// \code
2005 ///   int a, b = 0;
2006 ///   int c;
2007 ///   int d = 2, e;
2008 /// \endcode
2009 /// declStmt(containsDeclaration(
2010 ///       0, varDecl(hasInitializer(anything()))))
2011 ///   matches only 'int d = 2, e;', and
2012 /// declStmt(containsDeclaration(1, varDecl()))
2013 /// \code
2014 ///   matches 'int a, b = 0' as well as 'int d = 2, e;'
2015 ///   but 'int c;' is not matched.
2016 /// \endcode
2017 AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N,
2018                internal::Matcher<Decl>, InnerMatcher) {
2019   const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end());
2020   if (N >= NumDecls)
2021     return false;
2022   DeclStmt::const_decl_iterator Iterator = Node.decl_begin();
2023   std::advance(Iterator, N);
2024   return InnerMatcher.matches(**Iterator, Finder, Builder);
2025 }
2026
2027 /// \brief Matches a constructor initializer.
2028 ///
2029 /// Given
2030 /// \code
2031 ///   struct Foo {
2032 ///     Foo() : foo_(1) { }
2033 ///     int foo_;
2034 ///   };
2035 /// \endcode
2036 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything()))))
2037 ///   record matches Foo, hasAnyConstructorInitializer matches foo_(1)
2038 AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer,
2039               internal::Matcher<CXXCtorInitializer>, InnerMatcher) {
2040   for (CXXConstructorDecl::init_const_iterator I = Node.init_begin();
2041        I != Node.init_end(); ++I) {
2042     if (InnerMatcher.matches(**I, Finder, Builder)) {
2043       return true;
2044     }
2045   }
2046   return false;
2047 }
2048
2049 /// \brief Matches the field declaration of a constructor initializer.
2050 ///
2051 /// Given
2052 /// \code
2053 ///   struct Foo {
2054 ///     Foo() : foo_(1) { }
2055 ///     int foo_;
2056 ///   };
2057 /// \endcode
2058 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2059 ///     forField(hasName("foo_"))))))
2060 ///   matches Foo
2061 /// with forField matching foo_
2062 AST_MATCHER_P(CXXCtorInitializer, forField,
2063               internal::Matcher<FieldDecl>, InnerMatcher) {
2064   const FieldDecl *NodeAsDecl = Node.getMember();
2065   return (NodeAsDecl != NULL &&
2066       InnerMatcher.matches(*NodeAsDecl, Finder, Builder));
2067 }
2068
2069 /// \brief Matches the initializer expression of a constructor initializer.
2070 ///
2071 /// Given
2072 /// \code
2073 ///   struct Foo {
2074 ///     Foo() : foo_(1) { }
2075 ///     int foo_;
2076 ///   };
2077 /// \endcode
2078 /// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(
2079 ///     withInitializer(integerLiteral(equals(1)))))))
2080 ///   matches Foo
2081 /// with withInitializer matching (1)
2082 AST_MATCHER_P(CXXCtorInitializer, withInitializer,
2083               internal::Matcher<Expr>, InnerMatcher) {
2084   const Expr* NodeAsExpr = Node.getInit();
2085   return (NodeAsExpr != NULL &&
2086       InnerMatcher.matches(*NodeAsExpr, Finder, Builder));
2087 }
2088
2089 /// \brief Matches a contructor initializer if it is explicitly written in
2090 /// code (as opposed to implicitly added by the compiler).
2091 ///
2092 /// Given
2093 /// \code
2094 ///   struct Foo {
2095 ///     Foo() { }
2096 ///     Foo(int) : foo_("A") { }
2097 ///     string foo_;
2098 ///   };
2099 /// \endcode
2100 /// constructorDecl(hasAnyConstructorInitializer(isWritten()))
2101 ///   will match Foo(int), but not Foo()
2102 AST_MATCHER(CXXCtorInitializer, isWritten) {
2103   return Node.isWritten();
2104 }
2105
2106 /// \brief Matches a constructor declaration that has been implicitly added
2107 /// by the compiler (eg. implicit default/copy constructors).
2108 AST_MATCHER(CXXConstructorDecl, isImplicit) {
2109   return Node.isImplicit();
2110 }
2111
2112 /// \brief Matches any argument of a call expression or a constructor call
2113 /// expression.
2114 ///
2115 /// Given
2116 /// \code
2117 ///   void x(int, int, int) { int y; x(1, y, 42); }
2118 /// \endcode
2119 /// callExpr(hasAnyArgument(declRefExpr()))
2120 ///   matches x(1, y, 42)
2121 /// with hasAnyArgument(...)
2122 ///   matching y
2123 AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>,
2124                           InnerMatcher) {
2125   TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value ||
2126                          llvm::is_base_of<CXXConstructExpr,
2127                                           NodeType>::value),
2128                          instantiated_with_wrong_types);
2129   for (unsigned I = 0; I < Node.getNumArgs(); ++I) {
2130     if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(),
2131                              Finder, Builder)) {
2132       return true;
2133     }
2134   }
2135   return false;
2136 }
2137
2138 /// \brief Matches the n'th parameter of a function declaration.
2139 ///
2140 /// Given
2141 /// \code
2142 ///   class X { void f(int x) {} };
2143 /// \endcode
2144 /// methodDecl(hasParameter(0, hasType(varDecl())))
2145 ///   matches f(int x) {}
2146 /// with hasParameter(...)
2147 ///   matching int x
2148 AST_MATCHER_P2(FunctionDecl, hasParameter,
2149                unsigned, N, internal::Matcher<ParmVarDecl>,
2150                InnerMatcher) {
2151   return (N < Node.getNumParams() &&
2152           InnerMatcher.matches(
2153               *Node.getParamDecl(N), Finder, Builder));
2154 }
2155
2156 /// \brief Matches any parameter of a function declaration.
2157 ///
2158 /// Does not match the 'this' parameter of a method.
2159 ///
2160 /// Given
2161 /// \code
2162 ///   class X { void f(int x, int y, int z) {} };
2163 /// \endcode
2164 /// methodDecl(hasAnyParameter(hasName("y")))
2165 ///   matches f(int x, int y, int z) {}
2166 /// with hasAnyParameter(...)
2167 ///   matching int y
2168 AST_MATCHER_P(FunctionDecl, hasAnyParameter,
2169               internal::Matcher<ParmVarDecl>, InnerMatcher) {
2170   for (unsigned I = 0; I < Node.getNumParams(); ++I) {
2171     if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) {
2172       return true;
2173     }
2174   }
2175   return false;
2176 }
2177
2178 /// \brief Matches \c FunctionDecls that have a specific parameter count.
2179 ///
2180 /// Given
2181 /// \code
2182 ///   void f(int i) {}
2183 ///   void g(int i, int j) {}
2184 /// \endcode
2185 /// functionDecl(parameterCountIs(2))
2186 ///   matches g(int i, int j) {}
2187 AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) {
2188   return Node.getNumParams() == N;
2189 }
2190
2191 /// \brief Matches the return type of a function declaration.
2192 ///
2193 /// Given:
2194 /// \code
2195 ///   class X { int f() { return 1; } };
2196 /// \endcode
2197 /// methodDecl(returns(asString("int")))
2198 ///   matches int f() { return 1; }
2199 AST_MATCHER_P(FunctionDecl, returns,
2200               internal::Matcher<QualType>, InnerMatcher) {
2201   return InnerMatcher.matches(Node.getResultType(), Finder, Builder);
2202 }
2203
2204 /// \brief Matches extern "C" function declarations.
2205 ///
2206 /// Given:
2207 /// \code
2208 ///   extern "C" void f() {}
2209 ///   extern "C" { void g() {} }
2210 ///   void h() {}
2211 /// \endcode
2212 /// functionDecl(isExternC())
2213 ///   matches the declaration of f and g, but not the declaration h
2214 AST_MATCHER(FunctionDecl, isExternC) {
2215   return Node.isExternC();
2216 }
2217
2218 /// \brief Matches the condition expression of an if statement, for loop,
2219 /// or conditional operator.
2220 ///
2221 /// Example matches true (matcher = hasCondition(boolLiteral(equals(true))))
2222 /// \code
2223 ///   if (true) {}
2224 /// \endcode
2225 AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>,
2226                           InnerMatcher) {
2227   TOOLING_COMPILE_ASSERT(
2228     (llvm::is_base_of<IfStmt, NodeType>::value) ||
2229     (llvm::is_base_of<ForStmt, NodeType>::value) ||
2230     (llvm::is_base_of<WhileStmt, NodeType>::value) ||
2231     (llvm::is_base_of<DoStmt, NodeType>::value) ||
2232     (llvm::is_base_of<ConditionalOperator, NodeType>::value),
2233     has_condition_requires_if_statement_conditional_operator_or_loop);
2234   const Expr *const Condition = Node.getCond();
2235   return (Condition != NULL &&
2236           InnerMatcher.matches(*Condition, Finder, Builder));
2237 }
2238
2239 /// \brief Matches the condition variable statement in an if statement.
2240 ///
2241 /// Given
2242 /// \code
2243 ///   if (A* a = GetAPointer()) {}
2244 /// \endcode
2245 /// hasConditionVariableStatment(...)
2246 ///   matches 'A* a = GetAPointer()'.
2247 AST_MATCHER_P(IfStmt, hasConditionVariableStatement,
2248               internal::Matcher<DeclStmt>, InnerMatcher) {
2249   const DeclStmt* const DeclarationStatement =
2250     Node.getConditionVariableDeclStmt();
2251   return DeclarationStatement != NULL &&
2252          InnerMatcher.matches(*DeclarationStatement, Finder, Builder);
2253 }
2254
2255 /// \brief Matches the index expression of an array subscript expression.
2256 ///
2257 /// Given
2258 /// \code
2259 ///   int i[5];
2260 ///   void f() { i[1] = 42; }
2261 /// \endcode
2262 /// arraySubscriptExpression(hasIndex(integerLiteral()))
2263 ///   matches \c i[1] with the \c integerLiteral() matching \c 1
2264 AST_MATCHER_P(ArraySubscriptExpr, hasIndex,
2265               internal::Matcher<Expr>, InnerMatcher) {
2266   if (const Expr* Expression = Node.getIdx())
2267     return InnerMatcher.matches(*Expression, Finder, Builder);
2268   return false;
2269 }
2270
2271 /// \brief Matches the base expression of an array subscript expression.
2272 ///
2273 /// Given
2274 /// \code
2275 ///   int i[5];
2276 ///   void f() { i[1] = 42; }
2277 /// \endcode
2278 /// arraySubscriptExpression(hasBase(implicitCastExpr(
2279 ///     hasSourceExpression(declRefExpr()))))
2280 ///   matches \c i[1] with the \c declRefExpr() matching \c i
2281 AST_MATCHER_P(ArraySubscriptExpr, hasBase,
2282               internal::Matcher<Expr>, InnerMatcher) {
2283   if (const Expr* Expression = Node.getBase())
2284     return InnerMatcher.matches(*Expression, Finder, Builder);
2285   return false;
2286 }
2287
2288 /// \brief Matches a 'for', 'while', or 'do while' statement that has
2289 /// a given body.
2290 ///
2291 /// Given
2292 /// \code
2293 ///   for (;;) {}
2294 /// \endcode
2295 /// hasBody(compoundStmt())
2296 ///   matches 'for (;;) {}'
2297 /// with compoundStmt()
2298 ///   matching '{}'
2299 AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>,
2300                           InnerMatcher) {
2301   TOOLING_COMPILE_ASSERT(
2302       (llvm::is_base_of<DoStmt, NodeType>::value) ||
2303       (llvm::is_base_of<ForStmt, NodeType>::value) ||
2304       (llvm::is_base_of<WhileStmt, NodeType>::value),
2305       has_body_requires_for_while_or_do_statement);
2306   const Stmt *const Statement = Node.getBody();
2307   return (Statement != NULL &&
2308           InnerMatcher.matches(*Statement, Finder, Builder));
2309 }
2310
2311 /// \brief Matches compound statements where at least one substatement matches
2312 /// a given matcher.
2313 ///
2314 /// Given
2315 /// \code
2316 ///   { {}; 1+2; }
2317 /// \endcode
2318 /// hasAnySubstatement(compoundStmt())
2319 ///   matches '{ {}; 1+2; }'
2320 /// with compoundStmt()
2321 ///   matching '{}'
2322 AST_MATCHER_P(CompoundStmt, hasAnySubstatement,
2323               internal::Matcher<Stmt>, InnerMatcher) {
2324   for (CompoundStmt::const_body_iterator It = Node.body_begin();
2325        It != Node.body_end();
2326        ++It) {
2327     if (InnerMatcher.matches(**It, Finder, Builder)) return true;
2328   }
2329   return false;
2330 }
2331
2332 /// \brief Checks that a compound statement contains a specific number of
2333 /// child statements.
2334 ///
2335 /// Example: Given
2336 /// \code
2337 ///   { for (;;) {} }
2338 /// \endcode
2339 /// compoundStmt(statementCountIs(0)))
2340 ///   matches '{}'
2341 ///   but does not match the outer compound statement.
2342 AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) {
2343   return Node.size() == N;
2344 }
2345
2346 /// \brief Matches literals that are equal to the given value.
2347 ///
2348 /// Example matches true (matcher = boolLiteral(equals(true)))
2349 /// \code
2350 ///   true
2351 /// \endcode
2352 ///
2353 /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>,
2354 ///            Matcher<FloatingLiteral>, Matcher<IntegerLiteral>
2355 template <typename ValueT>
2356 internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT>
2357 equals(const ValueT &Value) {
2358   return internal::PolymorphicMatcherWithParam1<
2359     internal::ValueEqualsMatcher,
2360     ValueT>(Value);
2361 }
2362
2363 /// \brief Matches the operator Name of operator expressions (binary or
2364 /// unary).
2365 ///
2366 /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||")))
2367 /// \code
2368 ///   !(a || b)
2369 /// \endcode
2370 AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) {
2371   TOOLING_COMPILE_ASSERT(
2372     (llvm::is_base_of<BinaryOperator, NodeType>::value) ||
2373     (llvm::is_base_of<UnaryOperator, NodeType>::value),
2374     has_condition_requires_if_statement_or_conditional_operator);
2375   return Name == Node.getOpcodeStr(Node.getOpcode());
2376 }
2377
2378 /// \brief Matches the left hand side of binary operator expressions.
2379 ///
2380 /// Example matches a (matcher = binaryOperator(hasLHS()))
2381 /// \code
2382 ///   a || b
2383 /// \endcode
2384 AST_MATCHER_P(BinaryOperator, hasLHS,
2385               internal::Matcher<Expr>, InnerMatcher) {
2386   Expr *LeftHandSide = Node.getLHS();
2387   return (LeftHandSide != NULL &&
2388           InnerMatcher.matches(*LeftHandSide, Finder, Builder));
2389 }
2390
2391 /// \brief Matches the right hand side of binary operator expressions.
2392 ///
2393 /// Example matches b (matcher = binaryOperator(hasRHS()))
2394 /// \code
2395 ///   a || b
2396 /// \endcode
2397 AST_MATCHER_P(BinaryOperator, hasRHS,
2398               internal::Matcher<Expr>, InnerMatcher) {
2399   Expr *RightHandSide = Node.getRHS();
2400   return (RightHandSide != NULL &&
2401           InnerMatcher.matches(*RightHandSide, Finder, Builder));
2402 }
2403
2404 /// \brief Matches if either the left hand side or the right hand side of a
2405 /// binary operator matches.
2406 inline internal::Matcher<BinaryOperator> hasEitherOperand(
2407     const internal::Matcher<Expr> &InnerMatcher) {
2408   return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher));
2409 }
2410
2411 /// \brief Matches if the operand of a unary operator matches.
2412 ///
2413 /// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true))))
2414 /// \code
2415 ///   !true
2416 /// \endcode
2417 AST_MATCHER_P(UnaryOperator, hasUnaryOperand,
2418               internal::Matcher<Expr>, InnerMatcher) {
2419   const Expr * const Operand = Node.getSubExpr();
2420   return (Operand != NULL &&
2421           InnerMatcher.matches(*Operand, Finder, Builder));
2422 }
2423
2424 /// \brief Matches if the cast's source expression matches the given matcher.
2425 ///
2426 /// Example: matches "a string" (matcher =
2427 ///                                  hasSourceExpression(constructExpr()))
2428 /// \code
2429 /// class URL { URL(string); };
2430 /// URL url = "a string";
2431 AST_MATCHER_P(CastExpr, hasSourceExpression,
2432               internal::Matcher<Expr>, InnerMatcher) {
2433   const Expr* const SubExpression = Node.getSubExpr();
2434   return (SubExpression != NULL &&
2435           InnerMatcher.matches(*SubExpression, Finder, Builder));
2436 }
2437
2438 /// \brief Matches casts whose destination type matches a given matcher.
2439 ///
2440 /// (Note: Clang's AST refers to other conversions as "casts" too, and calls
2441 /// actual casts "explicit" casts.)
2442 AST_MATCHER_P(ExplicitCastExpr, hasDestinationType,
2443               internal::Matcher<QualType>, InnerMatcher) {
2444   const QualType NodeType = Node.getTypeAsWritten();
2445   return InnerMatcher.matches(NodeType, Finder, Builder);
2446 }
2447
2448 /// \brief Matches implicit casts whose destination type matches a given
2449 /// matcher.
2450 ///
2451 /// FIXME: Unit test this matcher
2452 AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType,
2453               internal::Matcher<QualType>, InnerMatcher) {
2454   return InnerMatcher.matches(Node.getType(), Finder, Builder);
2455 }
2456
2457 /// \brief Matches the true branch expression of a conditional operator.
2458 ///
2459 /// Example matches a
2460 /// \code
2461 ///   condition ? a : b
2462 /// \endcode
2463 AST_MATCHER_P(ConditionalOperator, hasTrueExpression,
2464               internal::Matcher<Expr>, InnerMatcher) {
2465   Expr *Expression = Node.getTrueExpr();
2466   return (Expression != NULL &&
2467           InnerMatcher.matches(*Expression, Finder, Builder));
2468 }
2469
2470 /// \brief Matches the false branch expression of a conditional operator.
2471 ///
2472 /// Example matches b
2473 /// \code
2474 ///   condition ? a : b
2475 /// \endcode
2476 AST_MATCHER_P(ConditionalOperator, hasFalseExpression,
2477               internal::Matcher<Expr>, InnerMatcher) {
2478   Expr *Expression = Node.getFalseExpr();
2479   return (Expression != NULL &&
2480           InnerMatcher.matches(*Expression, Finder, Builder));
2481 }
2482
2483 /// \brief Matches if a declaration has a body attached.
2484 ///
2485 /// Example matches A, va, fa
2486 /// \code
2487 ///   class A {};
2488 ///   class B;  // Doesn't match, as it has no body.
2489 ///   int va;
2490 ///   extern int vb;  // Doesn't match, as it doesn't define the variable.
2491 ///   void fa() {}
2492 ///   void fb();  // Doesn't match, as it has no body.
2493 /// \endcode
2494 ///
2495 /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>
2496 AST_POLYMORPHIC_MATCHER(isDefinition) {
2497   TOOLING_COMPILE_ASSERT(
2498       (llvm::is_base_of<TagDecl, NodeType>::value) ||
2499       (llvm::is_base_of<VarDecl, NodeType>::value) ||
2500       (llvm::is_base_of<FunctionDecl, NodeType>::value),
2501       is_definition_requires_isThisDeclarationADefinition_method);
2502   return Node.isThisDeclarationADefinition();
2503 }
2504
2505 /// \brief Matches the class declaration that the given method declaration
2506 /// belongs to.
2507 ///
2508 /// FIXME: Generalize this for other kinds of declarations.
2509 /// FIXME: What other kind of declarations would we need to generalize
2510 /// this to?
2511 ///
2512 /// Example matches A() in the last line
2513 ///     (matcher = constructExpr(hasDeclaration(methodDecl(
2514 ///         ofClass(hasName("A"))))))
2515 /// \code
2516 ///   class A {
2517 ///    public:
2518 ///     A();
2519 ///   };
2520 ///   A a = A();
2521 /// \endcode
2522 AST_MATCHER_P(CXXMethodDecl, ofClass,
2523               internal::Matcher<CXXRecordDecl>, InnerMatcher) {
2524   const CXXRecordDecl *Parent = Node.getParent();
2525   return (Parent != NULL &&
2526           InnerMatcher.matches(*Parent, Finder, Builder));
2527 }
2528
2529 /// \brief Matches if the given method declaration is virtual.
2530 ///
2531 /// Given
2532 /// \code
2533 ///   class A {
2534 ///    public:
2535 ///     virtual void x();
2536 ///   };
2537 /// \endcode
2538 ///   matches A::x
2539 AST_MATCHER(CXXMethodDecl, isVirtual) {
2540   return Node.isVirtual();
2541 }
2542
2543 /// \brief Matches if the given method declaration overrides another method.
2544 ///
2545 /// Given
2546 /// \code
2547 ///   class A {
2548 ///    public:
2549 ///     virtual void x();
2550 ///   };
2551 ///   class B : public A {
2552 ///    public:
2553 ///     virtual void x();
2554 ///   };
2555 /// \endcode
2556 ///   matches B::x
2557 AST_MATCHER(CXXMethodDecl, isOverride) {
2558   return Node.size_overridden_methods() > 0;
2559 }
2560
2561 /// \brief Matches member expressions that are called with '->' as opposed
2562 /// to '.'.
2563 ///
2564 /// Member calls on the implicit this pointer match as called with '->'.
2565 ///
2566 /// Given
2567 /// \code
2568 ///   class Y {
2569 ///     void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; }
2570 ///     int a;
2571 ///     static int b;
2572 ///   };
2573 /// \endcode
2574 /// memberExpr(isArrow())
2575 ///   matches this->x, x, y.x, a, this->b
2576 AST_MATCHER(MemberExpr, isArrow) {
2577   return Node.isArrow();
2578 }
2579
2580 /// \brief Matches QualType nodes that are of integer type.
2581 ///
2582 /// Given
2583 /// \code
2584 ///   void a(int);
2585 ///   void b(long);
2586 ///   void c(double);
2587 /// \endcode
2588 /// functionDecl(hasAnyParameter(hasType(isInteger())))
2589 /// matches "a(int)", "b(long)", but not "c(double)".
2590 AST_MATCHER(QualType, isInteger) {
2591     return Node->isIntegerType();
2592 }
2593
2594 /// \brief Matches QualType nodes that are const-qualified, i.e., that
2595 /// include "top-level" const.
2596 ///
2597 /// Given
2598 /// \code
2599 ///   void a(int);
2600 ///   void b(int const);
2601 ///   void c(const int);
2602 ///   void d(const int*);
2603 ///   void e(int const) {};
2604 /// \endcode
2605 /// functionDecl(hasAnyParameter(hasType(isConstQualified())))
2606 ///   matches "void b(int const)", "void c(const int)" and
2607 ///   "void e(int const) {}". It does not match d as there
2608 ///   is no top-level const on the parameter type "const int *".
2609 AST_MATCHER(QualType, isConstQualified) {
2610   return Node.isConstQualified();
2611 }
2612
2613 /// \brief Matches QualType nodes that have local CV-qualifiers attached to
2614 /// the node, not hidden within a typedef.
2615 ///
2616 /// Given
2617 /// \code
2618 ///   typedef const int const_int;
2619 ///   const_int i;
2620 ///   int *const j;
2621 ///   int *volatile k;
2622 ///   int m;
2623 /// \endcode
2624 /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k.
2625 /// \c i is const-qualified but the qualifier is not local.
2626 AST_MATCHER(QualType, hasLocalQualifiers) {
2627   return Node.hasLocalQualifiers();
2628 }
2629
2630 /// \brief Matches a member expression where the member is matched by a
2631 /// given matcher.
2632 ///
2633 /// Given
2634 /// \code
2635 ///   struct { int first, second; } first, second;
2636 ///   int i(second.first);
2637 ///   int j(first.second);
2638 /// \endcode
2639 /// memberExpr(member(hasName("first")))
2640 ///   matches second.first
2641 ///   but not first.second (because the member name there is "second").
2642 AST_MATCHER_P(MemberExpr, member,
2643               internal::Matcher<ValueDecl>, InnerMatcher) {
2644   return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder);
2645 }
2646
2647 /// \brief Matches a member expression where the object expression is
2648 /// matched by a given matcher.
2649 ///
2650 /// Given
2651 /// \code
2652 ///   struct X { int m; };
2653 ///   void f(X x) { x.m; m; }
2654 /// \endcode
2655 /// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))))
2656 ///   matches "x.m" and "m"
2657 /// with hasObjectExpression(...)
2658 ///   matching "x" and the implicit object expression of "m" which has type X*.
2659 AST_MATCHER_P(MemberExpr, hasObjectExpression,
2660               internal::Matcher<Expr>, InnerMatcher) {
2661   return InnerMatcher.matches(*Node.getBase(), Finder, Builder);
2662 }
2663
2664 /// \brief Matches any using shadow declaration.
2665 ///
2666 /// Given
2667 /// \code
2668 ///   namespace X { void b(); }
2669 ///   using X::b;
2670 /// \endcode
2671 /// usingDecl(hasAnyUsingShadowDecl(hasName("b"))))
2672 ///   matches \code using X::b \endcode
2673 AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl,
2674               internal::Matcher<UsingShadowDecl>, InnerMatcher) {
2675   for (UsingDecl::shadow_iterator II = Node.shadow_begin();
2676        II != Node.shadow_end(); ++II) {
2677     if (InnerMatcher.matches(**II, Finder, Builder))
2678       return true;
2679   }
2680   return false;
2681 }
2682
2683 /// \brief Matches a using shadow declaration where the target declaration is
2684 /// matched by the given matcher.
2685 ///
2686 /// Given
2687 /// \code
2688 ///   namespace X { int a; void b(); }
2689 ///   using X::a;
2690 ///   using X::b;
2691 /// \endcode
2692 /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl())))
2693 ///   matches \code using X::b \endcode
2694 ///   but not \code using X::a \endcode
2695 AST_MATCHER_P(UsingShadowDecl, hasTargetDecl,
2696               internal::Matcher<NamedDecl>, InnerMatcher) {
2697   return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder);
2698 }
2699
2700 /// \brief Matches template instantiations of function, class, or static
2701 /// member variable template instantiations.
2702 ///
2703 /// Given
2704 /// \code
2705 ///   template <typename T> class X {}; class A {}; X<A> x;
2706 /// \endcode
2707 /// or
2708 /// \code
2709 ///   template <typename T> class X {}; class A {}; template class X<A>;
2710 /// \endcode
2711 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2712 ///   matches the template instantiation of X<A>.
2713 ///
2714 /// But given
2715 /// \code
2716 ///   template <typename T>  class X {}; class A {};
2717 ///   template <> class X<A> {}; X<A> x;
2718 /// \endcode
2719 /// recordDecl(hasName("::X"), isTemplateInstantiation())
2720 ///   does not match, as X<A> is an explicit template specialization.
2721 ///
2722 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2723 AST_POLYMORPHIC_MATCHER(isTemplateInstantiation) {
2724   TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2725                          (llvm::is_base_of<VarDecl, NodeType>::value) ||
2726                          (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2727                          requires_getTemplateSpecializationKind_method);
2728   return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation ||
2729           Node.getTemplateSpecializationKind() ==
2730           TSK_ExplicitInstantiationDefinition);
2731 }
2732
2733 /// \brief Matches explicit template specializations of function, class, or
2734 /// static member variable template instantiations.
2735 ///
2736 /// Given
2737 /// \code
2738 ///   template<typename T> void A(T t) { }
2739 ///   template<> void A(int N) { }
2740 /// \endcode
2741 /// functionDecl(isExplicitTemplateSpecialization())
2742 ///   matches the specialization A<int>().
2743 ///
2744 /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl>
2745 AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization) {
2746   TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) ||
2747                          (llvm::is_base_of<VarDecl, NodeType>::value) ||
2748                          (llvm::is_base_of<CXXRecordDecl, NodeType>::value),
2749                          requires_getTemplateSpecializationKind_method);
2750   return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
2751 }
2752
2753 /// \brief Matches \c TypeLocs for which the given inner
2754 /// QualType-matcher matches.
2755 inline internal::BindableMatcher<TypeLoc> loc(
2756     const internal::Matcher<QualType> &InnerMatcher) {
2757   return internal::BindableMatcher<TypeLoc>(
2758       new internal::TypeLocTypeMatcher(InnerMatcher));
2759 }
2760
2761 /// \brief Matches builtin Types.
2762 ///
2763 /// Given
2764 /// \code
2765 ///   struct A {};
2766 ///   A a;
2767 ///   int b;
2768 ///   float c;
2769 ///   bool d;
2770 /// \endcode
2771 /// builtinType()
2772 ///   matches "int b", "float c" and "bool d"
2773 AST_TYPE_MATCHER(BuiltinType, builtinType);
2774
2775 /// \brief Matches all kinds of arrays.
2776 ///
2777 /// Given
2778 /// \code
2779 ///   int a[] = { 2, 3 };
2780 ///   int b[4];
2781 ///   void f() { int c[a[0]]; }
2782 /// \endcode
2783 /// arrayType()
2784 ///   matches "int a[]", "int b[4]" and "int c[a[0]]";
2785 AST_TYPE_MATCHER(ArrayType, arrayType);
2786
2787 /// \brief Matches C99 complex types.
2788 ///
2789 /// Given
2790 /// \code
2791 ///   _Complex float f;
2792 /// \endcode
2793 /// complexType()
2794 ///   matches "_Complex float f"
2795 AST_TYPE_MATCHER(ComplexType, complexType);
2796
2797 /// \brief Matches arrays and C99 complex types that have a specific element
2798 /// type.
2799 ///
2800 /// Given
2801 /// \code
2802 ///   struct A {};
2803 ///   A a[7];
2804 ///   int b[7];
2805 /// \endcode
2806 /// arrayType(hasElementType(builtinType()))
2807 ///   matches "int b[7]"
2808 ///
2809 /// Usable as: Matcher<ArrayType>, Matcher<ComplexType>
2810 AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement);
2811
2812 /// \brief Matches C arrays with a specified constant size.
2813 ///
2814 /// Given
2815 /// \code
2816 ///   void() {
2817 ///     int a[2];
2818 ///     int b[] = { 2, 3 };
2819 ///     int c[b[0]];
2820 ///   }
2821 /// \endcode
2822 /// constantArrayType()
2823 ///   matches "int a[2]"
2824 AST_TYPE_MATCHER(ConstantArrayType, constantArrayType);
2825
2826 /// \brief Matches \c ConstantArrayType nodes that have the specified size.
2827 ///
2828 /// Given
2829 /// \code
2830 ///   int a[42];
2831 ///   int b[2 * 21];
2832 ///   int c[41], d[43];
2833 /// \endcode
2834 /// constantArrayType(hasSize(42))
2835 ///   matches "int a[42]" and "int b[2 * 21]"
2836 AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) {
2837   return Node.getSize() == N;
2838 }
2839
2840 /// \brief Matches C++ arrays whose size is a value-dependent expression.
2841 ///
2842 /// Given
2843 /// \code
2844 ///   template<typename T, int Size>
2845 ///   class array {
2846 ///     T data[Size];
2847 ///   };
2848 /// \endcode
2849 /// dependentSizedArrayType
2850 ///   matches "T data[Size]"
2851 AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType);
2852
2853 /// \brief Matches C arrays with unspecified size.
2854 ///
2855 /// Given
2856 /// \code
2857 ///   int a[] = { 2, 3 };
2858 ///   int b[42];
2859 ///   void f(int c[]) { int d[a[0]]; };
2860 /// \endcode
2861 /// incompleteArrayType()
2862 ///   matches "int a[]" and "int c[]"
2863 AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType);
2864
2865 /// \brief Matches C arrays with a specified size that is not an
2866 /// integer-constant-expression.
2867 ///
2868 /// Given
2869 /// \code
2870 ///   void f() {
2871 ///     int a[] = { 2, 3 }
2872 ///     int b[42];
2873 ///     int c[a[0]];
2874 /// \endcode
2875 /// variableArrayType()
2876 ///   matches "int c[a[0]]"
2877 AST_TYPE_MATCHER(VariableArrayType, variableArrayType);
2878
2879 /// \brief Matches \c VariableArrayType nodes that have a specific size
2880 /// expression.
2881 ///
2882 /// Given
2883 /// \code
2884 ///   void f(int b) {
2885 ///     int a[b];
2886 ///   }
2887 /// \endcode
2888 /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
2889 ///   varDecl(hasName("b")))))))
2890 ///   matches "int a[b]"
2891 AST_MATCHER_P(VariableArrayType, hasSizeExpr,
2892               internal::Matcher<Expr>, InnerMatcher) {
2893   return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder);
2894 }
2895
2896 /// \brief Matches atomic types.
2897 ///
2898 /// Given
2899 /// \code
2900 ///   _Atomic(int) i;
2901 /// \endcode
2902 /// atomicType()
2903 ///   matches "_Atomic(int) i"
2904 AST_TYPE_MATCHER(AtomicType, atomicType);
2905
2906 /// \brief Matches atomic types with a specific value type.
2907 ///
2908 /// Given
2909 /// \code
2910 ///   _Atomic(int) i;
2911 ///   _Atomic(float) f;
2912 /// \endcode
2913 /// atomicType(hasValueType(isInteger()))
2914 ///  matches "_Atomic(int) i"
2915 ///
2916 /// Usable as: Matcher<AtomicType>
2917 AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue);
2918
2919 /// \brief Matches types nodes representing C++11 auto types.
2920 ///
2921 /// Given:
2922 /// \code
2923 ///   auto n = 4;
2924 ///   int v[] = { 2, 3 }
2925 ///   for (auto i : v) { }
2926 /// \endcode
2927 /// autoType()
2928 ///   matches "auto n" and "auto i"
2929 AST_TYPE_MATCHER(AutoType, autoType);
2930
2931 /// \brief Matches \c AutoType nodes where the deduced type is a specific type.
2932 ///
2933 /// Note: There is no \c TypeLoc for the deduced type and thus no
2934 /// \c getDeducedLoc() matcher.
2935 ///
2936 /// Given
2937 /// \code
2938 ///   auto a = 1;
2939 ///   auto b = 2.0;
2940 /// \endcode
2941 /// autoType(hasDeducedType(isInteger()))
2942 ///   matches "auto a"
2943 ///
2944 /// Usable as: Matcher<AutoType>
2945 AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType);
2946
2947 /// \brief Matches \c FunctionType nodes.
2948 ///
2949 /// Given
2950 /// \code
2951 ///   int (*f)(int);
2952 ///   void g();
2953 /// \endcode
2954 /// functionType()
2955 ///   matches "int (*f)(int)" and the type of "g".
2956 AST_TYPE_MATCHER(FunctionType, functionType);
2957
2958 /// \brief Matches \c ParenType nodes.
2959 ///
2960 /// Given
2961 /// \code
2962 ///   int (*ptr_to_array)[4];
2963 ///   int *array_of_ptrs[4];
2964 /// \endcode
2965 ///
2966 /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not
2967 /// \c array_of_ptrs.
2968 AST_TYPE_MATCHER(ParenType, parenType);
2969
2970 /// \brief Matches \c ParenType nodes where the inner type is a specific type.
2971 ///
2972 /// Given
2973 /// \code
2974 ///   int (*ptr_to_array)[4];
2975 ///   int (*ptr_to_func)(int);
2976 /// \endcode
2977 ///
2978 /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches
2979 /// \c ptr_to_func but not \c ptr_to_array.
2980 ///
2981 /// Usable as: Matcher<ParenType>
2982 AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType);
2983
2984 /// \brief Matches block pointer types, i.e. types syntactically represented as
2985 /// "void (^)(int)".
2986 ///
2987 /// The \c pointee is always required to be a \c FunctionType.
2988 AST_TYPE_MATCHER(BlockPointerType, blockPointerType);
2989
2990 /// \brief Matches member pointer types.
2991 /// Given
2992 /// \code
2993 ///   struct A { int i; }
2994 ///   A::* ptr = A::i;
2995 /// \endcode
2996 /// memberPointerType()
2997 ///   matches "A::* ptr"
2998 AST_TYPE_MATCHER(MemberPointerType, memberPointerType);
2999
3000 /// \brief Matches pointer types.
3001 ///
3002 /// Given
3003 /// \code
3004 ///   int *a;
3005 ///   int &b = *a;
3006 ///   int c = 5;
3007 /// \endcode
3008 /// pointerType()
3009 ///   matches "int *a"
3010 AST_TYPE_MATCHER(PointerType, pointerType);
3011
3012 /// \brief Matches both lvalue and rvalue reference types.
3013 ///
3014 /// Given
3015 /// \code
3016 ///   int *a;
3017 ///   int &b = *a;
3018 ///   int &&c = 1;
3019 ///   auto &d = b;
3020 ///   auto &&e = c;
3021 ///   auto &&f = 2;
3022 ///   int g = 5;
3023 /// \endcode
3024 ///
3025 /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f.
3026 AST_TYPE_MATCHER(ReferenceType, referenceType);
3027
3028 /// \brief Matches lvalue reference types.
3029 ///
3030 /// Given:
3031 /// \code
3032 ///   int *a;
3033 ///   int &b = *a;
3034 ///   int &&c = 1;
3035 ///   auto &d = b;
3036 ///   auto &&e = c;
3037 ///   auto &&f = 2;
3038 ///   int g = 5;
3039 /// \endcode
3040 ///
3041 /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is
3042 /// matched since the type is deduced as int& by reference collapsing rules.
3043 AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType);
3044
3045 /// \brief Matches rvalue reference types.
3046 ///
3047 /// Given:
3048 /// \code
3049 ///   int *a;
3050 ///   int &b = *a;
3051 ///   int &&c = 1;
3052 ///   auto &d = b;
3053 ///   auto &&e = c;
3054 ///   auto &&f = 2;
3055 ///   int g = 5;
3056 /// \endcode
3057 ///
3058 /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not
3059 /// matched as it is deduced to int& by reference collapsing rules.
3060 AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType);
3061
3062 /// \brief Narrows PointerType (and similar) matchers to those where the
3063 /// \c pointee matches a given matcher.
3064 ///
3065 /// Given
3066 /// \code
3067 ///   int *a;
3068 ///   int const *b;
3069 ///   float const *f;
3070 /// \endcode
3071 /// pointerType(pointee(isConstQualified(), isInteger()))
3072 ///   matches "int const *b"
3073 ///
3074 /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>,
3075 ///   Matcher<PointerType>, Matcher<ReferenceType>
3076 AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee);
3077
3078 /// \brief Matches typedef types.
3079 ///
3080 /// Given
3081 /// \code
3082 ///   typedef int X;
3083 /// \endcode
3084 /// typedefType()
3085 ///   matches "typedef int X"
3086 AST_TYPE_MATCHER(TypedefType, typedefType);
3087
3088 /// \brief Matches template specialization types.
3089 ///
3090 /// Given
3091 /// \code
3092 ///   template <typename T>
3093 ///   class C { };
3094 ///
3095 ///   template class C<int>;  // A
3096 ///   C<char> var;            // B
3097 /// \code
3098 ///
3099 /// \c templateSpecializationType() matches the type of the explicit
3100 /// instantiation in \c A and the type of the variable declaration in \c B.
3101 AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType);
3102
3103 /// \brief Matches record types (e.g. structs, classes).
3104 ///
3105 /// Given
3106 /// \code
3107 ///   class C {};
3108 ///   struct S {};
3109 ///
3110 ///   C c;
3111 ///   S s;
3112 /// \code
3113 ///
3114 /// \c recordType() matches the type of the variable declarations of both \c c
3115 /// and \c s.
3116 AST_TYPE_MATCHER(RecordType, recordType);
3117
3118 /// \brief Matches types specified with an elaborated type keyword or with a
3119 /// qualified name.
3120 ///
3121 /// Given
3122 /// \code
3123 ///   namespace N {
3124 ///     namespace M {
3125 ///       class D {};
3126 ///     }
3127 ///   }
3128 ///   class C {};
3129 ///
3130 ///   class C c;
3131 ///   N::M::D d;
3132 /// \code
3133 ///
3134 /// \c elaboratedType() matches the type of the variable declarations of both
3135 /// \c c and \c d.
3136 AST_TYPE_MATCHER(ElaboratedType, elaboratedType);
3137
3138 /// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier,
3139 /// matches \c InnerMatcher if the qualifier exists.
3140 ///
3141 /// Given
3142 /// \code
3143 ///   namespace N {
3144 ///     namespace M {
3145 ///       class D {};
3146 ///     }
3147 ///   }
3148 ///   N::M::D d;
3149 /// \code
3150 ///
3151 /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N"))))
3152 /// matches the type of the variable declaration of \c d.
3153 AST_MATCHER_P(ElaboratedType, hasQualifier,
3154               internal::Matcher<NestedNameSpecifier>, InnerMatcher) {
3155   if (const NestedNameSpecifier *Qualifier = Node.getQualifier())
3156     return InnerMatcher.matches(*Qualifier, Finder, Builder);
3157
3158   return false;
3159 }
3160
3161 /// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher.
3162 ///
3163 /// Given
3164 /// \code
3165 ///   namespace N {
3166 ///     namespace M {
3167 ///       class D {};
3168 ///     }
3169 ///   }
3170 ///   N::M::D d;
3171 /// \code
3172 ///
3173 /// \c elaboratedType(namesType(recordType(
3174 /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable
3175 /// declaration of \c d.
3176 AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>,
3177               InnerMatcher) {
3178   return InnerMatcher.matches(Node.getNamedType(), Finder, Builder);
3179 }
3180
3181 /// \brief Matches declarations whose declaration context, interpreted as a
3182 /// Decl, matches \c InnerMatcher.
3183 ///
3184 /// Given
3185 /// \code
3186 ///   namespace N {
3187 ///     namespace M {
3188 ///       class D {};
3189 ///     }
3190 ///   }
3191 /// \code
3192 ///
3193 /// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the
3194 /// declaration of \c class \c D.
3195 AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) {
3196   return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()),
3197                               Finder, Builder);
3198 }
3199
3200 /// \brief Matches nested name specifiers.
3201 ///
3202 /// Given
3203 /// \code
3204 ///   namespace ns {
3205 ///     struct A { static void f(); };
3206 ///     void A::f() {}
3207 ///     void g() { A::f(); }
3208 ///   }
3209 ///   ns::A a;
3210 /// \endcode
3211 /// nestedNameSpecifier()
3212 ///   matches "ns::" and both "A::"
3213 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
3214
3215 /// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc.
3216 const internal::VariadicAllOfMatcher<
3217   NestedNameSpecifierLoc> nestedNameSpecifierLoc;
3218
3219 /// \brief Matches \c NestedNameSpecifierLocs for which the given inner
3220 /// NestedNameSpecifier-matcher matches.
3221 inline internal::BindableMatcher<NestedNameSpecifierLoc> loc(
3222     const internal::Matcher<NestedNameSpecifier> &InnerMatcher) {
3223   return internal::BindableMatcher<NestedNameSpecifierLoc>(
3224       new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>(
3225           InnerMatcher));
3226 }
3227
3228 /// \brief Matches nested name specifiers that specify a type matching the
3229 /// given \c QualType matcher without qualifiers.
3230 ///
3231 /// Given
3232 /// \code
3233 ///   struct A { struct B { struct C {}; }; };
3234 ///   A::B::C c;
3235 /// \endcode
3236 /// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A")))))
3237 ///   matches "A::"
3238 AST_MATCHER_P(NestedNameSpecifier, specifiesType,
3239               internal::Matcher<QualType>, InnerMatcher) {
3240   if (Node.getAsType() == NULL)
3241     return false;
3242   return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder);
3243 }
3244
3245 /// \brief Matches nested name specifier locs that specify a type matching the
3246 /// given \c TypeLoc.
3247 ///
3248 /// Given
3249 /// \code
3250 ///   struct A { struct B { struct C {}; }; };
3251 ///   A::B::C c;
3252 /// \endcode
3253 /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type(
3254 ///   hasDeclaration(recordDecl(hasName("A")))))))
3255 ///   matches "A::"
3256 AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc,
3257               internal::Matcher<TypeLoc>, InnerMatcher) {
3258   return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder);
3259 }
3260
3261 /// \brief Matches on the prefix of a \c NestedNameSpecifier.
3262 ///
3263 /// Given
3264 /// \code
3265 ///   struct A { struct B { struct C {}; }; };
3266 ///   A::B::C c;
3267 /// \endcode
3268 /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and
3269 ///   matches "A::"
3270 AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix,
3271                        internal::Matcher<NestedNameSpecifier>, InnerMatcher,
3272                        0) {
3273   NestedNameSpecifier *NextNode = Node.getPrefix();
3274   if (NextNode == NULL)
3275     return false;
3276   return InnerMatcher.matches(*NextNode, Finder, Builder);
3277 }
3278
3279 /// \brief Matches on the prefix of a \c NestedNameSpecifierLoc.
3280 ///
3281 /// Given
3282 /// \code
3283 ///   struct A { struct B { struct C {}; }; };
3284 ///   A::B::C c;
3285 /// \endcode
3286 /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A")))))
3287 ///   matches "A::"
3288 AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix,
3289                        internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher,
3290                        1) {
3291   NestedNameSpecifierLoc NextNode = Node.getPrefix();
3292   if (!NextNode)
3293     return false;
3294   return InnerMatcher.matches(NextNode, Finder, Builder);
3295 }
3296
3297 /// \brief Matches nested name specifiers that specify a namespace matching the
3298 /// given namespace matcher.
3299 ///
3300 /// Given
3301 /// \code
3302 ///   namespace ns { struct A {}; }
3303 ///   ns::A a;
3304 /// \endcode
3305 /// nestedNameSpecifier(specifiesNamespace(hasName("ns")))
3306 ///   matches "ns::"
3307 AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace,
3308               internal::Matcher<NamespaceDecl>, InnerMatcher) {
3309   if (Node.getAsNamespace() == NULL)
3310     return false;
3311   return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder);
3312 }
3313
3314 /// \brief Overloads for the \c equalsNode matcher.
3315 /// FIXME: Implement for other node types.
3316 /// @{
3317
3318 /// \brief Matches if a node equals another node.
3319 ///
3320 /// \c Decl has pointer identity in the AST.
3321 AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) {
3322   return &Node == Other;
3323 }
3324 /// \brief Matches if a node equals another node.
3325 ///
3326 /// \c Stmt has pointer identity in the AST.
3327 ///
3328 AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) {
3329   return &Node == Other;
3330 }
3331
3332 /// @}
3333
3334 } // end namespace ast_matchers
3335 } // end namespace clang
3336
3337 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H