head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.11
	netbsd-11-0-RC3:1.1.1.11
	netbsd-11-0-RC2:1.1.1.11
	netbsd-11-0-RC1:1.1.1.11
	perseant-exfatfs-base-20250801:1.1.1.11
	netbsd-11:1.1.1.11.0.10
	netbsd-11-base:1.1.1.11
	netbsd-10-1-RELEASE:1.1.1.11
	perseant-exfatfs-base-20240630:1.1.1.11
	perseant-exfatfs:1.1.1.11.0.8
	perseant-exfatfs-base:1.1.1.11
	netbsd-8-3-RELEASE:1.1.1.9
	netbsd-9-4-RELEASE:1.1.1.10
	netbsd-10-0-RELEASE:1.1.1.11
	netbsd-10-0-RC6:1.1.1.11
	netbsd-10-0-RC5:1.1.1.11
	netbsd-10-0-RC4:1.1.1.11
	netbsd-10-0-RC3:1.1.1.11
	netbsd-10-0-RC2:1.1.1.11
	netbsd-10-0-RC1:1.1.1.11
	netbsd-10:1.1.1.11.0.6
	netbsd-10-base:1.1.1.11
	netbsd-9-3-RELEASE:1.1.1.10
	cjep_sun2x:1.1.1.11.0.4
	cjep_sun2x-base:1.1.1.11
	cjep_staticlib_x-base1:1.1.1.11
	netbsd-9-2-RELEASE:1.1.1.10
	cjep_staticlib_x:1.1.1.11.0.2
	cjep_staticlib_x-base:1.1.1.11
	netbsd-9-1-RELEASE:1.1.1.10
	phil-wifi-20200421:1.1.1.11
	phil-wifi-20200411:1.1.1.11
	phil-wifi-20200406:1.1.1.11
	netbsd-8-2-RELEASE:1.1.1.9
	netbsd-9-0-RELEASE:1.1.1.10
	netbsd-9-0-RC2:1.1.1.10
	netbsd-9-0-RC1:1.1.1.10
	netbsd-9:1.1.1.10.0.6
	netbsd-9-base:1.1.1.10
	phil-wifi-20190609:1.1.1.10
	netbsd-8-1-RELEASE:1.1.1.9
	netbsd-8-1-RC1:1.1.1.9
	pgoyette-compat-merge-20190127:1.1.1.10
	pgoyette-compat-20190127:1.1.1.10
	pgoyette-compat-20190118:1.1.1.10
	pgoyette-compat-1226:1.1.1.10
	pgoyette-compat-1126:1.1.1.10
	pgoyette-compat-1020:1.1.1.10
	pgoyette-compat-0930:1.1.1.10
	pgoyette-compat-0906:1.1.1.10
	netbsd-7-2-RELEASE:1.1.1.6.2.1
	pgoyette-compat-0728:1.1.1.10
	clang-337282:1.1.1.10
	netbsd-8-0-RELEASE:1.1.1.9
	phil-wifi:1.1.1.10.0.4
	phil-wifi-base:1.1.1.10
	pgoyette-compat-0625:1.1.1.10
	netbsd-8-0-RC2:1.1.1.9
	pgoyette-compat-0521:1.1.1.10
	pgoyette-compat-0502:1.1.1.10
	pgoyette-compat-0422:1.1.1.10
	netbsd-8-0-RC1:1.1.1.9
	pgoyette-compat-0415:1.1.1.10
	pgoyette-compat-0407:1.1.1.10
	pgoyette-compat-0330:1.1.1.10
	pgoyette-compat-0322:1.1.1.10
	pgoyette-compat-0315:1.1.1.10
	netbsd-7-1-2-RELEASE:1.1.1.6.2.1
	pgoyette-compat:1.1.1.10.0.2
	pgoyette-compat-base:1.1.1.10
	netbsd-7-1-1-RELEASE:1.1.1.6.2.1
	clang-319952:1.1.1.10
	matt-nb8-mediatek:1.1.1.9.0.10
	matt-nb8-mediatek-base:1.1.1.9
	clang-309604:1.1.1.10
	perseant-stdc-iso10646:1.1.1.9.0.8
	perseant-stdc-iso10646-base:1.1.1.9
	netbsd-8:1.1.1.9.0.6
	netbsd-8-base:1.1.1.9
	prg-localcount2-base3:1.1.1.9
	prg-localcount2-base2:1.1.1.9
	prg-localcount2-base1:1.1.1.9
	prg-localcount2:1.1.1.9.0.4
	prg-localcount2-base:1.1.1.9
	pgoyette-localcount-20170426:1.1.1.9
	bouyer-socketcan-base1:1.1.1.9
	pgoyette-localcount-20170320:1.1.1.9
	netbsd-7-1:1.1.1.6.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.6.2.1
	netbsd-7-1-RC2:1.1.1.6.2.1
	clang-294123:1.1.1.9
	netbsd-7-nhusb-base-20170116:1.1.1.6.2.1
	bouyer-socketcan:1.1.1.9.0.2
	bouyer-socketcan-base:1.1.1.9
	clang-291444:1.1.1.9
	pgoyette-localcount-20170107:1.1.1.8
	netbsd-7-1-RC1:1.1.1.6.2.1
	pgoyette-localcount-20161104:1.1.1.8
	netbsd-7-0-2-RELEASE:1.1.1.6.2.1
	localcount-20160914:1.1.1.8
	netbsd-7-nhusb:1.1.1.6.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.6.2.1
	clang-280599:1.1.1.8
	pgoyette-localcount-20160806:1.1.1.8
	pgoyette-localcount-20160726:1.1.1.8
	pgoyette-localcount:1.1.1.8.0.2
	pgoyette-localcount-base:1.1.1.8
	netbsd-7-0-1-RELEASE:1.1.1.6.2.1
	clang-261930:1.1.1.8
	netbsd-7-0:1.1.1.6.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.6.2.1
	netbsd-7-0-RC3:1.1.1.6.2.1
	netbsd-7-0-RC2:1.1.1.6.2.1
	netbsd-7-0-RC1:1.1.1.6.2.1
	clang-237755:1.1.1.7
	clang-232565:1.1.1.7
	clang-227398:1.1.1.7
	tls-maxphys-base:1.1.1.6
	tls-maxphys:1.1.1.6.0.4
	netbsd-7:1.1.1.6.0.2
	netbsd-7-base:1.1.1.6
	clang-215315:1.1.1.6
	clang-209886:1.1.1.5
	yamt-pagecache:1.1.1.4.0.4
	yamt-pagecache-base9:1.1.1.4
	tls-earlyentropy:1.1.1.4.0.2
	tls-earlyentropy-base:1.1.1.5
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.4
	riastradh-drm2-base3:1.1.1.4
	clang-202566:1.1.1.4
	clang-201163:1.1.1.4
	clang-199312:1.1.1.3
	clang-198450:1.1.1.2
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.48;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.01.05.15.37.59;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	wh3aCSIWykURqWjx;

1.1.1.3
date	2014.01.15.21.26.18;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	NQXlzzA0SPkc5glx;

1.1.1.4
date	2014.02.14.20.07.02;	author joerg;	state Exp;
branches
	1.1.1.4.2.1
	1.1.1.4.4.1;
next	1.1.1.5;
commitid	annVkZ1sc17rF6px;

1.1.1.5
date	2014.05.30.18.14.50;	author joerg;	state Exp;
branches;
next	1.1.1.6;
commitid	8q0kdlBlCn09GACx;

1.1.1.6
date	2014.08.10.17.08.25;	author joerg;	state Exp;
branches
	1.1.1.6.2.1
	1.1.1.6.4.1;
next	1.1.1.7;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.7
date	2015.01.29.19.57.27;	author joerg;	state Exp;
branches;
next	1.1.1.8;
commitid	mlISSizlPKvepX7y;

1.1.1.8
date	2016.02.27.22.11.46;	author joerg;	state Exp;
branches
	1.1.1.8.2.1;
next	1.1.1.9;
commitid	tIimz3oDlh1NpBWy;

1.1.1.9
date	2017.01.11.10.33.10;	author joerg;	state Exp;
branches;
next	1.1.1.10;
commitid	CNnUNfII1jgNmxBz;

1.1.1.10
date	2017.08.01.19.34.42;	author joerg;	state Exp;
branches
	1.1.1.10.4.1;
next	1.1.1.11;
commitid	pMuDy65V0VicSx1A;

1.1.1.11
date	2019.11.13.22.23.09;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.4.2.1
date	2014.08.10.07.08.25;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.4.4.1
date	2014.02.14.20.07.02;	author yamt;	state dead;
branches;
next	1.1.1.4.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.4.4.2
date	2014.05.22.16.19.48;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.6.2.1
date	2015.06.04.20.04.46;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.6.4.1
date	2014.08.10.17.08.25;	author tls;	state dead;
branches;
next	1.1.1.6.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.6.4.2
date	2014.08.19.23.49.27;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.8.2.1
date	2017.03.20.06.53.38;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.10.4.1
date	2020.04.13.07.50.37;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===- unittest/ASTMatchers/Dynamic/RegistryTest.cpp - Registry unit tests -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===-----------------------------------------------------------------------===//

#include <vector>

#include "../ASTMatchersTest.h"
#include "clang/ASTMatchers/Dynamic/Registry.h"
#include "gtest/gtest.h"

