Home | History | Annotate | Download | only in ASTMatchers
      1 //===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher 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 "gtest/gtest.h"
     16 
     17 namespace clang {
     18 namespace ast_matchers {
     19 
     20 #if GTEST_HAS_DEATH_TEST
     21 TEST(HasNameDeathTest, DiesOnEmptyName) {
     22   ASSERT_DEBUG_DEATH({
     23     DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
     24     EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
     25   }, "");
     26 }
     27 
     28 TEST(HasNameDeathTest, DiesOnEmptyPattern) {
     29   ASSERT_DEBUG_DEATH({
     30       DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
     31       EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
     32     }, "");
     33 }
     34 
     35 TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
     36   ASSERT_DEBUG_DEATH({
     37     DeclarationMatcher IsDerivedFromEmpty = recordDecl(isDerivedFrom(""));
     38     EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
     39   }, "");
     40 }
     41 #endif
     42 
     43 TEST(Decl, MatchesDeclarations) {
     44   EXPECT_TRUE(notMatches("", decl(usingDecl())));
     45   EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
     46                       decl(usingDecl())));
     47 }
     48 
     49 TEST(NameableDeclaration, MatchesVariousDecls) {
     50   DeclarationMatcher NamedX = namedDecl(hasName("X"));
     51   EXPECT_TRUE(matches("typedef int X;", NamedX));
     52   EXPECT_TRUE(matches("int X;", NamedX));
     53   EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
     54   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
     55   EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
     56   EXPECT_TRUE(matches("namespace X { }", NamedX));
     57   EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
     58 
     59   EXPECT_TRUE(notMatches("#define X 1", NamedX));
     60 }
     61 
     62 TEST(NameableDeclaration, REMatchesVariousDecls) {
     63   DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
     64   EXPECT_TRUE(matches("typedef int Xa;", NamedX));
     65   EXPECT_TRUE(matches("int Xb;", NamedX));
     66   EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
     67   EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
     68   EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
     69   EXPECT_TRUE(matches("namespace Xij { }", NamedX));
     70   EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
     71 
     72   EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
     73 
     74   DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
     75   EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
     76   EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
     77 
     78   DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
     79   EXPECT_TRUE(matches("int abc;", Abc));
     80   EXPECT_TRUE(matches("int aFOObBARc;", Abc));
     81   EXPECT_TRUE(notMatches("int cab;", Abc));
     82   EXPECT_TRUE(matches("int cabc;", Abc));
     83 
     84   DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
     85   EXPECT_TRUE(matches("int k;", StartsWithK));
     86   EXPECT_TRUE(matches("int kAbc;", StartsWithK));
     87   EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
     88   EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
     89   EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
     90 }
     91 
     92 TEST(DeclarationMatcher, MatchClass) {
     93   DeclarationMatcher ClassMatcher(recordDecl());
     94 #if !defined(_MSC_VER)
     95   EXPECT_FALSE(matches("", ClassMatcher));
     96 #else
     97   // Matches class type_info.
     98   EXPECT_TRUE(matches("", ClassMatcher));
     99 #endif
    100 
    101   DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
    102   EXPECT_TRUE(matches("class X;", ClassX));
    103   EXPECT_TRUE(matches("class X {};", ClassX));
    104   EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
    105   EXPECT_TRUE(notMatches("", ClassX));
    106 }
    107 
    108 TEST(DeclarationMatcher, ClassIsDerived) {
    109   DeclarationMatcher IsDerivedFromX = recordDecl(isDerivedFrom("X"));
    110 
    111   EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
    112   EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
    113   EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
    114   EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
    115   EXPECT_TRUE(notMatches("", IsDerivedFromX));
    116 
    117   DeclarationMatcher IsAX = recordDecl(isSameOrDerivedFrom("X"));
    118 
    119   EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
    120   EXPECT_TRUE(matches("class X {};", IsAX));
    121   EXPECT_TRUE(matches("class X;", IsAX));
    122   EXPECT_TRUE(notMatches("class Y;", IsAX));
    123   EXPECT_TRUE(notMatches("", IsAX));
    124 
    125   DeclarationMatcher ZIsDerivedFromX =
    126       recordDecl(hasName("Z"), isDerivedFrom("X"));
    127   EXPECT_TRUE(
    128       matches("class X {}; class Y : public X {}; class Z : public Y {};",
    129               ZIsDerivedFromX));
    130   EXPECT_TRUE(
    131       matches("class X {};"
    132               "template<class T> class Y : public X {};"
    133               "class Z : public Y<int> {};", ZIsDerivedFromX));
    134   EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
    135                       ZIsDerivedFromX));
    136   EXPECT_TRUE(
    137       matches("template<class T> class X {}; "
    138               "template<class T> class Z : public X<T> {};",
    139               ZIsDerivedFromX));
    140   EXPECT_TRUE(
    141       matches("template<class T, class U=T> class X {}; "
    142               "template<class T> class Z : public X<T> {};",
    143               ZIsDerivedFromX));
    144   EXPECT_TRUE(
    145       notMatches("template<class X> class A { class Z : public X {}; };",
    146                  ZIsDerivedFromX));
    147   EXPECT_TRUE(
    148       matches("template<class X> class A { public: class Z : public X {}; }; "
    149               "class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
    150   EXPECT_TRUE(
    151       matches("template <class T> class X {}; "
    152               "template<class Y> class A { class Z : public X<Y> {}; };",
    153               ZIsDerivedFromX));
    154   EXPECT_TRUE(
    155       notMatches("template<template<class T> class X> class A { "
    156                  "  class Z : public X<int> {}; };", ZIsDerivedFromX));
    157   EXPECT_TRUE(
    158       matches("template<template<class T> class X> class A { "
    159               "  public: class Z : public X<int> {}; }; "
    160               "template<class T> class X {}; void y() { A<X>::Z z; }",
    161               ZIsDerivedFromX));
    162   EXPECT_TRUE(
    163       notMatches("template<class X> class A { class Z : public X::D {}; };",
    164                  ZIsDerivedFromX));
    165   EXPECT_TRUE(
    166       matches("template<class X> class A { public: "
    167               "  class Z : public X::D {}; }; "
    168               "class Y { public: class X {}; typedef X D; }; "
    169               "void y() { A<Y>::Z z; }", ZIsDerivedFromX));
    170   EXPECT_TRUE(
    171       matches("class X {}; typedef X Y; class Z : public Y {};",
    172               ZIsDerivedFromX));
    173   EXPECT_TRUE(
    174       matches("template<class T> class Y { typedef typename T::U X; "
    175               "  class Z : public X {}; };", ZIsDerivedFromX));
    176   EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
    177                       ZIsDerivedFromX));
    178   EXPECT_TRUE(
    179       notMatches("template<class T> class X {}; "
    180                 "template<class T> class A { class Z : public X<T>::D {}; };",
    181                 ZIsDerivedFromX));
    182   EXPECT_TRUE(
    183       matches("template<class T> class X { public: typedef X<T> D; }; "
    184               "template<class T> class A { public: "
    185               "  class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
    186               ZIsDerivedFromX));
    187   EXPECT_TRUE(
    188       notMatches("template<class X> class A { class Z : public X::D::E {}; };",
    189                  ZIsDerivedFromX));
    190   EXPECT_TRUE(
    191       matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
    192               ZIsDerivedFromX));
    193   EXPECT_TRUE(
    194       matches("class X {}; class Y : public X {}; "
    195               "typedef Y V; typedef V W; class Z : public W {};",
    196               ZIsDerivedFromX));
    197   EXPECT_TRUE(
    198       matches("template<class T, class U> class X {}; "
    199               "template<class T> class A { class Z : public X<T, int> {}; };",
    200               ZIsDerivedFromX));
    201   EXPECT_TRUE(
    202       notMatches("template<class X> class D { typedef X A; typedef A B; "
    203                  "  typedef B C; class Z : public C {}; };",
    204                  ZIsDerivedFromX));
    205   EXPECT_TRUE(
    206       matches("class X {}; typedef X A; typedef A B; "
    207               "class Z : public B {};", ZIsDerivedFromX));
    208   EXPECT_TRUE(
    209       matches("class X {}; typedef X A; typedef A B; typedef B C; "
    210               "class Z : public C {};", ZIsDerivedFromX));
    211   EXPECT_TRUE(
    212       matches("class U {}; typedef U X; typedef X V; "
    213               "class Z : public V {};", ZIsDerivedFromX));
    214   EXPECT_TRUE(
    215       matches("class Base {}; typedef Base X; "
    216               "class Z : public Base {};", ZIsDerivedFromX));
    217   EXPECT_TRUE(
    218       matches("class Base {}; typedef Base Base2; typedef Base2 X; "
    219               "class Z : public Base {};", ZIsDerivedFromX));
    220   EXPECT_TRUE(
    221       notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
    222                  "class Z : public Base {};", ZIsDerivedFromX));
    223   EXPECT_TRUE(
    224       matches("class A {}; typedef A X; typedef A Y; "
    225               "class Z : public Y {};", ZIsDerivedFromX));
    226   EXPECT_TRUE(
    227       notMatches("template <typename T> class Z;"
    228                  "template <> class Z<void> {};"
    229                  "template <typename T> class Z : public Z<void> {};",
    230                  IsDerivedFromX));
    231   EXPECT_TRUE(
    232       matches("template <typename T> class X;"
    233               "template <> class X<void> {};"
    234               "template <typename T> class X : public X<void> {};",
    235               IsDerivedFromX));
    236   EXPECT_TRUE(matches(
    237       "class X {};"
    238       "template <typename T> class Z;"
    239       "template <> class Z<void> {};"
    240       "template <typename T> class Z : public Z<void>, public X {};",
    241       ZIsDerivedFromX));
    242   EXPECT_TRUE(
    243       notMatches("template<int> struct X;"
    244                  "template<int i> struct X : public X<i-1> {};",
    245                  recordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
    246   EXPECT_TRUE(matches(
    247       "struct A {};"
    248       "template<int> struct X;"
    249       "template<int i> struct X : public X<i-1> {};"
    250       "template<> struct X<0> : public A {};"
    251       "struct B : public X<42> {};",
    252       recordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
    253 
    254   // FIXME: Once we have better matchers for template type matching,
    255   // get rid of the Variable(...) matching and match the right template
    256   // declarations directly.
    257   const char *RecursiveTemplateOneParameter =
    258       "class Base1 {}; class Base2 {};"
    259       "template <typename T> class Z;"
    260       "template <> class Z<void> : public Base1 {};"
    261       "template <> class Z<int> : public Base2 {};"
    262       "template <> class Z<float> : public Z<void> {};"
    263       "template <> class Z<double> : public Z<int> {};"
    264       "template <typename T> class Z : public Z<float>, public Z<double> {};"
    265       "void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
    266   EXPECT_TRUE(matches(
    267       RecursiveTemplateOneParameter,
    268       varDecl(hasName("z_float"),
    269               hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
    270   EXPECT_TRUE(notMatches(
    271       RecursiveTemplateOneParameter,
    272       varDecl(hasName("z_float"),
    273               hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
    274   EXPECT_TRUE(matches(
    275       RecursiveTemplateOneParameter,
    276       varDecl(hasName("z_char"),
    277               hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
    278                                                 isDerivedFrom("Base2")))))));
    279 
    280   const char *RecursiveTemplateTwoParameters =
    281       "class Base1 {}; class Base2 {};"
    282       "template <typename T1, typename T2> class Z;"
    283       "template <typename T> class Z<void, T> : public Base1 {};"
    284       "template <typename T> class Z<int, T> : public Base2 {};"
    285       "template <typename T> class Z<float, T> : public Z<void, T> {};"
    286       "template <typename T> class Z<double, T> : public Z<int, T> {};"
    287       "template <typename T1, typename T2> class Z : "
    288       "    public Z<float, T2>, public Z<double, T2> {};"
    289       "void f() { Z<float, void> z_float; Z<double, void> z_double; "
    290       "           Z<char, void> z_char; }";
    291   EXPECT_TRUE(matches(
    292       RecursiveTemplateTwoParameters,
    293       varDecl(hasName("z_float"),
    294               hasInitializer(hasType(recordDecl(isDerivedFrom("Base1")))))));
    295   EXPECT_TRUE(notMatches(
    296       RecursiveTemplateTwoParameters,
    297       varDecl(hasName("z_float"),
    298               hasInitializer(hasType(recordDecl(isDerivedFrom("Base2")))))));
    299   EXPECT_TRUE(matches(
    300       RecursiveTemplateTwoParameters,
    301       varDecl(hasName("z_char"),
    302               hasInitializer(hasType(recordDecl(isDerivedFrom("Base1"),
    303                                                 isDerivedFrom("Base2")))))));
    304   EXPECT_TRUE(matches(
    305       "namespace ns { class X {}; class Y : public X {}; }",
    306       recordDecl(isDerivedFrom("::ns::X"))));
    307   EXPECT_TRUE(notMatches(
    308       "class X {}; class Y : public X {};",
    309       recordDecl(isDerivedFrom("::ns::X"))));
    310 
    311   EXPECT_TRUE(matches(
    312       "class X {}; class Y : public X {};",
    313       recordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
    314 }
    315 
    316 TEST(DeclarationMatcher, hasMethod) {
    317   EXPECT_TRUE(matches("class A { void func(); };",
    318                       recordDecl(hasMethod(hasName("func")))));
    319   EXPECT_TRUE(notMatches("class A { void func(); };",
    320                          recordDecl(hasMethod(isPublic()))));
    321 }
    322 
    323 TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
    324   EXPECT_TRUE(matches(
    325      "template <typename T> struct A {"
    326      "  template <typename T2> struct F {};"
    327      "};"
    328      "template <typename T> struct B : A<T>::template F<T> {};"
    329      "B<int> b;",
    330      recordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
    331 }
    332 
    333 TEST(DeclarationMatcher, hasDeclContext) {
    334   EXPECT_TRUE(matches(
    335       "namespace N {"
    336       "  namespace M {"
    337       "    class D {};"
    338       "  }"
    339       "}",
    340       recordDecl(hasDeclContext(namedDecl(hasName("M"))))));
    341   EXPECT_TRUE(notMatches(
    342       "namespace N {"
    343       "  namespace M {"
    344       "    class D {};"
    345       "  }"
    346       "}",
    347       recordDecl(hasDeclContext(namedDecl(hasName("N"))))));
    348 }
    349 
    350 TEST(ClassTemplate, DoesNotMatchClass) {
    351   DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
    352   EXPECT_TRUE(notMatches("class X;", ClassX));
    353   EXPECT_TRUE(notMatches("class X {};", ClassX));
    354 }
    355 
    356 TEST(ClassTemplate, MatchesClassTemplate) {
    357   DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
    358   EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
    359   EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
    360 }
    361 
    362 TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
    363   EXPECT_TRUE(notMatches("template<typename T> class X { };"
    364                          "template<> class X<int> { int a; };",
    365               classTemplateDecl(hasName("X"),
    366                                 hasDescendant(fieldDecl(hasName("a"))))));
    367 }
    368 
    369 TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
    370   EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
    371                          "template<typename T> class X<T, int> { int a; };",
    372               classTemplateDecl(hasName("X"),
    373                                 hasDescendant(fieldDecl(hasName("a"))))));
    374 }
    375 
    376 TEST(AllOf, AllOverloadsWork) {
    377   const char Program[] =
    378       "struct T { };"
    379       "int f(int, T*, int, int);"
    380       "void g(int x) { T t; f(x, &t, 3, 4); }";
    381   EXPECT_TRUE(matches(Program,
    382       callExpr(allOf(callee(functionDecl(hasName("f"))),
    383                      hasArgument(0, declRefExpr(to(varDecl())))))));
    384   EXPECT_TRUE(matches(Program,
    385       callExpr(allOf(callee(functionDecl(hasName("f"))),
    386                      hasArgument(0, declRefExpr(to(varDecl()))),
    387                      hasArgument(1, hasType(pointsTo(
    388                                         recordDecl(hasName("T")))))))));
    389   EXPECT_TRUE(matches(Program,
    390       callExpr(allOf(callee(functionDecl(hasName("f"))),
    391                      hasArgument(0, declRefExpr(to(varDecl()))),
    392                      hasArgument(1, hasType(pointsTo(
    393                                         recordDecl(hasName("T"))))),
    394                      hasArgument(2, integerLiteral(equals(3)))))));
    395   EXPECT_TRUE(matches(Program,
    396       callExpr(allOf(callee(functionDecl(hasName("f"))),
    397                      hasArgument(0, declRefExpr(to(varDecl()))),
    398                      hasArgument(1, hasType(pointsTo(
    399                                         recordDecl(hasName("T"))))),
    400                      hasArgument(2, integerLiteral(equals(3))),
    401                      hasArgument(3, integerLiteral(equals(4)))))));
    402 }
    403 
    404 TEST(DeclarationMatcher, MatchAnyOf) {
    405   DeclarationMatcher YOrZDerivedFromX =
    406       recordDecl(anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
    407   EXPECT_TRUE(
    408       matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
    409   EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
    410   EXPECT_TRUE(
    411       notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
    412   EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
    413 
    414   DeclarationMatcher XOrYOrZOrU =
    415       recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
    416   EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
    417   EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
    418 
    419   DeclarationMatcher XOrYOrZOrUOrV =
    420       recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
    421                        hasName("V")));
    422   EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
    423   EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
    424   EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
    425   EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
    426   EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
    427   EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
    428 }
    429 
    430 TEST(DeclarationMatcher, MatchHas) {
    431   DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
    432   EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
    433   EXPECT_TRUE(matches("class X {};", HasClassX));
    434 
    435   DeclarationMatcher YHasClassX =
    436       recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
    437   EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
    438   EXPECT_TRUE(notMatches("class X {};", YHasClassX));
    439   EXPECT_TRUE(
    440       notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
    441 }
    442 
    443 TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
    444   DeclarationMatcher Recursive =
    445     recordDecl(
    446       has(recordDecl(
    447         has(recordDecl(hasName("X"))),
    448         has(recordDecl(hasName("Y"))),
    449         hasName("Z"))),
    450       has(recordDecl(
    451         has(recordDecl(hasName("A"))),
    452         has(recordDecl(hasName("B"))),
    453         hasName("C"))),
    454       hasName("F"));
    455 
    456   EXPECT_TRUE(matches(
    457       "class F {"
    458       "  class Z {"
    459       "    class X {};"
    460       "    class Y {};"
    461       "  };"
    462       "  class C {"
    463       "    class A {};"
    464       "    class B {};"
    465       "  };"
    466       "};", Recursive));
    467 
    468   EXPECT_TRUE(matches(
    469       "class F {"
    470       "  class Z {"
    471       "    class A {};"
    472       "    class X {};"
    473       "    class Y {};"
    474       "  };"
    475       "  class C {"
    476       "    class X {};"
    477       "    class A {};"
    478       "    class B {};"
    479       "  };"
    480       "};", Recursive));
    481 
    482   EXPECT_TRUE(matches(
    483       "class O1 {"
    484       "  class O2 {"
    485       "    class F {"
    486       "      class Z {"
    487       "        class A {};"
    488       "        class X {};"
    489       "        class Y {};"
    490       "      };"
    491       "      class C {"
    492       "        class X {};"
    493       "        class A {};"
    494       "        class B {};"
    495       "      };"
    496       "    };"
    497       "  };"
    498       "};", Recursive));
    499 }
    500 
    501 TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
    502   DeclarationMatcher Recursive =
    503       recordDecl(
    504           anyOf(
    505               has(recordDecl(
    506                   anyOf(
    507                       has(recordDecl(
    508                           hasName("X"))),
    509                       has(recordDecl(
    510                           hasName("Y"))),
    511                       hasName("Z")))),
    512               has(recordDecl(
    513                   anyOf(
    514                       hasName("C"),
    515                       has(recordDecl(
    516                           hasName("A"))),
    517                       has(recordDecl(
    518                           hasName("B")))))),
    519               hasName("F")));
    520 
    521   EXPECT_TRUE(matches("class F {};", Recursive));
    522   EXPECT_TRUE(matches("class Z {};", Recursive));
    523   EXPECT_TRUE(matches("class C {};", Recursive));
    524   EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
    525   EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
    526   EXPECT_TRUE(
    527       matches("class O1 { class O2 {"
    528               "  class M { class N { class B {}; }; }; "
    529               "}; };", Recursive));
    530 }
    531 
    532 TEST(DeclarationMatcher, MatchNot) {
    533   DeclarationMatcher NotClassX =
    534       recordDecl(
    535           isDerivedFrom("Y"),
    536           unless(hasName("X")));
    537   EXPECT_TRUE(notMatches("", NotClassX));
    538   EXPECT_TRUE(notMatches("class Y {};", NotClassX));
    539   EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
    540   EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
    541   EXPECT_TRUE(
    542       notMatches("class Y {}; class Z {}; class X : public Y {};",
    543                  NotClassX));
    544 
    545   DeclarationMatcher ClassXHasNotClassY =
    546       recordDecl(
    547           hasName("X"),
    548           has(recordDecl(hasName("Z"))),
    549           unless(
    550               has(recordDecl(hasName("Y")))));
    551   EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
    552   EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
    553                          ClassXHasNotClassY));
    554 }
    555 
    556 TEST(DeclarationMatcher, HasDescendant) {
    557   DeclarationMatcher ZDescendantClassX =
    558       recordDecl(
    559           hasDescendant(recordDecl(hasName("X"))),
    560           hasName("Z"));
    561   EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
    562   EXPECT_TRUE(
    563       matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
    564   EXPECT_TRUE(
    565       matches("class Z { class A { class Y { class X {}; }; }; };",
    566               ZDescendantClassX));
    567   EXPECT_TRUE(
    568       matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
    569               ZDescendantClassX));
    570   EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
    571 
    572   DeclarationMatcher ZDescendantClassXHasClassY =
    573       recordDecl(
    574           hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
    575                               hasName("X"))),
    576           hasName("Z"));
    577   EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
    578               ZDescendantClassXHasClassY));
    579   EXPECT_TRUE(
    580       matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
    581               ZDescendantClassXHasClassY));
    582   EXPECT_TRUE(notMatches(
    583       "class Z {"
    584       "  class A {"
    585       "    class B {"
    586       "      class X {"
    587       "        class C {"
    588       "          class Y {};"
    589       "        };"
    590       "      };"
    591       "    }; "
    592       "  };"
    593       "};", ZDescendantClassXHasClassY));
    594 
    595   DeclarationMatcher ZDescendantClassXDescendantClassY =
    596       recordDecl(
    597           hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
    598                                    hasName("X"))),
    599           hasName("Z"));
    600   EXPECT_TRUE(
    601       matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
    602               ZDescendantClassXDescendantClassY));
    603   EXPECT_TRUE(matches(
    604       "class Z {"
    605       "  class A {"
    606       "    class X {"
    607       "      class B {"
    608       "        class Y {};"
    609       "      };"
    610       "      class Y {};"
    611       "    };"
    612       "  };"
    613       "};", ZDescendantClassXDescendantClassY));
    614 }
    615 
    616 // Implements a run method that returns whether BoundNodes contains a
    617 // Decl bound to Id that can be dynamically cast to T.
    618 // Optionally checks that the check succeeded a specific number of times.
    619 template <typename T>
    620 class VerifyIdIsBoundTo : public BoundNodesCallback {
    621 public:
    622   // Create an object that checks that a node of type \c T was bound to \c Id.
    623   // Does not check for a certain number of matches.
    624   explicit VerifyIdIsBoundTo(llvm::StringRef Id)
    625     : Id(Id), ExpectedCount(-1), Count(0) {}
    626 
    627   // Create an object that checks that a node of type \c T was bound to \c Id.
    628   // Checks that there were exactly \c ExpectedCount matches.
    629   VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
    630     : Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
    631 
    632   // Create an object that checks that a node of type \c T was bound to \c Id.
    633   // Checks that there was exactly one match with the name \c ExpectedName.
    634   // Note that \c T must be a NamedDecl for this to work.
    635   VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
    636                     int ExpectedCount = 1)
    637       : Id(Id), ExpectedCount(ExpectedCount), Count(0),
    638         ExpectedName(ExpectedName) {}
    639 
    640   ~VerifyIdIsBoundTo() {
    641     if (ExpectedCount != -1)
    642       EXPECT_EQ(ExpectedCount, Count);
    643     if (!ExpectedName.empty())
    644       EXPECT_EQ(ExpectedName, Name);
    645   }
    646 
    647   virtual bool run(const BoundNodes *Nodes) {
    648     if (Nodes->getNodeAs<T>(Id)) {
    649       ++Count;
    650       if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
    651         Name = Named->getNameAsString();
    652       } else if (const NestedNameSpecifier *NNS =
    653                  Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
    654         llvm::raw_string_ostream OS(Name);
    655         NNS->print(OS, PrintingPolicy(LangOptions()));
    656       }
    657       return true;
    658     }
    659     return false;
    660   }
    661 
    662   virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
    663     return run(Nodes);
    664   }
    665 
    666 private:
    667   const std::string Id;
    668   const int ExpectedCount;
    669   int Count;
    670   const std::string ExpectedName;
    671   std::string Name;
    672 };
    673 
    674 TEST(HasDescendant, MatchesDescendantTypes) {
    675   EXPECT_TRUE(matches("void f() { int i = 3; }",
    676                       decl(hasDescendant(loc(builtinType())))));
    677   EXPECT_TRUE(matches("void f() { int i = 3; }",
    678                       stmt(hasDescendant(builtinType()))));
    679 
    680   EXPECT_TRUE(matches("void f() { int i = 3; }",
    681                       stmt(hasDescendant(loc(builtinType())))));
    682   EXPECT_TRUE(matches("void f() { int i = 3; }",
    683                       stmt(hasDescendant(qualType(builtinType())))));
    684 
    685   EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
    686                          stmt(hasDescendant(isInteger()))));
    687 
    688   EXPECT_TRUE(matchAndVerifyResultTrue(
    689       "void f() { int a; float c; int d; int e; }",
    690       functionDecl(forEachDescendant(
    691           varDecl(hasDescendant(isInteger())).bind("x"))),
    692       new VerifyIdIsBoundTo<Decl>("x", 3)));
    693 }
    694 
    695 TEST(HasDescendant, MatchesDescendantsOfTypes) {
    696   EXPECT_TRUE(matches("void f() { int*** i; }",
    697                       qualType(hasDescendant(builtinType()))));
    698   EXPECT_TRUE(matches("void f() { int*** i; }",
    699                       qualType(hasDescendant(
    700                           pointerType(pointee(builtinType()))))));
    701   EXPECT_TRUE(matches("void f() { int*** i; }",
    702                       typeLoc(hasDescendant(loc(builtinType())))));
    703 
    704   EXPECT_TRUE(matchAndVerifyResultTrue(
    705       "void f() { int*** i; }",
    706       qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
    707       new VerifyIdIsBoundTo<Type>("x", 2)));
    708 }
    709 
    710 TEST(Has, MatchesChildrenOfTypes) {
    711   EXPECT_TRUE(matches("int i;",
    712                       varDecl(hasName("i"), has(isInteger()))));
    713   EXPECT_TRUE(notMatches("int** i;",
    714                          varDecl(hasName("i"), has(isInteger()))));
    715   EXPECT_TRUE(matchAndVerifyResultTrue(
    716       "int (*f)(float, int);",
    717       qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
    718       new VerifyIdIsBoundTo<QualType>("x", 2)));
    719 }
    720 
    721 TEST(Has, MatchesChildTypes) {
    722   EXPECT_TRUE(matches(
    723       "int* i;",
    724       varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
    725   EXPECT_TRUE(notMatches(
    726       "int* i;",
    727       varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
    728 }
    729 
    730 TEST(Enum, DoesNotMatchClasses) {
    731   EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
    732 }
    733 
    734 TEST(Enum, MatchesEnums) {
    735   EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
    736 }
    737 
    738 TEST(EnumConstant, Matches) {
    739   DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
    740   EXPECT_TRUE(matches("enum X{ A };", Matcher));
    741   EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
    742   EXPECT_TRUE(notMatches("enum X {};", Matcher));
    743 }
    744 
    745 TEST(StatementMatcher, Has) {
    746   StatementMatcher HasVariableI =
    747       expr(hasType(pointsTo(recordDecl(hasName("X")))),
    748            has(declRefExpr(to(varDecl(hasName("i"))))));
    749 
    750   EXPECT_TRUE(matches(
    751       "class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
    752   EXPECT_TRUE(notMatches(
    753       "class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
    754 }
    755 
    756 TEST(StatementMatcher, HasDescendant) {
    757   StatementMatcher HasDescendantVariableI =
    758       expr(hasType(pointsTo(recordDecl(hasName("X")))),
    759            hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
    760 
    761   EXPECT_TRUE(matches(
    762       "class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
    763       HasDescendantVariableI));
    764   EXPECT_TRUE(notMatches(
    765       "class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
    766       HasDescendantVariableI));
    767 }
    768 
    769 TEST(TypeMatcher, MatchesClassType) {
    770   TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
    771 
    772   EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
    773   EXPECT_TRUE(notMatches("class A {};", TypeA));
    774 
    775   TypeMatcher TypeDerivedFromA = hasDeclaration(recordDecl(isDerivedFrom("A")));
    776 
    777   EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
    778               TypeDerivedFromA));
    779   EXPECT_TRUE(notMatches("class A {};", TypeA));
    780 
    781   TypeMatcher TypeAHasClassB = hasDeclaration(
    782       recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
    783 
    784   EXPECT_TRUE(
    785       matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
    786 }
    787 
    788 TEST(Matcher, BindMatchedNodes) {
    789   DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
    790 
    791   EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
    792       ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
    793 
    794   EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
    795       ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
    796 
    797   TypeMatcher TypeAHasClassB = hasDeclaration(
    798       recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
    799 
    800   EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
    801       TypeAHasClassB,
    802       new VerifyIdIsBoundTo<Decl>("b")));
    803 
    804   StatementMatcher MethodX =
    805       callExpr(callee(methodDecl(hasName("x")))).bind("x");
    806 
    807   EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
    808       MethodX,
    809       new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
    810 }
    811 
    812 TEST(Matcher, BindTheSameNameInAlternatives) {
    813   StatementMatcher matcher = anyOf(
    814       binaryOperator(hasOperatorName("+"),
    815                      hasLHS(expr().bind("x")),
    816                      hasRHS(integerLiteral(equals(0)))),
    817       binaryOperator(hasOperatorName("+"),
    818                      hasLHS(integerLiteral(equals(0))),
    819                      hasRHS(expr().bind("x"))));
    820 
    821   EXPECT_TRUE(matchAndVerifyResultTrue(
    822       // The first branch of the matcher binds x to 0 but then fails.
    823       // The second branch binds x to f() and succeeds.
    824       "int f() { return 0 + f(); }",
    825       matcher,
    826       new VerifyIdIsBoundTo<CallExpr>("x")));
    827 }
    828 
    829 TEST(Matcher, BindsIDForMemoizedResults) {
    830   // Using the same matcher in two match expressions will make memoization
    831   // kick in.
    832   DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
    833   EXPECT_TRUE(matchAndVerifyResultTrue(
    834       "class A { class B { class X {}; }; };",
    835       DeclarationMatcher(anyOf(
    836           recordDecl(hasName("A"), hasDescendant(ClassX)),
    837           recordDecl(hasName("B"), hasDescendant(ClassX)))),
    838       new VerifyIdIsBoundTo<Decl>("x", 2)));
    839 }
    840 
    841 TEST(HasDeclaration, HasDeclarationOfEnumType) {
    842   EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
    843                       expr(hasType(pointsTo(
    844                           qualType(hasDeclaration(enumDecl(hasName("X")))))))));
    845 }
    846 
    847 TEST(HasDeclaration, HasGetDeclTraitTest) {
    848   EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
    849   EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
    850   EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
    851 }
    852 
    853 TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
    854   EXPECT_TRUE(matches("typedef int X; X a;",
    855                       varDecl(hasName("a"),
    856                               hasType(typedefType(hasDeclaration(decl()))))));
    857 
    858   // FIXME: Add tests for other types with getDecl() (e.g. RecordType)
    859 }
    860 
    861 TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
    862   EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
    863                       varDecl(hasType(templateSpecializationType(
    864                           hasDeclaration(namedDecl(hasName("A"))))))));
    865 }
    866 
    867 TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
    868   TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
    869   EXPECT_TRUE(
    870       matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
    871   EXPECT_TRUE(
    872       notMatches("class X {}; void y(X *x) { x; }",
    873                  expr(hasType(ClassX))));
    874   EXPECT_TRUE(
    875       matches("class X {}; void y(X *x) { x; }",
    876               expr(hasType(pointsTo(ClassX)))));
    877 }
    878 
    879 TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
    880   TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
    881   EXPECT_TRUE(
    882       matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
    883   EXPECT_TRUE(
    884       notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
    885   EXPECT_TRUE(
    886       matches("class X {}; void y() { X *x; }",
    887               varDecl(hasType(pointsTo(ClassX)))));
    888 }
    889 
    890 TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
    891   DeclarationMatcher ClassX = recordDecl(hasName("X"));
    892   EXPECT_TRUE(
    893       matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
    894   EXPECT_TRUE(
    895       notMatches("class X {}; void y(X *x) { x; }",
    896                  expr(hasType(ClassX))));
    897 }
    898 
    899 TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
    900   DeclarationMatcher ClassX = recordDecl(hasName("X"));
    901   EXPECT_TRUE(
    902       matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
    903   EXPECT_TRUE(
    904       notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
    905 }
    906 
    907 TEST(Matcher, Call) {
    908   // FIXME: Do we want to overload Call() to directly take
    909   // Matcher<Decl>, too?
    910   StatementMatcher MethodX = callExpr(hasDeclaration(methodDecl(hasName("x"))));
    911 
    912   EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
    913   EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
    914 
    915   StatementMatcher MethodOnY =
    916       memberCallExpr(on(hasType(recordDecl(hasName("Y")))));
    917 
    918   EXPECT_TRUE(
    919       matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
    920               MethodOnY));
    921   EXPECT_TRUE(
    922       matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
    923               MethodOnY));
    924   EXPECT_TRUE(
    925       notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
    926                  MethodOnY));
    927   EXPECT_TRUE(
    928       notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
    929                  MethodOnY));
    930   EXPECT_TRUE(
    931       notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
    932                  MethodOnY));
    933 
    934   StatementMatcher MethodOnYPointer =
    935       memberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
    936 
    937   EXPECT_TRUE(
    938       matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
    939               MethodOnYPointer));
    940   EXPECT_TRUE(
    941       matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
    942               MethodOnYPointer));
    943   EXPECT_TRUE(
    944       matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
    945               MethodOnYPointer));
    946   EXPECT_TRUE(
    947       notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
    948                  MethodOnYPointer));
    949   EXPECT_TRUE(
    950       notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
    951                  MethodOnYPointer));
    952 }
    953 
    954 TEST(Matcher, Lambda) {
    955   EXPECT_TRUE(matches("auto f = [&] (int i) { return i; };",
    956                       lambdaExpr()));
    957 }
    958 
    959 TEST(Matcher, ForRange) {
    960   EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
    961                       "void f() { for (auto &a : as); }",
    962                       forRangeStmt()));
    963   EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
    964                          forRangeStmt()));
    965 }
    966 
    967 TEST(Matcher, UserDefinedLiteral) {
    968   EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
    969                       "  return i + 1;"
    970                       "}"
    971                       "char c = 'a'_inc;",
    972                       userDefinedLiteral()));
    973 }
    974 
    975 TEST(Matcher, FlowControl) {
    976   EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
    977   EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
    978                       continueStmt()));
    979   EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
    980   EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
    981   EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
    982 }
    983 
    984 TEST(HasType, MatchesAsString) {
    985   EXPECT_TRUE(
    986       matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
    987               memberCallExpr(on(hasType(asString("class Y *"))))));
    988   EXPECT_TRUE(matches("class X { void x(int x) {} };",
    989       methodDecl(hasParameter(0, hasType(asString("int"))))));
    990   EXPECT_TRUE(matches("namespace ns { struct A {}; }  struct B { ns::A a; };",
    991       fieldDecl(hasType(asString("ns::A")))));
    992   EXPECT_TRUE(matches("namespace { struct A {}; }  struct B { A a; };",
    993       fieldDecl(hasType(asString("struct <anonymous>::A")))));
    994 }
    995 
    996 TEST(Matcher, OverloadedOperatorCall) {
    997   StatementMatcher OpCall = operatorCallExpr();
    998   // Unary operator
    999   EXPECT_TRUE(matches("class Y { }; "
   1000               "bool operator!(Y x) { return false; }; "
   1001               "Y y; bool c = !y;", OpCall));
   1002   // No match -- special operators like "new", "delete"
   1003   // FIXME: operator new takes size_t, for which we need stddef.h, for which
   1004   // we need to figure out include paths in the test.
   1005   // EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
   1006   //             "class Y { }; "
   1007   //             "void *operator new(size_t size) { return 0; } "
   1008   //             "Y *y = new Y;", OpCall));
   1009   EXPECT_TRUE(notMatches("class Y { }; "
   1010               "void operator delete(void *p) { } "
   1011               "void a() {Y *y = new Y; delete y;}", OpCall));
   1012   // Binary operator
   1013   EXPECT_TRUE(matches("class Y { }; "
   1014               "bool operator&&(Y x, Y y) { return true; }; "
   1015               "Y a; Y b; bool c = a && b;",
   1016               OpCall));
   1017   // No match -- normal operator, not an overloaded one.
   1018   EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
   1019   EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
   1020 }
   1021 
   1022 TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
   1023   StatementMatcher OpCallAndAnd =
   1024       operatorCallExpr(hasOverloadedOperatorName("&&"));
   1025   EXPECT_TRUE(matches("class Y { }; "
   1026               "bool operator&&(Y x, Y y) { return true; }; "
   1027               "Y a; Y b; bool c = a && b;", OpCallAndAnd));
   1028   StatementMatcher OpCallLessLess =
   1029       operatorCallExpr(hasOverloadedOperatorName("<<"));
   1030   EXPECT_TRUE(notMatches("class Y { }; "
   1031               "bool operator&&(Y x, Y y) { return true; }; "
   1032               "Y a; Y b; bool c = a && b;",
   1033               OpCallLessLess));
   1034   DeclarationMatcher ClassWithOpStar =
   1035     recordDecl(hasMethod(hasOverloadedOperatorName("*")));
   1036   EXPECT_TRUE(matches("class Y { int operator*(); };",
   1037                       ClassWithOpStar));
   1038   EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
   1039               ClassWithOpStar)) ;
   1040 }
   1041 
   1042 TEST(Matcher, NestedOverloadedOperatorCalls) {
   1043   EXPECT_TRUE(matchAndVerifyResultTrue(
   1044         "class Y { }; "
   1045         "Y& operator&&(Y& x, Y& y) { return x; }; "
   1046         "Y a; Y b; Y c; Y d = a && b && c;",
   1047         operatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
   1048         new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
   1049   EXPECT_TRUE(matches(
   1050         "class Y { }; "
   1051         "Y& operator&&(Y& x, Y& y) { return x; }; "
   1052         "Y a; Y b; Y c; Y d = a && b && c;",
   1053         operatorCallExpr(hasParent(operatorCallExpr()))));
   1054   EXPECT_TRUE(matches(
   1055         "class Y { }; "
   1056         "Y& operator&&(Y& x, Y& y) { return x; }; "
   1057         "Y a; Y b; Y c; Y d = a && b && c;",
   1058         operatorCallExpr(hasDescendant(operatorCallExpr()))));
   1059 }
   1060 
   1061 TEST(Matcher, ThisPointerType) {
   1062   StatementMatcher MethodOnY =
   1063     memberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
   1064 
   1065   EXPECT_TRUE(
   1066       matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
   1067               MethodOnY));
   1068   EXPECT_TRUE(
   1069       matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
   1070               MethodOnY));
   1071   EXPECT_TRUE(
   1072       matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
   1073               MethodOnY));
   1074   EXPECT_TRUE(
   1075       matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
   1076               MethodOnY));
   1077   EXPECT_TRUE(
   1078       matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
   1079               MethodOnY));
   1080 
   1081   EXPECT_TRUE(matches(
   1082       "class Y {"
   1083       "  public: virtual void x();"
   1084       "};"
   1085       "class X : public Y {"
   1086       "  public: virtual void x();"
   1087       "};"
   1088       "void z() { X *x; x->Y::x(); }", MethodOnY));
   1089 }
   1090 
   1091 TEST(Matcher, VariableUsage) {
   1092   StatementMatcher Reference =
   1093       declRefExpr(to(
   1094           varDecl(hasInitializer(
   1095               memberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
   1096 
   1097   EXPECT_TRUE(matches(
   1098       "class Y {"
   1099       " public:"
   1100       "  bool x() const;"
   1101       "};"
   1102       "void z(const Y &y) {"
   1103       "  bool b = y.x();"
   1104       "  if (b) {}"
   1105       "}", Reference));
   1106 
   1107   EXPECT_TRUE(notMatches(
   1108       "class Y {"
   1109       " public:"
   1110       "  bool x() const;"
   1111       "};"
   1112       "void z(const Y &y) {"
   1113       "  bool b = y.x();"
   1114       "}", Reference));
   1115 }
   1116 
   1117 TEST(Matcher, FindsVarDeclInFunctionParameter) {
   1118   EXPECT_TRUE(matches(
   1119       "void f(int i) {}",
   1120       varDecl(hasName("i"))));
   1121 }
   1122 
   1123 TEST(Matcher, CalledVariable) {
   1124   StatementMatcher CallOnVariableY =
   1125       memberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
   1126 
   1127   EXPECT_TRUE(matches(
   1128       "class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
   1129   EXPECT_TRUE(matches(
   1130       "class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
   1131   EXPECT_TRUE(matches(
   1132       "class Y { public: void x(); };"
   1133       "class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
   1134   EXPECT_TRUE(matches(
   1135       "class Y { public: void x(); };"
   1136       "class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
   1137   EXPECT_TRUE(notMatches(
   1138       "class Y { public: void x(); };"
   1139       "class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
   1140       CallOnVariableY));
   1141 }
   1142 
   1143 TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
   1144   EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
   1145                       unaryExprOrTypeTraitExpr()));
   1146   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
   1147                          alignOfExpr(anything())));
   1148   // FIXME: Uncomment once alignof is enabled.
   1149   // EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
   1150   //                     unaryExprOrTypeTraitExpr()));
   1151   // EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
   1152   //                        sizeOfExpr()));
   1153 }
   1154 
   1155 TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
   1156   EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
   1157       hasArgumentOfType(asString("int")))));
   1158   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
   1159       hasArgumentOfType(asString("float")))));
   1160   EXPECT_TRUE(matches(
   1161       "struct A {}; void x() { A a; int b = sizeof(a); }",
   1162       sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
   1163   EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
   1164       hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
   1165 }
   1166 
   1167 TEST(MemberExpression, DoesNotMatchClasses) {
   1168   EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
   1169 }
   1170 
   1171 TEST(MemberExpression, MatchesMemberFunctionCall) {
   1172   EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
   1173 }
   1174 
   1175 TEST(MemberExpression, MatchesVariable) {
   1176   EXPECT_TRUE(
   1177       matches("class Y { void x() { this->y; } int y; };", memberExpr()));
   1178   EXPECT_TRUE(
   1179       matches("class Y { void x() { y; } int y; };", memberExpr()));
   1180   EXPECT_TRUE(
   1181       matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
   1182 }
   1183 
   1184 TEST(MemberExpression, MatchesStaticVariable) {
   1185   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
   1186               memberExpr()));
   1187   EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
   1188               memberExpr()));
   1189   EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
   1190               memberExpr()));
   1191 }
   1192 
   1193 TEST(IsInteger, MatchesIntegers) {
   1194   EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
   1195   EXPECT_TRUE(matches(
   1196       "long long i = 0; void f(long long) { }; void g() {f(i);}",
   1197       callExpr(hasArgument(0, declRefExpr(
   1198                                   to(varDecl(hasType(isInteger()))))))));
   1199 }
   1200 
   1201 TEST(IsInteger, ReportsNoFalsePositives) {
   1202   EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
   1203   EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
   1204                       callExpr(hasArgument(0, declRefExpr(
   1205                           to(varDecl(hasType(isInteger()))))))));
   1206 }
   1207 
   1208 TEST(IsArrow, MatchesMemberVariablesViaArrow) {
   1209   EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
   1210               memberExpr(isArrow())));
   1211   EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
   1212               memberExpr(isArrow())));
   1213   EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
   1214               memberExpr(isArrow())));
   1215 }
   1216 
   1217 TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
   1218   EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
   1219               memberExpr(isArrow())));
   1220   EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
   1221               memberExpr(isArrow())));
   1222   EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
   1223               memberExpr(isArrow())));
   1224 }
   1225 
   1226 TEST(IsArrow, MatchesMemberCallsViaArrow) {
   1227   EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
   1228               memberExpr(isArrow())));
   1229   EXPECT_TRUE(matches("class Y { void x() { x(); } };",
   1230               memberExpr(isArrow())));
   1231   EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
   1232               memberExpr(isArrow())));
   1233 }
   1234 
   1235 TEST(Callee, MatchesDeclarations) {
   1236   StatementMatcher CallMethodX = callExpr(callee(methodDecl(hasName("x"))));
   1237 
   1238   EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
   1239   EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
   1240 }
   1241 
   1242 TEST(Callee, MatchesMemberExpressions) {
   1243   EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
   1244               callExpr(callee(memberExpr()))));
   1245   EXPECT_TRUE(
   1246       notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
   1247 }
   1248 
   1249 TEST(Function, MatchesFunctionDeclarations) {
   1250   StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
   1251 
   1252   EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
   1253   EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
   1254 
   1255 #if !defined(_MSC_VER)
   1256   // FIXME: Make this work for MSVC.
   1257   // Dependent contexts, but a non-dependent call.
   1258   EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
   1259                       CallFunctionF));
   1260   EXPECT_TRUE(
   1261       matches("void f(); template <int N> struct S { void g() { f(); } };",
   1262               CallFunctionF));
   1263 #endif
   1264 
   1265   // Depedent calls don't match.
   1266   EXPECT_TRUE(
   1267       notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
   1268                  CallFunctionF));
   1269   EXPECT_TRUE(
   1270       notMatches("void f(int);"
   1271                  "template <typename T> struct S { void g(T t) { f(t); } };",
   1272                  CallFunctionF));
   1273 }
   1274 
   1275 TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
   1276   EXPECT_TRUE(
   1277       matches("template <typename T> void f(T t) {}",
   1278       functionTemplateDecl(hasName("f"))));
   1279 }
   1280 
   1281 TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
   1282   EXPECT_TRUE(
   1283       notMatches("void f(double d); void f(int t) {}",
   1284       functionTemplateDecl(hasName("f"))));
   1285 }
   1286 
   1287 TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
   1288   EXPECT_TRUE(
   1289       notMatches("void g(); template <typename T> void f(T t) {}"
   1290                  "template <> void f(int t) { g(); }",
   1291       functionTemplateDecl(hasName("f"),
   1292                            hasDescendant(declRefExpr(to(
   1293                                functionDecl(hasName("g"))))))));
   1294 }
   1295 
   1296 TEST(Matcher, Argument) {
   1297   StatementMatcher CallArgumentY = callExpr(
   1298       hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
   1299 
   1300   EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
   1301   EXPECT_TRUE(
   1302       matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
   1303   EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
   1304 
   1305   StatementMatcher WrongIndex = callExpr(
   1306       hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
   1307   EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
   1308 }
   1309 
   1310 TEST(Matcher, AnyArgument) {
   1311   StatementMatcher CallArgumentY = callExpr(
   1312       hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
   1313   EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
   1314   EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
   1315   EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
   1316 }
   1317 
   1318 TEST(Matcher, ArgumentCount) {
   1319   StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
   1320 
   1321   EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
   1322   EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
   1323   EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
   1324 }
   1325 
   1326 TEST(Matcher, ParameterCount) {
   1327   DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
   1328   EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
   1329   EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
   1330   EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
   1331   EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
   1332 }
   1333 
   1334 TEST(Matcher, References) {
   1335   DeclarationMatcher ReferenceClassX = varDecl(
   1336       hasType(references(recordDecl(hasName("X")))));
   1337   EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
   1338                       ReferenceClassX));
   1339   EXPECT_TRUE(
   1340       matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
   1341   EXPECT_TRUE(
   1342       notMatches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
   1343   EXPECT_TRUE(
   1344       notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
   1345 }
   1346 
   1347 TEST(QualType, hasCanonicalType) {
   1348   EXPECT_TRUE(notMatches("typedef int &int_ref;"
   1349                          "int a;"
   1350                          "int_ref b = a;",
   1351                          varDecl(hasType(qualType(referenceType())))));
   1352   EXPECT_TRUE(
   1353       matches("typedef int &int_ref;"
   1354               "int a;"
   1355               "int_ref b = a;",
   1356               varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
   1357 }
   1358 
   1359 TEST(HasParameter, CallsInnerMatcher) {
   1360   EXPECT_TRUE(matches("class X { void x(int) {} };",
   1361       methodDecl(hasParameter(0, varDecl()))));
   1362   EXPECT_TRUE(notMatches("class X { void x(int) {} };",
   1363       methodDecl(hasParameter(0, hasName("x")))));
   1364 }
   1365 
   1366 TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
   1367   EXPECT_TRUE(notMatches("class X { void x(int) {} };",
   1368       methodDecl(hasParameter(42, varDecl()))));
   1369 }
   1370 
   1371 TEST(HasType, MatchesParameterVariableTypesStrictly) {
   1372   EXPECT_TRUE(matches("class X { void x(X x) {} };",
   1373       methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
   1374   EXPECT_TRUE(notMatches("class X { void x(const X &x) {} };",
   1375       methodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
   1376   EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
   1377       methodDecl(hasParameter(0,
   1378                               hasType(pointsTo(recordDecl(hasName("X"))))))));
   1379   EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
   1380       methodDecl(hasParameter(0,
   1381                               hasType(references(recordDecl(hasName("X"))))))));
   1382 }
   1383 
   1384 TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
   1385   EXPECT_TRUE(matches("class Y {}; class X { void x(X x, Y y) {} };",
   1386       methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
   1387   EXPECT_TRUE(matches("class Y {}; class X { void x(Y y, X x) {} };",
   1388       methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
   1389 }
   1390 
   1391 TEST(Returns, MatchesReturnTypes) {
   1392   EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
   1393                       functionDecl(returns(asString("int")))));
   1394   EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
   1395                          functionDecl(returns(asString("float")))));
   1396   EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
   1397                       functionDecl(returns(hasDeclaration(
   1398                           recordDecl(hasName("Y")))))));
   1399 }
   1400 
   1401 TEST(IsExternC, MatchesExternCFunctionDeclarations) {
   1402   EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
   1403   EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
   1404               functionDecl(isExternC())));
   1405   EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
   1406 }
   1407 
   1408 TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
   1409   EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
   1410       methodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
   1411 }
   1412 
   1413 TEST(HasAnyParameter, DoesNotMatchThisPointer) {
   1414   EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
   1415       methodDecl(hasAnyParameter(hasType(pointsTo(
   1416           recordDecl(hasName("X"))))))));
   1417 }
   1418 
   1419 TEST(HasName, MatchesParameterVariableDeclartions) {
   1420   EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
   1421       methodDecl(hasAnyParameter(hasName("x")))));
   1422   EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
   1423       methodDecl(hasAnyParameter(hasName("x")))));
   1424 }
   1425 
   1426 TEST(Matcher, MatchesClassTemplateSpecialization) {
   1427   EXPECT_TRUE(matches("template<typename T> struct A {};"
   1428                       "template<> struct A<int> {};",
   1429                       classTemplateSpecializationDecl()));
   1430   EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
   1431                       classTemplateSpecializationDecl()));
   1432   EXPECT_TRUE(notMatches("template<typename T> struct A {};",
   1433                          classTemplateSpecializationDecl()));
   1434 }
   1435 
   1436 TEST(Matcher, MatchesTypeTemplateArgument) {
   1437   EXPECT_TRUE(matches(
   1438       "template<typename T> struct B {};"
   1439       "B<int> b;",
   1440       classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
   1441           asString("int"))))));
   1442 }
   1443 
   1444 TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
   1445   EXPECT_TRUE(matches(
   1446       "struct B { int next; };"
   1447       "template<int(B::*next_ptr)> struct A {};"
   1448       "A<&B::next> a;",
   1449       classTemplateSpecializationDecl(hasAnyTemplateArgument(
   1450           refersToDeclaration(fieldDecl(hasName("next")))))));
   1451 
   1452   EXPECT_TRUE(notMatches(
   1453       "template <typename T> struct A {};"
   1454       "A<int> a;",
   1455       classTemplateSpecializationDecl(hasAnyTemplateArgument(
   1456           refersToDeclaration(decl())))));
   1457 }
   1458 
   1459 TEST(Matcher, MatchesSpecificArgument) {
   1460   EXPECT_TRUE(matches(
   1461       "template<typename T, typename U> class A {};"
   1462       "A<bool, int> a;",
   1463       classTemplateSpecializationDecl(hasTemplateArgument(
   1464           1, refersToType(asString("int"))))));
   1465   EXPECT_TRUE(notMatches(
   1466       "template<typename T, typename U> class A {};"
   1467       "A<int, bool> a;",
   1468       classTemplateSpecializationDecl(hasTemplateArgument(
   1469           1, refersToType(asString("int"))))));
   1470 }
   1471 
   1472 TEST(Matcher, MatchesAccessSpecDecls) {
   1473   EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
   1474   EXPECT_TRUE(
   1475       matches("class C { public: int i; };", accessSpecDecl(isPublic())));
   1476   EXPECT_TRUE(
   1477       notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
   1478   EXPECT_TRUE(
   1479       notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
   1480 
   1481   EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
   1482 }
   1483 
   1484 TEST(Matcher, ConstructorCall) {
   1485   StatementMatcher Constructor = constructExpr();
   1486 
   1487   EXPECT_TRUE(
   1488       matches("class X { public: X(); }; void x() { X x; }", Constructor));
   1489   EXPECT_TRUE(
   1490       matches("class X { public: X(); }; void x() { X x = X(); }",
   1491               Constructor));
   1492   EXPECT_TRUE(
   1493       matches("class X { public: X(int); }; void x() { X x = 0; }",
   1494               Constructor));
   1495   EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
   1496 }
   1497 
   1498 TEST(Matcher, ConstructorArgument) {
   1499   StatementMatcher Constructor = constructExpr(
   1500       hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
   1501 
   1502   EXPECT_TRUE(
   1503       matches("class X { public: X(int); }; void x() { int y; X x(y); }",
   1504               Constructor));
   1505   EXPECT_TRUE(
   1506       matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
   1507               Constructor));
   1508   EXPECT_TRUE(
   1509       matches("class X { public: X(int); }; void x() { int y; X x = y; }",
   1510               Constructor));
   1511   EXPECT_TRUE(
   1512       notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
   1513                  Constructor));
   1514 
   1515   StatementMatcher WrongIndex = constructExpr(
   1516       hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
   1517   EXPECT_TRUE(
   1518       notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
   1519                  WrongIndex));
   1520 }
   1521 
   1522 TEST(Matcher, ConstructorArgumentCount) {
   1523   StatementMatcher Constructor1Arg = constructExpr(argumentCountIs(1));
   1524 
   1525   EXPECT_TRUE(
   1526       matches("class X { public: X(int); }; void x() { X x(0); }",
   1527               Constructor1Arg));
   1528   EXPECT_TRUE(
   1529       matches("class X { public: X(int); }; void x() { X x = X(0); }",
   1530               Constructor1Arg));
   1531   EXPECT_TRUE(
   1532       matches("class X { public: X(int); }; void x() { X x = 0; }",
   1533               Constructor1Arg));
   1534   EXPECT_TRUE(
   1535       notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
   1536                  Constructor1Arg));
   1537 }
   1538 
   1539 TEST(Matcher,ThisExpr) {
   1540   EXPECT_TRUE(
   1541       matches("struct X { int a; int f () { return a; } };", thisExpr()));
   1542   EXPECT_TRUE(
   1543       notMatches("struct X { int f () { int a; return a; } };", thisExpr()));
   1544 }
   1545 
   1546 TEST(Matcher, BindTemporaryExpression) {
   1547   StatementMatcher TempExpression = bindTemporaryExpr();
   1548 
   1549   std::string ClassString = "class string { public: string(); ~string(); }; ";
   1550 
   1551   EXPECT_TRUE(
   1552       matches(ClassString +
   1553               "string GetStringByValue();"
   1554               "void FunctionTakesString(string s);"
   1555               "void run() { FunctionTakesString(GetStringByValue()); }",
   1556               TempExpression));
   1557 
   1558   EXPECT_TRUE(
   1559       notMatches(ClassString +
   1560                  "string* GetStringPointer(); "
   1561                  "void FunctionTakesStringPtr(string* s);"
   1562                  "void run() {"
   1563                  "  string* s = GetStringPointer();"
   1564                  "  FunctionTakesStringPtr(GetStringPointer());"
   1565                  "  FunctionTakesStringPtr(s);"
   1566                  "}",
   1567                  TempExpression));
   1568 
   1569   EXPECT_TRUE(
   1570       notMatches("class no_dtor {};"
   1571                  "no_dtor GetObjByValue();"
   1572                  "void ConsumeObj(no_dtor param);"
   1573                  "void run() { ConsumeObj(GetObjByValue()); }",
   1574                  TempExpression));
   1575 }
   1576 
   1577 TEST(MaterializeTemporaryExpr, MatchesTemporary) {
   1578   std::string ClassString =
   1579       "class string { public: string(); int length(); }; ";
   1580 
   1581   EXPECT_TRUE(
   1582       matches(ClassString +
   1583               "string GetStringByValue();"
   1584               "void FunctionTakesString(string s);"
   1585               "void run() { FunctionTakesString(GetStringByValue()); }",
   1586               materializeTemporaryExpr()));
   1587 
   1588   EXPECT_TRUE(
   1589       notMatches(ClassString +
   1590                  "string* GetStringPointer(); "
   1591                  "void FunctionTakesStringPtr(string* s);"
   1592                  "void run() {"
   1593                  "  string* s = GetStringPointer();"
   1594                  "  FunctionTakesStringPtr(GetStringPointer());"
   1595                  "  FunctionTakesStringPtr(s);"
   1596                  "}",
   1597                  materializeTemporaryExpr()));
   1598 
   1599   EXPECT_TRUE(
   1600       notMatches(ClassString +
   1601                  "string GetStringByValue();"
   1602                  "void run() { int k = GetStringByValue().length(); }",
   1603                  materializeTemporaryExpr()));
   1604 
   1605   EXPECT_TRUE(
   1606       notMatches(ClassString +
   1607                  "string GetStringByValue();"
   1608                  "void run() { GetStringByValue(); }",
   1609                  materializeTemporaryExpr()));
   1610 }
   1611 
   1612 TEST(ConstructorDeclaration, SimpleCase) {
   1613   EXPECT_TRUE(matches("class Foo { Foo(int i); };",
   1614                       constructorDecl(ofClass(hasName("Foo")))));
   1615   EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
   1616                          constructorDecl(ofClass(hasName("Bar")))));
   1617 }
   1618 
   1619 TEST(ConstructorDeclaration, IsImplicit) {
   1620   // This one doesn't match because the constructor is not added by the
   1621   // compiler (it is not needed).
   1622   EXPECT_TRUE(notMatches("class Foo { };",
   1623                          constructorDecl(isImplicit())));
   1624   // The compiler added the implicit default constructor.
   1625   EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
   1626                       constructorDecl(isImplicit())));
   1627   EXPECT_TRUE(matches("class Foo { Foo(){} };",
   1628                       constructorDecl(unless(isImplicit()))));
   1629 }
   1630 
   1631 TEST(DestructorDeclaration, MatchesVirtualDestructor) {
   1632   EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
   1633                       destructorDecl(ofClass(hasName("Foo")))));
   1634 }
   1635 
   1636 TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
   1637   EXPECT_TRUE(notMatches("class Foo {};",
   1638                          destructorDecl(ofClass(hasName("Foo")))));
   1639 }
   1640 
   1641 TEST(HasAnyConstructorInitializer, SimpleCase) {
   1642   EXPECT_TRUE(notMatches(
   1643       "class Foo { Foo() { } };",
   1644       constructorDecl(hasAnyConstructorInitializer(anything()))));
   1645   EXPECT_TRUE(matches(
   1646       "class Foo {"
   1647       "  Foo() : foo_() { }"
   1648       "  int foo_;"
   1649       "};",
   1650       constructorDecl(hasAnyConstructorInitializer(anything()))));
   1651 }
   1652 
   1653 TEST(HasAnyConstructorInitializer, ForField) {
   1654   static const char Code[] =
   1655       "class Baz { };"
   1656       "class Foo {"
   1657       "  Foo() : foo_() { }"
   1658       "  Baz foo_;"
   1659       "  Baz bar_;"
   1660       "};";
   1661   EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
   1662       forField(hasType(recordDecl(hasName("Baz"))))))));
   1663   EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
   1664       forField(hasName("foo_"))))));
   1665   EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
   1666       forField(hasType(recordDecl(hasName("Bar"))))))));
   1667 }
   1668 
   1669 TEST(HasAnyConstructorInitializer, WithInitializer) {
   1670   static const char Code[] =
   1671       "class Foo {"
   1672       "  Foo() : foo_(0) { }"
   1673       "  int foo_;"
   1674       "};";
   1675   EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
   1676       withInitializer(integerLiteral(equals(0)))))));
   1677   EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
   1678       withInitializer(integerLiteral(equals(1)))))));
   1679 }
   1680 
   1681 TEST(HasAnyConstructorInitializer, IsWritten) {
   1682   static const char Code[] =
   1683       "struct Bar { Bar(){} };"
   1684       "class Foo {"
   1685       "  Foo() : foo_() { }"
   1686       "  Bar foo_;"
   1687       "  Bar bar_;"
   1688       "};";
   1689   EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
   1690       allOf(forField(hasName("foo_")), isWritten())))));
   1691   EXPECT_TRUE(notMatches(Code, constructorDecl(hasAnyConstructorInitializer(
   1692       allOf(forField(hasName("bar_")), isWritten())))));
   1693   EXPECT_TRUE(matches(Code, constructorDecl(hasAnyConstructorInitializer(
   1694       allOf(forField(hasName("bar_")), unless(isWritten()))))));
   1695 }
   1696 
   1697 TEST(Matcher, NewExpression) {
   1698   StatementMatcher New = newExpr();
   1699 
   1700   EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
   1701   EXPECT_TRUE(
   1702       matches("class X { public: X(); }; void x() { new X(); }", New));
   1703   EXPECT_TRUE(
   1704       matches("class X { public: X(int); }; void x() { new X(0); }", New));
   1705   EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
   1706 }
   1707 
   1708 TEST(Matcher, NewExpressionArgument) {
   1709   StatementMatcher New = constructExpr(
   1710       hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
   1711 
   1712   EXPECT_TRUE(
   1713       matches("class X { public: X(int); }; void x() { int y; new X(y); }",
   1714               New));
   1715   EXPECT_TRUE(
   1716       matches("class X { public: X(int); }; void x() { int y; new X(y); }",
   1717               New));
   1718   EXPECT_TRUE(
   1719       notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
   1720                  New));
   1721 
   1722   StatementMatcher WrongIndex = constructExpr(
   1723       hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
   1724   EXPECT_TRUE(
   1725       notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
   1726                  WrongIndex));
   1727 }
   1728 
   1729 TEST(Matcher, NewExpressionArgumentCount) {
   1730   StatementMatcher New = constructExpr(argumentCountIs(1));
   1731 
   1732   EXPECT_TRUE(
   1733       matches("class X { public: X(int); }; void x() { new X(0); }", New));
   1734   EXPECT_TRUE(
   1735       notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
   1736                  New));
   1737 }
   1738 
   1739 TEST(Matcher, DeleteExpression) {
   1740   EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
   1741                       deleteExpr()));
   1742 }
   1743 
   1744 TEST(Matcher, DefaultArgument) {
   1745   StatementMatcher Arg = defaultArgExpr();
   1746 
   1747   EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
   1748   EXPECT_TRUE(
   1749       matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
   1750   EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
   1751 }
   1752 
   1753 TEST(Matcher, StringLiterals) {
   1754   StatementMatcher Literal = stringLiteral();
   1755   EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
   1756   // wide string
   1757   EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
   1758   // with escaped characters
   1759   EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
   1760   // no matching -- though the data type is the same, there is no string literal
   1761   EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
   1762 }
   1763 
   1764 TEST(Matcher, CharacterLiterals) {
   1765   StatementMatcher CharLiteral = characterLiteral();
   1766   EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
   1767   // wide character
   1768   EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
   1769   // wide character, Hex encoded, NOT MATCHED!
   1770   EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
   1771   EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
   1772 }
   1773 
   1774 TEST(Matcher, IntegerLiterals) {
   1775   StatementMatcher HasIntLiteral = integerLiteral();
   1776   EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
   1777   EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
   1778   EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
   1779   EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
   1780 
   1781   // Non-matching cases (character literals, float and double)
   1782   EXPECT_TRUE(notMatches("int i = L'a';",
   1783                 HasIntLiteral));  // this is actually a character
   1784                                   // literal cast to int
   1785   EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
   1786   EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
   1787   EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
   1788 }
   1789 
   1790 TEST(Matcher, NullPtrLiteral) {
   1791   EXPECT_TRUE(matches("int* i = nullptr;", nullPtrLiteralExpr()));
   1792 }
   1793 
   1794 TEST(Matcher, AsmStatement) {
   1795   EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
   1796 }
   1797 
   1798 TEST(Matcher, Conditions) {
   1799   StatementMatcher Condition = ifStmt(hasCondition(boolLiteral(equals(true))));
   1800 
   1801   EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
   1802   EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
   1803   EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
   1804   EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
   1805   EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
   1806 }
   1807 
   1808 TEST(MatchBinaryOperator, HasOperatorName) {
   1809   StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
   1810 
   1811   EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
   1812   EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
   1813 }
   1814 
   1815 TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
   1816   StatementMatcher OperatorTrueFalse =
   1817       binaryOperator(hasLHS(boolLiteral(equals(true))),
   1818                      hasRHS(boolLiteral(equals(false))));
   1819 
   1820   EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
   1821   EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
   1822   EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
   1823 }
   1824 
   1825 TEST(MatchBinaryOperator, HasEitherOperand) {
   1826   StatementMatcher HasOperand =
   1827       binaryOperator(hasEitherOperand(boolLiteral(equals(false))));
   1828 
   1829   EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
   1830   EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
   1831   EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
   1832 }
   1833 
   1834 TEST(Matcher, BinaryOperatorTypes) {
   1835   // Integration test that verifies the AST provides all binary operators in
   1836   // a way we expect.
   1837   // FIXME: Operator ','
   1838   EXPECT_TRUE(
   1839       matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
   1840   EXPECT_TRUE(
   1841       matches("bool b; bool c = (b = true);",
   1842               binaryOperator(hasOperatorName("="))));
   1843   EXPECT_TRUE(
   1844       matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
   1845   EXPECT_TRUE(
   1846       matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
   1847   EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
   1848   EXPECT_TRUE(
   1849       matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
   1850   EXPECT_TRUE(
   1851       matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
   1852   EXPECT_TRUE(
   1853       matches("int i = 1; int j = (i <<= 2);",
   1854               binaryOperator(hasOperatorName("<<="))));
   1855   EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
   1856   EXPECT_TRUE(
   1857       matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
   1858   EXPECT_TRUE(
   1859       matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
   1860   EXPECT_TRUE(
   1861       matches("int i = 1; int j = (i >>= 2);",
   1862               binaryOperator(hasOperatorName(">>="))));
   1863   EXPECT_TRUE(
   1864       matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
   1865   EXPECT_TRUE(
   1866       matches("int i = 42; int j = (i ^= 42);",
   1867               binaryOperator(hasOperatorName("^="))));
   1868   EXPECT_TRUE(
   1869       matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
   1870   EXPECT_TRUE(
   1871       matches("int i = 42; int j = (i %= 42);",
   1872               binaryOperator(hasOperatorName("%="))));
   1873   EXPECT_TRUE(
   1874       matches("bool b = 42  &23;", binaryOperator(hasOperatorName("&"))));
   1875   EXPECT_TRUE(
   1876       matches("bool b = true && false;",
   1877               binaryOperator(hasOperatorName("&&"))));
   1878   EXPECT_TRUE(
   1879       matches("bool b = true; bool c = (b &= false);",
   1880               binaryOperator(hasOperatorName("&="))));
   1881   EXPECT_TRUE(
   1882       matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
   1883   EXPECT_TRUE(
   1884       matches("bool b = true || false;",
   1885               binaryOperator(hasOperatorName("||"))));
   1886   EXPECT_TRUE(
   1887       matches("bool b = true; bool c = (b |= false);",
   1888               binaryOperator(hasOperatorName("|="))));
   1889   EXPECT_TRUE(
   1890       matches("int i = 42  *23;", binaryOperator(hasOperatorName("*"))));
   1891   EXPECT_TRUE(
   1892       matches("int i = 42; int j = (i *= 23);",
   1893               binaryOperator(hasOperatorName("*="))));
   1894   EXPECT_TRUE(
   1895       matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
   1896   EXPECT_TRUE(
   1897       matches("int i = 42; int j = (i /= 23);",
   1898               binaryOperator(hasOperatorName("/="))));
   1899   EXPECT_TRUE(
   1900       matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
   1901   EXPECT_TRUE(
   1902       matches("int i = 42; int j = (i += 23);",
   1903               binaryOperator(hasOperatorName("+="))));
   1904   EXPECT_TRUE(
   1905       matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
   1906   EXPECT_TRUE(
   1907       matches("int i = 42; int j = (i -= 23);",
   1908               binaryOperator(hasOperatorName("-="))));
   1909   EXPECT_TRUE(
   1910       matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
   1911               binaryOperator(hasOperatorName("->*"))));
   1912   EXPECT_TRUE(
   1913       matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
   1914               binaryOperator(hasOperatorName(".*"))));
   1915 
   1916   // Member expressions as operators are not supported in matches.
   1917   EXPECT_TRUE(
   1918       notMatches("struct A { void x(A *a) { a->x(this); } };",
   1919                  binaryOperator(hasOperatorName("->"))));
   1920 
   1921   // Initializer assignments are not represented as operator equals.
   1922   EXPECT_TRUE(
   1923       notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
   1924 
   1925   // Array indexing is not represented as operator.
   1926   EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
   1927 
   1928   // Overloaded operators do not match at all.
   1929   EXPECT_TRUE(notMatches(
   1930       "struct A { bool operator&&(const A &a) const { return false; } };"
   1931       "void x() { A a, b; a && b; }",
   1932       binaryOperator()));
   1933 }
   1934 
   1935 TEST(MatchUnaryOperator, HasOperatorName) {
   1936   StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
   1937 
   1938   EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
   1939   EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
   1940 }
   1941 
   1942 TEST(MatchUnaryOperator, HasUnaryOperand) {
   1943   StatementMatcher OperatorOnFalse =
   1944       unaryOperator(hasUnaryOperand(boolLiteral(equals(false))));
   1945 
   1946   EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
   1947   EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
   1948 }
   1949 
   1950 TEST(Matcher, UnaryOperatorTypes) {
   1951   // Integration test that verifies the AST provides all unary operators in
   1952   // a way we expect.
   1953   EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
   1954   EXPECT_TRUE(
   1955       matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
   1956   EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
   1957   EXPECT_TRUE(
   1958       matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
   1959   EXPECT_TRUE(
   1960       matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
   1961   EXPECT_TRUE(
   1962       matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
   1963   EXPECT_TRUE(
   1964       matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
   1965   EXPECT_TRUE(
   1966       matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
   1967   EXPECT_TRUE(
   1968       matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
   1969   EXPECT_TRUE(
   1970       matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
   1971 
   1972   // We don't match conversion operators.
   1973   EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
   1974 
   1975   // Function calls are not represented as operator.
   1976   EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
   1977 
   1978   // Overloaded operators do not match at all.
   1979   // FIXME: We probably want to add that.
   1980   EXPECT_TRUE(notMatches(
   1981       "struct A { bool operator!() const { return false; } };"
   1982       "void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
   1983 }
   1984 
   1985 TEST(Matcher, ConditionalOperator) {
   1986   StatementMatcher Conditional = conditionalOperator(
   1987       hasCondition(boolLiteral(equals(true))),
   1988       hasTrueExpression(boolLiteral(equals(false))));
   1989 
   1990   EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
   1991   EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
   1992   EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
   1993 
   1994   StatementMatcher ConditionalFalse = conditionalOperator(
   1995       hasFalseExpression(boolLiteral(equals(false))));
   1996 
   1997   EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
   1998   EXPECT_TRUE(
   1999       notMatches("void x() { true ? false : true; }", ConditionalFalse));
   2000 }
   2001 
   2002 TEST(ArraySubscriptMatchers, ArraySubscripts) {
   2003   EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
   2004                       arraySubscriptExpr()));
   2005   EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
   2006                          arraySubscriptExpr()));
   2007 }
   2008 
   2009 TEST(ArraySubscriptMatchers, ArrayIndex) {
   2010   EXPECT_TRUE(matches(
   2011       "int i[2]; void f() { i[1] = 1; }",
   2012       arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
   2013   EXPECT_TRUE(matches(
   2014       "int i[2]; void f() { 1[i] = 1; }",
   2015       arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
   2016   EXPECT_TRUE(notMatches(
   2017       "int i[2]; void f() { i[1] = 1; }",
   2018       arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
   2019 }
   2020 
   2021 TEST(ArraySubscriptMatchers, MatchesArrayBase) {
   2022   EXPECT_TRUE(matches(
   2023       "int i[2]; void f() { i[1] = 2; }",
   2024       arraySubscriptExpr(hasBase(implicitCastExpr(
   2025           hasSourceExpression(declRefExpr()))))));
   2026 }
   2027 
   2028 TEST(Matcher, HasNameSupportsNamespaces) {
   2029   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
   2030               recordDecl(hasName("a::b::C"))));
   2031   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
   2032               recordDecl(hasName("::a::b::C"))));
   2033   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
   2034               recordDecl(hasName("b::C"))));
   2035   EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
   2036               recordDecl(hasName("C"))));
   2037   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2038               recordDecl(hasName("c::b::C"))));
   2039   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2040               recordDecl(hasName("a::c::C"))));
   2041   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2042               recordDecl(hasName("a::b::A"))));
   2043   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2044               recordDecl(hasName("::C"))));
   2045   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2046               recordDecl(hasName("::b::C"))));
   2047   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2048               recordDecl(hasName("z::a::b::C"))));
   2049   EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
   2050               recordDecl(hasName("a+b::C"))));
   2051   EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
   2052               recordDecl(hasName("C"))));
   2053 }
   2054 
   2055 TEST(Matcher, HasNameSupportsOuterClasses) {
   2056   EXPECT_TRUE(
   2057       matches("class A { class B { class C; }; };",
   2058               recordDecl(hasName("A::B::C"))));
   2059   EXPECT_TRUE(
   2060       matches("class A { class B { class C; }; };",
   2061               recordDecl(hasName("::A::B::C"))));
   2062   EXPECT_TRUE(
   2063       matches("class A { class B { class C; }; };",
   2064               recordDecl(hasName("B::C"))));
   2065   EXPECT_TRUE(
   2066       matches("class A { class B { class C; }; };",
   2067               recordDecl(hasName("C"))));
   2068   EXPECT_TRUE(
   2069       notMatches("class A { class B { class C; }; };",
   2070                  recordDecl(hasName("c::B::C"))));
   2071   EXPECT_TRUE(
   2072       notMatches("class A { class B { class C; }; };",
   2073                  recordDecl(hasName("A::c::C"))));
   2074   EXPECT_TRUE(
   2075       notMatches("class A { class B { class C; }; };",
   2076                  recordDecl(hasName("A::B::A"))));
   2077   EXPECT_TRUE(
   2078       notMatches("class A { class B { class C; }; };",
   2079                  recordDecl(hasName("::C"))));
   2080   EXPECT_TRUE(
   2081       notMatches("class A { class B { class C; }; };",
   2082                  recordDecl(hasName("::B::C"))));
   2083   EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
   2084               recordDecl(hasName("z::A::B::C"))));
   2085   EXPECT_TRUE(
   2086       notMatches("class A { class B { class C; }; };",
   2087                  recordDecl(hasName("A+B::C"))));
   2088 }
   2089 
   2090 TEST(Matcher, IsDefinition) {
   2091   DeclarationMatcher DefinitionOfClassA =
   2092       recordDecl(hasName("A"), isDefinition());
   2093   EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
   2094   EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
   2095 
   2096   DeclarationMatcher DefinitionOfVariableA =
   2097       varDecl(hasName("a"), isDefinition());
   2098   EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
   2099   EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
   2100 
   2101   DeclarationMatcher DefinitionOfMethodA =
   2102       methodDecl(hasName("a"), isDefinition());
   2103   EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
   2104   EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
   2105 }
   2106 
   2107 TEST(Matcher, OfClass) {
   2108   StatementMatcher Constructor = constructExpr(hasDeclaration(methodDecl(
   2109       ofClass(hasName("X")))));
   2110 
   2111   EXPECT_TRUE(
   2112       matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
   2113   EXPECT_TRUE(
   2114       matches("class X { public: X(); }; void x(int) { X x = X(); }",
   2115               Constructor));
   2116   EXPECT_TRUE(
   2117       notMatches("class Y { public: Y(); }; void x(int) { Y y; }",
   2118                  Constructor));
   2119 }
   2120 
   2121 TEST(Matcher, VisitsTemplateInstantiations) {
   2122   EXPECT_TRUE(matches(
   2123       "class A { public: void x(); };"
   2124       "template <typename T> class B { public: void y() { T t; t.x(); } };"
   2125       "void f() { B<A> b; b.y(); }",
   2126       callExpr(callee(methodDecl(hasName("x"))))));
   2127 
   2128   EXPECT_TRUE(matches(
   2129       "class A { public: void x(); };"
   2130       "class C {"
   2131       " public:"
   2132       "  template <typename T> class B { public: void y() { T t; t.x(); } };"
   2133       "};"
   2134       "void f() {"
   2135       "  C::B<A> b; b.y();"
   2136       "}",
   2137       recordDecl(hasName("C"),
   2138                  hasDescendant(callExpr(callee(methodDecl(hasName("x"))))))));
   2139 }
   2140 
   2141 TEST(Matcher, HandlesNullQualTypes) {
   2142   // FIXME: Add a Type matcher so we can replace uses of this
   2143   // variable with Type(True())
   2144   const TypeMatcher AnyType = anything();
   2145 
   2146   // We don't really care whether this matcher succeeds; we're testing that
   2147   // it completes without crashing.
   2148   EXPECT_TRUE(matches(
   2149       "struct A { };"
   2150       "template <typename T>"
   2151       "void f(T t) {"
   2152       "  T local_t(t /* this becomes a null QualType in the AST */);"
   2153       "}"
   2154       "void g() {"
   2155       "  f(0);"
   2156       "}",
   2157       expr(hasType(TypeMatcher(
   2158           anyOf(
   2159               TypeMatcher(hasDeclaration(anything())),
   2160               pointsTo(AnyType),
   2161               references(AnyType)
   2162               // Other QualType matchers should go here.
   2163                 ))))));
   2164 }
   2165 
   2166 // For testing AST_MATCHER_P().
   2167 AST_MATCHER_P(Decl, just, internal::Matcher<Decl>, AMatcher) {
   2168   // Make sure all special variables are used: node, match_finder,
   2169   // bound_nodes_builder, and the parameter named 'AMatcher'.
   2170   return AMatcher.matches(Node, Finder, Builder);
   2171 }
   2172 
   2173 TEST(AstMatcherPMacro, Works) {
   2174   DeclarationMatcher HasClassB = just(has(recordDecl(hasName("B")).bind("b")));
   2175 
   2176   EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
   2177       HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
   2178 
   2179   EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
   2180       HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
   2181 
   2182   EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
   2183       HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
   2184 }
   2185 
   2186 AST_POLYMORPHIC_MATCHER_P(
   2187     polymorphicHas, internal::Matcher<Decl>, AMatcher) {
   2188   TOOLING_COMPILE_ASSERT((llvm::is_same<NodeType, Decl>::value) ||
   2189                          (llvm::is_same<NodeType, Stmt>::value),
   2190                          assert_node_type_is_accessible);
   2191   return Finder->matchesChildOf(
   2192       Node, AMatcher, Builder,
   2193       ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
   2194       ASTMatchFinder::BK_First);
   2195 }
   2196 
   2197 TEST(AstPolymorphicMatcherPMacro, Works) {
   2198   DeclarationMatcher HasClassB =
   2199       polymorphicHas(recordDecl(hasName("B")).bind("b"));
   2200 
   2201   EXPECT_TRUE(matchAndVerifyResultTrue("class A { class B {}; };",
   2202       HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
   2203 
   2204   EXPECT_TRUE(matchAndVerifyResultFalse("class A { class B {}; };",
   2205       HasClassB, new VerifyIdIsBoundTo<Decl>("a")));
   2206 
   2207   EXPECT_TRUE(matchAndVerifyResultFalse("class A { class C {}; };",
   2208       HasClassB, new VerifyIdIsBoundTo<Decl>("b")));
   2209 
   2210   StatementMatcher StatementHasClassB =
   2211       polymorphicHas(recordDecl(hasName("B")));
   2212 
   2213   EXPECT_TRUE(matches("void x() { class B {}; }", StatementHasClassB));
   2214 }
   2215 
   2216 TEST(For, FindsForLoops) {
   2217   EXPECT_TRUE(matches("void f() { for(;;); }", forStmt()));
   2218   EXPECT_TRUE(matches("void f() { if(true) for(;;); }", forStmt()));
   2219   EXPECT_TRUE(notMatches("int as[] = { 1, 2, 3 };"
   2220                          "void f() { for (auto &a : as); }",
   2221                          forStmt()));
   2222 }
   2223 
   2224 TEST(For, ForLoopInternals) {
   2225   EXPECT_TRUE(matches("void f(){ int i; for (; i < 3 ; ); }",
   2226                       forStmt(hasCondition(anything()))));
   2227   EXPECT_TRUE(matches("void f() { for (int i = 0; ;); }",
   2228                       forStmt(hasLoopInit(anything()))));
   2229 }
   2230 
   2231 TEST(For, NegativeForLoopInternals) {
   2232   EXPECT_TRUE(notMatches("void f(){ for (int i = 0; ; ++i); }",
   2233                          forStmt(hasCondition(expr()))));
   2234   EXPECT_TRUE(notMatches("void f() {int i; for (; i < 4; ++i) {} }",
   2235                          forStmt(hasLoopInit(anything()))));
   2236 }
   2237 
   2238 TEST(For, ReportsNoFalsePositives) {
   2239   EXPECT_TRUE(notMatches("void f() { ; }", forStmt()));
   2240   EXPECT_TRUE(notMatches("void f() { if(true); }", forStmt()));
   2241 }
   2242 
   2243 TEST(CompoundStatement, HandlesSimpleCases) {
   2244   EXPECT_TRUE(notMatches("void f();", compoundStmt()));
   2245   EXPECT_TRUE(matches("void f() {}", compoundStmt()));
   2246   EXPECT_TRUE(matches("void f() {{}}", compoundStmt()));
   2247 }
   2248 
   2249 TEST(CompoundStatement, DoesNotMatchEmptyStruct) {
   2250   // It's not a compound statement just because there's "{}" in the source
   2251   // text. This is an AST search, not grep.
   2252   EXPECT_TRUE(notMatches("namespace n { struct S {}; }",
   2253               compoundStmt()));
   2254   EXPECT_TRUE(matches("namespace n { struct S { void f() {{}} }; }",
   2255               compoundStmt()));
   2256 }
   2257 
   2258 TEST(HasBody, FindsBodyOfForWhileDoLoops) {
   2259   EXPECT_TRUE(matches("void f() { for(;;) {} }",
   2260               forStmt(hasBody(compoundStmt()))));
   2261   EXPECT_TRUE(notMatches("void f() { for(;;); }",
   2262               forStmt(hasBody(compoundStmt()))));
   2263   EXPECT_TRUE(matches("void f() { while(true) {} }",
   2264               whileStmt(hasBody(compoundStmt()))));
   2265   EXPECT_TRUE(matches("void f() { do {} while(true); }",
   2266               doStmt(hasBody(compoundStmt()))));
   2267 }
   2268 
   2269 TEST(HasAnySubstatement, MatchesForTopLevelCompoundStatement) {
   2270   // The simplest case: every compound statement is in a function
   2271   // definition, and the function body itself must be a compound
   2272   // statement.
   2273   EXPECT_TRUE(matches("void f() { for (;;); }",
   2274               compoundStmt(hasAnySubstatement(forStmt()))));
   2275 }
   2276 
   2277 TEST(HasAnySubstatement, IsNotRecursive) {
   2278   // It's really "has any immediate substatement".
   2279   EXPECT_TRUE(notMatches("void f() { if (true) for (;;); }",
   2280               compoundStmt(hasAnySubstatement(forStmt()))));
   2281 }
   2282 
   2283 TEST(HasAnySubstatement, MatchesInNestedCompoundStatements) {
   2284   EXPECT_TRUE(matches("void f() { if (true) { for (;;); } }",
   2285               compoundStmt(hasAnySubstatement(forStmt()))));
   2286 }
   2287 
   2288 TEST(HasAnySubstatement, FindsSubstatementBetweenOthers) {
   2289   EXPECT_TRUE(matches("void f() { 1; 2; 3; for (;;); 4; 5; 6; }",
   2290               compoundStmt(hasAnySubstatement(forStmt()))));
   2291 }
   2292 
   2293 TEST(StatementCountIs, FindsNoStatementsInAnEmptyCompoundStatement) {
   2294   EXPECT_TRUE(matches("void f() { }",
   2295               compoundStmt(statementCountIs(0))));
   2296   EXPECT_TRUE(notMatches("void f() {}",
   2297               compoundStmt(statementCountIs(1))));
   2298 }
   2299 
   2300 TEST(StatementCountIs, AppearsToMatchOnlyOneCount) {
   2301   EXPECT_TRUE(matches("void f() { 1; }",
   2302               compoundStmt(statementCountIs(1))));
   2303   EXPECT_TRUE(notMatches("void f() { 1; }",
   2304               compoundStmt(statementCountIs(0))));
   2305   EXPECT_TRUE(notMatches("void f() { 1; }",
   2306               compoundStmt(statementCountIs(2))));
   2307 }
   2308 
   2309 TEST(StatementCountIs, WorksWithMultipleStatements) {
   2310   EXPECT_TRUE(matches("void f() { 1; 2; 3; }",
   2311               compoundStmt(statementCountIs(3))));
   2312 }
   2313 
   2314 TEST(StatementCountIs, WorksWithNestedCompoundStatements) {
   2315   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
   2316               compoundStmt(statementCountIs(1))));
   2317   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
   2318               compoundStmt(statementCountIs(2))));
   2319   EXPECT_TRUE(notMatches("void f() { { 1; } { 1; 2; 3; 4; } }",
   2320               compoundStmt(statementCountIs(3))));
   2321   EXPECT_TRUE(matches("void f() { { 1; } { 1; 2; 3; 4; } }",
   2322               compoundStmt(statementCountIs(4))));
   2323 }
   2324 
   2325 TEST(Member, WorksInSimplestCase) {
   2326   EXPECT_TRUE(matches("struct { int first; } s; int i(s.first);",
   2327                       memberExpr(member(hasName("first")))));
   2328 }
   2329 
   2330 TEST(Member, DoesNotMatchTheBaseExpression) {
   2331   // Don't pick out the wrong part of the member expression, this should
   2332   // be checking the member (name) only.
   2333   EXPECT_TRUE(notMatches("struct { int i; } first; int i(first.i);",
   2334                          memberExpr(member(hasName("first")))));
   2335 }
   2336 
   2337 TEST(Member, MatchesInMemberFunctionCall) {
   2338   EXPECT_TRUE(matches("void f() {"
   2339                       "  struct { void first() {}; } s;"
   2340                       "  s.first();"
   2341                       "};",
   2342                       memberExpr(member(hasName("first")))));
   2343 }
   2344 
   2345 TEST(Member, MatchesMember) {
   2346   EXPECT_TRUE(matches(
   2347       "struct A { int i; }; void f() { A a; a.i = 2; }",
   2348       memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
   2349   EXPECT_TRUE(notMatches(
   2350       "struct A { float f; }; void f() { A a; a.f = 2.0f; }",
   2351       memberExpr(hasDeclaration(fieldDecl(hasType(isInteger()))))));
   2352 }
   2353 
   2354 TEST(Member, UnderstandsAccess) {
   2355   EXPECT_TRUE(matches(
   2356       "struct A { int i; };", fieldDecl(isPublic(), hasName("i"))));
   2357   EXPECT_TRUE(notMatches(
   2358       "struct A { int i; };", fieldDecl(isProtected(), hasName("i"))));
   2359   EXPECT_TRUE(notMatches(
   2360       "struct A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
   2361 
   2362   EXPECT_TRUE(notMatches(
   2363       "class A { int i; };", fieldDecl(isPublic(), hasName("i"))));
   2364   EXPECT_TRUE(notMatches(
   2365       "class A { int i; };", fieldDecl(isProtected(), hasName("i"))));
   2366   EXPECT_TRUE(matches(
   2367       "class A { int i; };", fieldDecl(isPrivate(), hasName("i"))));
   2368 
   2369   EXPECT_TRUE(notMatches(
   2370       "class A { protected: int i; };", fieldDecl(isPublic(), hasName("i"))));
   2371   EXPECT_TRUE(matches("class A { protected: int i; };",
   2372                       fieldDecl(isProtected(), hasName("i"))));
   2373   EXPECT_TRUE(notMatches(
   2374       "class A { protected: int i; };", fieldDecl(isPrivate(), hasName("i"))));
   2375 
   2376   // Non-member decls have the AccessSpecifier AS_none and thus aren't matched.
   2377   EXPECT_TRUE(notMatches("int i;", varDecl(isPublic(), hasName("i"))));
   2378   EXPECT_TRUE(notMatches("int i;", varDecl(isProtected(), hasName("i"))));
   2379   EXPECT_TRUE(notMatches("int i;", varDecl(isPrivate(), hasName("i"))));
   2380 }
   2381 
   2382 TEST(Member, MatchesMemberAllocationFunction) {
   2383   // Fails in C++11 mode
   2384   EXPECT_TRUE(matchesConditionally(
   2385       "namespace std { typedef typeof(sizeof(int)) size_t; }"
   2386       "class X { void *operator new(std::size_t); };",
   2387       methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
   2388 
   2389   EXPECT_TRUE(matches("class X { void operator delete(void*); };",
   2390                       methodDecl(ofClass(hasName("X")))));
   2391 
   2392   // Fails in C++11 mode
   2393   EXPECT_TRUE(matchesConditionally(
   2394       "namespace std { typedef typeof(sizeof(int)) size_t; }"
   2395       "class X { void operator delete[](void*, std::size_t); };",
   2396       methodDecl(ofClass(hasName("X"))), true, "-std=gnu++98"));
   2397 }
   2398 
   2399 TEST(HasObjectExpression, DoesNotMatchMember) {
   2400   EXPECT_TRUE(notMatches(
   2401       "class X {}; struct Z { X m; }; void f(Z z) { z.m; }",
   2402       memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
   2403 }
   2404 
   2405 TEST(HasObjectExpression, MatchesBaseOfVariable) {
   2406   EXPECT_TRUE(matches(
   2407       "struct X { int m; }; void f(X x) { x.m; }",
   2408       memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X")))))));
   2409   EXPECT_TRUE(matches(
   2410       "struct X { int m; }; void f(X* x) { x->m; }",
   2411       memberExpr(hasObjectExpression(
   2412           hasType(pointsTo(recordDecl(hasName("X"))))))));
   2413 }
   2414 
   2415 TEST(HasObjectExpression,
   2416      MatchesObjectExpressionOfImplicitlyFormedMemberExpression) {
   2417   EXPECT_TRUE(matches(
   2418       "class X {}; struct S { X m; void f() { this->m; } };",
   2419       memberExpr(hasObjectExpression(
   2420           hasType(pointsTo(recordDecl(hasName("S"))))))));
   2421   EXPECT_TRUE(matches(
   2422       "class X {}; struct S { X m; void f() { m; } };",
   2423       memberExpr(hasObjectExpression(
   2424           hasType(pointsTo(recordDecl(hasName("S"))))))));
   2425 }
   2426 
   2427 TEST(Field, DoesNotMatchNonFieldMembers) {
   2428   EXPECT_TRUE(notMatches("class X { void m(); };", fieldDecl(hasName("m"))));
   2429   EXPECT_TRUE(notMatches("class X { class m {}; };", fieldDecl(hasName("m"))));
   2430   EXPECT_TRUE(notMatches("class X { enum { m }; };", fieldDecl(hasName("m"))));
   2431   EXPECT_TRUE(notMatches("class X { enum m {}; };", fieldDecl(hasName("m"))));
   2432 }
   2433 
   2434 TEST(Field, MatchesField) {
   2435   EXPECT_TRUE(matches("class X { int m; };", fieldDecl(hasName("m"))));
   2436 }
   2437 
   2438 TEST(IsConstQualified, MatchesConstInt) {
   2439   EXPECT_TRUE(matches("const int i = 42;",
   2440                       varDecl(hasType(isConstQualified()))));
   2441 }
   2442 
   2443 TEST(IsConstQualified, MatchesConstPointer) {
   2444   EXPECT_TRUE(matches("int i = 42; int* const p(&i);",
   2445                       varDecl(hasType(isConstQualified()))));
   2446 }
   2447 
   2448 TEST(IsConstQualified, MatchesThroughTypedef) {
   2449   EXPECT_TRUE(matches("typedef const int const_int; const_int i = 42;",
   2450                       varDecl(hasType(isConstQualified()))));
   2451   EXPECT_TRUE(matches("typedef int* int_ptr; const int_ptr p(0);",
   2452                       varDecl(hasType(isConstQualified()))));
   2453 }
   2454 
   2455 TEST(IsConstQualified, DoesNotMatchInappropriately) {
   2456   EXPECT_TRUE(notMatches("typedef int nonconst_int; nonconst_int i = 42;",
   2457                          varDecl(hasType(isConstQualified()))));
   2458   EXPECT_TRUE(notMatches("int const* p;",
   2459                          varDecl(hasType(isConstQualified()))));
   2460 }
   2461 
   2462 TEST(CastExpression, MatchesExplicitCasts) {
   2463   EXPECT_TRUE(matches("char *p = reinterpret_cast<char *>(&p);",castExpr()));
   2464   EXPECT_TRUE(matches("void *p = (void *)(&p);", castExpr()));
   2465   EXPECT_TRUE(matches("char q, *p = const_cast<char *>(&q);", castExpr()));
   2466   EXPECT_TRUE(matches("char c = char(0);", castExpr()));
   2467 }
   2468 TEST(CastExpression, MatchesImplicitCasts) {
   2469   // This test creates an implicit cast from int to char.
   2470   EXPECT_TRUE(matches("char c = 0;", castExpr()));
   2471   // This test creates an implicit cast from lvalue to rvalue.
   2472   EXPECT_TRUE(matches("char c = 0, d = c;", castExpr()));
   2473 }
   2474 
   2475 TEST(CastExpression, DoesNotMatchNonCasts) {
   2476   EXPECT_TRUE(notMatches("char c = '0';", castExpr()));
   2477   EXPECT_TRUE(notMatches("char c, &q = c;", castExpr()));
   2478   EXPECT_TRUE(notMatches("int i = (0);", castExpr()));
   2479   EXPECT_TRUE(notMatches("int i = 0;", castExpr()));
   2480 }
   2481 
   2482 TEST(ReinterpretCast, MatchesSimpleCase) {
   2483   EXPECT_TRUE(matches("char* p = reinterpret_cast<char*>(&p);",
   2484                       reinterpretCastExpr()));
   2485 }
   2486 
   2487 TEST(ReinterpretCast, DoesNotMatchOtherCasts) {
   2488   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", reinterpretCastExpr()));
   2489   EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
   2490                          reinterpretCastExpr()));
   2491   EXPECT_TRUE(notMatches("void* p = static_cast<void*>(&p);",
   2492                          reinterpretCastExpr()));
   2493   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
   2494                          "B b;"
   2495                          "D* p = dynamic_cast<D*>(&b);",
   2496                          reinterpretCastExpr()));
   2497 }
   2498 
   2499 TEST(FunctionalCast, MatchesSimpleCase) {
   2500   std::string foo_class = "class Foo { public: Foo(char*); };";
   2501   EXPECT_TRUE(matches(foo_class + "void r() { Foo f = Foo(\"hello world\"); }",
   2502                       functionalCastExpr()));
   2503 }
   2504 
   2505 TEST(FunctionalCast, DoesNotMatchOtherCasts) {
   2506   std::string FooClass = "class Foo { public: Foo(char*); };";
   2507   EXPECT_TRUE(
   2508       notMatches(FooClass + "void r() { Foo f = (Foo) \"hello world\"; }",
   2509                  functionalCastExpr()));
   2510   EXPECT_TRUE(
   2511       notMatches(FooClass + "void r() { Foo f = \"hello world\"; }",
   2512                  functionalCastExpr()));
   2513 }
   2514 
   2515 TEST(DynamicCast, MatchesSimpleCase) {
   2516   EXPECT_TRUE(matches("struct B { virtual ~B() {} }; struct D : B {};"
   2517                       "B b;"
   2518                       "D* p = dynamic_cast<D*>(&b);",
   2519                       dynamicCastExpr()));
   2520 }
   2521 
   2522 TEST(StaticCast, MatchesSimpleCase) {
   2523   EXPECT_TRUE(matches("void* p(static_cast<void*>(&p));",
   2524                       staticCastExpr()));
   2525 }
   2526 
   2527 TEST(StaticCast, DoesNotMatchOtherCasts) {
   2528   EXPECT_TRUE(notMatches("char* p = (char*)(&p);", staticCastExpr()));
   2529   EXPECT_TRUE(notMatches("char q, *p = const_cast<char*>(&q);",
   2530                          staticCastExpr()));
   2531   EXPECT_TRUE(notMatches("void* p = reinterpret_cast<char*>(&p);",
   2532                          staticCastExpr()));
   2533   EXPECT_TRUE(notMatches("struct B { virtual ~B() {} }; struct D : B {};"
   2534                          "B b;"
   2535                          "D* p = dynamic_cast<D*>(&b);",
   2536                          staticCastExpr()));
   2537 }
   2538 
   2539 TEST(CStyleCast, MatchesSimpleCase) {
   2540   EXPECT_TRUE(matches("int i = (int) 2.2f;", cStyleCastExpr()));
   2541 }
   2542 
   2543 TEST(CStyleCast, DoesNotMatchOtherCasts) {
   2544   EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);"
   2545                          "char q, *r = const_cast<char*>(&q);"
   2546                          "void* s = reinterpret_cast<char*>(&s);"
   2547                          "struct B { virtual ~B() {} }; struct D : B {};"
   2548                          "B b;"
   2549                          "D* t = dynamic_cast<D*>(&b);",
   2550                          cStyleCastExpr()));
   2551 }
   2552 
   2553 TEST(HasDestinationType, MatchesSimpleCase) {
   2554   EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
   2555                       staticCastExpr(hasDestinationType(
   2556                           pointsTo(TypeMatcher(anything()))))));
   2557 }
   2558 
   2559 TEST(HasImplicitDestinationType, MatchesSimpleCase) {
   2560   // This test creates an implicit const cast.
   2561   EXPECT_TRUE(matches("int x; const int i = x;",
   2562                       implicitCastExpr(
   2563                           hasImplicitDestinationType(isInteger()))));
   2564   // This test creates an implicit array-to-pointer cast.
   2565   EXPECT_TRUE(matches("int arr[3]; int *p = arr;",
   2566                       implicitCastExpr(hasImplicitDestinationType(
   2567                           pointsTo(TypeMatcher(anything()))))));
   2568 }
   2569 
   2570 TEST(HasImplicitDestinationType, DoesNotMatchIncorrectly) {
   2571   // This test creates an implicit cast from int to char.
   2572   EXPECT_TRUE(notMatches("char c = 0;",
   2573                       implicitCastExpr(hasImplicitDestinationType(
   2574                           unless(anything())))));
   2575   // This test creates an implicit array-to-pointer cast.
   2576   EXPECT_TRUE(notMatches("int arr[3]; int *p = arr;",
   2577                       implicitCastExpr(hasImplicitDestinationType(
   2578                           unless(anything())))));
   2579 }
   2580 
   2581 TEST(ImplicitCast, MatchesSimpleCase) {
   2582   // This test creates an implicit const cast.
   2583   EXPECT_TRUE(matches("int x = 0; const int y = x;",
   2584                       varDecl(hasInitializer(implicitCastExpr()))));
   2585   // This test creates an implicit cast from int to char.
   2586   EXPECT_TRUE(matches("char c = 0;",
   2587                       varDecl(hasInitializer(implicitCastExpr()))));
   2588   // This test creates an implicit array-to-pointer cast.
   2589   EXPECT_TRUE(matches("int arr[6]; int *p = arr;",
   2590                       varDecl(hasInitializer(implicitCastExpr()))));
   2591 }
   2592 
   2593 TEST(ImplicitCast, DoesNotMatchIncorrectly) {
   2594   // This test verifies that implicitCastExpr() matches exactly when implicit casts
   2595   // are present, and that it ignores explicit and paren casts.
   2596 
   2597   // These two test cases have no casts.
   2598   EXPECT_TRUE(notMatches("int x = 0;",
   2599                          varDecl(hasInitializer(implicitCastExpr()))));
   2600   EXPECT_TRUE(notMatches("int x = 0, &y = x;",
   2601                          varDecl(hasInitializer(implicitCastExpr()))));
   2602 
   2603   EXPECT_TRUE(notMatches("int x = 0; double d = (double) x;",
   2604                          varDecl(hasInitializer(implicitCastExpr()))));
   2605   EXPECT_TRUE(notMatches("const int *p; int *q = const_cast<int *>(p);",
   2606                          varDecl(hasInitializer(implicitCastExpr()))));
   2607 
   2608   EXPECT_TRUE(notMatches("int x = (0);",
   2609                          varDecl(hasInitializer(implicitCastExpr()))));
   2610 }
   2611 
   2612 TEST(IgnoringImpCasts, MatchesImpCasts) {
   2613   // This test checks that ignoringImpCasts matches when implicit casts are
   2614   // present and its inner matcher alone does not match.
   2615   // Note that this test creates an implicit const cast.
   2616   EXPECT_TRUE(matches("int x = 0; const int y = x;",
   2617                       varDecl(hasInitializer(ignoringImpCasts(
   2618                           declRefExpr(to(varDecl(hasName("x")))))))));
   2619   // This test creates an implict cast from int to char.
   2620   EXPECT_TRUE(matches("char x = 0;",
   2621                       varDecl(hasInitializer(ignoringImpCasts(
   2622                           integerLiteral(equals(0)))))));
   2623 }
   2624 
   2625 TEST(IgnoringImpCasts, DoesNotMatchIncorrectly) {
   2626   // These tests verify that ignoringImpCasts does not match if the inner
   2627   // matcher does not match.
   2628   // Note that the first test creates an implicit const cast.
   2629   EXPECT_TRUE(notMatches("int x; const int y = x;",
   2630                          varDecl(hasInitializer(ignoringImpCasts(
   2631                              unless(anything()))))));
   2632   EXPECT_TRUE(notMatches("int x; int y = x;",
   2633                          varDecl(hasInitializer(ignoringImpCasts(
   2634                              unless(anything()))))));
   2635 
   2636   // These tests verify that ignoringImplictCasts does not look through explicit
   2637   // casts or parentheses.
   2638   EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
   2639                          varDecl(hasInitializer(ignoringImpCasts(
   2640                              integerLiteral())))));
   2641   EXPECT_TRUE(notMatches("int i = (0);",
   2642                          varDecl(hasInitializer(ignoringImpCasts(
   2643                              integerLiteral())))));
   2644   EXPECT_TRUE(notMatches("float i = (float)0;",
   2645                          varDecl(hasInitializer(ignoringImpCasts(
   2646                              integerLiteral())))));
   2647   EXPECT_TRUE(notMatches("float i = float(0);",
   2648                          varDecl(hasInitializer(ignoringImpCasts(
   2649                              integerLiteral())))));
   2650 }
   2651 
   2652 TEST(IgnoringImpCasts, MatchesWithoutImpCasts) {
   2653   // This test verifies that expressions that do not have implicit casts
   2654   // still match the inner matcher.
   2655   EXPECT_TRUE(matches("int x = 0; int &y = x;",
   2656                       varDecl(hasInitializer(ignoringImpCasts(
   2657                           declRefExpr(to(varDecl(hasName("x")))))))));
   2658 }
   2659 
   2660 TEST(IgnoringParenCasts, MatchesParenCasts) {
   2661   // This test checks that ignoringParenCasts matches when parentheses and/or
   2662   // casts are present and its inner matcher alone does not match.
   2663   EXPECT_TRUE(matches("int x = (0);",
   2664                       varDecl(hasInitializer(ignoringParenCasts(
   2665                           integerLiteral(equals(0)))))));
   2666   EXPECT_TRUE(matches("int x = (((((0)))));",
   2667                       varDecl(hasInitializer(ignoringParenCasts(
   2668                           integerLiteral(equals(0)))))));
   2669 
   2670   // This test creates an implict cast from int to char in addition to the
   2671   // parentheses.
   2672   EXPECT_TRUE(matches("char x = (0);",
   2673                       varDecl(hasInitializer(ignoringParenCasts(
   2674                           integerLiteral(equals(0)))))));
   2675 
   2676   EXPECT_TRUE(matches("char x = (char)0;",
   2677                       varDecl(hasInitializer(ignoringParenCasts(
   2678                           integerLiteral(equals(0)))))));
   2679   EXPECT_TRUE(matches("char* p = static_cast<char*>(0);",
   2680                       varDecl(hasInitializer(ignoringParenCasts(
   2681                           integerLiteral(equals(0)))))));
   2682 }
   2683 
   2684 TEST(IgnoringParenCasts, MatchesWithoutParenCasts) {
   2685   // This test verifies that expressions that do not have any casts still match.
   2686   EXPECT_TRUE(matches("int x = 0;",
   2687                       varDecl(hasInitializer(ignoringParenCasts(
   2688                           integerLiteral(equals(0)))))));
   2689 }
   2690 
   2691 TEST(IgnoringParenCasts, DoesNotMatchIncorrectly) {
   2692   // These tests verify that ignoringImpCasts does not match if the inner
   2693   // matcher does not match.
   2694   EXPECT_TRUE(notMatches("int x = ((0));",
   2695                          varDecl(hasInitializer(ignoringParenCasts(
   2696                              unless(anything()))))));
   2697 
   2698   // This test creates an implicit cast from int to char in addition to the
   2699   // parentheses.
   2700   EXPECT_TRUE(notMatches("char x = ((0));",
   2701                          varDecl(hasInitializer(ignoringParenCasts(
   2702                              unless(anything()))))));
   2703 
   2704   EXPECT_TRUE(notMatches("char *x = static_cast<char *>((0));",
   2705                          varDecl(hasInitializer(ignoringParenCasts(
   2706                              unless(anything()))))));
   2707 }
   2708 
   2709 TEST(IgnoringParenAndImpCasts, MatchesParenImpCasts) {
   2710   // This test checks that ignoringParenAndImpCasts matches when
   2711   // parentheses and/or implicit casts are present and its inner matcher alone
   2712   // does not match.
   2713   // Note that this test creates an implicit const cast.
   2714   EXPECT_TRUE(matches("int x = 0; const int y = x;",
   2715                       varDecl(hasInitializer(ignoringParenImpCasts(
   2716                           declRefExpr(to(varDecl(hasName("x")))))))));
   2717   // This test creates an implicit cast from int to char.
   2718   EXPECT_TRUE(matches("const char x = (0);",
   2719                       varDecl(hasInitializer(ignoringParenImpCasts(
   2720                           integerLiteral(equals(0)))))));
   2721 }
   2722 
   2723 TEST(IgnoringParenAndImpCasts, MatchesWithoutParenImpCasts) {
   2724   // This test verifies that expressions that do not have parentheses or
   2725   // implicit casts still match.
   2726   EXPECT_TRUE(matches("int x = 0; int &y = x;",
   2727                       varDecl(hasInitializer(ignoringParenImpCasts(
   2728                           declRefExpr(to(varDecl(hasName("x")))))))));
   2729   EXPECT_TRUE(matches("int x = 0;",
   2730                       varDecl(hasInitializer(ignoringParenImpCasts(
   2731                           integerLiteral(equals(0)))))));
   2732 }
   2733 
   2734 TEST(IgnoringParenAndImpCasts, DoesNotMatchIncorrectly) {
   2735   // These tests verify that ignoringParenImpCasts does not match if
   2736   // the inner matcher does not match.
   2737   // This test creates an implicit cast.
   2738   EXPECT_TRUE(notMatches("char c = ((3));",
   2739                          varDecl(hasInitializer(ignoringParenImpCasts(
   2740                              unless(anything()))))));
   2741   // These tests verify that ignoringParenAndImplictCasts does not look
   2742   // through explicit casts.
   2743   EXPECT_TRUE(notMatches("float y = (float(0));",
   2744                          varDecl(hasInitializer(ignoringParenImpCasts(
   2745                              integerLiteral())))));
   2746   EXPECT_TRUE(notMatches("float y = (float)0;",
   2747                          varDecl(hasInitializer(ignoringParenImpCasts(
   2748                              integerLiteral())))));
   2749   EXPECT_TRUE(notMatches("char* p = static_cast<char*>(0);",
   2750                          varDecl(hasInitializer(ignoringParenImpCasts(
   2751                              integerLiteral())))));
   2752 }
   2753 
   2754 TEST(HasSourceExpression, MatchesImplicitCasts) {
   2755   EXPECT_TRUE(matches("class string {}; class URL { public: URL(string s); };"
   2756                       "void r() {string a_string; URL url = a_string; }",
   2757                       implicitCastExpr(
   2758                           hasSourceExpression(constructExpr()))));
   2759 }
   2760 
   2761 TEST(HasSourceExpression, MatchesExplicitCasts) {
   2762   EXPECT_TRUE(matches("float x = static_cast<float>(42);",
   2763                       explicitCastExpr(
   2764                           hasSourceExpression(hasDescendant(
   2765                               expr(integerLiteral()))))));
   2766 }
   2767 
   2768 TEST(Statement, DoesNotMatchDeclarations) {
   2769   EXPECT_TRUE(notMatches("class X {};", stmt()));
   2770 }
   2771 
   2772 TEST(Statement, MatchesCompoundStatments) {
   2773   EXPECT_TRUE(matches("void x() {}", stmt()));
   2774 }
   2775 
   2776 TEST(DeclarationStatement, DoesNotMatchCompoundStatements) {
   2777   EXPECT_TRUE(notMatches("void x() {}", declStmt()));
   2778 }
   2779 
   2780 TEST(DeclarationStatement, MatchesVariableDeclarationStatements) {
   2781   EXPECT_TRUE(matches("void x() { int a; }", declStmt()));
   2782 }
   2783 
   2784 TEST(InitListExpression, MatchesInitListExpression) {
   2785   EXPECT_TRUE(matches("int a[] = { 1, 2 };",
   2786                       initListExpr(hasType(asString("int [2]")))));
   2787   EXPECT_TRUE(matches("struct B { int x, y; }; B b = { 5, 6 };",
   2788                       initListExpr(hasType(recordDecl(hasName("B"))))));
   2789 }
   2790 
   2791 TEST(UsingDeclaration, MatchesUsingDeclarations) {
   2792   EXPECT_TRUE(matches("namespace X { int x; } using X::x;",
   2793                       usingDecl()));
   2794 }
   2795 
   2796 TEST(UsingDeclaration, MatchesShadowUsingDelcarations) {
   2797   EXPECT_TRUE(matches("namespace f { int a; } using f::a;",
   2798                       usingDecl(hasAnyUsingShadowDecl(hasName("a")))));
   2799 }
   2800 
   2801 TEST(UsingDeclaration, MatchesSpecificTarget) {
   2802   EXPECT_TRUE(matches("namespace f { int a; void b(); } using f::b;",
   2803                       usingDecl(hasAnyUsingShadowDecl(
   2804                           hasTargetDecl(functionDecl())))));
   2805   EXPECT_TRUE(notMatches("namespace f { int a; void b(); } using f::a;",
   2806                          usingDecl(hasAnyUsingShadowDecl(
   2807                              hasTargetDecl(functionDecl())))));
   2808 }
   2809 
   2810 TEST(UsingDeclaration, ThroughUsingDeclaration) {
   2811   EXPECT_TRUE(matches(
   2812       "namespace a { void f(); } using a::f; void g() { f(); }",
   2813       declRefExpr(throughUsingDecl(anything()))));
   2814   EXPECT_TRUE(notMatches(
   2815       "namespace a { void f(); } using a::f; void g() { a::f(); }",
   2816       declRefExpr(throughUsingDecl(anything()))));
   2817 }
   2818 
   2819 TEST(SingleDecl, IsSingleDecl) {
   2820   StatementMatcher SingleDeclStmt =
   2821       declStmt(hasSingleDecl(varDecl(hasInitializer(anything()))));
   2822   EXPECT_TRUE(matches("void f() {int a = 4;}", SingleDeclStmt));
   2823   EXPECT_TRUE(notMatches("void f() {int a;}", SingleDeclStmt));
   2824   EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
   2825                           SingleDeclStmt));
   2826 }
   2827 
   2828 TEST(DeclStmt, ContainsDeclaration) {
   2829   DeclarationMatcher MatchesInit = varDecl(hasInitializer(anything()));
   2830 
   2831   EXPECT_TRUE(matches("void f() {int a = 4;}",
   2832                       declStmt(containsDeclaration(0, MatchesInit))));
   2833   EXPECT_TRUE(matches("void f() {int a = 4, b = 3;}",
   2834                       declStmt(containsDeclaration(0, MatchesInit),
   2835                                containsDeclaration(1, MatchesInit))));
   2836   unsigned WrongIndex = 42;
   2837   EXPECT_TRUE(notMatches("void f() {int a = 4, b = 3;}",
   2838                          declStmt(containsDeclaration(WrongIndex,
   2839                                                       MatchesInit))));
   2840 }
   2841 
   2842 TEST(DeclCount, DeclCountIsCorrect) {
   2843   EXPECT_TRUE(matches("void f() {int i,j;}",
   2844                       declStmt(declCountIs(2))));
   2845   EXPECT_TRUE(notMatches("void f() {int i,j; int k;}",
   2846                          declStmt(declCountIs(3))));
   2847   EXPECT_TRUE(notMatches("void f() {int i,j, k, l;}",
   2848                          declStmt(declCountIs(3))));
   2849 }
   2850 
   2851 TEST(While, MatchesWhileLoops) {
   2852   EXPECT_TRUE(notMatches("void x() {}", whileStmt()));
   2853   EXPECT_TRUE(matches("void x() { while(true); }", whileStmt()));
   2854   EXPECT_TRUE(notMatches("void x() { do {} while(true); }", whileStmt()));
   2855 }
   2856 
   2857 TEST(Do, MatchesDoLoops) {
   2858   EXPECT_TRUE(matches("void x() { do {} while(true); }", doStmt()));
   2859   EXPECT_TRUE(matches("void x() { do ; while(false); }", doStmt()));
   2860 }
   2861 
   2862 TEST(Do, DoesNotMatchWhileLoops) {
   2863   EXPECT_TRUE(notMatches("void x() { while(true) {} }", doStmt()));
   2864 }
   2865 
   2866 TEST(SwitchCase, MatchesCase) {
   2867   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchCase()));
   2868   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchCase()));
   2869   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchCase()));
   2870   EXPECT_TRUE(notMatches("void x() { switch(42) {} }", switchCase()));
   2871 }
   2872 
   2873 TEST(SwitchCase, MatchesSwitch) {
   2874   EXPECT_TRUE(matches("void x() { switch(42) { case 42:; } }", switchStmt()));
   2875   EXPECT_TRUE(matches("void x() { switch(42) { default:; } }", switchStmt()));
   2876   EXPECT_TRUE(matches("void x() { switch(42) default:; }", switchStmt()));
   2877   EXPECT_TRUE(notMatches("void x() {}", switchStmt()));
   2878 }
   2879 
   2880 TEST(ExceptionHandling, SimpleCases) {
   2881   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", catchStmt()));
   2882   EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", tryStmt()));
   2883   EXPECT_TRUE(notMatches("void foo() try { } catch(int X) { }", throwExpr()));
   2884   EXPECT_TRUE(matches("void foo() try { throw; } catch(int X) { }",
   2885                       throwExpr()));
   2886   EXPECT_TRUE(matches("void foo() try { throw 5;} catch(int X) { }",
   2887                       throwExpr()));
   2888 }
   2889 
   2890 TEST(HasConditionVariableStatement, DoesNotMatchCondition) {
   2891   EXPECT_TRUE(notMatches(
   2892       "void x() { if(true) {} }",
   2893       ifStmt(hasConditionVariableStatement(declStmt()))));
   2894   EXPECT_TRUE(notMatches(
   2895       "void x() { int x; if((x = 42)) {} }",
   2896       ifStmt(hasConditionVariableStatement(declStmt()))));
   2897 }
   2898 
   2899 TEST(HasConditionVariableStatement, MatchesConditionVariables) {
   2900   EXPECT_TRUE(matches(
   2901       "void x() { if(int* a = 0) {} }",
   2902       ifStmt(hasConditionVariableStatement(declStmt()))));
   2903 }
   2904 
   2905 TEST(ForEach, BindsOneNode) {
   2906   EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; };",
   2907       recordDecl(hasName("C"), forEach(fieldDecl(hasName("x")).bind("x"))),
   2908       new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
   2909 }
   2910 
   2911 TEST(ForEach, BindsMultipleNodes) {
   2912   EXPECT_TRUE(matchAndVerifyResultTrue("class C { int x; int y; int z; };",
   2913       recordDecl(hasName("C"), forEach(fieldDecl().bind("f"))),
   2914       new VerifyIdIsBoundTo<FieldDecl>("f", 3)));
   2915 }
   2916 
   2917 TEST(ForEach, BindsRecursiveCombinations) {
   2918   EXPECT_TRUE(matchAndVerifyResultTrue(
   2919       "class C { class D { int x; int y; }; class E { int y; int z; }; };",
   2920       recordDecl(hasName("C"),
   2921                  forEach(recordDecl(forEach(fieldDecl().bind("f"))))),
   2922       new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
   2923 }
   2924 
   2925 TEST(ForEachDescendant, BindsOneNode) {
   2926   EXPECT_TRUE(matchAndVerifyResultTrue("class C { class D { int x; }; };",
   2927       recordDecl(hasName("C"),
   2928                  forEachDescendant(fieldDecl(hasName("x")).bind("x"))),
   2929       new VerifyIdIsBoundTo<FieldDecl>("x", 1)));
   2930 }
   2931 
   2932 TEST(ForEachDescendant, NestedForEachDescendant) {
   2933   DeclarationMatcher m = recordDecl(
   2934       isDefinition(), decl().bind("x"), hasName("C"));
   2935   EXPECT_TRUE(matchAndVerifyResultTrue(
   2936     "class A { class B { class C {}; }; };",
   2937     recordDecl(hasName("A"), anyOf(m, forEachDescendant(m))),
   2938     new VerifyIdIsBoundTo<Decl>("x", "C")));
   2939 
   2940   // FIXME: This is not really a useful matcher, but the result is still
   2941   // surprising (currently binds "A").
   2942   //EXPECT_TRUE(matchAndVerifyResultTrue(
   2943   //  "class A { class B { class C {}; }; };",
   2944   //  recordDecl(hasName("A"), allOf(hasDescendant(m), anyOf(m, anything()))),
   2945   //  new VerifyIdIsBoundTo<Decl>("x", "C")));
   2946 }
   2947 
   2948 TEST(ForEachDescendant, BindsMultipleNodes) {
   2949   EXPECT_TRUE(matchAndVerifyResultTrue(
   2950       "class C { class D { int x; int y; }; "
   2951       "          class E { class F { int y; int z; }; }; };",
   2952       recordDecl(hasName("C"), forEachDescendant(fieldDecl().bind("f"))),
   2953       new VerifyIdIsBoundTo<FieldDecl>("f", 4)));
   2954 }
   2955 
   2956 TEST(ForEachDescendant, BindsRecursiveCombinations) {
   2957   EXPECT_TRUE(matchAndVerifyResultTrue(
   2958       "class C { class D { "
   2959       "          class E { class F { class G { int y; int z; }; }; }; }; };",
   2960       recordDecl(hasName("C"), forEachDescendant(recordDecl(
   2961           forEachDescendant(fieldDecl().bind("f"))))),
   2962       new VerifyIdIsBoundTo<FieldDecl>("f", 8)));
   2963 }
   2964 
   2965 TEST(ForEachDescendant, BindsCorrectNodes) {
   2966   EXPECT_TRUE(matchAndVerifyResultTrue(
   2967       "class C { void f(); int i; };",
   2968       recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
   2969       new VerifyIdIsBoundTo<FieldDecl>("decl", 1)));
   2970   EXPECT_TRUE(matchAndVerifyResultTrue(
   2971       "class C { void f() {} int i; };",
   2972       recordDecl(hasName("C"), forEachDescendant(decl().bind("decl"))),
   2973       new VerifyIdIsBoundTo<FunctionDecl>("decl", 1)));
   2974 }
   2975 
   2976 TEST(FindAll, BindsNodeOnMatch) {
   2977   EXPECT_TRUE(matchAndVerifyResultTrue(
   2978       "class A {};",
   2979       recordDecl(hasName("::A"), findAll(recordDecl(hasName("::A")).bind("v"))),
   2980       new VerifyIdIsBoundTo<CXXRecordDecl>("v", 1)));
   2981 }
   2982 
   2983 TEST(FindAll, BindsDescendantNodeOnMatch) {
   2984   EXPECT_TRUE(matchAndVerifyResultTrue(
   2985       "class A { int a; int b; };",
   2986       recordDecl(hasName("::A"), findAll(fieldDecl().bind("v"))),
   2987       new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
   2988 }
   2989 
   2990 TEST(FindAll, BindsNodeAndDescendantNodesOnOneMatch) {
   2991   EXPECT_TRUE(matchAndVerifyResultTrue(
   2992       "class A { int a; int b; };",
   2993       recordDecl(hasName("::A"),
   2994                  findAll(decl(anyOf(recordDecl(hasName("::A")).bind("v"),
   2995                                     fieldDecl().bind("v"))))),
   2996       new VerifyIdIsBoundTo<Decl>("v", 3)));
   2997 
   2998   EXPECT_TRUE(matchAndVerifyResultTrue(
   2999       "class A { class B {}; class C {}; };",
   3000       recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("v"))),
   3001       new VerifyIdIsBoundTo<CXXRecordDecl>("v", 3)));
   3002 }
   3003 
   3004 TEST(EachOf, TriggersForEachMatch) {
   3005   EXPECT_TRUE(matchAndVerifyResultTrue(
   3006       "class A { int a; int b; };",
   3007       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
   3008                         has(fieldDecl(hasName("b")).bind("v")))),
   3009       new VerifyIdIsBoundTo<FieldDecl>("v", 2)));
   3010 }
   3011 
   3012 TEST(EachOf, BehavesLikeAnyOfUnlessBothMatch) {
   3013   EXPECT_TRUE(matchAndVerifyResultTrue(
   3014       "class A { int a; int c; };",
   3015       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
   3016                         has(fieldDecl(hasName("b")).bind("v")))),
   3017       new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
   3018   EXPECT_TRUE(matchAndVerifyResultTrue(
   3019       "class A { int c; int b; };",
   3020       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
   3021                         has(fieldDecl(hasName("b")).bind("v")))),
   3022       new VerifyIdIsBoundTo<FieldDecl>("v", 1)));
   3023   EXPECT_TRUE(notMatches(
   3024       "class A { int c; int d; };",
   3025       recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")),
   3026                         has(fieldDecl(hasName("b")).bind("v"))))));
   3027 }
   3028 
   3029 TEST(IsTemplateInstantiation, MatchesImplicitClassTemplateInstantiation) {
   3030   // Make sure that we can both match the class by name (::X) and by the type
   3031   // the template was instantiated with (via a field).
   3032 
   3033   EXPECT_TRUE(matches(
   3034       "template <typename T> class X {}; class A {}; X<A> x;",
   3035       recordDecl(hasName("::X"), isTemplateInstantiation())));
   3036 
   3037   EXPECT_TRUE(matches(
   3038       "template <typename T> class X { T t; }; class A {}; X<A> x;",
   3039       recordDecl(isTemplateInstantiation(), hasDescendant(
   3040           fieldDecl(hasType(recordDecl(hasName("A"))))))));
   3041 }
   3042 
   3043 TEST(IsTemplateInstantiation, MatchesImplicitFunctionTemplateInstantiation) {
   3044   EXPECT_TRUE(matches(
   3045       "template <typename T> void f(T t) {} class A {}; void g() { f(A()); }",
   3046       functionDecl(hasParameter(0, hasType(recordDecl(hasName("A")))),
   3047                isTemplateInstantiation())));
   3048 }
   3049 
   3050 TEST(IsTemplateInstantiation, MatchesExplicitClassTemplateInstantiation) {
   3051   EXPECT_TRUE(matches(
   3052       "template <typename T> class X { T t; }; class A {};"
   3053       "template class X<A>;",
   3054       recordDecl(isTemplateInstantiation(), hasDescendant(
   3055           fieldDecl(hasType(recordDecl(hasName("A"))))))));
   3056 }
   3057 
   3058 TEST(IsTemplateInstantiation,
   3059      MatchesInstantiationOfPartiallySpecializedClassTemplate) {
   3060   EXPECT_TRUE(matches(
   3061       "template <typename T> class X {};"
   3062       "template <typename T> class X<T*> {}; class A {}; X<A*> x;",
   3063       recordDecl(hasName("::X"), isTemplateInstantiation())));
   3064 }
   3065 
   3066 TEST(IsTemplateInstantiation,
   3067      MatchesInstantiationOfClassTemplateNestedInNonTemplate) {
   3068   EXPECT_TRUE(matches(
   3069       "class A {};"
   3070       "class X {"
   3071       "  template <typename U> class Y { U u; };"
   3072       "  Y<A> y;"
   3073       "};",
   3074       recordDecl(hasName("::X::Y"), isTemplateInstantiation())));
   3075 }
   3076 
   3077 TEST(IsTemplateInstantiation, DoesNotMatchInstantiationsInsideOfInstantiation) {
   3078   // FIXME: Figure out whether this makes sense. It doesn't affect the
   3079   // normal use case as long as the uppermost instantiation always is marked
   3080   // as template instantiation, but it might be confusing as a predicate.
   3081   EXPECT_TRUE(matches(
   3082       "class A {};"
   3083       "template <typename T> class X {"
   3084       "  template <typename U> class Y { U u; };"
   3085       "  Y<T> y;"
   3086       "}; X<A> x;",
   3087       recordDecl(hasName("::X<A>::Y"), unless(isTemplateInstantiation()))));
   3088 }
   3089 
   3090 TEST(IsTemplateInstantiation, DoesNotMatchExplicitClassTemplateSpecialization) {
   3091   EXPECT_TRUE(notMatches(
   3092       "template <typename T> class X {}; class A {};"
   3093       "template <> class X<A> {}; X<A> x;",
   3094       recordDecl(hasName("::X"), isTemplateInstantiation())));
   3095 }
   3096 
   3097 TEST(IsTemplateInstantiation, DoesNotMatchNonTemplate) {
   3098   EXPECT_TRUE(notMatches(
   3099       "class A {}; class Y { A a; };",
   3100       recordDecl(isTemplateInstantiation())));
   3101 }
   3102 
   3103 TEST(IsExplicitTemplateSpecialization,
   3104      DoesNotMatchPrimaryTemplate) {
   3105   EXPECT_TRUE(notMatches(
   3106       "template <typename T> class X {};",
   3107       recordDecl(isExplicitTemplateSpecialization())));
   3108   EXPECT_TRUE(notMatches(
   3109       "template <typename T> void f(T t);",
   3110       functionDecl(isExplicitTemplateSpecialization())));
   3111 }
   3112 
   3113 TEST(IsExplicitTemplateSpecialization,
   3114      DoesNotMatchExplicitTemplateInstantiations) {
   3115   EXPECT_TRUE(notMatches(
   3116       "template <typename T> class X {};"
   3117       "template class X<int>; extern template class X<long>;",
   3118       recordDecl(isExplicitTemplateSpecialization())));
   3119   EXPECT_TRUE(notMatches(
   3120       "template <typename T> void f(T t) {}"
   3121       "template void f(int t); extern template void f(long t);",
   3122       functionDecl(isExplicitTemplateSpecialization())));
   3123 }
   3124 
   3125 TEST(IsExplicitTemplateSpecialization,
   3126      DoesNotMatchImplicitTemplateInstantiations) {
   3127   EXPECT_TRUE(notMatches(
   3128       "template <typename T> class X {}; X<int> x;",
   3129       recordDecl(isExplicitTemplateSpecialization())));
   3130   EXPECT_TRUE(notMatches(
   3131       "template <typename T> void f(T t); void g() { f(10); }",
   3132       functionDecl(isExplicitTemplateSpecialization())));
   3133 }
   3134 
   3135 TEST(IsExplicitTemplateSpecialization,
   3136      MatchesExplicitTemplateSpecializations) {
   3137   EXPECT_TRUE(matches(
   3138       "template <typename T> class X {};"
   3139       "template<> class X<int> {};",
   3140       recordDecl(isExplicitTemplateSpecialization())));
   3141   EXPECT_TRUE(matches(
   3142       "template <typename T> void f(T t) {}"
   3143       "template<> void f(int t) {}",
   3144       functionDecl(isExplicitTemplateSpecialization())));
   3145 }
   3146 
   3147 TEST(HasAncenstor, MatchesDeclarationAncestors) {
   3148   EXPECT_TRUE(matches(
   3149       "class A { class B { class C {}; }; };",
   3150       recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("A"))))));
   3151 }
   3152 
   3153 TEST(HasAncenstor, FailsIfNoAncestorMatches) {
   3154   EXPECT_TRUE(notMatches(
   3155       "class A { class B { class C {}; }; };",
   3156       recordDecl(hasName("C"), hasAncestor(recordDecl(hasName("X"))))));
   3157 }
   3158 
   3159 TEST(HasAncestor, MatchesDeclarationsThatGetVisitedLater) {
   3160   EXPECT_TRUE(matches(
   3161       "class A { class B { void f() { C c; } class C {}; }; };",
   3162       varDecl(hasName("c"), hasType(recordDecl(hasName("C"),
   3163           hasAncestor(recordDecl(hasName("A"))))))));
   3164 }
   3165 
   3166 TEST(HasAncenstor, MatchesStatementAncestors) {
   3167   EXPECT_TRUE(matches(
   3168       "void f() { if (true) { while (false) { 42; } } }",
   3169       integerLiteral(equals(42), hasAncestor(ifStmt()))));
   3170 }
   3171 
   3172 TEST(HasAncestor, DrillsThroughDifferentHierarchies) {
   3173   EXPECT_TRUE(matches(
   3174       "void f() { if (true) { int x = 42; } }",
   3175       integerLiteral(equals(42), hasAncestor(functionDecl(hasName("f"))))));
   3176 }
   3177 
   3178 TEST(HasAncestor, BindsRecursiveCombinations) {
   3179   EXPECT_TRUE(matchAndVerifyResultTrue(
   3180       "class C { class D { class E { class F { int y; }; }; }; };",
   3181       fieldDecl(hasAncestor(recordDecl(hasAncestor(recordDecl().bind("r"))))),
   3182       new VerifyIdIsBoundTo<CXXRecordDecl>("r", 1)));
   3183 }
   3184 
   3185 TEST(HasAncestor, BindsCombinationsWithHasDescendant) {
   3186   EXPECT_TRUE(matchAndVerifyResultTrue(
   3187       "class C { class D { class E { class F { int y; }; }; }; };",
   3188       fieldDecl(hasAncestor(
   3189           decl(
   3190             hasDescendant(recordDecl(isDefinition(),
   3191                                      hasAncestor(recordDecl())))
   3192           ).bind("d")
   3193       )),
   3194       new VerifyIdIsBoundTo<CXXRecordDecl>("d", "E")));
   3195 }
   3196 
   3197 TEST(HasAncestor, MatchesClosestAncestor) {
   3198   EXPECT_TRUE(matchAndVerifyResultTrue(
   3199       "template <typename T> struct C {"
   3200       "  void f(int) {"
   3201       "    struct I { void g(T) { int x; } } i; i.g(42);"
   3202       "  }"
   3203       "};"
   3204       "template struct C<int>;",
   3205       varDecl(hasName("x"),
   3206               hasAncestor(functionDecl(hasParameter(
   3207                   0, varDecl(hasType(asString("int"))))).bind("f"))).bind("v"),
   3208       new VerifyIdIsBoundTo<FunctionDecl>("f", "g", 2)));
   3209 }
   3210 
   3211 TEST(HasAncestor, MatchesInTemplateInstantiations) {
   3212   EXPECT_TRUE(matches(
   3213       "template <typename T> struct A { struct B { struct C { T t; }; }; }; "
   3214       "A<int>::B::C a;",
   3215       fieldDecl(hasType(asString("int")),
   3216                 hasAncestor(recordDecl(hasName("A"))))));
   3217 }
   3218 
   3219 TEST(HasAncestor, MatchesInImplicitCode) {
   3220   EXPECT_TRUE(matches(
   3221       "struct X {}; struct A { A() {} X x; };",
   3222       constructorDecl(
   3223           hasAnyConstructorInitializer(withInitializer(expr(
   3224               hasAncestor(recordDecl(hasName("A")))))))));
   3225 }
   3226 
   3227 TEST(HasParent, MatchesOnlyParent) {
   3228   EXPECT_TRUE(matches(
   3229       "void f() { if (true) { int x = 42; } }",
   3230       compoundStmt(hasParent(ifStmt()))));
   3231   EXPECT_TRUE(notMatches(
   3232       "void f() { for (;;) { int x = 42; } }",
   3233       compoundStmt(hasParent(ifStmt()))));
   3234   EXPECT_TRUE(notMatches(
   3235       "void f() { if (true) for (;;) { int x = 42; } }",
   3236       compoundStmt(hasParent(ifStmt()))));
   3237 }
   3238 
   3239 TEST(HasAncestor, MatchesAllAncestors) {
   3240   EXPECT_TRUE(matches(
   3241       "template <typename T> struct C { static void f() { 42; } };"
   3242       "void t() { C<int>::f(); }",
   3243       integerLiteral(
   3244           equals(42),
   3245           allOf(hasAncestor(recordDecl(isTemplateInstantiation())),
   3246                 hasAncestor(recordDecl(unless(isTemplateInstantiation())))))));
   3247 }
   3248 
   3249 TEST(HasParent, MatchesAllParents) {
   3250   EXPECT_TRUE(matches(
   3251       "template <typename T> struct C { static void f() { 42; } };"
   3252       "void t() { C<int>::f(); }",
   3253       integerLiteral(
   3254           equals(42),
   3255           hasParent(compoundStmt(hasParent(functionDecl(
   3256               hasParent(recordDecl(isTemplateInstantiation())))))))));
   3257   EXPECT_TRUE(matches(
   3258       "template <typename T> struct C { static void f() { 42; } };"
   3259       "void t() { C<int>::f(); }",
   3260       integerLiteral(
   3261           equals(42),
   3262           hasParent(compoundStmt(hasParent(functionDecl(
   3263               hasParent(recordDecl(unless(isTemplateInstantiation()))))))))));
   3264   EXPECT_TRUE(matches(
   3265       "template <typename T> struct C { static void f() { 42; } };"
   3266       "void t() { C<int>::f(); }",
   3267       integerLiteral(equals(42),
   3268                      hasParent(compoundStmt(allOf(
   3269                          hasParent(functionDecl(
   3270                              hasParent(recordDecl(isTemplateInstantiation())))),
   3271                          hasParent(functionDecl(hasParent(recordDecl(
   3272                              unless(isTemplateInstantiation())))))))))));
   3273   EXPECT_TRUE(
   3274       notMatches("template <typename T> struct C { static void f() {} };"
   3275                  "void t() { C<int>::f(); }",
   3276                  compoundStmt(hasParent(recordDecl()))));
   3277 }
   3278 
   3279 TEST(TypeMatching, MatchesTypes) {
   3280   EXPECT_TRUE(matches("struct S {};", qualType().bind("loc")));
   3281 }
   3282 
   3283 TEST(TypeMatching, MatchesArrayTypes) {
   3284   EXPECT_TRUE(matches("int a[] = {2,3};", arrayType()));
   3285   EXPECT_TRUE(matches("int a[42];", arrayType()));
   3286   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", arrayType()));
   3287 
   3288   EXPECT_TRUE(notMatches("struct A {}; A a[7];",
   3289                          arrayType(hasElementType(builtinType()))));
   3290 
   3291   EXPECT_TRUE(matches(
   3292       "int const a[] = { 2, 3 };",
   3293       qualType(arrayType(hasElementType(builtinType())))));
   3294   EXPECT_TRUE(matches(
   3295       "int const a[] = { 2, 3 };",
   3296       qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
   3297   EXPECT_TRUE(matches(
   3298       "typedef const int T; T x[] = { 1, 2 };",
   3299       qualType(isConstQualified(), arrayType())));
   3300 
   3301   EXPECT_TRUE(notMatches(
   3302       "int a[] = { 2, 3 };",
   3303       qualType(isConstQualified(), arrayType(hasElementType(builtinType())))));
   3304   EXPECT_TRUE(notMatches(
   3305       "int a[] = { 2, 3 };",
   3306       qualType(arrayType(hasElementType(isConstQualified(), builtinType())))));
   3307   EXPECT_TRUE(notMatches(
   3308       "int const a[] = { 2, 3 };",
   3309       qualType(arrayType(hasElementType(builtinType())),
   3310                unless(isConstQualified()))));
   3311 
   3312   EXPECT_TRUE(matches("int a[2];",
   3313                       constantArrayType(hasElementType(builtinType()))));
   3314   EXPECT_TRUE(matches("const int a = 0;", qualType(isInteger())));
   3315 }
   3316 
   3317 TEST(TypeMatching, MatchesComplexTypes) {
   3318   EXPECT_TRUE(matches("_Complex float f;", complexType()));
   3319   EXPECT_TRUE(matches(
   3320     "_Complex float f;",
   3321     complexType(hasElementType(builtinType()))));
   3322   EXPECT_TRUE(notMatches(
   3323     "_Complex float f;",
   3324     complexType(hasElementType(isInteger()))));
   3325 }
   3326 
   3327 TEST(TypeMatching, MatchesConstantArrayTypes) {
   3328   EXPECT_TRUE(matches("int a[2];", constantArrayType()));
   3329   EXPECT_TRUE(notMatches(
   3330     "void f() { int a[] = { 2, 3 }; int b[a[0]]; }",
   3331     constantArrayType(hasElementType(builtinType()))));
   3332 
   3333   EXPECT_TRUE(matches("int a[42];", constantArrayType(hasSize(42))));
   3334   EXPECT_TRUE(matches("int b[2*21];", constantArrayType(hasSize(42))));
   3335   EXPECT_TRUE(notMatches("int c[41], d[43];", constantArrayType(hasSize(42))));
   3336 }
   3337 
   3338 TEST(TypeMatching, MatchesDependentSizedArrayTypes) {
   3339   EXPECT_TRUE(matches(
   3340     "template <typename T, int Size> class array { T data[Size]; };",
   3341     dependentSizedArrayType()));
   3342   EXPECT_TRUE(notMatches(
   3343     "int a[42]; int b[] = { 2, 3 }; void f() { int c[b[0]]; }",
   3344     dependentSizedArrayType()));
   3345 }
   3346 
   3347 TEST(TypeMatching, MatchesIncompleteArrayType) {
   3348   EXPECT_TRUE(matches("int a[] = { 2, 3 };", incompleteArrayType()));
   3349   EXPECT_TRUE(matches("void f(int a[]) {}", incompleteArrayType()));
   3350 
   3351   EXPECT_TRUE(notMatches("int a[42]; void f() { int b[a[0]]; }",
   3352                          incompleteArrayType()));
   3353 }
   3354 
   3355 TEST(TypeMatching, MatchesVariableArrayType) {
   3356   EXPECT_TRUE(matches("void f(int b) { int a[b]; }", variableArrayType()));
   3357   EXPECT_TRUE(notMatches("int a[] = {2, 3}; int b[42];", variableArrayType()));
   3358 
   3359   EXPECT_TRUE(matches(
   3360     "void f(int b) { int a[b]; }",
   3361     variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to(
   3362       varDecl(hasName("b")))))))));
   3363 }
   3364 
   3365 TEST(TypeMatching, MatchesAtomicTypes) {
   3366   EXPECT_TRUE(matches("_Atomic(int) i;", atomicType()));
   3367 
   3368   EXPECT_TRUE(matches("_Atomic(int) i;",
   3369                       atomicType(hasValueType(isInteger()))));
   3370   EXPECT_TRUE(notMatches("_Atomic(float) f;",
   3371                          atomicType(hasValueType(isInteger()))));
   3372 }
   3373 
   3374 TEST(TypeMatching, MatchesAutoTypes) {
   3375   EXPECT_TRUE(matches("auto i = 2;", autoType()));
   3376   EXPECT_TRUE(matches("int v[] = { 2, 3 }; void f() { for (int i : v) {} }",
   3377                       autoType()));
   3378 
   3379   EXPECT_TRUE(matches("auto a = 1;",
   3380                       autoType(hasDeducedType(isInteger()))));
   3381   EXPECT_TRUE(notMatches("auto b = 2.0;",
   3382                          autoType(hasDeducedType(isInteger()))));
   3383 }
   3384 
   3385 TEST(TypeMatching, MatchesFunctionTypes) {
   3386   EXPECT_TRUE(matches("int (*f)(int);", functionType()));
   3387   EXPECT_TRUE(matches("void f(int i) {}", functionType()));
   3388 }
   3389 
   3390 TEST(TypeMatching, PointerTypes) {
   3391   // FIXME: Reactive when these tests can be more specific (not matching
   3392   // implicit code on certain platforms), likely when we have hasDescendant for
   3393   // Types/TypeLocs.
   3394   //EXPECT_TRUE(matchAndVerifyResultTrue(
   3395   //    "int* a;",
   3396   //    pointerTypeLoc(pointeeLoc(typeLoc().bind("loc"))),
   3397   //    new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
   3398   //EXPECT_TRUE(matchAndVerifyResultTrue(
   3399   //    "int* a;",
   3400   //    pointerTypeLoc().bind("loc"),
   3401   //    new VerifyIdIsBoundTo<TypeLoc>("loc", 1)));
   3402   EXPECT_TRUE(matches(
   3403       "int** a;",
   3404       loc(pointerType(pointee(qualType())))));
   3405   EXPECT_TRUE(matches(
   3406       "int** a;",
   3407       loc(pointerType(pointee(pointerType())))));
   3408   EXPECT_TRUE(matches(
   3409       "int* b; int* * const a = &b;",
   3410       loc(qualType(isConstQualified(), pointerType()))));
   3411 
   3412   std::string Fragment = "struct A { int i; }; int A::* ptr = &A::i;";
   3413   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3414                                            hasType(blockPointerType()))));
   3415   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
   3416                                         hasType(memberPointerType()))));
   3417   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3418                                            hasType(pointerType()))));
   3419   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3420                                            hasType(referenceType()))));
   3421   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3422                                            hasType(lValueReferenceType()))));
   3423   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3424                                            hasType(rValueReferenceType()))));
   3425 
   3426   Fragment = "int *ptr;";
   3427   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3428                                            hasType(blockPointerType()))));
   3429   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3430                                            hasType(memberPointerType()))));
   3431   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ptr"),
   3432                                         hasType(pointerType()))));
   3433   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ptr"),
   3434                                            hasType(referenceType()))));
   3435 
   3436   Fragment = "int a; int &ref = a;";
   3437   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3438                                            hasType(blockPointerType()))));
   3439   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3440                                            hasType(memberPointerType()))));
   3441   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3442                                            hasType(pointerType()))));
   3443   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
   3444                                         hasType(referenceType()))));
   3445   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
   3446                                         hasType(lValueReferenceType()))));
   3447   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3448                                            hasType(rValueReferenceType()))));
   3449 
   3450   Fragment = "int &&ref = 2;";
   3451   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3452                                            hasType(blockPointerType()))));
   3453   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3454                                            hasType(memberPointerType()))));
   3455   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3456                                            hasType(pointerType()))));
   3457   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
   3458                                         hasType(referenceType()))));
   3459   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("ref"),
   3460                                            hasType(lValueReferenceType()))));
   3461   EXPECT_TRUE(matches(Fragment, varDecl(hasName("ref"),
   3462                                         hasType(rValueReferenceType()))));
   3463 }
   3464 
   3465 TEST(TypeMatching, AutoRefTypes) {
   3466   std::string Fragment = "auto a = 1;"
   3467                          "auto b = a;"
   3468                          "auto &c = a;"
   3469                          "auto &&d = c;"
   3470                          "auto &&e = 2;";
   3471   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("a"),
   3472                                            hasType(referenceType()))));
   3473   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("b"),
   3474                                            hasType(referenceType()))));
   3475   EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
   3476                                         hasType(referenceType()))));
   3477   EXPECT_TRUE(matches(Fragment, varDecl(hasName("c"),
   3478                                         hasType(lValueReferenceType()))));
   3479   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("c"),
   3480                                            hasType(rValueReferenceType()))));
   3481   EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
   3482                                         hasType(referenceType()))));
   3483   EXPECT_TRUE(matches(Fragment, varDecl(hasName("d"),
   3484                                         hasType(lValueReferenceType()))));
   3485   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("d"),
   3486                                            hasType(rValueReferenceType()))));
   3487   EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
   3488                                         hasType(referenceType()))));
   3489   EXPECT_TRUE(notMatches(Fragment, varDecl(hasName("e"),
   3490                                            hasType(lValueReferenceType()))));
   3491   EXPECT_TRUE(matches(Fragment, varDecl(hasName("e"),
   3492                                         hasType(rValueReferenceType()))));
   3493 }
   3494 
   3495 TEST(TypeMatching, PointeeTypes) {
   3496   EXPECT_TRUE(matches("int b; int &a = b;",
   3497                       referenceType(pointee(builtinType()))));
   3498   EXPECT_TRUE(matches("int *a;", pointerType(pointee(builtinType()))));
   3499 
   3500   EXPECT_TRUE(matches("int *a;",
   3501                       loc(pointerType(pointee(builtinType())))));
   3502 
   3503   EXPECT_TRUE(matches(
   3504       "int const *A;",
   3505       pointerType(pointee(isConstQualified(), builtinType()))));
   3506   EXPECT_TRUE(notMatches(
   3507       "int *A;",
   3508       pointerType(pointee(isConstQualified(), builtinType()))));
   3509 }
   3510 
   3511 TEST(TypeMatching, MatchesPointersToConstTypes) {
   3512   EXPECT_TRUE(matches("int b; int * const a = &b;",
   3513                       loc(pointerType())));
   3514   EXPECT_TRUE(matches("int b; int * const a = &b;",
   3515                       loc(pointerType())));
   3516   EXPECT_TRUE(matches(
   3517       "int b; const int * a = &b;",
   3518       loc(pointerType(pointee(builtinType())))));
   3519   EXPECT_TRUE(matches(
   3520       "int b; const int * a = &b;",
   3521       pointerType(pointee(builtinType()))));
   3522 }
   3523 
   3524 TEST(TypeMatching, MatchesTypedefTypes) {
   3525   EXPECT_TRUE(matches("typedef int X; X a;", varDecl(hasName("a"),
   3526                                                      hasType(typedefType()))));
   3527 }
   3528 
   3529 TEST(TypeMatching, MatchesTemplateSpecializationType) {
   3530   EXPECT_TRUE(matches("template <typename T> class A{}; A<int> a;",
   3531                       templateSpecializationType()));
   3532 }
   3533 
   3534 TEST(TypeMatching, MatchesRecordType) {
   3535   EXPECT_TRUE(matches("class C{}; C c;", recordType()));
   3536   EXPECT_TRUE(matches("struct S{}; S s;",
   3537                       recordType(hasDeclaration(recordDecl(hasName("S"))))));
   3538   EXPECT_TRUE(notMatches("int i;",
   3539                          recordType(hasDeclaration(recordDecl(hasName("S"))))));
   3540 }
   3541 
   3542 TEST(TypeMatching, MatchesElaboratedType) {
   3543   EXPECT_TRUE(matches(
   3544     "namespace N {"
   3545     "  namespace M {"
   3546     "    class D {};"
   3547     "  }"
   3548     "}"
   3549     "N::M::D d;", elaboratedType()));
   3550   EXPECT_TRUE(matches("class C {} c;", elaboratedType()));
   3551   EXPECT_TRUE(notMatches("class C {}; C c;", elaboratedType()));
   3552 }
   3553 
   3554 TEST(ElaboratedTypeNarrowing, hasQualifier) {
   3555   EXPECT_TRUE(matches(
   3556     "namespace N {"
   3557     "  namespace M {"
   3558     "    class D {};"
   3559     "  }"
   3560     "}"
   3561     "N::M::D d;",
   3562     elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
   3563   EXPECT_TRUE(notMatches(
   3564     "namespace M {"
   3565     "  class D {};"
   3566     "}"
   3567     "M::D d;",
   3568     elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))))));
   3569   EXPECT_TRUE(notMatches(
   3570     "struct D {"
   3571     "} d;",
   3572     elaboratedType(hasQualifier(nestedNameSpecifier()))));
   3573 }
   3574 
   3575 TEST(ElaboratedTypeNarrowing, namesType) {
   3576   EXPECT_TRUE(matches(
   3577     "namespace N {"
   3578     "  namespace M {"
   3579     "    class D {};"
   3580     "  }"
   3581     "}"
   3582     "N::M::D d;",
   3583     elaboratedType(elaboratedType(namesType(recordType(
   3584         hasDeclaration(namedDecl(hasName("D")))))))));
   3585   EXPECT_TRUE(notMatches(
   3586     "namespace M {"
   3587     "  class D {};"
   3588     "}"
   3589     "M::D d;",
   3590     elaboratedType(elaboratedType(namesType(typedefType())))));
   3591 }
   3592 
   3593 TEST(NNS, MatchesNestedNameSpecifiers) {
   3594   EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;",
   3595                       nestedNameSpecifier()));
   3596   EXPECT_TRUE(matches("template <typename T> class A { typename T::B b; };",
   3597                       nestedNameSpecifier()));
   3598   EXPECT_TRUE(matches("struct A { void f(); }; void A::f() {}",
   3599                       nestedNameSpecifier()));
   3600 
   3601   EXPECT_TRUE(matches(
   3602     "struct A { static void f() {} }; void g() { A::f(); }",
   3603     nestedNameSpecifier()));
   3604   EXPECT_TRUE(notMatches(
   3605     "struct A { static void f() {} }; void g(A* a) { a->f(); }",
   3606     nestedNameSpecifier()));
   3607 }
   3608 
   3609 TEST(NullStatement, SimpleCases) {
   3610   EXPECT_TRUE(matches("void f() {int i;;}", nullStmt()));
   3611   EXPECT_TRUE(notMatches("void f() {int i;}", nullStmt()));
   3612 }
   3613 
   3614 TEST(NNS, MatchesTypes) {
   3615   NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
   3616     specifiesType(hasDeclaration(recordDecl(hasName("A")))));
   3617   EXPECT_TRUE(matches("struct A { struct B {}; }; A::B b;", Matcher));
   3618   EXPECT_TRUE(matches("struct A { struct B { struct C {}; }; }; A::B::C c;",
   3619                       Matcher));
   3620   EXPECT_TRUE(notMatches("namespace A { struct B {}; } A::B b;", Matcher));
   3621 }
   3622 
   3623 TEST(NNS, MatchesNamespaceDecls) {
   3624   NestedNameSpecifierMatcher Matcher = nestedNameSpecifier(
   3625     specifiesNamespace(hasName("ns")));
   3626   EXPECT_TRUE(matches("namespace ns { struct A {}; } ns::A a;", Matcher));
   3627   EXPECT_TRUE(notMatches("namespace xx { struct A {}; } xx::A a;", Matcher));
   3628   EXPECT_TRUE(notMatches("struct ns { struct A {}; }; ns::A a;", Matcher));
   3629 }
   3630 
   3631 TEST(NNS, BindsNestedNameSpecifiers) {
   3632   EXPECT_TRUE(matchAndVerifyResultTrue(
   3633       "namespace ns { struct E { struct B {}; }; } ns::E::B b;",
   3634       nestedNameSpecifier(specifiesType(asString("struct ns::E"))).bind("nns"),
   3635       new VerifyIdIsBoundTo<NestedNameSpecifier>("nns", "ns::struct E::")));
   3636 }
   3637 
   3638 TEST(NNS, BindsNestedNameSpecifierLocs) {
   3639   EXPECT_TRUE(matchAndVerifyResultTrue(
   3640       "namespace ns { struct B {}; } ns::B b;",
   3641       loc(nestedNameSpecifier()).bind("loc"),
   3642       new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("loc", 1)));
   3643 }
   3644 
   3645 TEST(NNS, MatchesNestedNameSpecifierPrefixes) {
   3646   EXPECT_TRUE(matches(
   3647       "struct A { struct B { struct C {}; }; }; A::B::C c;",
   3648       nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A"))))));
   3649   EXPECT_TRUE(matches(
   3650       "struct A { struct B { struct C {}; }; }; A::B::C c;",
   3651       nestedNameSpecifierLoc(hasPrefix(
   3652           specifiesTypeLoc(loc(qualType(asString("struct A"))))))));
   3653 }
   3654 
   3655 TEST(NNS, DescendantsOfNestedNameSpecifiers) {
   3656   std::string Fragment =
   3657       "namespace a { struct A { struct B { struct C {}; }; }; };"
   3658       "void f() { a::A::B::C c; }";
   3659   EXPECT_TRUE(matches(
   3660       Fragment,
   3661       nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
   3662                           hasDescendant(nestedNameSpecifier(
   3663                               specifiesNamespace(hasName("a")))))));
   3664   EXPECT_TRUE(notMatches(
   3665       Fragment,
   3666       nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
   3667                           has(nestedNameSpecifier(
   3668                               specifiesNamespace(hasName("a")))))));
   3669   EXPECT_TRUE(matches(
   3670       Fragment,
   3671       nestedNameSpecifier(specifiesType(asString("struct a::A")),
   3672                           has(nestedNameSpecifier(
   3673                               specifiesNamespace(hasName("a")))))));
   3674 
   3675   // Not really useful because a NestedNameSpecifier can af at most one child,
   3676   // but to complete the interface.
   3677   EXPECT_TRUE(matchAndVerifyResultTrue(
   3678       Fragment,
   3679       nestedNameSpecifier(specifiesType(asString("struct a::A::B")),
   3680                           forEach(nestedNameSpecifier().bind("x"))),
   3681       new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 1)));
   3682 }
   3683 
   3684 TEST(NNS, NestedNameSpecifiersAsDescendants) {
   3685   std::string Fragment =
   3686       "namespace a { struct A { struct B { struct C {}; }; }; };"
   3687       "void f() { a::A::B::C c; }";
   3688   EXPECT_TRUE(matches(
   3689       Fragment,
   3690       decl(hasDescendant(nestedNameSpecifier(specifiesType(
   3691           asString("struct a::A")))))));
   3692   EXPECT_TRUE(matchAndVerifyResultTrue(
   3693       Fragment,
   3694       functionDecl(hasName("f"),
   3695                    forEachDescendant(nestedNameSpecifier().bind("x"))),
   3696       // Nested names: a, a::A and a::A::B.
   3697       new VerifyIdIsBoundTo<NestedNameSpecifier>("x", 3)));
   3698 }
   3699 
   3700 TEST(NNSLoc, DescendantsOfNestedNameSpecifierLocs) {
   3701   std::string Fragment =
   3702       "namespace a { struct A { struct B { struct C {}; }; }; };"
   3703       "void f() { a::A::B::C c; }";
   3704   EXPECT_TRUE(matches(
   3705       Fragment,
   3706       nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
   3707                              hasDescendant(loc(nestedNameSpecifier(
   3708                                  specifiesNamespace(hasName("a"))))))));
   3709   EXPECT_TRUE(notMatches(
   3710       Fragment,
   3711       nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
   3712                              has(loc(nestedNameSpecifier(
   3713                                  specifiesNamespace(hasName("a"))))))));
   3714   EXPECT_TRUE(matches(
   3715       Fragment,
   3716       nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A"))),
   3717                              has(loc(nestedNameSpecifier(
   3718                                  specifiesNamespace(hasName("a"))))))));
   3719 
   3720   EXPECT_TRUE(matchAndVerifyResultTrue(
   3721       Fragment,
   3722       nestedNameSpecifierLoc(loc(specifiesType(asString("struct a::A::B"))),
   3723                              forEach(nestedNameSpecifierLoc().bind("x"))),
   3724       new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 1)));
   3725 }
   3726 
   3727 TEST(NNSLoc, NestedNameSpecifierLocsAsDescendants) {
   3728   std::string Fragment =
   3729       "namespace a { struct A { struct B { struct C {}; }; }; };"
   3730       "void f() { a::A::B::C c; }";
   3731   EXPECT_TRUE(matches(
   3732       Fragment,
   3733       decl(hasDescendant(loc(nestedNameSpecifier(specifiesType(
   3734           asString("struct a::A"))))))));
   3735   EXPECT_TRUE(matchAndVerifyResultTrue(
   3736       Fragment,
   3737       functionDecl(hasName("f"),
   3738                    forEachDescendant(nestedNameSpecifierLoc().bind("x"))),
   3739       // Nested names: a, a::A and a::A::B.
   3740       new VerifyIdIsBoundTo<NestedNameSpecifierLoc>("x", 3)));
   3741 }
   3742 
   3743 template <typename T> class VerifyMatchOnNode : public BoundNodesCallback {
   3744 public:
   3745   VerifyMatchOnNode(StringRef Id, const internal::Matcher<T> &InnerMatcher,
   3746                     StringRef InnerId)
   3747       : Id(Id), InnerMatcher(InnerMatcher), InnerId(InnerId) {
   3748   }
   3749 
   3750   virtual bool run(const BoundNodes *Nodes) { return false; }
   3751 
   3752   virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
   3753     const T *Node = Nodes->getNodeAs<T>(Id);
   3754     return selectFirst<const T>(InnerId,
   3755                                 match(InnerMatcher, *Node, *Context)) != NULL;
   3756   }
   3757 private:
   3758   std::string Id;
   3759   internal::Matcher<T> InnerMatcher;
   3760   std::string InnerId;
   3761 };
   3762 
   3763 TEST(MatchFinder, CanMatchDeclarationsRecursively) {
   3764   EXPECT_TRUE(matchAndVerifyResultTrue(
   3765       "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
   3766       new VerifyMatchOnNode<clang::Decl>(
   3767           "X", decl(hasDescendant(recordDecl(hasName("X::Y")).bind("Y"))),
   3768           "Y")));
   3769   EXPECT_TRUE(matchAndVerifyResultFalse(
   3770       "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
   3771       new VerifyMatchOnNode<clang::Decl>(
   3772           "X", decl(hasDescendant(recordDecl(hasName("X::Z")).bind("Z"))),
   3773           "Z")));
   3774 }
   3775 
   3776 TEST(MatchFinder, CanMatchStatementsRecursively) {
   3777   EXPECT_TRUE(matchAndVerifyResultTrue(
   3778       "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
   3779       new VerifyMatchOnNode<clang::Stmt>(
   3780           "if", stmt(hasDescendant(forStmt().bind("for"))), "for")));
   3781   EXPECT_TRUE(matchAndVerifyResultFalse(
   3782       "void f() { if (1) { for (;;) { } } }", ifStmt().bind("if"),
   3783       new VerifyMatchOnNode<clang::Stmt>(
   3784           "if", stmt(hasDescendant(declStmt().bind("decl"))), "decl")));
   3785 }
   3786 
   3787 TEST(MatchFinder, CanMatchSingleNodesRecursively) {
   3788   EXPECT_TRUE(matchAndVerifyResultTrue(
   3789       "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
   3790       new VerifyMatchOnNode<clang::Decl>(
   3791           "X", recordDecl(has(recordDecl(hasName("X::Y")).bind("Y"))), "Y")));
   3792   EXPECT_TRUE(matchAndVerifyResultFalse(
   3793       "class X { class Y {}; };", recordDecl(hasName("::X")).bind("X"),
   3794       new VerifyMatchOnNode<clang::Decl>(
   3795           "X", recordDecl(has(recordDecl(hasName("X::Z")).bind("Z"))), "Z")));
   3796 }
   3797 
   3798 template <typename T>
   3799 class VerifyAncestorHasChildIsEqual : public BoundNodesCallback {
   3800 public:
   3801   virtual bool run(const BoundNodes *Nodes) { return false; }
   3802 
   3803   virtual bool run(const BoundNodes *Nodes, ASTContext *Context) {
   3804     const T *Node = Nodes->getNodeAs<T>("");
   3805     return verify(*Nodes, *Context, Node);
   3806   }
   3807 
   3808   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Stmt *Node) {
   3809     return selectFirst<const T>(
   3810         "", match(stmt(hasParent(stmt(has(stmt(equalsNode(Node)))).bind(""))),
   3811                   *Node, Context)) != NULL;
   3812   }
   3813   bool verify(const BoundNodes &Nodes, ASTContext &Context, const Decl *Node) {
   3814     return selectFirst<const T>(
   3815         "", match(decl(hasParent(decl(has(decl(equalsNode(Node)))).bind(""))),
   3816                   *Node, Context)) != NULL;
   3817   }
   3818 };
   3819 
   3820 TEST(IsEqualTo, MatchesNodesByIdentity) {
   3821   EXPECT_TRUE(matchAndVerifyResultTrue(
   3822       "class X { class Y {}; };", recordDecl(hasName("::X::Y")).bind(""),
   3823       new VerifyAncestorHasChildIsEqual<Decl>()));
   3824   EXPECT_TRUE(
   3825       matchAndVerifyResultTrue("void f() { if(true) {} }", ifStmt().bind(""),
   3826                                new VerifyAncestorHasChildIsEqual<Stmt>()));
   3827 }
   3828 
   3829 class VerifyStartOfTranslationUnit : public MatchFinder::MatchCallback {
   3830 public:
   3831   VerifyStartOfTranslationUnit() : Called(false) {}
   3832   virtual void run(const MatchFinder::MatchResult &Result) {
   3833     EXPECT_TRUE(Called);
   3834   }
   3835   virtual void onStartOfTranslationUnit() {
   3836     Called = true;
   3837   }
   3838   bool Called;
   3839 };
   3840 
   3841 TEST(MatchFinder, InterceptsStartOfTranslationUnit) {
   3842   MatchFinder Finder;
   3843   VerifyStartOfTranslationUnit VerifyCallback;
   3844   Finder.addMatcher(decl(), &VerifyCallback);
   3845   OwningPtr<FrontendActionFactory> Factory(newFrontendActionFactory(&Finder));
   3846   ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
   3847   EXPECT_TRUE(VerifyCallback.Called);
   3848 }
   3849 
   3850 } // end namespace ast_matchers
   3851 } // end namespace clang
   3852