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