namespace clang {
namespace ast_matchers {
namespace dynamic {
namespace {

using ast_matchers::internal::Matcher;

class RegistryTest : public ::testing::Test {
public:
  std::vector<ParserValue> Args() { return std::vector<ParserValue>(); }
  std::vector<ParserValue> Args(const VariantValue &Arg1) {
    std::vector<ParserValue> Out(1);
    Out[0].Value = Arg1;
    return Out;
  }
  std::vector<ParserValue> Args(const VariantValue &Arg1,
                                const VariantValue &Arg2) {
    std::vector<ParserValue> Out(2);
    Out[0].Value = Arg1;
    Out[1].Value = Arg2;
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  Diagnostics *Error = NULL) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    const VariantMatcher Out =
        Registry::constructMatcher(MatcherName, SourceRange(), Args(), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  const VariantValue &Arg1,
                                  Diagnostics *Error = NULL) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    const VariantMatcher Out = Registry::constructMatcher(
        MatcherName, SourceRange(), Args(Arg1), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  const VariantValue &Arg1,
                                  const VariantValue &Arg2,
                                  Diagnostics *Error = NULL) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    const VariantMatcher Out = Registry::constructMatcher(
        MatcherName, SourceRange(), Args(Arg1, Arg2), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }
};

TEST_F(RegistryTest, CanConstructNoArgs) {
  Matcher<Stmt> IsArrowValue = constructMatcher(
      "memberExpr", constructMatcher("isArrow")).getTypedMatcher<Stmt>();
  Matcher<Stmt> BoolValue =
      constructMatcher("boolLiteral").getTypedMatcher<Stmt>();

  const std::string ClassSnippet = "struct Foo { int x; };\n"
                                   "Foo *foo = new Foo;\n"
                                   "int i = foo->x;\n";
  const std::string BoolSnippet = "bool Foo = true;\n";

  EXPECT_TRUE(matches(ClassSnippet, IsArrowValue));
  EXPECT_TRUE(matches(BoolSnippet, BoolValue));
  EXPECT_FALSE(matches(ClassSnippet, BoolValue));
  EXPECT_FALSE(matches(BoolSnippet, IsArrowValue));
}

TEST_F(RegistryTest, ConstructWithSimpleArgs) {
  Matcher<Decl> Value = constructMatcher(
      "namedDecl", constructMatcher("hasName", std::string("X")))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("class X {};", Value));
  EXPECT_FALSE(matches("int x;", Value));

  Value = functionDecl(constructMatcher("parameterCountIs", 2)
                           .getTypedMatcher<FunctionDecl>());
  EXPECT_TRUE(matches("void foo(int,int);", Value));
  EXPECT_FALSE(matches("void foo(int);", Value));
}

TEST_F(RegistryTest, ConstructWithMatcherArgs) {
  Matcher<Decl> HasInitializerSimple = constructMatcher(
      "varDecl", constructMatcher("hasInitializer", constructMatcher("stmt")))
      .getTypedMatcher<Decl>();
  Matcher<Decl> HasInitializerComplex = constructMatcher(
      "varDecl",
      constructMatcher("hasInitializer", constructMatcher("callExpr")))
      .getTypedMatcher<Decl>();

  std::string code = "int i;";
  EXPECT_FALSE(matches(code, HasInitializerSimple));
  EXPECT_FALSE(matches(code, HasInitializerComplex));

  code = "int i = 1;";
  EXPECT_TRUE(matches(code, HasInitializerSimple));
  EXPECT_FALSE(matches(code, HasInitializerComplex));

  code = "int y(); int i = y();";
  EXPECT_TRUE(matches(code, HasInitializerSimple));
  EXPECT_TRUE(matches(code, HasInitializerComplex));

  Matcher<Decl> HasParameter =
      functionDecl(constructMatcher(
          "hasParameter", 1, constructMatcher("hasName", std::string("x")))
                       .getTypedMatcher<FunctionDecl>());
  EXPECT_TRUE(matches("void f(int a, int x);", HasParameter));
  EXPECT_FALSE(matches("void f(int x, int a);", HasParameter));
}

TEST_F(RegistryTest, OverloadedMatchers) {
  Matcher<Stmt> CallExpr0 = constructMatcher(
      "callExpr",
      constructMatcher("callee", constructMatcher("memberExpr",
                                                  constructMatcher("isArrow"))))
      .getTypedMatcher<Stmt>();

  Matcher<Stmt> CallExpr1 = constructMatcher(
      "callExpr",
      constructMatcher(
          "callee",
          constructMatcher("methodDecl",
                           constructMatcher("hasName", std::string("x")))))
      .getTypedMatcher<Stmt>();

  std::string Code = "class Y { public: void x(); }; void z() { Y y; y.x(); }";
  EXPECT_FALSE(matches(Code, CallExpr0));
  EXPECT_TRUE(matches(Code, CallExpr1));

  Code = "class Z { public: void z() { this->z(); } };";
  EXPECT_TRUE(matches(Code, CallExpr0));
  EXPECT_FALSE(matches(Code, CallExpr1));
}

TEST_F(RegistryTest, PolymorphicMatchers) {
  const VariantMatcher IsDefinition = constructMatcher("isDefinition");
  Matcher<Decl> Var =
      constructMatcher("varDecl", IsDefinition).getTypedMatcher<Decl>();
  Matcher<Decl> Class =
      constructMatcher("recordDecl", IsDefinition).getTypedMatcher<Decl>();
  Matcher<Decl> Func =
      constructMatcher("functionDecl", IsDefinition).getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("int a;", Var));
  EXPECT_FALSE(matches("extern int a;", Var));
  EXPECT_TRUE(matches("class A {};", Class));
  EXPECT_FALSE(matches("class A;", Class));
  EXPECT_TRUE(matches("void f(){};", Func));
  EXPECT_FALSE(matches("void f();", Func));

  Matcher<Decl> Anything = constructMatcher("anything").getTypedMatcher<Decl>();
  Matcher<Decl> RecordDecl = constructMatcher(
      "recordDecl", constructMatcher("hasName", std::string("Foo")),
      VariantMatcher::SingleMatcher(Anything)).getTypedMatcher<Decl>();

  EXPECT_TRUE(matches("int Foo;", Anything));
  EXPECT_TRUE(matches("class Foo {};", Anything));
  EXPECT_TRUE(matches("void Foo(){};", Anything));
  EXPECT_FALSE(matches("int Foo;", RecordDecl));
  EXPECT_TRUE(matches("class Foo {};", RecordDecl));
  EXPECT_FALSE(matches("void Foo(){};", RecordDecl));

  Matcher<Stmt> ConstructExpr = constructMatcher(
      "constructExpr",
      constructMatcher(
          "hasDeclaration",
          constructMatcher(
              "methodDecl",
              constructMatcher(
                  "ofClass", constructMatcher("hasName", std::string("Foo"))))))
                                    .getTypedMatcher<Stmt>();
  EXPECT_FALSE(matches("class Foo { public: Foo(); };", ConstructExpr));
  EXPECT_TRUE(
      matches("class Foo { public: Foo(); }; Foo foo = Foo();", ConstructExpr));
}

TEST_F(RegistryTest, TemplateArgument) {
  Matcher<Decl> HasTemplateArgument = constructMatcher(
      "classTemplateSpecializationDecl",
      constructMatcher(
          "hasAnyTemplateArgument",
          constructMatcher("refersToType",
                           constructMatcher("asString", std::string("int")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("template<typename T> class A {}; A<int> a;",
                      HasTemplateArgument));
  EXPECT_FALSE(matches("template<typename T> class A {}; A<char> a;",
                       HasTemplateArgument));
}

TEST_F(RegistryTest, TypeTraversal) {
  Matcher<Type> M = constructMatcher(
      "pointerType",
      constructMatcher("pointee", constructMatcher("isConstQualified"),
                       constructMatcher("isInteger"))).getTypedMatcher<Type>();
  EXPECT_FALSE(matches("int *a;", M));
  EXPECT_TRUE(matches("int const *b;", M));

  M = constructMatcher(
      "arrayType",
      constructMatcher("hasElementType", constructMatcher("builtinType")))
      .getTypedMatcher<Type>();
  EXPECT_FALSE(matches("struct A{}; A a[7];;", M));
  EXPECT_TRUE(matches("int b[7];", M));
}

TEST_F(RegistryTest, CXXCtorInitializer) {
  Matcher<Decl> CtorDecl = constructMatcher(
      "constructorDecl",
      constructMatcher(
          "hasAnyConstructorInitializer",
          constructMatcher("forField",
                           constructMatcher("hasName", std::string("foo")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("struct Foo { Foo() : foo(1) {} int foo; };", CtorDecl));
  EXPECT_FALSE(matches("struct Foo { Foo() {} int foo; };", CtorDecl));
  EXPECT_FALSE(matches("struct Foo { Foo() : bar(1) {} int bar; };", CtorDecl));
}

TEST_F(RegistryTest, Adaptative) {
  Matcher<Decl> D = constructMatcher(
      "recordDecl",
      constructMatcher(
          "has",
          constructMatcher("recordDecl",
                           constructMatcher("hasName", std::string("X")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("class X {};", D));
  EXPECT_TRUE(matches("class Y { class X {}; };", D));
  EXPECT_FALSE(matches("class Y { class Z {}; };", D));

  Matcher<Stmt> S = constructMatcher(
      "forStmt",
      constructMatcher(
          "hasDescendant",
          constructMatcher("varDecl",
                           constructMatcher("hasName", std::string("X")))))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("void foo() { for(int X;;); }", S));
  EXPECT_TRUE(matches("void foo() { for(;;) { int X; } }", S));
  EXPECT_FALSE(matches("void foo() { for(;;); }", S));
  EXPECT_FALSE(matches("void foo() { if (int X = 0){} }", S));

  S = constructMatcher(
      "compoundStmt", constructMatcher("hasParent", constructMatcher("ifStmt")))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("void foo() { if (true) { int x = 42; } }", S));
  EXPECT_FALSE(matches("void foo() { if (true) return; }", S));
}

TEST_F(RegistryTest, VariadicOp) {
  Matcher<Decl> D = constructMatcher(
      "anyOf",
      constructMatcher("recordDecl",
                       constructMatcher("hasName", std::string("Foo"))),
      constructMatcher("namedDecl",
                       constructMatcher("hasName", std::string("foo"))))
      .getTypedMatcher<Decl>();

  EXPECT_TRUE(matches("void foo(){}", D));
  EXPECT_TRUE(matches("struct Foo{};", D));
  EXPECT_FALSE(matches("int i = 0;", D));

  D = constructMatcher(
      "allOf", constructMatcher("recordDecl"),
      constructMatcher(
          "namedDecl",
          constructMatcher("anyOf",
                           constructMatcher("hasName", std::string("Foo")),
                           constructMatcher("hasName", std::string("Bar")))))
      .getTypedMatcher<Decl>();

  EXPECT_FALSE(matches("void foo(){}", D));
  EXPECT_TRUE(matches("struct Foo{};", D));
  EXPECT_FALSE(matches("int i = 0;", D));
  EXPECT_TRUE(matches("class Bar{};", D));
  EXPECT_FALSE(matches("class OtherBar{};", D));
}

TEST_F(RegistryTest, Errors) {
  // Incorrect argument count.
  OwningPtr<Diagnostics> Error(new Diagnostics());
  EXPECT_TRUE(constructMatcher("hasInitializer", Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = 1) != (Actual = 0)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("isArrow", std::string(), Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = 0) != (Actual = 1)",
            Error->toString());

  // Bad argument type
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("ofClass", std::string(), Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 1. (Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = String)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("recordDecl", constructMatcher("recordDecl"),
                               constructMatcher("parameterCountIs", 3),
                               Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 2. (Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = Matcher<FunctionDecl>)",
            Error->toString());

  // Bad argument type with variadic.
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("anyOf", std::string(), Error.get()).isNull());
  EXPECT_EQ(
      "Incorrect type for arg 1. (Expected = Matcher<>) != (Actual = String)",
      Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher(
      "recordDecl",
      constructMatcher("allOf",
                       constructMatcher("isDerivedFrom", std::string("FOO")),
                       constructMatcher("isArrow")),
      Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 1. "
            "(Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = Matcher<CXXRecordDecl>&Matcher<MemberExpr>)",
            Error->toString());
}

} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
} // end namespace clang
@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import clang 3.5svn r198450.
@
text
@a38 10
  llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName,
                                                Diagnostics *Error = 0) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor =
        Registry::lookupMatcherCtor(MatcherName, SourceRange(), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Ctor;
  }

d43 2
a44 4
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName, Error);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(), Error);
d54 2
a55 4
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName, Error);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1), Error);
d66 2
a67 5
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName, Error);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1, Arg2),
                                       Error);
