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