Clang Project

clang_source_code/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp
1//= unittests/ASTMatchers/ASTMatchersTraversalTest.cpp - matchers unit tests =//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ASTMatchersTest.h"
10#include "clang/AST/PrettyPrinter.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/ASTMatchers/ASTMatchers.h"
13#include "clang/Tooling/Tooling.h"
14#include "llvm/ADT/Triple.h"
15#include "llvm/Support/Host.h"
16#include "gtest/gtest.h"
17
18namespace clang {
19namespace ast_matchers {
20
21TEST(DeclarationMatcher, hasMethod) {
22  EXPECT_TRUE(matches("class A { void func(); };",
23                      cxxRecordDecl(hasMethod(hasName("func")))));
24  EXPECT_TRUE(notMatches("class A { void func(); };",
25                         cxxRecordDecl(hasMethod(isPublic()))));
26}
27
28TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
29  EXPECT_TRUE(matches(
30    "template <typename T> struct A {"
31      "  template <typename T2> struct F {};"
32      "};"
33      "template <typename T> struct B : A<T>::template F<T> {};"
34      "B<int> b;",
35    cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
36}
37
38TEST(DeclarationMatcher, hasDeclContext) {
39  EXPECT_TRUE(matches(
40    "namespace N {"
41      "  namespace M {"
42      "    class D {};"
43      "  }"
44      "}",
45    recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
46  EXPECT_TRUE(notMatches(
47    "namespace N {"
48      "  namespace M {"
49      "    class D {};"
50      "  }"
51      "}",
52    recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
53
54  EXPECT_TRUE(matches("namespace {"
55                        "  namespace M {"
56                        "    class D {};"
57                        "  }"
58                        "}",
59                      recordDecl(hasDeclContext(namespaceDecl(
60                        hasName("M"), hasDeclContext(namespaceDecl()))))));
61
62  EXPECT_TRUE(matches("class D{};"decl(hasDeclContext(decl()))));
63}
64
65TEST(HasDescendant, MatchesDescendantTypes) {
66  EXPECT_TRUE(matches("void f() { int i = 3; }",
67                      decl(hasDescendant(loc(builtinType())))));
68  EXPECT_TRUE(matches("void f() { int i = 3; }",
69                      stmt(hasDescendant(builtinType()))));
70
71  EXPECT_TRUE(matches("void f() { int i = 3; }",
72                      stmt(hasDescendant(loc(builtinType())))));
73  EXPECT_TRUE(matches("void f() { int i = 3; }",
74                      stmt(hasDescendant(qualType(builtinType())))));
75
76  EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
77                         stmt(hasDescendant(isInteger()))));
78
79  EXPECT_TRUE(matchAndVerifyResultTrue(
80    "void f() { int a; float c; int d; int e; }",
81    functionDecl(forEachDescendant(
82      varDecl(hasDescendant(isInteger())).bind("x"))),
83    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"3)));
84}
85
86TEST(HasDescendant, MatchesDescendantsOfTypes) {
87  EXPECT_TRUE(matches("void f() { int*** i; }",
88                      qualType(hasDescendant(builtinType()))));
89  EXPECT_TRUE(matches("void f() { int*** i; }",
90                      qualType(hasDescendant(
91                        pointerType(pointee(builtinType()))))));
92  EXPECT_TRUE(matches("void f() { int*** i; }",
93                      typeLoc(hasDescendant(loc(builtinType())))));
94
95  EXPECT_TRUE(matchAndVerifyResultTrue(
96    "void f() { int*** i; }",
97    qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
98    llvm::make_unique<VerifyIdIsBoundTo<Type>>("x"2)));
99}
100
101
102TEST(Has, MatchesChildrenOfTypes) {
103  EXPECT_TRUE(matches("int i;",
104                      varDecl(hasName("i"), has(isInteger()))));
105  EXPECT_TRUE(notMatches("int** i;",
106                         varDecl(hasName("i"), has(isInteger()))));
107  EXPECT_TRUE(matchAndVerifyResultTrue(
108    "int (*f)(float, int);",
109    qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
110    llvm::make_unique<VerifyIdIsBoundTo<QualType>>("x"2)));
111}
112
113TEST(Has, MatchesChildTypes) {
114  EXPECT_TRUE(matches(
115    "int* i;",
116    varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
117  EXPECT_TRUE(notMatches(
118    "int* i;",
119    varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
120}
121
122TEST(StatementMatcher, Has) {
123  StatementMatcher HasVariableI =
124      expr(hasType(pointsTo(recordDecl(hasName("X")))),
125           has(ignoringParenImpCasts(declRefExpr(to(varDecl(hasName("i")))))));
126
127  EXPECT_TRUE(matches(
128    "class X; X *x(int); void c() { int i; x(i); }"HasVariableI));
129  EXPECT_TRUE(notMatches(
130    "class X; X *x(int); void c() { int i; x(42); }"HasVariableI));
131}
132
133TEST(StatementMatcher, HasDescendant) {
134  StatementMatcher HasDescendantVariableI =
135    expr(hasType(pointsTo(recordDecl(hasName("X")))),
136         hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
137
138  EXPECT_TRUE(matches(
139    "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
140    HasDescendantVariableI));
141  EXPECT_TRUE(notMatches(
142    "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
143    HasDescendantVariableI));
144}
145
146TEST(TypeMatcher, MatchesClassType) {
147  TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
148
149  EXPECT_TRUE(matches("class A { public: A *a; };"TypeA));
150  EXPECT_TRUE(notMatches("class A {};"TypeA));
151
152  TypeMatcher TypeDerivedFromA =
153    hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
154
155  EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
156                      TypeDerivedFromA));
157  EXPECT_TRUE(notMatches("class A {};"TypeA));
158
159  TypeMatcher TypeAHasClassB = hasDeclaration(
160    recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
161
162  EXPECT_TRUE(
163    matches("class A { public: A *a; class B {}; };"TypeAHasClassB));
164
165  EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
166                       varDecl(hasType(namedDecl(hasName("S"))))));
167}
168
169TEST(TypeMatcher, MatchesDeclTypes) {
170  // TypedefType -> TypedefNameDecl
171  EXPECT_TRUE(matches("typedef int I; void f(I i);",
172                      parmVarDecl(hasType(namedDecl(hasName("I"))))));
173  // ObjCObjectPointerType
174  EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
175                          parmVarDecl(hasType(objcObjectPointerType()))));
176  // ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
177  EXPECT_TRUE(matchesObjC(
178    "@interface Foo @end void f(Foo *f);",
179    parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
180  // TemplateTypeParmType
181  EXPECT_TRUE(matches("template <typename T> void f(T t);",
182                      parmVarDecl(hasType(templateTypeParmType()))));
183  // TemplateTypeParmType -> TemplateTypeParmDecl
184  EXPECT_TRUE(matches("template <typename T> void f(T t);",
185                      parmVarDecl(hasType(namedDecl(hasName("T"))))));
186  // InjectedClassNameType
187  EXPECT_TRUE(matches("template <typename T> struct S {"
188                        "  void f(S s);"
189                        "};",
190                      parmVarDecl(hasType(injectedClassNameType()))));
191  EXPECT_TRUE(notMatches("template <typename T> struct S {"
192                           "  void g(S<T> s);"
193                           "};",
194                         parmVarDecl(hasType(injectedClassNameType()))));
195  // InjectedClassNameType -> CXXRecordDecl
196  EXPECT_TRUE(matches("template <typename T> struct S {"
197                        "  void f(S s);"
198                        "};",
199                      parmVarDecl(hasType(namedDecl(hasName("S"))))));
200
201  static const char Using[] = "template <typename T>"
202    "struct Base {"
203    "  typedef T Foo;"
204    "};"
205    ""
206    "template <typename T>"
207    "struct S : private Base<T> {"
208    "  using typename Base<T>::Foo;"
209    "  void f(Foo);"
210    "};";
211  // UnresolvedUsingTypenameDecl
212  EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
213  // UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
214  EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
215}
216
217TEST(HasDeclaration, HasDeclarationOfEnumType) {
218  EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
219                      expr(hasType(pointsTo(
220                        qualType(hasDeclaration(enumDecl(hasName("X")))))))));
221}
222
223TEST(HasDeclaration, HasGetDeclTraitTest) {
224  static_assert(internal::has_getDecl<TypedefType>::value,
225                "Expected TypedefType to have a getDecl.");
226  static_assert(internal::has_getDecl<RecordType>::value,
227                "Expected RecordType to have a getDecl.");
228  static_assert(!internal::has_getDecl<TemplateSpecializationType>::value,
229                "Expected TemplateSpecializationType to *not* have a getDecl.");
230}
231
232TEST(HasDeclaration, ElaboratedType) {
233  EXPECT_TRUE(matches(
234      "namespace n { template <typename T> struct X {}; }"
235      "void f(n::X<int>);",
236      parmVarDecl(hasType(qualType(hasDeclaration(cxxRecordDecl()))))));
237  EXPECT_TRUE(matches(
238      "namespace n { template <typename T> struct X {}; }"
239      "void f(n::X<int>);",
240      parmVarDecl(hasType(elaboratedType(hasDeclaration(cxxRecordDecl()))))));
241}
242
243TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
244  EXPECT_TRUE(matches("typedef int X; X a;",
245                      varDecl(hasName("a"),
246                              hasType(typedefType(hasDeclaration(decl()))))));
247
248  // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
249}
250
251TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
252  EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
253                      varDecl(hasType(templateSpecializationType(
254                        hasDeclaration(namedDecl(hasName("A"))))))));
255  EXPECT_TRUE(matches("template <typename T> class A {};"
256                      "template <typename T> class B { A<T> a; };",
257                      fieldDecl(hasType(templateSpecializationType(
258                        hasDeclaration(namedDecl(hasName("A"))))))));
259  EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
260                      varDecl(hasType(templateSpecializationType(
261                          hasDeclaration(cxxRecordDecl()))))));
262}
263
264TEST(HasDeclaration, HasDeclarationOfCXXNewExpr) {
265  EXPECT_TRUE(
266      matches("int *A = new int();",
267              cxxNewExpr(hasDeclaration(functionDecl(parameterCountIs(1))))));
268}
269
270TEST(HasDeclaration, HasDeclarationOfTypeAlias) {
271  EXPECT_TRUE(matches("template <typename T> using C = T; C<int> c;",
272                      varDecl(hasType(templateSpecializationType(
273                          hasDeclaration(typeAliasTemplateDecl()))))));
274}
275
276TEST(HasUnqualifiedDesugaredType, DesugarsUsing) {
277  EXPECT_TRUE(
278      matches("struct A {}; using B = A; B b;",
279              varDecl(hasType(hasUnqualifiedDesugaredType(recordType())))));
280  EXPECT_TRUE(
281      matches("struct A {}; using B = A; using C = B; C b;",
282              varDecl(hasType(hasUnqualifiedDesugaredType(recordType())))));
283}
284
285TEST(HasUnderlyingDecl, Matches) {
286  EXPECT_TRUE(matches("namespace N { template <class T> void f(T t); }"
287                      "template <class T> void g() { using N::f; f(T()); }",
288                      unresolvedLookupExpr(hasAnyDeclaration(
289                          namedDecl(hasUnderlyingDecl(hasName("::N::f")))))));
290  EXPECT_TRUE(matches(
291      "namespace N { template <class T> void f(T t); }"
292      "template <class T> void g() { N::f(T()); }",
293      unresolvedLookupExpr(hasAnyDeclaration(namedDecl(hasName("::N::f"))))));
294  EXPECT_TRUE(notMatches(
295      "namespace N { template <class T> void f(T t); }"
296      "template <class T> void g() { using N::f; f(T()); }",
297      unresolvedLookupExpr(hasAnyDeclaration(namedDecl(hasName("::N::f"))))));
298}
299
300TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
301  TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
302  EXPECT_TRUE(
303    matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
304  EXPECT_TRUE(
305    notMatches("class X {}; void y(X *x) { x; }",
306               expr(hasType(ClassX))));
307  EXPECT_TRUE(
308    matches("class X {}; void y(X *x) { x; }",
309            expr(hasType(pointsTo(ClassX)))));
310}
311
312TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
313  TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
314  EXPECT_TRUE(
315    matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
316  EXPECT_TRUE(
317    notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
318  EXPECT_TRUE(
319    matches("class X {}; void y() { X *x; }",
320            varDecl(hasType(pointsTo(ClassX)))));
321}
322
323TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
324  DeclarationMatcher ClassX = recordDecl(hasName("X"));
325  EXPECT_TRUE(
326    matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
327  EXPECT_TRUE(
328    notMatches("class X {}; void y(X *x) { x; }",
329               expr(hasType(ClassX))));
330}
331
332TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
333  DeclarationMatcher ClassX = recordDecl(hasName("X"));
334  EXPECT_TRUE(
335    matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
336  EXPECT_TRUE(
337    notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
338}
339
340TEST(HasType, MatchesTypedefDecl) {
341  EXPECT_TRUE(matches("typedef int X;", typedefDecl(hasType(asString("int")))));
342  EXPECT_TRUE(matches("typedef const int T;",
343                      typedefDecl(hasType(asString("const int")))));
344  EXPECT_TRUE(notMatches("typedef const int T;",
345                         typedefDecl(hasType(asString("int")))));
346  EXPECT_TRUE(matches("typedef int foo; typedef foo bar;",
347                      typedefDecl(hasType(asString("foo")), hasName("bar"))));
348}
349
350TEST(HasType, MatchesTypedefNameDecl) {
351  EXPECT_TRUE(matches("using X = int;", typedefNameDecl(hasType(asString("int")))));
352  EXPECT_TRUE(matches("using T = const int;",
353                      typedefNameDecl(hasType(asString("const int")))));
354  EXPECT_TRUE(notMatches("using T = const int;",
355                         typedefNameDecl(hasType(asString("int")))));
356  EXPECT_TRUE(matches("using foo = int; using bar = foo;",
357                      typedefNameDecl(hasType(asString("foo")), hasName("bar"))));
358}
359
360TEST(HasTypeLoc, MatchesDeclaratorDecls) {
361  EXPECT_TRUE(matches("int x;",
362                      varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
363
364  // Make sure we don't crash on implicit constructors.
365  EXPECT_TRUE(notMatches("class X {}; X x;",
366                         declaratorDecl(hasTypeLoc(loc(asString("int"))))));
367}
368
369
370TEST(Callee, MatchesDeclarations) {
371  StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
372
373  EXPECT_TRUE(matches("class Y { void x() { x(); } };"CallMethodX));
374  EXPECT_TRUE(notMatches("class Y { void x() {} };"CallMethodX));
375
376  CallMethodX = callExpr(callee(cxxConversionDecl()));
377  EXPECT_TRUE(
378    matches("struct Y { operator int() const; }; int i = Y();"CallMethodX));
379  EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
380                         CallMethodX));
381}
382
383TEST(Callee, MatchesMemberExpressions) {
384  EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
385                      callExpr(callee(memberExpr()))));
386  EXPECT_TRUE(
387    notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
388}
389
390TEST(Matcher, Argument) {
391  StatementMatcher CallArgumentY = callExpr(
392    hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
393
394  EXPECT_TRUE(matches("void x(int) { int y; x(y); }"CallArgumentY));
395  EXPECT_TRUE(
396    matches("class X { void x(int) { int y; x(y); } };"CallArgumentY));
397  EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }"CallArgumentY));
398
399  StatementMatcher WrongIndex = callExpr(
400    hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
401  EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }"WrongIndex));
402}
403
404TEST(Matcher, AnyArgument) {
405  auto HasArgumentY = hasAnyArgument(
406      ignoringParenImpCasts(declRefExpr(to(varDecl(hasName("y"))))));
407  StatementMatcher CallArgumentY = callExpr(HasArgumentY);
408  StatementMatcher CtorArgumentY = cxxConstructExpr(HasArgumentY);
409  StatementMatcher UnresolvedCtorArgumentY =
410      cxxUnresolvedConstructExpr(HasArgumentY);
411  StatementMatcher ObjCCallArgumentY = objcMessageExpr(HasArgumentY);
412  EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }"CallArgumentY));
413  EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }"CallArgumentY));
414  EXPECT_TRUE(matches("struct Y { Y(int, int); };"
415                      "void x() { int y; (void)Y(1, y); }",
416                      CtorArgumentY));
417  EXPECT_TRUE(matches("struct Y { Y(int, int); };"
418                      "void x() { int y; (void)Y(y, 42); }",
419                      CtorArgumentY));
420  EXPECT_TRUE(matches("template <class Y> void x() { int y; (void)Y(1, y); }",
421                      UnresolvedCtorArgumentY));
422  EXPECT_TRUE(matches("template <class Y> void x() { int y; (void)Y(y, 42); }",
423                      UnresolvedCtorArgumentY));
424  EXPECT_TRUE(matchesObjC("@interface I -(void)f:(int) y; @end "
425                          "void x(I* i) { int y; [i f:y]; }",
426                          ObjCCallArgumentY));
427  EXPECT_FALSE(matchesObjC("@interface I -(void)f:(int) z; @end "
428                           "void x(I* i) { int z; [i f:z]; }",
429                           ObjCCallArgumentY));
430  EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }"CallArgumentY));
431  EXPECT_TRUE(notMatches("struct Y { Y(int, int); };"
432                         "void x() { int y; (void)Y(1, 2); }",
433                         CtorArgumentY));
434  EXPECT_TRUE(notMatches("template <class Y>"
435                         "void x() { int y; (void)Y(1, 2); }",
436                         UnresolvedCtorArgumentY));
437
438  StatementMatcher ImplicitCastedArgument = callExpr(
439    hasAnyArgument(implicitCastExpr()));
440  EXPECT_TRUE(matches("void x(long) { int y; x(y); }"ImplicitCastedArgument));
441}
442
443TEST(Matcher, HasReceiver) {
444  EXPECT_TRUE(matchesObjC(
445      "@interface NSString @end "
446      "void f(NSString *x) {"
447      "[x containsString];"
448      "}",
449      objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))));
450
451  EXPECT_FALSE(matchesObjC(
452      "@interface NSString +(NSString *) stringWithFormat; @end "
453      "void f() { [NSString stringWithFormat]; }",
454      objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x"))))))));
455}
456
457TEST(Matcher, isInstanceMessage) {
458  EXPECT_TRUE(matchesObjC(
459      "@interface NSString @end "
460      "void f(NSString *x) {"
461      "[x containsString];"
462      "}",
463      objcMessageExpr(isInstanceMessage())));
464
465  EXPECT_FALSE(matchesObjC(
466      "@interface NSString +(NSString *) stringWithFormat; @end "
467      "void f() { [NSString stringWithFormat]; }",
468      objcMessageExpr(isInstanceMessage())));
469
470}
471
472TEST(MatcherCXXMemberCallExpr, On) {
473  auto Snippet1 = R"cc(
474        struct Y {
475          void m();
476        };
477        void z(Y y) { y.m(); }
478      )cc";
479  auto Snippet2 = R"cc(
480        struct Y {
481          void m();
482        };
483        struct X : public Y {};
484        void z(X x) { x.m(); }
485      )cc";
486  auto MatchesY = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))));
487  EXPECT_TRUE(matches(Snippet1, MatchesY));
488  EXPECT_TRUE(notMatches(Snippet2, MatchesY));
489
490  auto MatchesX = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X")))));
491  EXPECT_TRUE(matches(Snippet2, MatchesX));
492
493  // Parens are ignored.
494  auto Snippet3 = R"cc(
495    struct Y {
496      void m();
497    };
498    Y g();
499    void z(Y y) { (g()).m(); }
500  )cc";
501  auto MatchesCall = cxxMemberCallExpr(on(callExpr()));
502  EXPECT_TRUE(matches(Snippet3, MatchesCall));
503}
504
505TEST(MatcherCXXMemberCallExpr, OnImplicitObjectArgument) {
506  auto Snippet1 = R"cc(
507    struct Y {
508      void m();
509    };
510    void z(Y y) { y.m(); }
511  )cc";
512  auto Snippet2 = R"cc(
513    struct Y {
514      void m();
515    };
516    struct X : public Y {};
517    void z(X x) { x.m(); }
518  )cc";
519  auto MatchesY = cxxMemberCallExpr(
520      onImplicitObjectArgument(hasType(cxxRecordDecl(hasName("Y")))));
521  EXPECT_TRUE(matches(Snippet1, MatchesY));
522  EXPECT_TRUE(matches(Snippet2, MatchesY));
523
524  auto MatchesX = cxxMemberCallExpr(
525      onImplicitObjectArgument(hasType(cxxRecordDecl(hasName("X")))));
526  EXPECT_TRUE(notMatches(Snippet2, MatchesX));
527
528  // Parens are not ignored.
529  auto Snippet3 = R"cc(
530    struct Y {
531      void m();
532    };
533    Y g();
534    void z(Y y) { (g()).m(); }
535  )cc";
536  auto MatchesCall = cxxMemberCallExpr(onImplicitObjectArgument(callExpr()));
537  EXPECT_TRUE(notMatches(Snippet3, MatchesCall));
538}
539
540TEST(Matcher, HasObjectExpr) {
541  auto Snippet1 = R"cc(
542        struct X {
543          int m;
544          int f(X x) { return x.m; }
545        };
546      )cc";
547  auto Snippet2 = R"cc(
548        struct X {
549          int m;
550          int f(X x) { return m; }
551        };
552      )cc";
553  auto MatchesX =
554      memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X")))));
555  EXPECT_TRUE(matches(Snippet1, MatchesX));
556  EXPECT_TRUE(notMatches(Snippet2, MatchesX));
557
558  auto MatchesXPointer = memberExpr(
559      hasObjectExpression(hasType(pointsTo(cxxRecordDecl(hasName("X"))))));
560  EXPECT_TRUE(notMatches(Snippet1, MatchesXPointer));
561  EXPECT_TRUE(matches(Snippet2, MatchesXPointer));
562}
563
564TEST(ForEachArgumentWithParam, ReportsNoFalsePositives) {
565  StatementMatcher ArgumentY =
566    declRefExpr(to(varDecl(hasName("y")))).bind("arg");
567  DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
568  StatementMatcher CallExpr =
569    callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
570
571  // IntParam does not match.
572  EXPECT_TRUE(notMatches("void f(int* i) { int* y; f(y); }", CallExpr));
573  // ArgumentY does not match.
574  EXPECT_TRUE(notMatches("void f(int i) { int x; f(x); }", CallExpr));
575}
576
577TEST(ForEachArgumentWithParam, MatchesCXXMemberCallExpr) {
578  StatementMatcher ArgumentY =
579    declRefExpr(to(varDecl(hasName("y")))).bind("arg");
580  DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
581  StatementMatcher CallExpr =
582    callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
583  EXPECT_TRUE(matchAndVerifyResultTrue(
584    "struct S {"
585      "  const S& operator[](int i) { return *this; }"
586      "};"
587      "void f(S S1) {"
588      "  int y = 1;"
589      "  S1[y];"
590      "}",
591    CallExpr, llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param"1)));
592
593  StatementMatcher CallExpr2 =
594    callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
595  EXPECT_TRUE(matchAndVerifyResultTrue(
596    "struct S {"
597      "  static void g(int i);"
598      "};"
599      "void f() {"
600      "  int y = 1;"
601      "  S::g(y);"
602      "}",
603    CallExpr2, llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param"1)));
604}
605
606TEST(ForEachArgumentWithParam, MatchesCallExpr) {
607  StatementMatcher ArgumentY =
608    declRefExpr(to(varDecl(hasName("y")))).bind("arg");
609  DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
610  StatementMatcher CallExpr =
611    callExpr(forEachArgumentWithParam(ArgumentY, IntParam));
612
613  EXPECT_TRUE(
614    matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
615                             llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>(
616                               "param")));
617  EXPECT_TRUE(
618    matchAndVerifyResultTrue("void f(int i) { int y; f(y); }", CallExpr,
619                             llvm::make_unique<VerifyIdIsBoundTo<DeclRefExpr>>(
620                               "arg")));
621
622  EXPECT_TRUE(matchAndVerifyResultTrue(
623    "void f(int i, int j) { int y; f(y, y); }", CallExpr,
624    llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param"2)));
625  EXPECT_TRUE(matchAndVerifyResultTrue(
626    "void f(int i, int j) { int y; f(y, y); }", CallExpr,
627    llvm::make_unique<VerifyIdIsBoundTo<DeclRefExpr>>("arg"2)));
628}
629
630TEST(ForEachArgumentWithParam, MatchesConstructExpr) {
631  StatementMatcher ArgumentY =
632    declRefExpr(to(varDecl(hasName("y")))).bind("arg");
633  DeclarationMatcher IntParam = parmVarDecl(hasType(isInteger())).bind("param");
634  StatementMatcher ConstructExpr =
635    cxxConstructExpr(forEachArgumentWithParam(ArgumentY, IntParam));
636
637  EXPECT_TRUE(matchAndVerifyResultTrue(
638    "struct C {"
639      "  C(int i) {}"
640      "};"
641      "int y = 0;"
642      "C Obj(y);",
643    ConstructExpr,
644    llvm::make_unique<VerifyIdIsBoundTo<ParmVarDecl>>("param")));
645}
646
647TEST(ForEachArgumentWithParam, HandlesBoundNodesForNonMatches) {
648  EXPECT_TRUE(matchAndVerifyResultTrue(
649    "void g(int i, int j) {"
650      "  int a;"
651      "  int b;"
652      "  int c;"
653      "  g(a, 0);"
654      "  g(a, b);"
655      "  g(0, b);"
656      "}",
657    functionDecl(
658      forEachDescendant(varDecl().bind("v")),
659      forEachDescendant(callExpr(forEachArgumentWithParam(
660        declRefExpr(to(decl(equalsBoundNode("v")))), parmVarDecl())))),
661    llvm::make_unique<VerifyIdIsBoundTo<VarDecl>>("v"4)));
662}
663
664TEST(QualType, hasCanonicalType) {
665  EXPECT_TRUE(notMatches("typedef int &int_ref;"
666                           "int a;"
667                           "int_ref b = a;",
668                         varDecl(hasType(qualType(referenceType())))));
669  EXPECT_TRUE(
670    matches("typedef int &int_ref;"
671              "int a;"
672              "int_ref b = a;",
673            varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
674}
675
676TEST(HasParameter, CallsInnerMatcher) {
677  EXPECT_TRUE(matches("class X { void x(int) {} };",
678                      cxxMethodDecl(hasParameter(0, varDecl()))));
679  EXPECT_TRUE(notMatches("class X { void x(int) {} };",
680                         cxxMethodDecl(hasParameter(0, hasName("x")))));
681  EXPECT_TRUE(matchesObjC("@interface I -(void)f:(int) x; @end",
682                          objcMethodDecl(hasParameter(0, hasName("x")))));
683  EXPECT_TRUE(matchesObjC("int main() { void (^b)(int) = ^(int p) {}; }",
684                          blockDecl(hasParameter(0, hasName("p")))));
685}
686
687TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
688  EXPECT_TRUE(notMatches("class X { void x(int) {} };",
689                         cxxMethodDecl(hasParameter(42, varDecl()))));
690}
691
692TEST(HasType, MatchesParameterVariableTypesStrictly) {
693  EXPECT_TRUE(matches(
694    "class X { void x(X x) {} };",
695    cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
696  EXPECT_TRUE(notMatches(
697    "class X { void x(const X &x) {} };",
698    cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
699  EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
700                      cxxMethodDecl(hasParameter(
701                        0, hasType(pointsTo(recordDecl(hasName("X"))))))));
702  EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
703                      cxxMethodDecl(hasParameter(
704                        0, hasType(references(recordDecl(hasName("X"))))))));
705}
706
707TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
708  EXPECT_TRUE(matches(
709    "class Y {}; class X { void x(X x, Y y) {} };",
710    cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
711  EXPECT_TRUE(matches(
712    "class Y {}; class X { void x(Y y, X x) {} };",
713    cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
714  EXPECT_TRUE(matchesObjC("@interface I -(void)f:(int) x; @end",
715                          objcMethodDecl(hasAnyParameter(hasName("x")))));
716  EXPECT_TRUE(matchesObjC("int main() { void (^b)(int) = ^(int p) {}; }",
717                          blockDecl(hasAnyParameter(hasName("p")))));
718}
719
720TEST(Returns, MatchesReturnTypes) {
721  EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
722                      functionDecl(returns(asString("int")))));
723  EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
724                         functionDecl(returns(asString("float")))));
725  EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
726                      functionDecl(returns(hasDeclaration(
727                        recordDecl(hasName("Y")))))));
728}
729
730TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
731  EXPECT_TRUE(notMatches(
732    "class Y {}; class X { void x(int) {} };",
733    cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
734}
735
736TEST(HasAnyParameter, DoesNotMatchThisPointer) {
737  EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
738                         cxxMethodDecl(hasAnyParameter(
739                           hasType(pointsTo(recordDecl(hasName("X"))))))));
740}
741
742TEST(HasName, MatchesParameterVariableDeclarations) {
743  EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
744                      cxxMethodDecl(hasAnyParameter(hasName("x")))));
745  EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
746                         cxxMethodDecl(hasAnyParameter(hasName("x")))));
747}
748
749TEST(Matcher, MatchesTypeTemplateArgument) {
750  EXPECT_TRUE(matches(
751    "template<typename T> struct B {};"
752      "B<int> b;",
753    classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
754      asString("int"))))));
755}
756
757TEST(Matcher, MatchesTemplateTemplateArgument) {
758  EXPECT_TRUE(matches("template<template <typename> class S> class X {};"
759                      "template<typename T> class Y {};"
760                      "X<Y> xi;",
761                      classTemplateSpecializationDecl(hasAnyTemplateArgument(
762                          refersToTemplate(templateName())))));
763}
764
765TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
766  EXPECT_TRUE(matches(
767    "struct B { int next; };"
768      "template<int(B::*next_ptr)> struct A {};"
769      "A<&B::next> a;",
770    classTemplateSpecializationDecl(hasAnyTemplateArgument(
771      refersToDeclaration(fieldDecl(hasName("next")))))));
772
773  EXPECT_TRUE(notMatches(
774    "template <typename T> struct A {};"
775      "A<int> a;",
776    classTemplateSpecializationDecl(hasAnyTemplateArgument(
777      refersToDeclaration(decl())))));
778
779  EXPECT_TRUE(matches(
780    "struct B { int next; };"
781      "template<int(B::*next_ptr)> struct A {};"
782      "A<&B::next> a;",
783    templateSpecializationType(hasAnyTemplateArgument(isExpr(
784      hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
785
786  EXPECT_TRUE(notMatches(
787    "template <typename T> struct A {};"
788      "A<int> a;",
789    templateSpecializationType(hasAnyTemplateArgument(
790      refersToDeclaration(decl())))));
791}
792
793
794TEST(Matcher, MatchesSpecificArgument) {
795  EXPECT_TRUE(matches(
796    "template<typename T, typename U> class A {};"
797      "A<bool, int> a;",
798    classTemplateSpecializationDecl(hasTemplateArgument(
799      1, refersToType(asString("int"))))));
800  EXPECT_TRUE(notMatches(
801    "template<typename T, typename U> class A {};"
802      "A<int, bool> a;",
803    classTemplateSpecializationDecl(hasTemplateArgument(
804      1, refersToType(asString("int"))))));
805
806  EXPECT_TRUE(matches(
807    "template<typename T, typename U> class A {};"
808      "A<bool, int> a;",
809    templateSpecializationType(hasTemplateArgument(
810      1, refersToType(asString("int"))))));
811  EXPECT_TRUE(notMatches(
812    "template<typename T, typename U> class A {};"
813      "A<int, bool> a;",
814    templateSpecializationType(hasTemplateArgument(
815      1, refersToType(asString("int"))))));
816
817  EXPECT_TRUE(matches(
818    "template<typename T> void f() {};"
819      "void func() { f<int>(); }",
820    functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))));
821  EXPECT_TRUE(notMatches(
822    "template<typename T> void f() {};",
823    functionDecl(hasTemplateArgument(0, refersToType(asString("int"))))));
824}
825
826TEST(TemplateArgument, Matches) {
827  EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
828                      classTemplateSpecializationDecl(
829                        hasAnyTemplateArgument(templateArgument()))));
830  EXPECT_TRUE(matches(
831    "template<typename T> struct C {}; C<int> c;",
832    templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
833
834  EXPECT_TRUE(matches(
835    "template<typename T> void f() {};"
836      "void func() { f<int>(); }",
837    functionDecl(hasAnyTemplateArgument(templateArgument()))));
838}
839
840TEST(TemplateTypeParmDecl, CXXMethodDecl) {
841  const char input[] =
842      "template<typename T>\n"
843      "class Class {\n"
844      "  void method();\n"
845      "};\n"
846      "template<typename U>\n"
847      "void Class<U>::method() {}\n";
848  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T"))));
849  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U"))));
850}
851
852TEST(TemplateTypeParmDecl, VarDecl) {
853  const char input[] =
854      "template<typename T>\n"
855      "class Class {\n"
856      "  static T pi;\n"
857      "};\n"
858      "template<typename U>\n"
859      "U Class<U>::pi = U(3.1415926535897932385);\n";
860  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T"))));
861  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U"))));
862}
863
864TEST(TemplateTypeParmDecl, VarTemplatePartialSpecializationDecl) {
865  const char input[] =
866      "template<typename T>\n"
867      "struct Struct {\n"
868      "  template<typename T2> static int field;\n"
869      "};\n"
870      "template<typename U>\n"
871      "template<typename U2>\n"
872      "int Struct<U>::field<U2*> = 123;\n";
873  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T"))));
874  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2"))));
875  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U"))));
876  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2"))));
877}
878
879TEST(TemplateTypeParmDecl, ClassTemplatePartialSpecializationDecl) {
880  const char input[] =
881      "template<typename T>\n"
882      "class Class {\n"
883      "  template<typename T2> struct Struct;\n"
884      "};\n"
885      "template<typename U>\n"
886      "template<typename U2>\n"
887      "struct Class<U>::Struct<U2*> {};\n";
888  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T"))));
889  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T2"))));
890  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U"))));
891  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U2"))));
892}
893
894TEST(TemplateTypeParmDecl, EnumDecl) {
895  const char input[] =
896      "template<typename T>\n"
897      "struct Struct {\n"
898      "  enum class Enum : T;\n"
899      "};\n"
900      "template<typename U>\n"
901      "enum class Struct<U>::Enum : U {\n"
902      "  e1,\n"
903      "  e2\n"
904      "};\n";
905  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T"))));
906  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U"))));
907}
908
909TEST(TemplateTypeParmDecl, RecordDecl) {
910  const char input[] =
911      "template<typename T>\n"
912      "class Class {\n"
913      "  struct Struct;\n"
914      "};\n"
915      "template<typename U>\n"
916      "struct Class<U>::Struct {\n"
917      "  U field;\n"
918      "};\n";
919  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("T"))));
920  EXPECT_TRUE(matches(input, templateTypeParmDecl(hasName("U"))));
921}
922
923TEST(RefersToIntegralType, Matches) {
924  EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
925                      classTemplateSpecializationDecl(
926                        hasAnyTemplateArgument(refersToIntegralType(
927                          asString("int"))))));
928  EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
929                         classTemplateSpecializationDecl(hasAnyTemplateArgument(
930                           refersToIntegralType(asString("int"))))));
931}
932
933TEST(ConstructorDeclaration, SimpleCase) {
934  EXPECT_TRUE(matches("class Foo { Foo(int i); };",
935                      cxxConstructorDecl(ofClass(hasName("Foo")))));
936  EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
937                         cxxConstructorDecl(ofClass(hasName("Bar")))));
938}
939
940TEST(DestructorDeclaration, MatchesVirtualDestructor) {
941  EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
942                      cxxDestructorDecl(ofClass(hasName("Foo")))));
943}
944
945TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
946  EXPECT_TRUE(notMatches("class Foo {};",
947                         cxxDestructorDecl(ofClass(hasName("Foo")))));
948}
949
950TEST(HasAnyConstructorInitializer, SimpleCase) {
951  EXPECT_TRUE(
952    notMatches("class Foo { Foo() { } };",
953               cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
954  EXPECT_TRUE(
955    matches("class Foo {"
956              "  Foo() : foo_() { }"
957              "  int foo_;"
958              "};",
959            cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
960}
961
962TEST(HasAnyConstructorInitializer, ForField) {
963  static const char Code[] =
964    "class Baz { };"
965      "class Foo {"
966      "  Foo() : foo_(), bar_() { }"
967      "  Baz foo_;"
968      "  struct {"
969      "    Baz bar_;"
970      "  };"
971      "};";
972  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
973    forField(hasType(recordDecl(hasName("Baz"))))))));
974  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
975    forField(hasName("foo_"))))));
976  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
977    forField(hasName("bar_"))))));
978  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
979    forField(hasType(recordDecl(hasName("Bar"))))))));
980}
981
982TEST(HasAnyConstructorInitializer, WithInitializer) {
983  static const char Code[] =
984    "class Foo {"
985      "  Foo() : foo_(0) { }"
986      "  int foo_;"
987      "};";
988  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
989    withInitializer(integerLiteral(equals(0)))))));
990  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
991    withInitializer(integerLiteral(equals(1)))))));
992}
993
994TEST(HasAnyConstructorInitializer, IsWritten) {
995  static const char Code[] =
996    "struct Bar { Bar(){} };"
997      "class Foo {"
998      "  Foo() : foo_() { }"
999      "  Bar foo_;"
1000      "  Bar bar_;"
1001      "};";
1002  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
1003    allOf(forField(hasName("foo_")), isWritten())))));
1004  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
1005    allOf(forField(hasName("bar_")), isWritten())))));
1006  EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
1007    allOf(forField(hasName("bar_")), unless(isWritten()))))));
1008}
1009
1010TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
1011  static const char Code[] =
1012    "struct B {};"
1013      "struct D : B {"
1014      "  int I;"
1015      "  D(int i) : I(i) {}"
1016      "};"
1017      "struct E : B {"
1018      "  E() : B() {}"
1019      "};";
1020  EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
1021    hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
1022    hasName("E")))));
1023  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
1024    hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
1025    hasName("D")))));
1026  EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
1027    hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
1028    hasName("D")))));
1029  EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
1030    hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
1031    hasName("E")))));
1032}
1033
1034TEST(IfStmt, ChildTraversalMatchers) {
1035  EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
1036                      ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
1037  EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
1038                         ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
1039  EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
1040                      ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
1041  EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
1042                         ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
1043}
1044
1045TEST(MatchBinaryOperator, HasOperatorName) {
1046  StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
1047
1048  EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
1049  EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
1050}
1051
1052TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
1053  StatementMatcher OperatorTrueFalse =
1054    binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
1055                   hasRHS(cxxBoolLiteral(equals(false))));
1056
1057  EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
1058  EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
1059  EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
1060
1061  StatementMatcher OperatorIntPointer = arraySubscriptExpr(
1062    hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
1063  EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
1064  EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
1065}
1066
1067TEST(MatchBinaryOperator, HasEitherOperand) {
1068  StatementMatcher HasOperand =
1069    binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
1070
1071  EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
1072  EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
1073  EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
1074}
1075
1076TEST(Matcher, BinaryOperatorTypes) {
1077  // Integration test that verifies the AST provides all binary operators in
1078  // a way we expect.
1079  // FIXME: Operator ','
1080  EXPECT_TRUE(
1081    matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
1082  EXPECT_TRUE(
1083    matches("bool b; bool c = (b = true);",
1084            binaryOperator(hasOperatorName("="))));
1085  EXPECT_TRUE(
1086    matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
1087  EXPECT_TRUE(
1088    matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
1089  EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
1090  EXPECT_TRUE(
1091    matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
1092  EXPECT_TRUE(
1093    matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
1094  EXPECT_TRUE(
1095    matches("int i = 1; int j = (i <<= 2);",
1096            binaryOperator(hasOperatorName("<<="))));
1097  EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
1098  EXPECT_TRUE(
1099    matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
1100  EXPECT_TRUE(
1101    matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
1102  EXPECT_TRUE(
1103    matches("int i = 1; int j = (i >>= 2);",
1104            binaryOperator(hasOperatorName(">>="))));
1105  EXPECT_TRUE(
1106    matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
1107  EXPECT_TRUE(
1108    matches("int i = 42; int j = (i ^= 42);",
1109            binaryOperator(hasOperatorName("^="))));
1110  EXPECT_TRUE(
1111    matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
1112  EXPECT_TRUE(
1113    matches("int i = 42; int j = (i %= 42);",
1114            binaryOperator(hasOperatorName("%="))));
1115  EXPECT_TRUE(
1116    matches("bool b = 42  &23;", binaryOperator(hasOperatorName("&"))));
1117  EXPECT_TRUE(
1118    matches("bool b = true && false;",
1119            binaryOperator(hasOperatorName("&&"))));
1120  EXPECT_TRUE(
1121    matches("bool b = true; bool c = (b &= false);",
1122            binaryOperator(hasOperatorName("&="))));
1123  EXPECT_TRUE(
1124    matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
1125  EXPECT_TRUE(
1126    matches("bool b = true || false;",
1127            binaryOperator(hasOperatorName("||"))));
1128  EXPECT_TRUE(
1129    matches("bool b = true; bool c = (b |= false);",
1130            binaryOperator(hasOperatorName("|="))));
1131  EXPECT_TRUE(
1132    matches("int i = 42  *23;", binaryOperator(hasOperatorName("*"))));
1133  EXPECT_TRUE(
1134    matches("int i = 42; int j = (i *= 23);",
1135            binaryOperator(hasOperatorName("*="))));
1136  EXPECT_TRUE(
1137    matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
1138  EXPECT_TRUE(
1139    matches("int i = 42; int j = (i /= 23);",
1140            binaryOperator(hasOperatorName("/="))));
1141  EXPECT_TRUE(
1142    matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
1143  EXPECT_TRUE(
1144    matches("int i = 42; int j = (i += 23);",
1145            binaryOperator(hasOperatorName("+="))));
1146  EXPECT_TRUE(
1147    matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
1148  EXPECT_TRUE(
1149    matches("int i = 42; int j = (i -= 23);",
1150            binaryOperator(hasOperatorName("-="))));
1151  EXPECT_TRUE(
1152    matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
1153            binaryOperator(hasOperatorName("->*"))));
1154  EXPECT_TRUE(
1155    matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
1156            binaryOperator(hasOperatorName(".*"))));
1157
1158  // Member expressions as operators are not supported in matches.
1159  EXPECT_TRUE(
1160    notMatches("struct A { void x(A *a) { a->x(this); } };",
1161               binaryOperator(hasOperatorName("->"))));
1162
1163  // Initializer assignments are not represented as operator equals.
1164  EXPECT_TRUE(
1165    notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
1166
1167  // Array indexing is not represented as operator.
1168  EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
1169
1170  // Overloaded operators do not match at all.
1171  EXPECT_TRUE(notMatches(
1172    "struct A { bool operator&&(const A &a) const { return false; } };"
1173      "void x() { A a, b; a && b; }",
1174    binaryOperator()));
1175}
1176
1177TEST(MatchUnaryOperator, HasOperatorName) {
1178  StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
1179
1180  EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
1181  EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
1182}
1183
1184TEST(MatchUnaryOperator, HasUnaryOperand) {
1185  StatementMatcher OperatorOnFalse =
1186    unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
1187
1188  EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
1189  EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
1190}
1191
1192TEST(Matcher, UnaryOperatorTypes) {
1193  // Integration test that verifies the AST provides all unary operators in
1194  // a way we expect.
1195  EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
1196  EXPECT_TRUE(
1197    matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
1198  EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
1199  EXPECT_TRUE(
1200    matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
1201  EXPECT_TRUE(
1202    matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
1203  EXPECT_TRUE(
1204    matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
1205  EXPECT_TRUE(
1206    matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
1207  EXPECT_TRUE(
1208    matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
1209  EXPECT_TRUE(
1210    matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
1211  EXPECT_TRUE(
1212    matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
1213
1214  // We don't match conversion operators.
1215  EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
1216
1217  // Function calls are not represented as operator.
1218  EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
1219
1220  // Overloaded operators do not match at all.
1221  // FIXME: We probably want to add that.
1222  EXPECT_TRUE(notMatches(
1223    "struct A { bool operator!() const { return false; } };"
1224      "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
1225}
1226
1227TEST(ArraySubscriptMatchers, ArrayIndex) {
1228  EXPECT_TRUE(matches(
1229    "int i[2]; void f() { i[1] = 1; }",
1230    arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
1231  EXPECT_TRUE(matches(
1232    "int i[2]; void f() { 1[i] = 1; }",
1233    arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
1234  EXPECT_TRUE(notMatches(
1235    "int i[2]; void f() { i[1] = 1; }",
1236    arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
1237}
1238
1239TEST(ArraySubscriptMatchers, MatchesArrayBase) {
1240  EXPECT_TRUE(matches(
1241    "int i[2]; void f() { i[1] = 2; }",
1242    arraySubscriptExpr(hasBase(implicitCastExpr(
1243      hasSourceExpression(declRefExpr()))))));
1244}
1245
1246TEST(Matcher, OfClass) {
1247  StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
1248    ofClass(hasName("X")))));
1249
1250  EXPECT_TRUE(
1251    matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
1252  EXPECT_TRUE(
1253    matches("class X { public: X(); }; void x(int) { X x = X(); }",
1254            Constructor));
1255  EXPECT_TRUE(
1256    notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
1257               Constructor));
1258}
1259
1260TEST(Matcher, VisitsTemplateInstantiations) {
1261  EXPECT_TRUE(matches(
1262    "class A { public: void x(); };"
1263      "template <typename T> class B { public: void y() { T t; t.x(); } };"
1264      "void f() { B<A> b; b.y(); }",
1265    callExpr(callee(cxxMethodDecl(hasName("x"))))));
1266
1267  EXPECT_TRUE(matches(
1268    "class A { public: void x(); };"
1269      "class C {"
1270      " public:"
1271      "  template <typename T> class B { public: void y() { T t; t.x(); } };"
1272      "};"
1273      "void f() {"
1274      "  C::B<A> b; b.y();"
1275      "}",
1276    recordDecl(hasName("C"), hasDescendant(callExpr(
1277      callee(cxxMethodDecl(hasName("x"))))))));
1278}
1279
1280TEST(Matcher, HasCondition) {
1281  StatementMatcher IfStmt =
1282    ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
1283  EXPECT_TRUE(matches("void x() { if (true) {} }", IfStmt));
1284  EXPECT_TRUE(notMatches("void x() { if (false) {} }", IfStmt));
1285
1286  StatementMatcher ForStmt =
1287    forStmt(hasCondition(cxxBoolLiteral(equals(true))));
1288  EXPECT_TRUE(matches("void x() { for (;true;) {} }", ForStmt));
1289  EXPECT_TRUE(notMatches("void x() { for (;false;) {} }", ForStmt));
1290
1291  StatementMatcher WhileStmt =
1292    whileStmt(hasCondition(cxxBoolLiteral(equals(true))));
1293  EXPECT_TRUE(matches("void x() { while (true) {} }", WhileStmt));
1294  EXPECT_TRUE(notMatches("void x() { while (false) {} }", WhileStmt));
1295
1296  StatementMatcher SwitchStmt =
1297    switchStmt(hasCondition(integerLiteral(equals(42))));
1298  EXPECT_TRUE(matches("void x() { switch (42) {case 42:;} }", SwitchStmt));
1299  EXPECT_TRUE(notMatches("void x() { switch (43) {case 43:;} }", SwitchStmt));
1300}
1301
1302TEST(For, ForLoopInternals) {
1303  EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
1304                      forStmt(hasCondition(anything()))));
1305  EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
1306                      forStmt(hasLoopInit(anything()))));
1307}
1308
1309TEST(For, ForRangeLoopInternals) {
1310  EXPECT_TRUE(matches("void f(){ int a[] {1, 2}; for (int i : a); }",
1311                      cxxForRangeStmt(hasLoopVariable(anything()))));
1312  EXPECT_TRUE(matches(
1313    "void f(){ int a[] {1, 2}; for (int i : a); }",
1314    cxxForRangeStmt(hasRangeInit(declRefExpr(to(varDecl(hasName("a"))))))));
1315}
1316
1317TEST(For, NegativeForLoopInternals) {
1318  EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
1319                         forStmt(hasCondition(expr()))));
1320  EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
1321                         forStmt(hasLoopInit(anything()))));
1322}
1323
1324TEST(HasBody, FindsBodyOfForWhileDoLoops) {
1325  EXPECT_TRUE(matches("void f() { for(;;) {} }",
1326                      forStmt(hasBody(compoundStmt()))));
1327  EXPECT_TRUE(notMatches("void f() { for(;;); }",
1328                         forStmt(hasBody(compoundStmt()))));
1329  EXPECT_TRUE(matches("void f() { while(true) {} }",
1330                      whileStmt(hasBody(compoundStmt()))));
1331  EXPECT_TRUE(matches("void f() { do {} while(true); }",
1332                      doStmt(hasBody(compoundStmt()))));
1333  EXPECT_TRUE(matches("void f() { int p[2]; for (auto x : p) {} }",
1334                      cxxForRangeStmt(hasBody(compoundStmt()))));
1335  EXPECT_TRUE(matches("void f() {}", functionDecl(hasBody(compoundStmt()))));
1336  EXPECT_TRUE(notMatches("void f();", functionDecl(hasBody(compoundStmt()))));
1337  EXPECT_TRUE(matches("void f(); void f() {}",
1338                      functionDecl(hasBody(compoundStmt()))));
1339}
1340
1341TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
1342  // The simplest case: every compound statement is in a function
1343  // definition, and the function body itself must be a compound
1344  // statement.
1345  EXPECT_TRUE(matches("void f() { for (;;); }",
1346                      compoundStmt(hasAnySubstatement(forStmt()))));
1347}
1348
1349TEST(HasAnySubstatement, IsNotRecursive) {
1350  // It's really "has any immediate substatement".
1351  EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
1352                         compoundStmt(hasAnySubstatement(forStmt()))));
1353}
1354
1355TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
1356  EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
1357                      compoundStmt(hasAnySubstatement(forStmt()))));
1358}
1359
1360TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
1361  EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
1362                      compoundStmt(hasAnySubstatement(forStmt()))));
1363}
1364
1365TEST(Member, MatchesMemberAllocationFunction) {
1366  // Fails in C++11 mode
1367  EXPECT_TRUE(matchesConditionally(
1368    "namespace std { typedef typeof(sizeof(int)) size_t; }"
1369      "class X { void *operator new(std::size_t); };",
1370    cxxMethodDecl(ofClass(hasName("X"))), true"-std=gnu++98"));
1371
1372  EXPECT_TRUE(matches("class X { void operator delete(void*); };",
1373                      cxxMethodDecl(ofClass(hasName("X")))));
1374
1375  // Fails in C++11 mode
1376  EXPECT_TRUE(matchesConditionally(
1377    "namespace std { typedef typeof(sizeof(int)) size_t; }"
1378      "class X { void operator delete[](void*, std::size_t); };",
1379    cxxMethodDecl(ofClass(hasName("X"))), true"-std=gnu++98"));
1380}
1381
1382TEST(HasDestinationType, MatchesSimpleCase) {
1383  EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
1384                      cxxStaticCastExpr(hasDestinationType(
1385                        pointsTo(TypeMatcher(anything()))))));
1386}
1387
1388TEST(HasImplicitDestinationType, MatchesSimpleCase) {
1389  // This test creates an implicit const cast.
1390  EXPECT_TRUE(matches("int x; const int i = x;",
1391                      implicitCastExpr(
1392                        hasImplicitDestinationType(isInteger()))));
1393  // This test creates an implicit array-to-pointer cast.
1394  EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
1395                      implicitCastExpr(hasImplicitDestinationType(
1396                        pointsTo(TypeMatcher(anything()))))));
1397}
1398
1399TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
1400  // This test creates an implicit cast from int to char.
1401  EXPECT_TRUE(notMatches("char c = 0;",
1402                         implicitCastExpr(hasImplicitDestinationType(
1403                           unless(anything())))));
1404  // This test creates an implicit array-to-pointer cast.
1405  EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
1406                         implicitCastExpr(hasImplicitDestinationType(
1407                           unless(anything())))));
1408}
1409
1410TEST(IgnoringImplicit, MatchesImplicit) {
1411  EXPECT_TRUE(matches("class C {}; C a = C();",
1412                      varDecl(has(ignoringImplicit(cxxConstructExpr())))));
1413}
1414
1415TEST(IgnoringImplicit, MatchesNestedImplicit) {
1416  StringRef Code = R"(
1417
1418struct OtherType;
1419
1420struct SomeType
1421{
1422    SomeType() {}
1423    SomeType(const OtherType&) {}
1424    SomeType& operator=(OtherType const&) { return *this; }
1425};
1426
1427struct OtherType
1428{
1429    OtherType() {}
1430    ~OtherType() {}
1431};
1432
1433OtherType something()
1434{
1435    return {};
1436}
1437
1438int main()
1439{
1440    SomeType i = something();
1441}
1442)";
1443  EXPECT_TRUE(matches(Code, varDecl(
1444      hasName("i"),
1445      hasInitializer(exprWithCleanups(has(
1446        cxxConstructExpr(has(expr(ignoringImplicit(cxxConstructExpr(
1447          has(expr(ignoringImplicit(callExpr())))
1448          )))))
1449        )))
1450      )
1451  ));
1452}
1453
1454TEST(IgnoringImplicit, DoesNotMatchIncorrectly) {
1455  EXPECT_TRUE(
1456      notMatches("class C {}; C a = C();", varDecl(has(cxxConstructExpr()))));
1457}
1458
1459TEST(IgnoringImpCasts, MatchesImpCasts) {
1460  // This test checks that ignoringImpCasts matches when implicit casts are
1461  // present and its inner matcher alone does not match.
1462  // Note that this test creates an implicit const cast.
1463  EXPECT_TRUE(matches("int x = 0; const int y = x;",
1464                      varDecl(hasInitializer(ignoringImpCasts(
1465                        declRefExpr(to(varDecl(hasName("x")))))))));
1466  // This test creates an implict cast from int to char.
1467  EXPECT_TRUE(matches("char x = 0;",
1468                      varDecl(hasInitializer(ignoringImpCasts(
1469                        integerLiteral(equals(0)))))));
1470}
1471
1472TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
1473  // These tests verify that ignoringImpCasts does not match if the inner
1474  // matcher does not match.
1475  // Note that the first test creates an implicit const cast.
1476  EXPECT_TRUE(notMatches("int x; const int y = x;",
1477                         varDecl(hasInitializer(ignoringImpCasts(
1478                           unless(anything()))))));
1479  EXPECT_TRUE(notMatches("int x; int y = x;",
1480                         varDecl(hasInitializer(ignoringImpCasts(
1481                           unless(anything()))))));
1482
1483  // These tests verify that ignoringImplictCasts does not look through explicit
1484  // casts or parentheses.
1485  EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
1486                         varDecl(hasInitializer(ignoringImpCasts(
1487                           integerLiteral())))));
1488  EXPECT_TRUE(notMatches("int i = (0);",
1489                         varDecl(hasInitializer(ignoringImpCasts(
1490                           integerLiteral())))));
1491  EXPECT_TRUE(notMatches("float i = (float)0;",
1492                         varDecl(hasInitializer(ignoringImpCasts(
1493                           integerLiteral())))));
1494  EXPECT_TRUE(notMatches("float i = float(0);",
1495                         varDecl(hasInitializer(ignoringImpCasts(
1496                           integerLiteral())))));
1497}
1498
1499TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
1500  // This test verifies that expressions that do not have implicit casts
1501  // still match the inner matcher.
1502  EXPECT_TRUE(matches("int x = 0; int &y = x;",
1503                      varDecl(hasInitializer(ignoringImpCasts(
1504                        declRefExpr(to(varDecl(hasName("x")))))))));
1505}
1506
1507TEST(IgnoringParenCasts, MatchesParenCasts) {
1508  // This test checks that ignoringParenCasts matches when parentheses and/or
1509  // casts are present and its inner matcher alone does not match.
1510  EXPECT_TRUE(matches("int x = (0);",
1511                      varDecl(hasInitializer(ignoringParenCasts(
1512                        integerLiteral(equals(0)))))));
1513  EXPECT_TRUE(matches("int x = (((((0)))));",
1514                      varDecl(hasInitializer(ignoringParenCasts(
1515                        integerLiteral(equals(0)))))));
1516
1517  // This test creates an implict cast from int to char in addition to the
1518  // parentheses.
1519  EXPECT_TRUE(matches("char x = (0);",
1520                      varDecl(hasInitializer(ignoringParenCasts(
1521                        integerLiteral(equals(0)))))));
1522
1523  EXPECT_TRUE(matches("char x = (char)0;",
1524                      varDecl(hasInitializer(ignoringParenCasts(
1525                        integerLiteral(equals(0)))))));
1526  EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
1527                      varDecl(hasInitializer(ignoringParenCasts(
1528                        integerLiteral(equals(0)))))));
1529}
1530
1531TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
1532  // This test verifies that expressions that do not have any casts still match.
1533  EXPECT_TRUE(matches("int x = 0;",
1534                      varDecl(hasInitializer(ignoringParenCasts(
1535                        integerLiteral(equals(0)))))));
1536}
1537
1538TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
1539  // These tests verify that ignoringImpCasts does not match if the inner
1540  // matcher does not match.
1541  EXPECT_TRUE(notMatches("int x = ((0));",
1542                         varDecl(hasInitializer(ignoringParenCasts(
1543                           unless(anything()))))));
1544
1545  // This test creates an implicit cast from int to char in addition to the
1546  // parentheses.
1547  EXPECT_TRUE(notMatches("char x = ((0));",
1548                         varDecl(hasInitializer(ignoringParenCasts(
1549                           unless(anything()))))));
1550
1551  EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
1552                         varDecl(hasInitializer(ignoringParenCasts(
1553                           unless(anything()))))));
1554}
1555
1556TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
1557  // This test checks that ignoringParenAndImpCasts matches when
1558  // parentheses and/or implicit casts are present and its inner matcher alone
1559  // does not match.
1560  // Note that this test creates an implicit const cast.
1561  EXPECT_TRUE(matches("int x = 0; const int y = x;",
1562                      varDecl(hasInitializer(ignoringParenImpCasts(
1563                        declRefExpr(to(varDecl(hasName("x")))))))));
1564  // This test creates an implicit cast from int to char.
1565  EXPECT_TRUE(matches("const char x = (0);",
1566                      varDecl(hasInitializer(ignoringParenImpCasts(
1567                        integerLiteral(equals(0)))))));
1568}
1569
1570TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
1571  // This test verifies that expressions that do not have parentheses or
1572  // implicit casts still match.
1573  EXPECT_TRUE(matches("int x = 0; int &y = x;",
1574                      varDecl(hasInitializer(ignoringParenImpCasts(
1575                        declRefExpr(to(varDecl(hasName("x")))))))));
1576  EXPECT_TRUE(matches("int x = 0;",
1577                      varDecl(hasInitializer(ignoringParenImpCasts(
1578                        integerLiteral(equals(0)))))));
1579}
1580
1581TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
1582  // These tests verify that ignoringParenImpCasts does not match if
1583  // the inner matcher does not match.
1584  // This test creates an implicit cast.
1585  EXPECT_TRUE(notMatches("char c = ((3));",
1586                         varDecl(hasInitializer(ignoringParenImpCasts(
1587                           unless(anything()))))));
1588  // These tests verify that ignoringParenAndImplictCasts does not look
1589  // through explicit casts.
1590  EXPECT_TRUE(notMatches("float y = (float(0));",
1591                         varDecl(hasInitializer(ignoringParenImpCasts(
1592                           integerLiteral())))));
1593  EXPECT_TRUE(notMatches("float y = (float)0;",
1594                         varDecl(hasInitializer(ignoringParenImpCasts(
1595                           integerLiteral())))));
1596  EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
1597                         varDecl(hasInitializer(ignoringParenImpCasts(
1598                           integerLiteral())))));
1599}
1600
1601TEST(HasSourceExpression, MatchesImplicitCasts) {
1602  EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
1603                        "void r() {string a_string; URL url = a_string; }",
1604                      implicitCastExpr(
1605                        hasSourceExpression(cxxConstructExpr()))));
1606}
1607
1608TEST(HasSourceExpression, MatchesExplicitCasts) {
1609  EXPECT_TRUE(matches("float x = static_cast<float>(42);",
1610                      explicitCastExpr(
1611                        hasSourceExpression(hasDescendant(
1612                          expr(integerLiteral()))))));
1613}
1614
1615TEST(UsingDeclaration, MatchesSpecificTarget) {
1616  EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
1617                      usingDecl(hasAnyUsingShadowDecl(
1618                        hasTargetDecl(functionDecl())))));
1619  EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
1620                         usingDecl(hasAnyUsingShadowDecl(
1621                           hasTargetDecl(functionDecl())))));
1622}
1623
1624TEST(UsingDeclaration, ThroughUsingDeclaration) {
1625  EXPECT_TRUE(matches(
1626    "namespace a { void f(); } using a::f; void g() { f(); }",
1627    declRefExpr(throughUsingDecl(anything()))));
1628  EXPECT_TRUE(notMatches(
1629    "namespace a { void f(); } using a::f; void g() { a::f(); }",
1630    declRefExpr(throughUsingDecl(anything()))));
1631}
1632
1633TEST(SingleDecl, IsSingleDecl) {
1634  StatementMatcher SingleDeclStmt =
1635    declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
1636  EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
1637  EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
1638  EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
1639                         SingleDeclStmt));
1640}
1641
1642TEST(DeclStmt, ContainsDeclaration) {
1643  DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
1644
1645  EXPECT_TRUE(matches("void f() {int a = 4;}",
1646                      declStmt(containsDeclaration(0, MatchesInit))));
1647  EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
1648                      declStmt(containsDeclaration(0, MatchesInit),
1649                               containsDeclaration(1, MatchesInit))));
1650  unsigned WrongIndex = 42;
1651  EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
1652                         declStmt(containsDeclaration(WrongIndex,
1653                                                      MatchesInit))));
1654}
1655
1656TEST(SwitchCase, MatchesEachCase) {
1657  EXPECT_TRUE(notMatches("void x() { switch(42); }",
1658                         switchStmt(forEachSwitchCase(caseStmt()))));
1659  EXPECT_TRUE(matches("void x() { switch(42) case 42:; }",
1660                      switchStmt(forEachSwitchCase(caseStmt()))));
1661  EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }",
1662                      switchStmt(forEachSwitchCase(caseStmt()))));
1663  EXPECT_TRUE(notMatches(
1664    "void x() { if (1) switch(42) { case 42: switch (42) { default:; } } }",
1665    ifStmt(has(switchStmt(forEachSwitchCase(defaultStmt()))))));
1666  EXPECT_TRUE(matches("void x() { switch(42) { case 1+1: case 4:; } }",
1667                      switchStmt(forEachSwitchCase(
1668                        caseStmt(hasCaseConstant(
1669                            constantExpr(has(integerLiteral()))))))));
1670  EXPECT_TRUE(notMatches("void x() { switch(42) { case 1+1: case 2+2:; } }",
1671                         switchStmt(forEachSwitchCase(
1672                           caseStmt(hasCaseConstant(
1673                               constantExpr(has(integerLiteral()))))))));
1674  EXPECT_TRUE(notMatches("void x() { switch(42) { case 1 ... 2:; } }",
1675                         switchStmt(forEachSwitchCase(
1676                           caseStmt(hasCaseConstant(
1677                               constantExpr(has(integerLiteral()))))))));
1678  EXPECT_TRUE(matchAndVerifyResultTrue(
1679    "void x() { switch (42) { case 1: case 2: case 3: default:; } }",
1680    switchStmt(forEachSwitchCase(caseStmt().bind("x"))),
1681    llvm::make_unique<VerifyIdIsBoundTo<CaseStmt>>("x"3)));
1682}
1683
1684TEST(ForEachConstructorInitializer, MatchesInitializers) {
1685  EXPECT_TRUE(matches(
1686    "struct X { X() : i(42), j(42) {} int i, j; };",
1687    cxxConstructorDecl(forEachConstructorInitializer(cxxCtorInitializer()))));
1688}
1689
1690TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
1691  EXPECT_TRUE(notMatches(
1692    "void x() { if(true) {} }",
1693    ifStmt(hasConditionVariableStatement(declStmt()))));
1694  EXPECT_TRUE(notMatches(
1695    "void x() { int x; if((x = 42)) {} }",
1696    ifStmt(hasConditionVariableStatement(declStmt()))));
1697}
1698
1699TEST(HasConditionVariableStatement, MatchesConditionVariables) {
1700  EXPECT_TRUE(matches(
1701    "void x() { if(int* a = 0) {} }",
1702    ifStmt(hasConditionVariableStatement(declStmt()))));
1703}
1704
1705TEST(ForEach, BindsOneNode) {
1706  EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
1707                                       recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
1708                                       llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("x"1)));
1709}
1710
1711TEST(ForEach, BindsMultipleNodes) {
1712  EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
1713                                       recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
1714                                       llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f"3)));
1715}
1716
1717TEST(ForEach, BindsRecursiveCombinations) {
1718  EXPECT_TRUE(matchAndVerifyResultTrue(
1719    "class C { class D { int x; int y; }; class E { int y; int z; }; };",
1720    recordDecl(hasName("C"),
1721               forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
1722    llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f"4)));
1723}
1724
1725TEST(ForEachDescendant, BindsOneNode) {
1726  EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
1727                                       recordDecl(hasName("C"),
1728                                                  forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
1729                                       llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("x"1)));
1730}
1731
1732TEST(ForEachDescendant, NestedForEachDescendant) {
1733  DeclarationMatcher m = recordDecl(
1734    isDefinition(), decl().bind("x"), hasName("C"));
1735  EXPECT_TRUE(matchAndVerifyResultTrue(
1736    "class A { class B { class C {}; }; };",
1737    recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
1738    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x""C")));
1739
1740  // Check that a partial match of 'm' that binds 'x' in the
1741  // first part of anyOf(m, anything()) will not overwrite the
1742  // binding created by the earlier binding in the hasDescendant.
1743  EXPECT_TRUE(matchAndVerifyResultTrue(
1744    "class A { class B { class C {}; }; };",
1745    recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
1746    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x""C")));
1747}
1748
1749TEST(ForEachDescendant, BindsMultipleNodes) {
1750  EXPECT_TRUE(matchAndVerifyResultTrue(
1751    "class C { class D { int x; int y; }; "
1752      "          class E { class F { int y; int z; }; }; };",
1753    recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
1754    llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f"4)));
1755}
1756
1757TEST(ForEachDescendant, BindsRecursiveCombinations) {
1758  EXPECT_TRUE(matchAndVerifyResultTrue(
1759    "class C { class D { "
1760      "          class E { class F { class G { int y; int z; }; }; }; }; };",
1761    recordDecl(hasName("C"), forEachDescendant(recordDecl(
1762      forEachDescendant(fieldDecl().bind("f"))))),
1763    llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("f"8)));
1764}
1765
1766TEST(ForEachDescendant, BindsCombinations) {
1767  EXPECT_TRUE(matchAndVerifyResultTrue(
1768    "void f() { if(true) {} if (true) {} while (true) {} if (true) {} while "
1769      "(true) {} }",
1770    compoundStmt(forEachDescendant(ifStmt().bind("if")),
1771                 forEachDescendant(whileStmt().bind("while"))),
1772    llvm::make_unique<VerifyIdIsBoundTo<IfStmt>>("if"6)));
1773}
1774
1775TEST(Has, DoesNotDeleteBindings) {
1776  EXPECT_TRUE(matchAndVerifyResultTrue(
1777    "class X { int a; };", recordDecl(decl().bind("x"), has(fieldDecl())),
1778    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1779}
1780
1781TEST(LoopingMatchers, DoNotOverwritePreviousMatchResultOnFailure) {
1782  // Those matchers cover all the cases where an inner matcher is called
1783  // and there is not a 1:1 relationship between the match of the outer
1784  // matcher and the match of the inner matcher.
1785  // The pattern to look for is:
1786  //   ... return InnerMatcher.matches(...); ...
1787  // In which case no special handling is needed.
1788  //
1789  // On the other hand, if there are multiple alternative matches
1790  // (for example forEach*) or matches might be discarded (for example has*)
1791  // the implementation must make sure that the discarded matches do not
1792  // affect the bindings.
1793  // When new such matchers are added, add a test here that:
1794  // - matches a simple node, and binds it as the first thing in the matcher:
1795  //     recordDecl(decl().bind("x"), hasName("X")))
1796  // - uses the matcher under test afterwards in a way that not the first
1797  //   alternative is matched; for anyOf, that means the first branch
1798  //   would need to return false; for hasAncestor, it means that not
1799  //   the direct parent matches the inner matcher.
1800
1801  EXPECT_TRUE(matchAndVerifyResultTrue(
1802    "class X { int y; };",
1803    recordDecl(
1804      recordDecl().bind("x"), hasName("::X"),
1805      anyOf(forEachDescendant(recordDecl(hasName("Y"))), anything())),
1806    llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x"1)));
1807  EXPECT_TRUE(matchAndVerifyResultTrue(
1808    "class X {};", recordDecl(recordDecl().bind("x"), hasName("::X"),
1809                              anyOf(unless(anything()), anything())),
1810    llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("x"1)));
1811  EXPECT_TRUE(matchAndVerifyResultTrue(
1812    "template<typename T1, typename T2> class X {}; X<float, int> x;",
1813    classTemplateSpecializationDecl(
1814      decl().bind("x"),
1815      hasAnyTemplateArgument(refersToType(asString("int")))),
1816    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1817  EXPECT_TRUE(matchAndVerifyResultTrue(
1818    "class X { void f(); void g(); };",
1819    cxxRecordDecl(decl().bind("x"), hasMethod(hasName("g"))),
1820    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1821  EXPECT_TRUE(matchAndVerifyResultTrue(
1822    "class X { X() : a(1), b(2) {} double a; int b; };",
1823    recordDecl(decl().bind("x"),
1824               has(cxxConstructorDecl(
1825                 hasAnyConstructorInitializer(forField(hasName("b")))))),
1826    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1827  EXPECT_TRUE(matchAndVerifyResultTrue(
1828    "void x(int, int) { x(0, 42); }",
1829    callExpr(expr().bind("x"), hasAnyArgument(integerLiteral(equals(42)))),
1830    llvm::make_unique<VerifyIdIsBoundTo<Expr>>("x"1)));
1831  EXPECT_TRUE(matchAndVerifyResultTrue(
1832    "void x(int, int y) {}",
1833    functionDecl(decl().bind("x"), hasAnyParameter(hasName("y"))),
1834    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1835  EXPECT_TRUE(matchAndVerifyResultTrue(
1836    "void x() { return; if (true) {} }",
1837    functionDecl(decl().bind("x"),
1838                 has(compoundStmt(hasAnySubstatement(ifStmt())))),
1839    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1840  EXPECT_TRUE(matchAndVerifyResultTrue(
1841    "namespace X { void b(int); void b(); }"
1842      "using X::b;",
1843    usingDecl(decl().bind("x"), hasAnyUsingShadowDecl(hasTargetDecl(
1844      functionDecl(parameterCountIs(1))))),
1845    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1846  EXPECT_TRUE(matchAndVerifyResultTrue(
1847    "class A{}; class B{}; class C : B, A {};",
1848    cxxRecordDecl(decl().bind("x"), isDerivedFrom("::A")),
1849    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1850  EXPECT_TRUE(matchAndVerifyResultTrue(
1851    "class A{}; typedef A B; typedef A C; typedef A D;"
1852      "class E : A {};",
1853    cxxRecordDecl(decl().bind("x"), isDerivedFrom("C")),
1854    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1855  EXPECT_TRUE(matchAndVerifyResultTrue(
1856    "class A { class B { void f() {} }; };",
1857    functionDecl(decl().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
1858    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1859  EXPECT_TRUE(matchAndVerifyResultTrue(
1860    "template <typename T> struct A { struct B {"
1861      "  void f() { if(true) {} }"
1862      "}; };"
1863      "void t() { A<int>::B b; b.f(); }",
1864    ifStmt(stmt().bind("x"), hasAncestor(recordDecl(hasName("::A")))),
1865    llvm::make_unique<VerifyIdIsBoundTo<Stmt>>("x"2)));
1866  EXPECT_TRUE(matchAndVerifyResultTrue(
1867    "class A {};",
1868    recordDecl(hasName("::A"), decl().bind("x"), unless(hasName("fooble"))),
1869    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1870  EXPECT_TRUE(matchAndVerifyResultTrue(
1871    "class A { A() : s(), i(42) {} const char *s; int i; };",
1872    cxxConstructorDecl(hasName("::A::A"), decl().bind("x"),
1873                       forEachConstructorInitializer(forField(hasName("i")))),
1874    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("x"1)));
1875}
1876
1877TEST(ForEachDescendant, BindsCorrectNodes) {
1878  EXPECT_TRUE(matchAndVerifyResultTrue(
1879    "class C { void f(); int i; };",
1880    recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
1881    llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("decl"1)));
1882  EXPECT_TRUE(matchAndVerifyResultTrue(
1883    "class C { void f() {} int i; };",
1884    recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
1885    llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("decl"1)));
1886}
1887
1888TEST(FindAll, BindsNodeOnMatch) {
1889  EXPECT_TRUE(matchAndVerifyResultTrue(
1890    "class A {};",
1891    recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
1892    llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("v"1)));
1893}
1894
1895TEST(FindAll, BindsDescendantNodeOnMatch) {
1896  EXPECT_TRUE(matchAndVerifyResultTrue(
1897    "class A { int a; int b; };",
1898    recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
1899    llvm::make_unique<VerifyIdIsBoundTo<FieldDecl>>("v"2)));
1900}
1901
1902TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
1903  EXPECT_TRUE(matchAndVerifyResultTrue(
1904    "class A { int a; int b; };",
1905    recordDecl(hasName("::A"),
1906               findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
1907                                  fieldDecl().bind("v"))))),
1908    llvm::make_unique<VerifyIdIsBoundTo<Decl>>("v"3)));
1909
1910  EXPECT_TRUE(matchAndVerifyResultTrue(
1911    "class A { class B {}; class C {}; };",
1912    recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
1913    llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("v"3)));
1914}
1915
1916TEST(HasAncenstor, MatchesDeclarationAncestors) {
1917  EXPECT_TRUE(matches(
1918    "class A { class B { class C {}; }; };",
1919    recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
1920}
1921
1922TEST(HasAncenstor, FailsIfNoAncestorMatches) {
1923  EXPECT_TRUE(notMatches(
1924    "class A { class B { class C {}; }; };",
1925    recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
1926}
1927
1928TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
1929  EXPECT_TRUE(matches(
1930    "class A { class B { void f() { C c; } class C {}; }; };",
1931    varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
1932                                             hasAncestor(recordDecl(hasName("A"))))))));
1933}
1934
1935TEST(HasAncenstor, MatchesStatementAncestors) {
1936  EXPECT_TRUE(matches(
1937    "void f() { if (true) { while (false) { 42; } } }",
1938    integerLiteral(equals(42), hasAncestor(ifStmt()))));
1939}
1940
1941TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
1942  EXPECT_TRUE(matches(
1943    "void f() { if (true) { int x = 42; } }",
1944    integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
1945}
1946
1947TEST(HasAncestor, BindsRecursiveCombinations) {
1948  EXPECT_TRUE(matchAndVerifyResultTrue(
1949    "class C { class D { class E { class F { int y; }; }; }; };",
1950    fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
1951    llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("r"1)));
1952}
1953
1954TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
1955  EXPECT_TRUE(matchAndVerifyResultTrue(
1956    "class C { class D { class E { class F { int y; }; }; }; };",
1957    fieldDecl(hasAncestor(
1958      decl(
1959        hasDescendant(recordDecl(isDefinition(),
1960                                 hasAncestor(recordDecl())))
1961      ).bind("d")
1962    )),
1963    llvm::make_unique<VerifyIdIsBoundTo<CXXRecordDecl>>("d""E")));
1964}
1965
1966TEST(HasAncestor, MatchesClosestAncestor) {
1967  EXPECT_TRUE(matchAndVerifyResultTrue(
1968    "template <typename T> struct C {"
1969      "  void f(int) {"
1970      "    struct I { void g(T) { int x; } } i; i.g(42);"
1971      "  }"
1972      "};"
1973      "template struct C<int>;",
1974    varDecl(hasName("x"),
1975            hasAncestor(functionDecl(hasParameter(
1976              0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
1977    llvm::make_unique<VerifyIdIsBoundTo<FunctionDecl>>("f""g"2)));
1978}
1979
1980TEST(HasAncestor, MatchesInTemplateInstantiations) {
1981  EXPECT_TRUE(matches(
1982    "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
1983      "A<int>::B::C a;",
1984    fieldDecl(hasType(asString("int")),
1985              hasAncestor(recordDecl(hasName("A"))))));
1986}
1987
1988TEST(HasAncestor, MatchesInImplicitCode) {
1989  EXPECT_TRUE(matches(
1990    "struct X {}; struct A { A() {} X x; };",
1991    cxxConstructorDecl(
1992      hasAnyConstructorInitializer(withInitializer(expr(
1993        hasAncestor(recordDecl(hasName("A")))))))));
1994}
1995
1996TEST(HasParent, MatchesOnlyParent) {
1997  EXPECT_TRUE(matches(
1998    "void f() { if (true) { int x = 42; } }",
1999    compoundStmt(hasParent(ifStmt()))));
2000  EXPECT_TRUE(notMatches(
2001    "void f() { for (;;) { int x = 42; } }",
2002    compoundStmt(hasParent(ifStmt()))));
2003  EXPECT_TRUE(notMatches(
2004    "void f() { if (true) for (;;) { int x = 42; } }",
2005    compoundStmt(hasParent(ifStmt()))));
2006}
2007
2008TEST(HasAncestor, MatchesAllAncestors) {
2009  EXPECT_TRUE(matches(
2010    "template <typename T> struct C { static void f() { 42; } };"
2011      "void t() { C<int>::f(); }",
2012    integerLiteral(
2013      equals(42),
2014      allOf(
2015        hasAncestor(cxxRecordDecl(isTemplateInstantiation())),
2016        hasAncestor(cxxRecordDecl(unless(isTemplateInstantiation())))))));
2017}
2018
2019TEST(HasAncestor, ImplicitArrayCopyCtorDeclRefExpr) {
2020  EXPECT_TRUE(matches("struct MyClass {\n"
2021                        "  int c[1];\n"
2022                        "  static MyClass Create() { return MyClass(); }\n"
2023                        "};",
2024                      declRefExpr(to(decl(hasAncestor(decl()))))));
2025}
2026
2027TEST(HasAncestor, AnonymousUnionMemberExpr) {
2028  EXPECT_TRUE(matches("int F() {\n"
2029                        "  union { int i; };\n"
2030                        "  return i;\n"
2031                        "}\n",
2032                      memberExpr(member(hasAncestor(decl())))));
2033  EXPECT_TRUE(matches("void f() {\n"
2034                        "  struct {\n"
2035                        "    struct { int a; int b; };\n"
2036                        "  } s;\n"
2037                        "  s.a = 4;\n"
2038                        "}\n",
2039                      memberExpr(member(hasAncestor(decl())))));
2040  EXPECT_TRUE(matches("void f() {\n"
2041                        "  struct {\n"
2042                        "    struct { int a; int b; };\n"
2043                        "  } s;\n"
2044                        "  s.a = 4;\n"
2045                        "}\n",
2046                      declRefExpr(to(decl(hasAncestor(decl()))))));
2047}
2048TEST(HasAncestor, NonParmDependentTemplateParmVarDeclRefExpr) {
2049  EXPECT_TRUE(matches("struct PartitionAllocator {\n"
2050                        "  template<typename T>\n"
2051                        "  static int quantizedSize(int count) {\n"
2052                        "    return count;\n"
2053                        "  }\n"
2054                        "  void f() { quantizedSize<int>(10); }\n"
2055                        "};",
2056                      declRefExpr(to(decl(hasAncestor(decl()))))));
2057}
2058
2059TEST(HasAncestor, AddressOfExplicitSpecializationFunction) {
2060  EXPECT_TRUE(matches("template <class T> void f();\n"
2061                        "template <> void f<int>();\n"
2062                        "void (*get_f())() { return f<int>; }\n",
2063                      declRefExpr(to(decl(hasAncestor(decl()))))));
2064}
2065
2066TEST(HasParent, MatchesAllParents) {
2067  EXPECT_TRUE(matches(
2068    "template <typename T> struct C { static void f() { 42; } };"
2069      "void t() { C<int>::f(); }",
2070    integerLiteral(
2071      equals(42),
2072      hasParent(compoundStmt(hasParent(functionDecl(
2073        hasParent(cxxRecordDecl(isTemplateInstantiation())))))))));
2074  EXPECT_TRUE(
2075    matches("template <typename T> struct C { static void f() { 42; } };"
2076              "void t() { C<int>::f(); }",
2077            integerLiteral(
2078              equals(42),
2079              hasParent(compoundStmt(hasParent(functionDecl(hasParent(
2080                cxxRecordDecl(unless(isTemplateInstantiation()))))))))));
2081  EXPECT_TRUE(matches(
2082    "template <typename T> struct C { static void f() { 42; } };"
2083      "void t() { C<int>::f(); }",
2084    integerLiteral(equals(42),
2085                   hasParent(compoundStmt(
2086                     allOf(hasParent(functionDecl(hasParent(
2087                       cxxRecordDecl(isTemplateInstantiation())))),
2088                           hasParent(functionDecl(hasParent(cxxRecordDecl(
2089                             unless(isTemplateInstantiation())))))))))));
2090  EXPECT_TRUE(
2091    notMatches("template <typename T> struct C { static void f() {} };"
2092                 "void t() { C<int>::f(); }",
2093               compoundStmt(hasParent(recordDecl()))));
2094}
2095
2096TEST(HasParent, NoDuplicateParents) {
2097  class HasDuplicateParents : public BoundNodesCallback {
2098  public:
2099    bool run(const BoundNodes *Nodes) override { return false; }
2100    bool run(const BoundNodes *Nodes, ASTContext *Context) override {
2101      const Stmt *Node = Nodes->getNodeAs<Stmt>("node");
2102      std::set<const void *> Parents;
2103      for (const auto &Parent : Context->getParents(*Node)) {
2104        if (!Parents.insert(Parent.getMemoizationData()).second) {
2105          return true;
2106        }
2107      }
2108      return false;
2109    }
2110  };
2111  EXPECT_FALSE(matchAndVerifyResultTrue(
2112    "template <typename T> int Foo() { return 1 + 2; }\n"
2113      "int x = Foo<int>() + Foo<unsigned>();",
2114    stmt().bind("node"), llvm::make_unique<HasDuplicateParents>()));
2115}
2116
2117TEST(TypeMatching, PointeeTypes) {
2118  EXPECT_TRUE(matches("int b; int &a = b;",
2119                      referenceType(pointee(builtinType()))));
2120  EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
2121
2122  EXPECT_TRUE(matches("int *a;",
2123                      loc(pointerType(pointee(builtinType())))));
2124
2125  EXPECT_TRUE(matches(
2126    "int const *A;",
2127    pointerType(pointee(isConstQualified(), builtinType()))));
2128  EXPECT_TRUE(notMatches(
2129    "int *A;",
2130    pointerType(pointee(isConstQualified(), builtinType()))));
2131}
2132
2133TEST(ElaboratedTypeNarrowing, hasQualifier) {
2134  EXPECT_TRUE(matches(
2135    "namespace N {"
2136      "  namespace M {"
2137      "    class D {};"
2138      "  }"
2139      "}"
2140      "N::M::D d;",
2141    elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
2142  EXPECT_TRUE(notMatches(
2143    "namespace M {"
2144      "  class D {};"
2145      "}"
2146      "M::D d;",
2147    elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
2148  EXPECT_TRUE(notMatches(
2149    "struct D {"
2150      "} d;",
2151    elaboratedType(hasQualifier(nestedNameSpecifier()))));
2152}
2153
2154TEST(ElaboratedTypeNarrowing, namesType) {
2155  EXPECT_TRUE(matches(
2156    "namespace N {"
2157      "  namespace M {"
2158      "    class D {};"
2159      "  }"
2160      "}"
2161      "N::M::D d;",
2162    elaboratedType(elaboratedType(namesType(recordType(
2163      hasDeclaration(namedDecl(hasName("D")))))))));
2164  EXPECT_TRUE(notMatches(
2165    "namespace M {"
2166      "  class D {};"
2167      "}"
2168      "M::D d;",
2169    elaboratedType(elaboratedType(namesType(typedefType())))));
2170}
2171
2172TEST(NNS, BindsNestedNameSpecifiers) {
2173  EXPECT_TRUE(matchAndVerifyResultTrue(
2174    "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
2175    nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
2176    llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>(
2177      "nns""ns::struct E::")));
2178}
2179
2180TEST(NNS, BindsNestedNameSpecifierLocs) {
2181  EXPECT_TRUE(matchAndVerifyResultTrue(
2182    "namespace ns { struct B {}; } ns::B b;",
2183    loc(nestedNameSpecifier()).bind("loc"),
2184    llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("loc"1)));
2185}
2186
2187TEST(NNS, DescendantsOfNestedNameSpecifiers) {
2188  std::string Fragment =
2189    "namespace a { struct A { struct B { struct C {}; }; }; };"
2190      "void f() { a::A::B::C c; }";
2191  EXPECT_TRUE(matches(
2192    Fragment,
2193    nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
2194                        hasDescendant(nestedNameSpecifier(
2195                          specifiesNamespace(hasName("a")))))));
2196  EXPECT_TRUE(notMatches(
2197    Fragment,
2198    nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
2199                        has(nestedNameSpecifier(
2200                          specifiesNamespace(hasName("a")))))));
2201  EXPECT_TRUE(matches(
2202    Fragment,
2203    nestedNameSpecifier(specifiesType(asString("struct a::A")),
2204                        has(nestedNameSpecifier(
2205                          specifiesNamespace(hasName("a")))))));
2206
2207  // Not really useful because a NestedNameSpecifier can af at most one child,
2208  // but to complete the interface.
2209  EXPECT_TRUE(matchAndVerifyResultTrue(
2210    Fragment,
2211    nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
2212                        forEach(nestedNameSpecifier().bind("x"))),
2213    llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>("x"1)));
2214}
2215
2216TEST(NNS, NestedNameSpecifiersAsDescendants) {
2217  std::string Fragment =
2218    "namespace a { struct A { struct B { struct C {}; }; }; };"
2219      "void f() { a::A::B::C c; }";
2220  EXPECT_TRUE(matches(
2221    Fragment,
2222    decl(hasDescendant(nestedNameSpecifier(specifiesType(
2223      asString("struct a::A")))))));
2224  EXPECT_TRUE(matchAndVerifyResultTrue(
2225    Fragment,
2226    functionDecl(hasName("f"),
2227                 forEachDescendant(nestedNameSpecifier().bind("x"))),
2228    // Nested names: a, a::A and a::A::B.
2229    llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifier>>("x"3)));
2230}
2231
2232TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
2233  std::string Fragment =
2234    "namespace a { struct A { struct B { struct C {}; }; }; };"
2235      "void f() { a::A::B::C c; }";
2236  EXPECT_TRUE(matches(
2237    Fragment,
2238    nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
2239                           hasDescendant(loc(nestedNameSpecifier(
2240                             specifiesNamespace(hasName("a"))))))));
2241  EXPECT_TRUE(notMatches(
2242    Fragment,
2243    nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
2244                           has(loc(nestedNameSpecifier(
2245                             specifiesNamespace(hasName("a"))))))));
2246  EXPECT_TRUE(matches(
2247    Fragment,
2248    nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
2249                           has(loc(nestedNameSpecifier(
2250                             specifiesNamespace(hasName("a"))))))));
2251
2252  EXPECT_TRUE(matchAndVerifyResultTrue(
2253    Fragment,
2254    nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
2255                           forEach(nestedNameSpecifierLoc().bind("x"))),
2256    llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("x"1)));
2257}
2258
2259TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
2260  std::string Fragment =
2261    "namespace a { struct A { struct B { struct C {}; }; }; };"
2262      "void f() { a::A::B::C c; }";
2263  EXPECT_TRUE(matches(
2264    Fragment,
2265    decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
2266      asString("struct a::A"))))))));
2267  EXPECT_TRUE(matchAndVerifyResultTrue(
2268    Fragment,
2269    functionDecl(hasName("f"),
2270                 forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
2271    // Nested names: a, a::A and a::A::B.
2272    llvm::make_unique<VerifyIdIsBoundTo<NestedNameSpecifierLoc>>("x"3)));
2273}
2274template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
2275public:
2276  VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
2277                    StringRef InnerId)
2278    : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
2279  }
2280
2281  bool run(const BoundNodes *Nodes) override { return false; }
2282
2283  bool run(const BoundNodes *Nodes, ASTContext *Context) override {
2284    const T *Node = Nodes->getNodeAs<T>(Id);
2285    return selectFirst<T>(InnerId, match(InnerMatcher, *Node, *Context)) !=
2286      nullptr;
2287  }
2288private:
2289  std::string Id;
2290  internal::Matcher<T> InnerMatcher;
2291  std::string InnerId;
2292};
2293
2294TEST(MatchFinder, CanMatchDeclarationsRecursively) {
2295  EXPECT_TRUE(matchAndVerifyResultTrue(
2296    "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
2297    llvm::make_unique<VerifyMatchOnNode<Decl>>(
2298      "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
2299      "Y")));
2300  EXPECT_TRUE(matchAndVerifyResultFalse(
2301    "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
2302    llvm::make_unique<VerifyMatchOnNode<Decl>>(
2303      "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
2304      "Z")));
2305}
2306
2307TEST(MatchFinder, CanMatchStatementsRecursively) {
2308  EXPECT_TRUE(matchAndVerifyResultTrue(
2309    "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
2310    llvm::make_unique<VerifyMatchOnNode<Stmt>>(
2311      "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
2312  EXPECT_TRUE(matchAndVerifyResultFalse(
2313    "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
2314    llvm::make_unique<VerifyMatchOnNode<Stmt>>(
2315      "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
2316}
2317
2318TEST(MatchFinder, CanMatchSingleNodesRecursively) {
2319  EXPECT_TRUE(matchAndVerifyResultTrue(
2320    "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
2321    llvm::make_unique<VerifyMatchOnNode<Decl>>(
2322      "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
2323  EXPECT_TRUE(matchAndVerifyResultFalse(
2324    "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
2325    llvm::make_unique<VerifyMatchOnNode<Decl>>(
2326      "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
2327}
2328
2329TEST(StatementMatcher, HasReturnValue) {
2330  StatementMatcher RetVal = returnStmt(hasReturnValue(binaryOperator()));
2331  EXPECT_TRUE(matches("int F() { int a, b; return a + b; }"RetVal));
2332  EXPECT_FALSE(matches("int F() { int a; return a; }"RetVal));
2333  EXPECT_FALSE(matches("void F() { return; }"RetVal));
2334}
2335
2336TEST(StatementMatcher, ForFunction) {
2337  const auto CppString1 =
2338    "struct PosVec {"
2339      "  PosVec& operator=(const PosVec&) {"
2340      "    auto x = [] { return 1; };"
2341      "    return *this;"
2342      "  }"
2343      "};";
2344  const auto CppString2 =
2345    "void F() {"
2346      "  struct S {"
2347      "    void F2() {"
2348      "       return;"
2349      "    }"
2350      "  };"
2351      "}";
2352  EXPECT_TRUE(
2353    matches(
2354      CppString1,
2355      returnStmt(forFunction(hasName("operator=")),
2356                 has(unaryOperator(hasOperatorName("*"))))));
2357  EXPECT_TRUE(
2358    notMatches(
2359      CppString1,
2360      returnStmt(forFunction(hasName("operator=")),
2361                 has(integerLiteral()))));
2362  EXPECT_TRUE(
2363    matches(
2364      CppString1,
2365      returnStmt(forFunction(hasName("operator()")),
2366                 has(integerLiteral()))));
2367  EXPECT_TRUE(matches(CppString2, returnStmt(forFunction(hasName("F2")))));
2368  EXPECT_TRUE(notMatches(CppString2, returnStmt(forFunction(hasName("F")))));
2369}
2370
2371TEST(Matcher, ForEachOverriden) {
2372  const auto ForEachOverriddenInClass = [](const char *ClassName) {
2373    return cxxMethodDecl(ofClass(hasName(ClassName)), isVirtual(),
2374                         forEachOverridden(cxxMethodDecl().bind("overridden")))
2375        .bind("override");
2376  };
2377  static const char Code1[] = "class A { virtual void f(); };"
2378                              "class B : public A { void f(); };"
2379                              "class C : public B { void f(); };";
2380  // C::f overrides A::f.
2381  EXPECT_TRUE(matchAndVerifyResultTrue(
2382      Code1, ForEachOverriddenInClass("C"),
2383      llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override""f"1)));
2384  EXPECT_TRUE(matchAndVerifyResultTrue(
2385      Code1, ForEachOverriddenInClass("C"),
2386      llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden""f",
2387                                                          1)));
2388  // B::f overrides A::f.
2389  EXPECT_TRUE(matchAndVerifyResultTrue(
2390      Code1, ForEachOverriddenInClass("B"),
2391      llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override""f"1)));
2392  EXPECT_TRUE(matchAndVerifyResultTrue(
2393      Code1, ForEachOverriddenInClass("B"),
2394      llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden""f",
2395                                                          1)));
2396  // A::f overrides nothing.
2397  EXPECT_TRUE(notMatches(Code1ForEachOverriddenInClass("A")));
2398
2399  static const char Code2[] =
2400      "class A1 { virtual void f(); };"
2401      "class A2 { virtual void f(); };"
2402      "class B : public A1, public A2 { void f(); };";
2403  // B::f overrides A1::f and A2::f. This produces two matches.
2404  EXPECT_TRUE(matchAndVerifyResultTrue(
2405      Code2, ForEachOverriddenInClass("B"),
2406      llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("override""f"2)));
2407  EXPECT_TRUE(matchAndVerifyResultTrue(
2408      Code2, ForEachOverriddenInClass("B"),
2409      llvm::make_unique<VerifyIdIsBoundTo<CXXMethodDecl>>("overridden""f",
2410                                                          2)));
2411  // A1::f overrides nothing.
2412  EXPECT_TRUE(notMatches(Code2ForEachOverriddenInClass("A1")));
2413}
2414
2415TEST(Matcher, HasAnyDeclaration) {
2416  std::string Fragment = "void foo(int p1);"
2417                         "void foo(int *p2);"
2418                         "void bar(int p3);"
2419                         "template <typename T> void baz(T t) { foo(t); }";
2420
2421  EXPECT_TRUE(
2422      matches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(functionDecl(
2423                            hasParameter(0, parmVarDecl(hasName("p1"))))))));
2424  EXPECT_TRUE(
2425      matches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(functionDecl(
2426                            hasParameter(0, parmVarDecl(hasName("p2"))))))));
2427  EXPECT_TRUE(
2428      notMatches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(functionDecl(
2429                               hasParameter(0, parmVarDecl(hasName("p3"))))))));
2430  EXPECT_TRUE(notMatches(Fragment, unresolvedLookupExpr(hasAnyDeclaration(
2431                                       functionDecl(hasName("bar"))))));
2432}
2433
2434TEST(SubstTemplateTypeParmType, HasReplacementType) {
2435  std::string Fragment = "template<typename T>"
2436                         "double F(T t);"
2437                         "int i;"
2438                         "double j = F(i);";
2439  EXPECT_TRUE(matches(Fragment, substTemplateTypeParmType(hasReplacementType(
2440                                    qualType(asString("int"))))));
2441  EXPECT_TRUE(notMatches(Fragment, substTemplateTypeParmType(hasReplacementType(
2442                                       qualType(asString("double"))))));
2443  EXPECT_TRUE(
2444      notMatches("template<int N>"
2445                 "double F();"
2446                 "double j = F<5>();",
2447                 substTemplateTypeParmType(hasReplacementType(qualType()))));
2448}
2449
2450TEST(ClassTemplateSpecializationDecl, HasSpecializedTemplate) {
2451  auto Matcher = classTemplateSpecializationDecl(
2452      hasSpecializedTemplate(classTemplateDecl()));
2453  EXPECT_TRUE(
2454      matches("template<typename T> class A {}; typedef A<int> B;", Matcher));
2455  EXPECT_TRUE(notMatches("template<typename T> class A {};", Matcher));
2456}
2457
2458// namespace ast_matchers
2459// namespace clang
2460