a297 11

  D = recordDecl(
      has(fieldDecl(hasName("Foo"))),
      constructMatcher(
          "unless",
          constructMatcher("namedDecl",
                           constructMatcher("hasName", std::string("Bar"))))
          .getTypedMatcher<Decl>());

  EXPECT_FALSE(matches("class Bar{ int Foo; };", D));
  EXPECT_TRUE(matches("class OtherBar{ int Foo; };", D));
a309 9
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("anyOf", Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = (2, )) != (Actual = 0)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("unless", std::string(), std::string(),
                               Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = (1, 1)) != (Actual = 2)",
            Error->toString());
d327 1
a327 2
  EXPECT_TRUE(constructMatcher("anyOf", std::string(), std::string(),
                               Error.get()).isNull());
@


1.1.1.3
log
@Import Clang 3.5svn r199312
@
text
@d10 2
a14 1
#include <vector>
@


1.1.1.4
log
@Import Clang 3.5svn r201163.
@
text
@a86 44

  typedef std::vector<MatcherCompletion> CompVector;

  CompVector getCompletions() {
    return Registry::getCompletions(
        llvm::ArrayRef<std::pair<MatcherCtor, unsigned> >());
  }

  CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1) {
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo1));
    return Registry::getCompletions(Context);
  }

  CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1,
                            StringRef MatcherName2, unsigned ArgNo2) {
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo1));
    Ctor = lookupMatcherCtor(MatcherName2);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo2));
    return Registry::getCompletions(Context);
  }

  bool hasCompletion(const CompVector &Comps, StringRef TypedText,
                     StringRef MatcherDecl = StringRef(), unsigned *Index = 0) {
    for (CompVector::const_iterator I = Comps.begin(), E = Comps.end(); I != E;
         ++I) {
      if (I->TypedText == TypedText &&
          (MatcherDecl.empty() || I->MatcherDecl == MatcherDecl)) {
        if (Index)
          *Index = I - Comps.begin();
        return true;
      }
    }
    return false;
  }
a380 41
TEST_F(RegistryTest, Completion) {
  CompVector Comps = getCompletions();
  EXPECT_TRUE(hasCompletion(
      Comps, "hasParent(", "Matcher<Decl|Stmt> hasParent(Matcher<Decl|Stmt>)"));
  EXPECT_TRUE(hasCompletion(Comps, "whileStmt(",
                            "Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)"));

  CompVector WhileComps = getCompletions("whileStmt", 0);

  unsigned HasBodyIndex, HasParentIndex, AllOfIndex;
  EXPECT_TRUE(hasCompletion(WhileComps, "hasBody(",
                            "Matcher<WhileStmt> hasBody(Matcher<Stmt>)",
                            &HasBodyIndex));
  EXPECT_TRUE(hasCompletion(WhileComps, "hasParent(",
                            "Matcher<Stmt> hasParent(Matcher<Decl|Stmt>)",
                            &HasParentIndex));
  EXPECT_TRUE(hasCompletion(WhileComps, "allOf(",
                            "Matcher<T> allOf(Matcher<T>...)", &AllOfIndex));
  EXPECT_GT(HasParentIndex, HasBodyIndex);
  EXPECT_GT(AllOfIndex, HasParentIndex);

  EXPECT_FALSE(hasCompletion(WhileComps, "whileStmt("));
  EXPECT_FALSE(hasCompletion(WhileComps, "ifStmt("));

  CompVector AllOfWhileComps =
      getCompletions("allOf", 0, "whileStmt", 0);
  ASSERT_EQ(AllOfWhileComps.size(), WhileComps.size());
  EXPECT_TRUE(std::equal(WhileComps.begin(), WhileComps.end(),
                         AllOfWhileComps.begin()));

  CompVector DeclWhileComps =
      getCompletions("decl", 0, "whileStmt", 0);
  EXPECT_EQ(0u, DeclWhileComps.size());

  CompVector NamedDeclComps = getCompletions("namedDecl", 0);
  EXPECT_TRUE(
      hasCompletion(NamedDeclComps, "isPublic()", "Matcher<Decl> isPublic()"));
  EXPECT_TRUE(hasCompletion(NamedDeclComps, "hasName(\"",
                            "Matcher<NamedDecl> hasName(string)"));
}

@


1.1.1.4.2.1
log
@Rebase.
@
text
@d38 8
a45 2
  llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) {
    return Registry::lookupMatcherCtor(MatcherName);
d52 1
a52 1
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
d65 1
a65 1
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
d69 1
a69 1
    EXPECT_EQ("", DummyError.toStringFull()) << MatcherName;
d79 1
a79 1
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
a213 19

  Matcher<Decl> DeclDecl = declaratorDecl(hasTypeLoc(
      constructMatcher(
          "loc", constructMatcher("asString", std::string("const double *")))
          .getTypedMatcher<TypeLoc>()));

  Matcher<NestedNameSpecifierLoc> NNSL =
      constructMatcher(
          "loc", VariantMatcher::SingleMatcher(nestedNameSpecifier(
                     specifiesType(hasDeclaration(recordDecl(hasName("A")))))))
          .getTypedMatcher<NestedNameSpecifierLoc>();

  Code = "const double * x = 0;";
  EXPECT_TRUE(matches(Code, DeclDecl));
  EXPECT_FALSE(matches(Code, NNSL));

  Code = "struct A { struct B {}; }; A::B a_b;";
  EXPECT_FALSE(matches(Code, DeclDecl));
  EXPECT_TRUE(matches(Code, NNSL));
d373 1
a373 1
  std::unique_ptr<Diagnostics> Error(new Diagnostics());
@


1.1.1.5
log
@Import Clang 3.5svn r209886.
@
text
@d38 8
a45 2
  llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) {
    return Registry::lookupMatcherCtor(MatcherName);
d52 1
a52 1
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
d65 1
a65 1
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
d69 1
a69 1
    EXPECT_EQ("", DummyError.toStringFull()) << MatcherName;
d79 1
a79 1
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
a213 19

  Matcher<Decl> DeclDecl = declaratorDecl(hasTypeLoc(
      constructMatcher(
          "loc", constructMatcher("asString", std::string("const double *")))
          .getTypedMatcher<TypeLoc>()));

  Matcher<NestedNameSpecifierLoc> NNSL =
      constructMatcher(
          "loc", VariantMatcher::SingleMatcher(nestedNameSpecifier(
                     specifiesType(hasDeclaration(recordDecl(hasName("A")))))))
          .getTypedMatcher<NestedNameSpecifierLoc>();

  Code = "const double * x = 0;";
  EXPECT_TRUE(matches(Code, DeclDecl));
  EXPECT_FALSE(matches(Code, NNSL));

  Code = "struct A { struct B {}; }; A::B a_b;";
  EXPECT_FALSE(matches(Code, DeclDecl));
  EXPECT_TRUE(matches(Code, NNSL));
d373 1
a373 1
  std::unique_ptr<Diagnostics> Error(new Diagnostics());
@


1.1.1.6
log
@Import clang 3.6svn r215315.
@
text
@d43 1
a43 1
                                  Diagnostics *Error = nullptr) {
d56 1
a56 1
                                  Diagnostics *Error = nullptr) {
d70 1
a70 1
                                  Diagnostics *Error = nullptr) {
d86 1
a86 1
        ArrayRef<std::pair<MatcherCtor, unsigned> >());
d113 1
a113 2
                     StringRef MatcherDecl = StringRef(),
                     unsigned *Index = nullptr) {
@


1.1.1.6.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@d85 2
a86 3
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    return Registry::getMatcherCompletions(
        Registry::getAcceptedCompletionTypes(Context));
d95 1
a95 2
    return Registry::getMatcherCompletions(
        Registry::getAcceptedCompletionTypes(Context));
d109 1
a109 2
    return Registry::getMatcherCompletions(
        Registry::getAcceptedCompletionTypes(Context));
d113 2
a114 1
                     StringRef MatcherDecl = StringRef()) {
d119 2
d350 1
a350 1
      constructMatcher("functionDecl",
a382 7

  D = constructMatcher(
          "namedDecl", constructMatcher("hasName", std::string("Foo")),
          constructMatcher("unless", constructMatcher("recordDecl")))
          .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("void Foo(){}", D));
  EXPECT_TRUE(notMatches("struct Foo {};", D));
a440 1
  // Overloaded
a442 1
  // Variadic.
a444 6
  // Polymorphic.
  EXPECT_TRUE(hasCompletion(
      Comps, "hasDescendant(",
      "Matcher<NestedNameSpecifier|NestedNameSpecifierLoc|QualType|...> "
      "hasDescendant(Matcher<CXXCtorInitializer|NestedNameSpecifier|"
      "NestedNameSpecifierLoc|...>)"));
d448 1
d450 2
a451 1
                            "Matcher<WhileStmt> hasBody(Matcher<Stmt>)"));
d453 6
a458 3
                            "Matcher<Stmt> hasParent(Matcher<Decl|Stmt>)"));
  EXPECT_TRUE(
      hasCompletion(WhileComps, "allOf(", "Matcher<T> allOf(Matcher<T>...)"));
a477 14

  // Heterogeneous overloads.
  Comps = getCompletions("classTemplateSpecializationDecl", 0);
  EXPECT_TRUE(hasCompletion(
      Comps, "isSameOrDerivedFrom(",
      "Matcher<CXXRecordDecl> isSameOrDerivedFrom(string|Matcher<NamedDecl>)"));
}

TEST_F(RegistryTest, HasArgs) {
  Matcher<Decl> Value = constructMatcher(
      "decl", constructMatcher("hasAttr", std::string("attr::WarnUnused")))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};", Value));
  EXPECT_FALSE(matches("struct X {};", Value));
@


1.1.1.7
log
@Import Clang 3.6RC1 r227398.
@
text
@d85 2
a86 3
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    return Registry::getMatcherCompletions(
        Registry::getAcceptedCompletionTypes(Context));
d95 1
a95 2
    return Registry::getMatcherCompletions(
        Registry::getAcceptedCompletionTypes(Context));
d109 1
a109 2
    return Registry::getMatcherCompletions(
        Registry::getAcceptedCompletionTypes(Context));
d113 2
a114 1
                     StringRef MatcherDecl = StringRef()) {
d119 2
d350 1
a350 1
      constructMatcher("functionDecl",
a382 7

  D = constructMatcher(
          "namedDecl", constructMatcher("hasName", std::string("Foo")),
          constructMatcher("unless", constructMatcher("recordDecl")))
          .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("void Foo(){}", D));
  EXPECT_TRUE(notMatches("struct Foo {};", D));
a440 1
  // Overloaded
a442 1
  // Variadic.
a444 6
  // Polymorphic.
  EXPECT_TRUE(hasCompletion(
      Comps, "hasDescendant(",
      "Matcher<NestedNameSpecifier|NestedNameSpecifierLoc|QualType|...> "
      "hasDescendant(Matcher<CXXCtorInitializer|NestedNameSpecifier|"
      "NestedNameSpecifierLoc|...>)"));
d448 1
d450 2
a451 1
                            "Matcher<WhileStmt> hasBody(Matcher<Stmt>)"));
d453 6
a458 3
                            "Matcher<Stmt> hasParent(Matcher<Decl|Stmt>)"));
  EXPECT_TRUE(
      hasCompletion(WhileComps, "allOf(", "Matcher<T> allOf(Matcher<T>...)"));
a477 14

  // Heterogeneous overloads.
  Comps = getCompletions("classTemplateSpecializationDecl", 0);
  EXPECT_TRUE(hasCompletion(
      Comps, "isSameOrDerivedFrom(",
      "Matcher<CXXRecordDecl> isSameOrDerivedFrom(string|Matcher<NamedDecl>)"));
}

TEST_F(RegistryTest, HasArgs) {
  Matcher<Decl> Value = constructMatcher(
      "decl", constructMatcher("hasAttr", std::string("attr::WarnUnused")))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};", Value));
  EXPECT_FALSE(matches("struct X {};", Value));
@


1.1.1.8
log
@Import Clang 3.8.0rc3 r261930.
@
text
@d132 1
a132 1
      constructMatcher("cxxBoolLiteral").getTypedMatcher<Stmt>();
d147 1
a147 1
      "namedDecl", constructMatcher("hasName", StringRef("X")))
d181 1
a181 1
          "hasParameter", 1, constructMatcher("hasName", StringRef("x")))
d198 2
a199 2
          constructMatcher("cxxMethodDecl",
                           constructMatcher("hasName", StringRef("x")))))
d212 1
a212 1
          "loc", constructMatcher("asString", StringRef("const double *")))
d247 1
a247 1
      "recordDecl", constructMatcher("hasName", StringRef("Foo")),
d258 1
a258 1
      "cxxConstructExpr",
d262 1
a262 1
              "cxxMethodDecl",
d264 1
a264 1
                  "ofClass", constructMatcher("hasName", StringRef("Foo"))))))
d277 1
a277 1
                           constructMatcher("asString", StringRef("int")))))
d303 1
a303 1
      "cxxConstructorDecl",
d307 1
a307 1
                           constructMatcher("hasName", StringRef("foo")))))
d320 1
a320 1
                           constructMatcher("hasName", StringRef("X")))))
d331 1
a331 1
                           constructMatcher("hasName", StringRef("X")))))
d349 1
a349 1
                       constructMatcher("hasName", StringRef("Foo"))),
d351 1
a351 1
                       constructMatcher("hasName", StringRef("foo"))))
d363 2
a364 2
                           constructMatcher("hasName", StringRef("Foo")),
                           constructMatcher("hasName", StringRef("Bar")))))
d378 1
a378 1
                           constructMatcher("hasName", StringRef("Bar"))))
d385 1
a385 1
          "namedDecl", constructMatcher("hasName", StringRef("Foo")),
d399 1
a399 1
  EXPECT_TRUE(constructMatcher("isArrow", StringRef(), Error.get()).isNull());
d407 1
a407 1
  EXPECT_TRUE(constructMatcher("unless", StringRef(), StringRef(),
d414 1
a414 1
  EXPECT_TRUE(constructMatcher("ofClass", StringRef(), Error.get()).isNull());
d419 3
a421 4
  EXPECT_TRUE(
      constructMatcher("cxxRecordDecl", constructMatcher("cxxRecordDecl"),
                       constructMatcher("parameterCountIs", 3), Error.get())
          .isNull());
d428 1
a428 1
  EXPECT_TRUE(constructMatcher("anyOf", StringRef(), StringRef(),
d435 1
a435 1
      "cxxRecordDecl",
d437 1
a437 1
                       constructMatcher("isDerivedFrom", StringRef("FOO")),
d450 1
a450 3
      Comps, "hasParent(",
      "Matcher<TemplateArgument|NestedNameSpecifierLoc|Decl|...> "
      "hasParent(Matcher<TemplateArgument|NestedNameSpecifierLoc|Decl|...>)"));
d457 2
a458 2
      "Matcher<TemplateArgument|NestedNameSpecifier|NestedNameSpecifierLoc|...>"
      " hasDescendant(Matcher<TemplateArgument|NestedNameSpecifier|"
d466 1
a466 3
                            "Matcher<Stmt> "
                            "hasParent(Matcher<TemplateArgument|"
                            "NestedNameSpecifierLoc|Decl|...>)"));
d498 1
a498 1
      "decl", constructMatcher("hasAttr", StringRef("attr::WarnUnused")))
@


1.1.1.8.2.1
log
@Sync with HEAD
@
text
@d424 1
a424 1
            "(Actual = Matcher<FunctionDecl|FunctionProtoType>)",
d452 2
a453 2
      "Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...> "
      "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)"));
d460 3
a462 2
      "Matcher<NestedNameSpecifierLoc|QualType|TypeLoc|...> "
      "hasDescendant(Matcher<NestedNameSpecifierLoc|QualType|TypeLoc|...>)"));
d468 4
a471 4
  EXPECT_TRUE(hasCompletion(
      WhileComps, "hasParent(",
      "Matcher<Stmt> "
      "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)"));
a508 6
TEST_F(RegistryTest, ParenExpr) {
  Matcher<Stmt> Value = constructMatcher("parenExpr").getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("int i = (1);", Value));
  EXPECT_FALSE(matches("int i = 1;", Value));
}

@


1.1.1.9
log
@Import Clang pre-4.0.0 r291444.
@
text
@d424 1
a424 1
            "(Actual = Matcher<FunctionDecl|FunctionProtoType>)",
d452 2
a453 2
      "Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...> "
      "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)"));
d460 3
a462 2
      "Matcher<NestedNameSpecifierLoc|QualType|TypeLoc|...> "
      "hasDescendant(Matcher<NestedNameSpecifierLoc|QualType|TypeLoc|...>)"));
d468 4
a471 4
  EXPECT_TRUE(hasCompletion(
      WhileComps, "hasParent(",
      "Matcher<Stmt> "
      "hasParent(Matcher<NestedNameSpecifierLoc|TypeLoc|Decl|...>)"));
a508 6
TEST_F(RegistryTest, ParenExpr) {
  Matcher<Stmt> Value = constructMatcher("parenExpr").getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("int i = (1);", Value));
  EXPECT_FALSE(matches("int i = 1;", Value));
}

@


1.1.1.10
log
@Import clang r309604 from branches/release_50
@
text
@a513 43
TEST_F(RegistryTest, EqualsMatcher) {
  Matcher<Stmt> BooleanStmt = constructMatcher(
      "cxxBoolLiteral", constructMatcher("equals", VariantValue(true)))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("bool x = true;", BooleanStmt));
  EXPECT_FALSE(matches("bool x = false;", BooleanStmt));
  EXPECT_FALSE(matches("bool x = 0;", BooleanStmt));

  BooleanStmt = constructMatcher(
      "cxxBoolLiteral", constructMatcher("equals", VariantValue(0)))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("bool x = false;", BooleanStmt));
  EXPECT_FALSE(matches("bool x = true;", BooleanStmt));
  EXPECT_FALSE(matches("bool x = 0;", BooleanStmt));

  Matcher<Stmt> DoubleStmt = constructMatcher(
      "floatLiteral", constructMatcher("equals", VariantValue(1.2)))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("double x = 1.2;", DoubleStmt));
#if 0
  // FIXME floatLiteral matching should work regardless of suffix.
  EXPECT_TRUE(matches("double x = 1.2f;", DoubleStmt));
  EXPECT_TRUE(matches("double x = 1.2l;", DoubleStmt));
#endif
  EXPECT_TRUE(matches("double x = 12e-1;", DoubleStmt));
  EXPECT_FALSE(matches("double x = 1.23;", DoubleStmt));

  Matcher<Stmt> IntegerStmt = constructMatcher(
      "integerLiteral", constructMatcher("equals", VariantValue(42)))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("int x = 42;", IntegerStmt));
  EXPECT_FALSE(matches("int x = 1;", IntegerStmt));

  Matcher<Stmt> CharStmt = constructMatcher(
      "characterLiteral", constructMatcher("equals", VariantValue('x')))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("int x = 'x';", CharStmt));
  EXPECT_TRUE(matches("int x = L'x';", CharStmt));
  EXPECT_TRUE(matches("int x = u'x';", CharStmt));
  EXPECT_TRUE(matches("int x = U'x';", CharStmt));
  EXPECT_FALSE(matches("int x = 120;", CharStmt));
}

@


1.1.1.10.4.1
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.11
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.6.4.1
log
@file RegistryTest.cpp was added on branch tls-maxphys on 2014-08-19 23:49:27 +0000
@
text
@d1 483
@


1.1.1.6.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 483
//===- unittest/ASTMatchers/Dynamic/RegistryTest.cpp - Registry unit tests -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===-----------------------------------------------------------------------===//

#include "../ASTMatchersTest.h"
#include "clang/ASTMatchers/Dynamic/Registry.h"
#include "gtest/gtest.h"
#include <vector>

namespace clang {
namespace ast_matchers {
namespace dynamic {
namespace {

using ast_matchers::internal::Matcher;

class RegistryTest : public ::testing::Test {
public:
  std::vector<ParserValue> Args() { return std::vector<ParserValue>(); }
  std::vector<ParserValue> Args(const VariantValue &Arg1) {
    std::vector<ParserValue> Out(1);
    Out[0].Value = Arg1;
    return Out;
  }
  std::vector<ParserValue> Args(const VariantValue &Arg1,
                                const VariantValue &Arg2) {
    std::vector<ParserValue> Out(2);
    Out[0].Value = Arg1;
    Out[1].Value = Arg2;
    return Out;
  }

  llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName) {
    return Registry::lookupMatcherCtor(MatcherName);
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  Diagnostics *Error = nullptr) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  const VariantValue &Arg1,
                                  Diagnostics *Error = nullptr) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1), Error);
    EXPECT_EQ("", DummyError.toStringFull()) << MatcherName;
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  const VariantValue &Arg1,
                                  const VariantValue &Arg2,
                                  Diagnostics *Error = nullptr) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1, Arg2),
                                       Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  typedef std::vector<MatcherCompletion> CompVector;

  CompVector getCompletions() {
    return Registry::getCompletions(
        ArrayRef<std::pair<MatcherCtor, unsigned> >());
  }

  CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1) {
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo1));
    return Registry::getCompletions(Context);
  }

  CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1,
                            StringRef MatcherName2, unsigned ArgNo2) {
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo1));
    Ctor = lookupMatcherCtor(MatcherName2);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo2));
    return Registry::getCompletions(Context);
  }

  bool hasCompletion(const CompVector &Comps, StringRef TypedText,
                     StringRef MatcherDecl = StringRef(),
                     unsigned *Index = nullptr) {
    for (CompVector::const_iterator I = Comps.begin(), E = Comps.end(); I != E;
         ++I) {
      if (I->TypedText == TypedText &&
          (MatcherDecl.empty() || I->MatcherDecl == MatcherDecl)) {
        if (Index)
          *Index = I - Comps.begin();
        return true;
      }
    }
    return false;
  }
};

TEST_F(RegistryTest, CanConstructNoArgs) {
  Matcher<Stmt> IsArrowValue = constructMatcher(
      "memberExpr", constructMatcher("isArrow")).getTypedMatcher<Stmt>();
  Matcher<Stmt> BoolValue =
      constructMatcher("boolLiteral").getTypedMatcher<Stmt>();

  const std::string ClassSnippet = "struct Foo { int x; };\n"
                                   "Foo *foo = new Foo;\n"
                                   "int i = foo->x;\n";
  const std::string BoolSnippet = "bool Foo = true;\n";

  EXPECT_TRUE(matches(ClassSnippet, IsArrowValue));
  EXPECT_TRUE(matches(BoolSnippet, BoolValue));
  EXPECT_FALSE(matches(ClassSnippet, BoolValue));
  EXPECT_FALSE(matches(BoolSnippet, IsArrowValue));
}

TEST_F(RegistryTest, ConstructWithSimpleArgs) {
  Matcher<Decl> Value = constructMatcher(
      "namedDecl", constructMatcher("hasName", std::string("X")))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("class X {};", Value));
  EXPECT_FALSE(matches("int x;", Value));

  Value = functionDecl(constructMatcher("parameterCountIs", 2)
                           .getTypedMatcher<FunctionDecl>());
  EXPECT_TRUE(matches("void foo(int,int);", Value));
  EXPECT_FALSE(matches("void foo(int);", Value));
}

TEST_F(RegistryTest, ConstructWithMatcherArgs) {
  Matcher<Decl> HasInitializerSimple = constructMatcher(
      "varDecl", constructMatcher("hasInitializer", constructMatcher("stmt")))
      .getTypedMatcher<Decl>();
  Matcher<Decl> HasInitializerComplex = constructMatcher(
      "varDecl",
      constructMatcher("hasInitializer", constructMatcher("callExpr")))
      .getTypedMatcher<Decl>();

  std::string code = "int i;";
  EXPECT_FALSE(matches(code, HasInitializerSimple));
  EXPECT_FALSE(matches(code, HasInitializerComplex));

  code = "int i = 1;";
  EXPECT_TRUE(matches(code, HasInitializerSimple));
  EXPECT_FALSE(matches(code, HasInitializerComplex));

  code = "int y(); int i = y();";
  EXPECT_TRUE(matches(code, HasInitializerSimple));
  EXPECT_TRUE(matches(code, HasInitializerComplex));

  Matcher<Decl> HasParameter =
      functionDecl(constructMatcher(
          "hasParameter", 1, constructMatcher("hasName", std::string("x")))
                       .getTypedMatcher<FunctionDecl>());
  EXPECT_TRUE(matches("void f(int a, int x);", HasParameter));
  EXPECT_FALSE(matches("void f(int x, int a);", HasParameter));
}

TEST_F(RegistryTest, OverloadedMatchers) {
  Matcher<Stmt> CallExpr0 = constructMatcher(
      "callExpr",
      constructMatcher("callee", constructMatcher("memberExpr",
                                                  constructMatcher("isArrow"))))
      .getTypedMatcher<Stmt>();

  Matcher<Stmt> CallExpr1 = constructMatcher(
      "callExpr",
      constructMatcher(
          "callee",
          constructMatcher("methodDecl",
                           constructMatcher("hasName", std::string("x")))))
      .getTypedMatcher<Stmt>();

  std::string Code = "class Y { public: void x(); }; void z() { Y y; y.x(); }";
  EXPECT_FALSE(matches(Code, CallExpr0));
  EXPECT_TRUE(matches(Code, CallExpr1));

  Code = "class Z { public: void z() { this->z(); } };";
  EXPECT_TRUE(matches(Code, CallExpr0));
  EXPECT_FALSE(matches(Code, CallExpr1));

  Matcher<Decl> DeclDecl = declaratorDecl(hasTypeLoc(
      constructMatcher(
          "loc", constructMatcher("asString", std::string("const double *")))
          .getTypedMatcher<TypeLoc>()));

  Matcher<NestedNameSpecifierLoc> NNSL =
      constructMatcher(
          "loc", VariantMatcher::SingleMatcher(nestedNameSpecifier(
                     specifiesType(hasDeclaration(recordDecl(hasName("A")))))))
          .getTypedMatcher<NestedNameSpecifierLoc>();

  Code = "const double * x = 0;";
  EXPECT_TRUE(matches(Code, DeclDecl));
  EXPECT_FALSE(matches(Code, NNSL));

  Code = "struct A { struct B {}; }; A::B a_b;";
  EXPECT_FALSE(matches(Code, DeclDecl));
  EXPECT_TRUE(matches(Code, NNSL));
}

TEST_F(RegistryTest, PolymorphicMatchers) {
  const VariantMatcher IsDefinition = constructMatcher("isDefinition");
  Matcher<Decl> Var =
      constructMatcher("varDecl", IsDefinition).getTypedMatcher<Decl>();
  Matcher<Decl> Class =
      constructMatcher("recordDecl", IsDefinition).getTypedMatcher<Decl>();
  Matcher<Decl> Func =
      constructMatcher("functionDecl", IsDefinition).getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("int a;", Var));
  EXPECT_FALSE(matches("extern int a;", Var));
  EXPECT_TRUE(matches("class A {};", Class));
  EXPECT_FALSE(matches("class A;", Class));
  EXPECT_TRUE(matches("void f(){};", Func));
  EXPECT_FALSE(matches("void f();", Func));

  Matcher<Decl> Anything = constructMatcher("anything").getTypedMatcher<Decl>();
  Matcher<Decl> RecordDecl = constructMatcher(
      "recordDecl", constructMatcher("hasName", std::string("Foo")),
      VariantMatcher::SingleMatcher(Anything)).getTypedMatcher<Decl>();

  EXPECT_TRUE(matches("int Foo;", Anything));
  EXPECT_TRUE(matches("class Foo {};", Anything));
  EXPECT_TRUE(matches("void Foo(){};", Anything));
  EXPECT_FALSE(matches("int Foo;", RecordDecl));
  EXPECT_TRUE(matches("class Foo {};", RecordDecl));
  EXPECT_FALSE(matches("void Foo(){};", RecordDecl));

  Matcher<Stmt> ConstructExpr = constructMatcher(
      "constructExpr",
      constructMatcher(
          "hasDeclaration",
          constructMatcher(
              "methodDecl",
              constructMatcher(
                  "ofClass", constructMatcher("hasName", std::string("Foo"))))))
                                    .getTypedMatcher<Stmt>();
  EXPECT_FALSE(matches("class Foo { public: Foo(); };", ConstructExpr));
  EXPECT_TRUE(
      matches("class Foo { public: Foo(); }; Foo foo = Foo();", ConstructExpr));
}

TEST_F(RegistryTest, TemplateArgument) {
  Matcher<Decl> HasTemplateArgument = constructMatcher(
      "classTemplateSpecializationDecl",
      constructMatcher(
          "hasAnyTemplateArgument",
          constructMatcher("refersToType",
                           constructMatcher("asString", std::string("int")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("template<typename T> class A {}; A<int> a;",
                      HasTemplateArgument));
  EXPECT_FALSE(matches("template<typename T> class A {}; A<char> a;",
                       HasTemplateArgument));
}

TEST_F(RegistryTest, TypeTraversal) {
  Matcher<Type> M = constructMatcher(
      "pointerType",
      constructMatcher("pointee", constructMatcher("isConstQualified"),
                       constructMatcher("isInteger"))).getTypedMatcher<Type>();
  EXPECT_FALSE(matches("int *a;", M));
  EXPECT_TRUE(matches("int const *b;", M));

  M = constructMatcher(
      "arrayType",
      constructMatcher("hasElementType", constructMatcher("builtinType")))
      .getTypedMatcher<Type>();
  EXPECT_FALSE(matches("struct A{}; A a[7];;", M));
  EXPECT_TRUE(matches("int b[7];", M));
}

TEST_F(RegistryTest, CXXCtorInitializer) {
  Matcher<Decl> CtorDecl = constructMatcher(
      "constructorDecl",
      constructMatcher(
          "hasAnyConstructorInitializer",
          constructMatcher("forField",
                           constructMatcher("hasName", std::string("foo")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("struct Foo { Foo() : foo(1) {} int foo; };", CtorDecl));
  EXPECT_FALSE(matches("struct Foo { Foo() {} int foo; };", CtorDecl));
  EXPECT_FALSE(matches("struct Foo { Foo() : bar(1) {} int bar; };", CtorDecl));
}

TEST_F(RegistryTest, Adaptative) {
  Matcher<Decl> D = constructMatcher(
      "recordDecl",
      constructMatcher(
          "has",
          constructMatcher("recordDecl",
                           constructMatcher("hasName", std::string("X")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("class X {};", D));
  EXPECT_TRUE(matches("class Y { class X {}; };", D));
  EXPECT_FALSE(matches("class Y { class Z {}; };", D));

  Matcher<Stmt> S = constructMatcher(
      "forStmt",
      constructMatcher(
          "hasDescendant",
          constructMatcher("varDecl",
                           constructMatcher("hasName", std::string("X")))))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("void foo() { for(int X;;); }", S));
  EXPECT_TRUE(matches("void foo() { for(;;) { int X; } }", S));
  EXPECT_FALSE(matches("void foo() { for(;;); }", S));
  EXPECT_FALSE(matches("void foo() { if (int X = 0){} }", S));

  S = constructMatcher(
      "compoundStmt", constructMatcher("hasParent", constructMatcher("ifStmt")))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("void foo() { if (true) { int x = 42; } }", S));
  EXPECT_FALSE(matches("void foo() { if (true) return; }", S));
}

TEST_F(RegistryTest, VariadicOp) {
  Matcher<Decl> D = constructMatcher(
      "anyOf",
      constructMatcher("recordDecl",
                       constructMatcher("hasName", std::string("Foo"))),
      constructMatcher("namedDecl",
                       constructMatcher("hasName", std::string("foo"))))
      .getTypedMatcher<Decl>();

  EXPECT_TRUE(matches("void foo(){}", D));
  EXPECT_TRUE(matches("struct Foo{};", D));
  EXPECT_FALSE(matches("int i = 0;", D));

  D = constructMatcher(
      "allOf", constructMatcher("recordDecl"),
      constructMatcher(
          "namedDecl",
          constructMatcher("anyOf",
                           constructMatcher("hasName", std::string("Foo")),
                           constructMatcher("hasName", std::string("Bar")))))
      .getTypedMatcher<Decl>();

  EXPECT_FALSE(matches("void foo(){}", D));
  EXPECT_TRUE(matches("struct Foo{};", D));
  EXPECT_FALSE(matches("int i = 0;", D));
  EXPECT_TRUE(matches("class Bar{};", D));
  EXPECT_FALSE(matches("class OtherBar{};", D));

  D = recordDecl(
      has(fieldDecl(hasName("Foo"))),
      constructMatcher(
          "unless",
          constructMatcher("namedDecl",
                           constructMatcher("hasName", std::string("Bar"))))
          .getTypedMatcher<Decl>());

  EXPECT_FALSE(matches("class Bar{ int Foo; };", D));
  EXPECT_TRUE(matches("class OtherBar{ int Foo; };", D));
}

TEST_F(RegistryTest, Errors) {
  // Incorrect argument count.
  std::unique_ptr<Diagnostics> Error(new Diagnostics());
  EXPECT_TRUE(constructMatcher("hasInitializer", Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = 1) != (Actual = 0)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("isArrow", std::string(), Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = 0) != (Actual = 1)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("anyOf", Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = (2, )) != (Actual = 0)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("unless", std::string(), std::string(),
                               Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = (1, 1)) != (Actual = 2)",
            Error->toString());

  // Bad argument type
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("ofClass", std::string(), Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 1. (Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = String)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("recordDecl", constructMatcher("recordDecl"),
                               constructMatcher("parameterCountIs", 3),
                               Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 2. (Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = Matcher<FunctionDecl>)",
            Error->toString());

  // Bad argument type with variadic.
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("anyOf", std::string(), std::string(),
                               Error.get()).isNull());
  EXPECT_EQ(
      "Incorrect type for arg 1. (Expected = Matcher<>) != (Actual = String)",
      Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher(
      "recordDecl",
      constructMatcher("allOf",
                       constructMatcher("isDerivedFrom", std::string("FOO")),
                       constructMatcher("isArrow")),
      Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 1. "
            "(Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = Matcher<CXXRecordDecl>&Matcher<MemberExpr>)",
            Error->toString());
}

TEST_F(RegistryTest, Completion) {
  CompVector Comps = getCompletions();
  EXPECT_TRUE(hasCompletion(
      Comps, "hasParent(", "Matcher<Decl|Stmt> hasParent(Matcher<Decl|Stmt>)"));
  EXPECT_TRUE(hasCompletion(Comps, "whileStmt(",
                            "Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)"));

  CompVector WhileComps = getCompletions("whileStmt", 0);

  unsigned HasBodyIndex, HasParentIndex, AllOfIndex;
  EXPECT_TRUE(hasCompletion(WhileComps, "hasBody(",
                            "Matcher<WhileStmt> hasBody(Matcher<Stmt>)",
                            &HasBodyIndex));
  EXPECT_TRUE(hasCompletion(WhileComps, "hasParent(",
                            "Matcher<Stmt> hasParent(Matcher<Decl|Stmt>)",
                            &HasParentIndex));
  EXPECT_TRUE(hasCompletion(WhileComps, "allOf(",
                            "Matcher<T> allOf(Matcher<T>...)", &AllOfIndex));
  EXPECT_GT(HasParentIndex, HasBodyIndex);
  EXPECT_GT(AllOfIndex, HasParentIndex);

  EXPECT_FALSE(hasCompletion(WhileComps, "whileStmt("));
  EXPECT_FALSE(hasCompletion(WhileComps, "ifStmt("));

  CompVector AllOfWhileComps =
      getCompletions("allOf", 0, "whileStmt", 0);
  ASSERT_EQ(AllOfWhileComps.size(), WhileComps.size());
  EXPECT_TRUE(std::equal(WhileComps.begin(), WhileComps.end(),
                         AllOfWhileComps.begin()));

  CompVector DeclWhileComps =
      getCompletions("decl", 0, "whileStmt", 0);
  EXPECT_EQ(0u, DeclWhileComps.size());

  CompVector NamedDeclComps = getCompletions("namedDecl", 0);
  EXPECT_TRUE(
      hasCompletion(NamedDeclComps, "isPublic()", "Matcher<Decl> isPublic()"));
  EXPECT_TRUE(hasCompletion(NamedDeclComps, "hasName(\"",
                            "Matcher<NamedDecl> hasName(string)"));
}

} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
} // end namespace clang
@


1.1.1.4.4.1
log
@file RegistryTest.cpp was added on branch yamt-pagecache on 2014-05-22 16:19:48 +0000
@
text
@d1 469
@


1.1.1.4.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 469
//===- unittest/ASTMatchers/Dynamic/RegistryTest.cpp - Registry unit tests -===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===-----------------------------------------------------------------------===//

#include "../ASTMatchersTest.h"
#include "clang/ASTMatchers/Dynamic/Registry.h"
#include "gtest/gtest.h"
#include <vector>

namespace clang {
namespace ast_matchers {
namespace dynamic {
namespace {

using ast_matchers::internal::Matcher;

class RegistryTest : public ::testing::Test {
public:
  std::vector<ParserValue> Args() { return std::vector<ParserValue>(); }
  std::vector<ParserValue> Args(const VariantValue &Arg1) {
    std::vector<ParserValue> Out(1);
    Out[0].Value = Arg1;
    return Out;
  }
  std::vector<ParserValue> Args(const VariantValue &Arg1,
                                const VariantValue &Arg2) {
    std::vector<ParserValue> Out(2);
    Out[0].Value = Arg1;
    Out[1].Value = Arg2;
    return Out;
  }

  llvm::Optional<MatcherCtor> lookupMatcherCtor(StringRef MatcherName,
                                                Diagnostics *Error = 0) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor =
        Registry::lookupMatcherCtor(MatcherName, SourceRange(), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Ctor;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  Diagnostics *Error = NULL) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName, Error);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  const VariantValue &Arg1,
                                  Diagnostics *Error = NULL) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName, Error);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1), Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  VariantMatcher constructMatcher(StringRef MatcherName,
                                  const VariantValue &Arg1,
                                  const VariantValue &Arg2,
                                  Diagnostics *Error = NULL) {
    Diagnostics DummyError;
    if (!Error) Error = &DummyError;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName, Error);
    VariantMatcher Out;
    if (Ctor)
      Out = Registry::constructMatcher(*Ctor, SourceRange(), Args(Arg1, Arg2),
                                       Error);
    EXPECT_EQ("", DummyError.toStringFull());
    return Out;
  }

  typedef std::vector<MatcherCompletion> CompVector;

  CompVector getCompletions() {
    return Registry::getCompletions(
        llvm::ArrayRef<std::pair<MatcherCtor, unsigned> >());
  }

  CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1) {
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo1));
    return Registry::getCompletions(Context);
  }

  CompVector getCompletions(StringRef MatcherName1, unsigned ArgNo1,
                            StringRef MatcherName2, unsigned ArgNo2) {
    std::vector<std::pair<MatcherCtor, unsigned> > Context;
    llvm::Optional<MatcherCtor> Ctor = lookupMatcherCtor(MatcherName1);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo1));
    Ctor = lookupMatcherCtor(MatcherName2);
    if (!Ctor)
      return CompVector();
    Context.push_back(std::make_pair(*Ctor, ArgNo2));
    return Registry::getCompletions(Context);
  }

  bool hasCompletion(const CompVector &Comps, StringRef TypedText,
                     StringRef MatcherDecl = StringRef(), unsigned *Index = 0) {
    for (CompVector::const_iterator I = Comps.begin(), E = Comps.end(); I != E;
         ++I) {
      if (I->TypedText == TypedText &&
          (MatcherDecl.empty() || I->MatcherDecl == MatcherDecl)) {
        if (Index)
          *Index = I - Comps.begin();
        return true;
      }
    }
    return false;
  }
};

TEST_F(RegistryTest, CanConstructNoArgs) {
  Matcher<Stmt> IsArrowValue = constructMatcher(
      "memberExpr", constructMatcher("isArrow")).getTypedMatcher<Stmt>();
  Matcher<Stmt> BoolValue =
      constructMatcher("boolLiteral").getTypedMatcher<Stmt>();

  const std::string ClassSnippet = "struct Foo { int x; };\n"
                                   "Foo *foo = new Foo;\n"
                                   "int i = foo->x;\n";
  const std::string BoolSnippet = "bool Foo = true;\n";

  EXPECT_TRUE(matches(ClassSnippet, IsArrowValue));
  EXPECT_TRUE(matches(BoolSnippet, BoolValue));
  EXPECT_FALSE(matches(ClassSnippet, BoolValue));
  EXPECT_FALSE(matches(BoolSnippet, IsArrowValue));
}

TEST_F(RegistryTest, ConstructWithSimpleArgs) {
  Matcher<Decl> Value = constructMatcher(
      "namedDecl", constructMatcher("hasName", std::string("X")))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("class X {};", Value));
  EXPECT_FALSE(matches("int x;", Value));

  Value = functionDecl(constructMatcher("parameterCountIs", 2)
                           .getTypedMatcher<FunctionDecl>());
  EXPECT_TRUE(matches("void foo(int,int);", Value));
  EXPECT_FALSE(matches("void foo(int);", Value));
}

TEST_F(RegistryTest, ConstructWithMatcherArgs) {
  Matcher<Decl> HasInitializerSimple = constructMatcher(
      "varDecl", constructMatcher("hasInitializer", constructMatcher("stmt")))
      .getTypedMatcher<Decl>();
  Matcher<Decl> HasInitializerComplex = constructMatcher(
      "varDecl",
      constructMatcher("hasInitializer", constructMatcher("callExpr")))
      .getTypedMatcher<Decl>();

  std::string code = "int i;";
  EXPECT_FALSE(matches(code, HasInitializerSimple));
  EXPECT_FALSE(matches(code, HasInitializerComplex));

  code = "int i = 1;";
  EXPECT_TRUE(matches(code, HasInitializerSimple));
  EXPECT_FALSE(matches(code, HasInitializerComplex));

  code = "int y(); int i = y();";
  EXPECT_TRUE(matches(code, HasInitializerSimple));
  EXPECT_TRUE(matches(code, HasInitializerComplex));

  Matcher<Decl> HasParameter =
      functionDecl(constructMatcher(
          "hasParameter", 1, constructMatcher("hasName", std::string("x")))
                       .getTypedMatcher<FunctionDecl>());
  EXPECT_TRUE(matches("void f(int a, int x);", HasParameter));
  EXPECT_FALSE(matches("void f(int x, int a);", HasParameter));
}

TEST_F(RegistryTest, OverloadedMatchers) {
  Matcher<Stmt> CallExpr0 = constructMatcher(
      "callExpr",
      constructMatcher("callee", constructMatcher("memberExpr",
                                                  constructMatcher("isArrow"))))
      .getTypedMatcher<Stmt>();

  Matcher<Stmt> CallExpr1 = constructMatcher(
      "callExpr",
      constructMatcher(
          "callee",
          constructMatcher("methodDecl",
                           constructMatcher("hasName", std::string("x")))))
      .getTypedMatcher<Stmt>();

  std::string Code = "class Y { public: void x(); }; void z() { Y y; y.x(); }";
  EXPECT_FALSE(matches(Code, CallExpr0));
  EXPECT_TRUE(matches(Code, CallExpr1));

  Code = "class Z { public: void z() { this->z(); } };";
  EXPECT_TRUE(matches(Code, CallExpr0));
  EXPECT_FALSE(matches(Code, CallExpr1));
}

TEST_F(RegistryTest, PolymorphicMatchers) {
  const VariantMatcher IsDefinition = constructMatcher("isDefinition");
  Matcher<Decl> Var =
      constructMatcher("varDecl", IsDefinition).getTypedMatcher<Decl>();
  Matcher<Decl> Class =
      constructMatcher("recordDecl", IsDefinition).getTypedMatcher<Decl>();
  Matcher<Decl> Func =
      constructMatcher("functionDecl", IsDefinition).getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("int a;", Var));
  EXPECT_FALSE(matches("extern int a;", Var));
  EXPECT_TRUE(matches("class A {};", Class));
  EXPECT_FALSE(matches("class A;", Class));
  EXPECT_TRUE(matches("void f(){};", Func));
  EXPECT_FALSE(matches("void f();", Func));

  Matcher<Decl> Anything = constructMatcher("anything").getTypedMatcher<Decl>();
  Matcher<Decl> RecordDecl = constructMatcher(
      "recordDecl", constructMatcher("hasName", std::string("Foo")),
      VariantMatcher::SingleMatcher(Anything)).getTypedMatcher<Decl>();

  EXPECT_TRUE(matches("int Foo;", Anything));
  EXPECT_TRUE(matches("class Foo {};", Anything));
  EXPECT_TRUE(matches("void Foo(){};", Anything));
  EXPECT_FALSE(matches("int Foo;", RecordDecl));
  EXPECT_TRUE(matches("class Foo {};", RecordDecl));
  EXPECT_FALSE(matches("void Foo(){};", RecordDecl));

  Matcher<Stmt> ConstructExpr = constructMatcher(
      "constructExpr",
      constructMatcher(
          "hasDeclaration",
          constructMatcher(
              "methodDecl",
              constructMatcher(
                  "ofClass", constructMatcher("hasName", std::string("Foo"))))))
                                    .getTypedMatcher<Stmt>();
  EXPECT_FALSE(matches("class Foo { public: Foo(); };", ConstructExpr));
  EXPECT_TRUE(
      matches("class Foo { public: Foo(); }; Foo foo = Foo();", ConstructExpr));
}

TEST_F(RegistryTest, TemplateArgument) {
  Matcher<Decl> HasTemplateArgument = constructMatcher(
      "classTemplateSpecializationDecl",
      constructMatcher(
          "hasAnyTemplateArgument",
          constructMatcher("refersToType",
                           constructMatcher("asString", std::string("int")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("template<typename T> class A {}; A<int> a;",
                      HasTemplateArgument));
  EXPECT_FALSE(matches("template<typename T> class A {}; A<char> a;",
                       HasTemplateArgument));
}

TEST_F(RegistryTest, TypeTraversal) {
  Matcher<Type> M = constructMatcher(
      "pointerType",
      constructMatcher("pointee", constructMatcher("isConstQualified"),
                       constructMatcher("isInteger"))).getTypedMatcher<Type>();
  EXPECT_FALSE(matches("int *a;", M));
  EXPECT_TRUE(matches("int const *b;", M));

  M = constructMatcher(
      "arrayType",
      constructMatcher("hasElementType", constructMatcher("builtinType")))
      .getTypedMatcher<Type>();
  EXPECT_FALSE(matches("struct A{}; A a[7];;", M));
  EXPECT_TRUE(matches("int b[7];", M));
}

TEST_F(RegistryTest, CXXCtorInitializer) {
  Matcher<Decl> CtorDecl = constructMatcher(
      "constructorDecl",
      constructMatcher(
          "hasAnyConstructorInitializer",
          constructMatcher("forField",
                           constructMatcher("hasName", std::string("foo")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("struct Foo { Foo() : foo(1) {} int foo; };", CtorDecl));
  EXPECT_FALSE(matches("struct Foo { Foo() {} int foo; };", CtorDecl));
  EXPECT_FALSE(matches("struct Foo { Foo() : bar(1) {} int bar; };", CtorDecl));
}

TEST_F(RegistryTest, Adaptative) {
  Matcher<Decl> D = constructMatcher(
      "recordDecl",
      constructMatcher(
          "has",
          constructMatcher("recordDecl",
                           constructMatcher("hasName", std::string("X")))))
      .getTypedMatcher<Decl>();
  EXPECT_TRUE(matches("class X {};", D));
  EXPECT_TRUE(matches("class Y { class X {}; };", D));
  EXPECT_FALSE(matches("class Y { class Z {}; };", D));

  Matcher<Stmt> S = constructMatcher(
      "forStmt",
      constructMatcher(
          "hasDescendant",
          constructMatcher("varDecl",
                           constructMatcher("hasName", std::string("X")))))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("void foo() { for(int X;;); }", S));
  EXPECT_TRUE(matches("void foo() { for(;;) { int X; } }", S));
  EXPECT_FALSE(matches("void foo() { for(;;); }", S));
  EXPECT_FALSE(matches("void foo() { if (int X = 0){} }", S));

  S = constructMatcher(
      "compoundStmt", constructMatcher("hasParent", constructMatcher("ifStmt")))
      .getTypedMatcher<Stmt>();
  EXPECT_TRUE(matches("void foo() { if (true) { int x = 42; } }", S));
  EXPECT_FALSE(matches("void foo() { if (true) return; }", S));
}

TEST_F(RegistryTest, VariadicOp) {
  Matcher<Decl> D = constructMatcher(
      "anyOf",
      constructMatcher("recordDecl",
                       constructMatcher("hasName", std::string("Foo"))),
      constructMatcher("namedDecl",
                       constructMatcher("hasName", std::string("foo"))))
      .getTypedMatcher<Decl>();

  EXPECT_TRUE(matches("void foo(){}", D));
  EXPECT_TRUE(matches("struct Foo{};", D));
  EXPECT_FALSE(matches("int i = 0;", D));

  D = constructMatcher(
      "allOf", constructMatcher("recordDecl"),
      constructMatcher(
          "namedDecl",
          constructMatcher("anyOf",
                           constructMatcher("hasName", std::string("Foo")),
                           constructMatcher("hasName", std::string("Bar")))))
      .getTypedMatcher<Decl>();

  EXPECT_FALSE(matches("void foo(){}", D));
  EXPECT_TRUE(matches("struct Foo{};", D));
  EXPECT_FALSE(matches("int i = 0;", D));
  EXPECT_TRUE(matches("class Bar{};", D));
  EXPECT_FALSE(matches("class OtherBar{};", D));

  D = recordDecl(
      has(fieldDecl(hasName("Foo"))),
      constructMatcher(
          "unless",
          constructMatcher("namedDecl",
                           constructMatcher("hasName", std::string("Bar"))))
          .getTypedMatcher<Decl>());

  EXPECT_FALSE(matches("class Bar{ int Foo; };", D));
  EXPECT_TRUE(matches("class OtherBar{ int Foo; };", D));
}

TEST_F(RegistryTest, Errors) {
  // Incorrect argument count.
  OwningPtr<Diagnostics> Error(new Diagnostics());
  EXPECT_TRUE(constructMatcher("hasInitializer", Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = 1) != (Actual = 0)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("isArrow", std::string(), Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = 0) != (Actual = 1)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("anyOf", Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = (2, )) != (Actual = 0)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("unless", std::string(), std::string(),
                               Error.get()).isNull());
  EXPECT_EQ("Incorrect argument count. (Expected = (1, 1)) != (Actual = 2)",
            Error->toString());

  // Bad argument type
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("ofClass", std::string(), Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 1. (Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = String)",
            Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("recordDecl", constructMatcher("recordDecl"),
                               constructMatcher("parameterCountIs", 3),
                               Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 2. (Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = Matcher<FunctionDecl>)",
            Error->toString());

  // Bad argument type with variadic.
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher("anyOf", std::string(), std::string(),
                               Error.get()).isNull());
  EXPECT_EQ(
      "Incorrect type for arg 1. (Expected = Matcher<>) != (Actual = String)",
      Error->toString());
  Error.reset(new Diagnostics());
  EXPECT_TRUE(constructMatcher(
      "recordDecl",
      constructMatcher("allOf",
                       constructMatcher("isDerivedFrom", std::string("FOO")),
                       constructMatcher("isArrow")),
      Error.get()).isNull());
  EXPECT_EQ("Incorrect type for arg 1. "
            "(Expected = Matcher<CXXRecordDecl>) != "
            "(Actual = Matcher<CXXRecordDecl>&Matcher<MemberExpr>)",
            Error->toString());
}

TEST_F(RegistryTest, Completion) {
  CompVector Comps = getCompletions();
  EXPECT_TRUE(hasCompletion(
      Comps, "hasParent(", "Matcher<Decl|Stmt> hasParent(Matcher<Decl|Stmt>)"));
  EXPECT_TRUE(hasCompletion(Comps, "whileStmt(",
                            "Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)"));

  CompVector WhileComps = getCompletions("whileStmt", 0);

  unsigned HasBodyIndex, HasParentIndex, AllOfIndex;
  EXPECT_TRUE(hasCompletion(WhileComps, "hasBody(",
                            "Matcher<WhileStmt> hasBody(Matcher<Stmt>)",
                            &HasBodyIndex));
  EXPECT_TRUE(hasCompletion(WhileComps, "hasParent(",
                            "Matcher<Stmt> hasParent(Matcher<Decl|Stmt>)",
                            &HasParentIndex));
  EXPECT_TRUE(hasCompletion(WhileComps, "allOf(",
                            "Matcher<T> allOf(Matcher<T>...)", &AllOfIndex));
  EXPECT_GT(HasParentIndex, HasBodyIndex);
  EXPECT_GT(AllOfIndex, HasParentIndex);

  EXPECT_FALSE(hasCompletion(WhileComps, "whileStmt("));
  EXPECT_FALSE(hasCompletion(WhileComps, "ifStmt("));

  CompVector AllOfWhileComps =
      getCompletions("allOf", 0, "whileStmt", 0);
  ASSERT_EQ(AllOfWhileComps.size(), WhileComps.size());
  EXPECT_TRUE(std::equal(WhileComps.begin(), WhileComps.end(),
                         AllOfWhileComps.begin()));

  CompVector DeclWhileComps =
      getCompletions("decl", 0, "whileStmt", 0);
  EXPECT_EQ(0u, DeclWhileComps.size());

  CompVector NamedDeclComps = getCompletions("namedDecl", 0);
  EXPECT_TRUE(
      hasCompletion(NamedDeclComps, "isPublic()", "Matcher<Decl> isPublic()"));
  EXPECT_TRUE(hasCompletion(NamedDeclComps, "hasName(\"",
                            "Matcher<NamedDecl> hasName(string)"));
}

} // end anonymous namespace
} // end namespace dynamic
} // end namespace ast_matchers
} // end namespace clang
@


