blob: 476a0be29040123701790aa4288ede059c76594d [file] [log] [blame]
//===- unittest/Tooling/ASTMatchersTest.cpp - AST matcher 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/AST/PrettyPrinter.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Host.h"
#include "gtest/gtest.h"
namespace clang {
namespace ast_matchers {
#if GTEST_HAS_DEATH_TEST
TEST(HasNameDeathTest, DiesOnEmptyName) {
ASSERT_DEBUG_DEATH({
DeclarationMatcher HasEmptyName = recordDecl(hasName(""));
EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
}, "");
}
TEST(HasNameDeathTest, DiesOnEmptyPattern) {
ASSERT_DEBUG_DEATH({
DeclarationMatcher HasEmptyName = recordDecl(matchesName(""));
EXPECT_TRUE(notMatches("class X {};", HasEmptyName));
}, "");
}
TEST(IsDerivedFromDeathTest, DiesOnEmptyBaseName) {
ASSERT_DEBUG_DEATH({
DeclarationMatcher IsDerivedFromEmpty = cxxRecordDecl(isDerivedFrom(""));
EXPECT_TRUE(notMatches("class X {};", IsDerivedFromEmpty));
}, "");
}
#endif
TEST(Finder, DynamicOnlyAcceptsSomeMatchers) {
MatchFinder Finder;
EXPECT_TRUE(Finder.addDynamicMatcher(decl(), nullptr));
EXPECT_TRUE(Finder.addDynamicMatcher(callExpr(), nullptr));
EXPECT_TRUE(Finder.addDynamicMatcher(constantArrayType(hasSize(42)),
nullptr));
// Do not accept non-toplevel matchers.
EXPECT_FALSE(Finder.addDynamicMatcher(isArrow(), nullptr));
EXPECT_FALSE(Finder.addDynamicMatcher(hasSize(2), nullptr));
EXPECT_FALSE(Finder.addDynamicMatcher(hasName("x"), nullptr));
}
TEST(Decl, MatchesDeclarations) {
EXPECT_TRUE(notMatches("", decl(usingDecl())));
EXPECT_TRUE(matches("namespace x { class X {}; } using x::X;",
decl(usingDecl())));
}
TEST(NameableDeclaration, MatchesVariousDecls) {
DeclarationMatcher NamedX = namedDecl(hasName("X"));
EXPECT_TRUE(matches("typedef int X;", NamedX));
EXPECT_TRUE(matches("int X;", NamedX));
EXPECT_TRUE(matches("class foo { virtual void X(); };", NamedX));
EXPECT_TRUE(matches("void foo() try { } catch(int X) { }", NamedX));
EXPECT_TRUE(matches("void foo() { int X; }", NamedX));
EXPECT_TRUE(matches("namespace X { }", NamedX));
EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
EXPECT_TRUE(notMatches("#define X 1", NamedX));
}
TEST(NameableDeclaration, REMatchesVariousDecls) {
DeclarationMatcher NamedX = namedDecl(matchesName("::X"));
EXPECT_TRUE(matches("typedef int Xa;", NamedX));
EXPECT_TRUE(matches("int Xb;", NamedX));
EXPECT_TRUE(matches("class foo { virtual void Xc(); };", NamedX));
EXPECT_TRUE(matches("void foo() try { } catch(int Xdef) { }", NamedX));
EXPECT_TRUE(matches("void foo() { int Xgh; }", NamedX));
EXPECT_TRUE(matches("namespace Xij { }", NamedX));
EXPECT_TRUE(matches("enum X { A, B, C };", NamedX));
EXPECT_TRUE(notMatches("#define Xkl 1", NamedX));
DeclarationMatcher StartsWithNo = namedDecl(matchesName("::no"));
EXPECT_TRUE(matches("int no_foo;", StartsWithNo));
EXPECT_TRUE(matches("class foo { virtual void nobody(); };", StartsWithNo));
DeclarationMatcher Abc = namedDecl(matchesName("a.*b.*c"));
EXPECT_TRUE(matches("int abc;", Abc));
EXPECT_TRUE(matches("int aFOObBARc;", Abc));
EXPECT_TRUE(notMatches("int cab;", Abc));
EXPECT_TRUE(matches("int cabc;", Abc));
DeclarationMatcher StartsWithK = namedDecl(matchesName(":k[^:]*$"));
EXPECT_TRUE(matches("int k;", StartsWithK));
EXPECT_TRUE(matches("int kAbc;", StartsWithK));
EXPECT_TRUE(matches("namespace x { int kTest; }", StartsWithK));
EXPECT_TRUE(matches("class C { int k; };", StartsWithK));
EXPECT_TRUE(notMatches("class C { int ckc; };", StartsWithK));
}
TEST(DeclarationMatcher, MatchClass) {
DeclarationMatcher ClassMatcher(recordDecl());
llvm::Triple Triple(llvm::sys::getDefaultTargetTriple());
if (Triple.getOS() != llvm::Triple::Win32 ||
Triple.getEnvironment() != llvm::Triple::MSVC)
EXPECT_FALSE(matches("", ClassMatcher));
else
// Matches class type_info.
EXPECT_TRUE(matches("", ClassMatcher));
DeclarationMatcher ClassX = recordDecl(recordDecl(hasName("X")));
EXPECT_TRUE(matches("class X;", ClassX));
EXPECT_TRUE(matches("class X {};", ClassX));
EXPECT_TRUE(matches("template<class T> class X {};", ClassX));
EXPECT_TRUE(notMatches("", ClassX));
}
TEST(DeclarationMatcher, ClassIsDerived) {
DeclarationMatcher IsDerivedFromX = cxxRecordDecl(isDerivedFrom("X"));
EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsDerivedFromX));
EXPECT_TRUE(notMatches("class X {};", IsDerivedFromX));
EXPECT_TRUE(notMatches("class X;", IsDerivedFromX));
EXPECT_TRUE(notMatches("class Y;", IsDerivedFromX));
EXPECT_TRUE(notMatches("", IsDerivedFromX));
DeclarationMatcher IsAX = cxxRecordDecl(isSameOrDerivedFrom("X"));
EXPECT_TRUE(matches("class X {}; class Y : public X {};", IsAX));
EXPECT_TRUE(matches("class X {};", IsAX));
EXPECT_TRUE(matches("class X;", IsAX));
EXPECT_TRUE(notMatches("class Y;", IsAX));
EXPECT_TRUE(notMatches("", IsAX));
DeclarationMatcher ZIsDerivedFromX =
cxxRecordDecl(hasName("Z"), isDerivedFrom("X"));
EXPECT_TRUE(
matches("class X {}; class Y : public X {}; class Z : public Y {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {};"
"template<class T> class Y : public X {};"
"class Z : public Y<int> {};", ZIsDerivedFromX));
EXPECT_TRUE(matches("class X {}; template<class T> class Z : public X {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T> class X {}; "
"template<class T> class Z : public X<T> {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T, class U=T> class X {}; "
"template<class T> class Z : public X<T> {};",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class A { class Z : public X {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class X> class A { public: class Z : public X {}; }; "
"class X{}; void y() { A<X>::Z z; }", ZIsDerivedFromX));
EXPECT_TRUE(
matches("template <class T> class X {}; "
"template<class Y> class A { class Z : public X<Y> {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<template<class T> class X> class A { "
" class Z : public X<int> {}; };", ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<template<class T> class X> class A { "
" public: class Z : public X<int> {}; }; "
"template<class T> class X {}; void y() { A<X>::Z z; }",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class A { class Z : public X::D {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class X> class A { public: "
" class Z : public X::D {}; }; "
"class Y { public: class X {}; typedef X D; }; "
"void y() { A<Y>::Z z; }", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X Y; class Z : public Y {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T> class Y { typedef typename T::U X; "
" class Z : public X {}; };", ZIsDerivedFromX));
EXPECT_TRUE(matches("class X {}; class Z : public ::X {};",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class T> class X {}; "
"template<class T> class A { class Z : public X<T>::D {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T> class X { public: typedef X<T> D; }; "
"template<class T> class A { public: "
" class Z : public X<T>::D {}; }; void y() { A<int>::Z z; }",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class A { class Z : public X::D::E {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X V; typedef V W; class Z : public W {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; class Y : public X {}; "
"typedef Y V; typedef V W; class Z : public W {};",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("template<class T, class U> class X {}; "
"template<class T> class A { class Z : public X<T, int> {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<class X> class D { typedef X A; typedef A B; "
" typedef B C; class Z : public C {}; };",
ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X A; typedef A B; "
"class Z : public B {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class X {}; typedef X A; typedef A B; typedef B C; "
"class Z : public C {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class U {}; typedef U X; typedef X V; "
"class Z : public V {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class Base {}; typedef Base X; "
"class Z : public Base {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class Base {}; typedef Base Base2; typedef Base2 X; "
"class Z : public Base {};", ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("class Base {}; class Base2 {}; typedef Base2 X; "
"class Z : public Base {};", ZIsDerivedFromX));
EXPECT_TRUE(
matches("class A {}; typedef A X; typedef A Y; "
"class Z : public Y {};", ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template <typename T> class Z;"
"template <> class Z<void> {};"
"template <typename T> class Z : public Z<void> {};",
IsDerivedFromX));
EXPECT_TRUE(
matches("template <typename T> class X;"
"template <> class X<void> {};"
"template <typename T> class X : public X<void> {};",
IsDerivedFromX));
EXPECT_TRUE(matches(
"class X {};"
"template <typename T> class Z;"
"template <> class Z<void> {};"
"template <typename T> class Z : public Z<void>, public X {};",
ZIsDerivedFromX));
EXPECT_TRUE(
notMatches("template<int> struct X;"
"template<int i> struct X : public X<i-1> {};",
cxxRecordDecl(isDerivedFrom(recordDecl(hasName("Some"))))));
EXPECT_TRUE(matches(
"struct A {};"
"template<int> struct X;"
"template<int i> struct X : public X<i-1> {};"
"template<> struct X<0> : public A {};"
"struct B : public X<42> {};",
cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl(hasName("A"))))));
// FIXME: Once we have better matchers for template type matching,
// get rid of the Variable(...) matching and match the right template
// declarations directly.
const char *RecursiveTemplateOneParameter =
"class Base1 {}; class Base2 {};"
"template <typename T> class Z;"
"template <> class Z<void> : public Base1 {};"
"template <> class Z<int> : public Base2 {};"
"template <> class Z<float> : public Z<void> {};"
"template <> class Z<double> : public Z<int> {};"
"template <typename T> class Z : public Z<float>, public Z<double> {};"
"void f() { Z<float> z_float; Z<double> z_double; Z<char> z_char; }";
EXPECT_TRUE(matches(
RecursiveTemplateOneParameter,
varDecl(hasName("z_float"),
hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
EXPECT_TRUE(notMatches(
RecursiveTemplateOneParameter,
varDecl(hasName("z_float"),
hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
EXPECT_TRUE(matches(
RecursiveTemplateOneParameter,
varDecl(hasName("z_char"),
hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
isDerivedFrom("Base2")))))));
const char *RecursiveTemplateTwoParameters =
"class Base1 {}; class Base2 {};"
"template <typename T1, typename T2> class Z;"
"template <typename T> class Z<void, T> : public Base1 {};"
"template <typename T> class Z<int, T> : public Base2 {};"
"template <typename T> class Z<float, T> : public Z<void, T> {};"
"template <typename T> class Z<double, T> : public Z<int, T> {};"
"template <typename T1, typename T2> class Z : "
" public Z<float, T2>, public Z<double, T2> {};"
"void f() { Z<float, void> z_float; Z<double, void> z_double; "
" Z<char, void> z_char; }";
EXPECT_TRUE(matches(
RecursiveTemplateTwoParameters,
varDecl(hasName("z_float"),
hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1")))))));
EXPECT_TRUE(notMatches(
RecursiveTemplateTwoParameters,
varDecl(hasName("z_float"),
hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base2")))))));
EXPECT_TRUE(matches(
RecursiveTemplateTwoParameters,
varDecl(hasName("z_char"),
hasInitializer(hasType(cxxRecordDecl(isDerivedFrom("Base1"),
isDerivedFrom("Base2")))))));
EXPECT_TRUE(matches(
"namespace ns { class X {}; class Y : public X {}; }",
cxxRecordDecl(isDerivedFrom("::ns::X"))));
EXPECT_TRUE(notMatches(
"class X {}; class Y : public X {};",
cxxRecordDecl(isDerivedFrom("::ns::X"))));
EXPECT_TRUE(matches(
"class X {}; class Y : public X {};",
cxxRecordDecl(isDerivedFrom(recordDecl(hasName("X")).bind("test")))));
EXPECT_TRUE(matches(
"template<typename T> class X {};"
"template<typename T> using Z = X<T>;"
"template <typename T> class Y : Z<T> {};",
cxxRecordDecl(isDerivedFrom(namedDecl(hasName("X"))))));
}
TEST(DeclarationMatcher, hasMethod) {
EXPECT_TRUE(matches("class A { void func(); };",
cxxRecordDecl(hasMethod(hasName("func")))));
EXPECT_TRUE(notMatches("class A { void func(); };",
cxxRecordDecl(hasMethod(isPublic()))));
}
TEST(DeclarationMatcher, ClassDerivedFromDependentTemplateSpecialization) {
EXPECT_TRUE(matches(
"template <typename T> struct A {"
" template <typename T2> struct F {};"
"};"
"template <typename T> struct B : A<T>::template F<T> {};"
"B<int> b;",
cxxRecordDecl(hasName("B"), isDerivedFrom(recordDecl()))));
}
TEST(DeclarationMatcher, hasDeclContext) {
EXPECT_TRUE(matches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}",
recordDecl(hasDeclContext(namespaceDecl(hasName("M"))))));
EXPECT_TRUE(notMatches(
"namespace N {"
" namespace M {"
" class D {};"
" }"
"}",
recordDecl(hasDeclContext(namespaceDecl(hasName("N"))))));
EXPECT_TRUE(matches("namespace {"
" namespace M {"
" class D {};"
" }"
"}",
recordDecl(hasDeclContext(namespaceDecl(
hasName("M"), hasDeclContext(namespaceDecl()))))));
EXPECT_TRUE(matches("class D{};", decl(hasDeclContext(decl()))));
}
TEST(DeclarationMatcher, translationUnitDecl) {
const std::string Code = "int MyVar1;\n"
"namespace NameSpace {\n"
"int MyVar2;\n"
"} // namespace NameSpace\n";
EXPECT_TRUE(matches(
Code, varDecl(hasName("MyVar1"), hasDeclContext(translationUnitDecl()))));
EXPECT_FALSE(matches(
Code, varDecl(hasName("MyVar2"), hasDeclContext(translationUnitDecl()))));
EXPECT_TRUE(matches(
Code,
varDecl(hasName("MyVar2"),
hasDeclContext(decl(hasDeclContext(translationUnitDecl()))))));
}
TEST(DeclarationMatcher, LinkageSpecification) {
EXPECT_TRUE(matches("extern \"C\" { void foo() {}; }", linkageSpecDecl()));
EXPECT_TRUE(notMatches("void foo() {};", linkageSpecDecl()));
}
TEST(ClassTemplate, DoesNotMatchClass) {
DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
EXPECT_TRUE(notMatches("class X;", ClassX));
EXPECT_TRUE(notMatches("class X {};", ClassX));
}
TEST(ClassTemplate, MatchesClassTemplate) {
DeclarationMatcher ClassX = classTemplateDecl(hasName("X"));
EXPECT_TRUE(matches("template<typename T> class X {};", ClassX));
EXPECT_TRUE(matches("class Z { template<class T> class X {}; };", ClassX));
}
TEST(ClassTemplate, DoesNotMatchClassTemplateExplicitSpecialization) {
EXPECT_TRUE(notMatches("template<typename T> class X { };"
"template<> class X<int> { int a; };",
classTemplateDecl(hasName("X"),
hasDescendant(fieldDecl(hasName("a"))))));
}
TEST(ClassTemplate, DoesNotMatchClassTemplatePartialSpecialization) {
EXPECT_TRUE(notMatches("template<typename T, typename U> class X { };"
"template<typename T> class X<T, int> { int a; };",
classTemplateDecl(hasName("X"),
hasDescendant(fieldDecl(hasName("a"))))));
}
TEST(AllOf, AllOverloadsWork) {
const char Program[] =
"struct T { };"
"int f(int, T*, int, int);"
"void g(int x) { T t; f(x, &t, 3, 4); }";
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl())))))));
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl()))),
hasArgument(1, hasType(pointsTo(
recordDecl(hasName("T")))))))));
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl()))),
hasArgument(1, hasType(pointsTo(
recordDecl(hasName("T"))))),
hasArgument(2, integerLiteral(equals(3)))))));
EXPECT_TRUE(matches(Program,
callExpr(allOf(callee(functionDecl(hasName("f"))),
hasArgument(0, declRefExpr(to(varDecl()))),
hasArgument(1, hasType(pointsTo(
recordDecl(hasName("T"))))),
hasArgument(2, integerLiteral(equals(3))),
hasArgument(3, integerLiteral(equals(4)))))));
}
TEST(ConstructVariadic, MismatchedTypes_Regression) {
EXPECT_TRUE(
matches("const int a = 0;",
internal::DynTypedMatcher::constructVariadic(
internal::DynTypedMatcher::VO_AnyOf,
ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>(),
{isConstQualified(), arrayType()})
.convertTo<QualType>()));
}
TEST(DeclarationMatcher, MatchAnyOf) {
DeclarationMatcher YOrZDerivedFromX = cxxRecordDecl(
anyOf(hasName("Y"), allOf(isDerivedFrom("X"), hasName("Z"))));
EXPECT_TRUE(matches("class X {}; class Z : public X {};", YOrZDerivedFromX));
EXPECT_TRUE(matches("class Y {};", YOrZDerivedFromX));
EXPECT_TRUE(
notMatches("class X {}; class W : public X {};", YOrZDerivedFromX));
EXPECT_TRUE(notMatches("class Z {};", YOrZDerivedFromX));
DeclarationMatcher XOrYOrZOrU =
recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U")));
EXPECT_TRUE(matches("class X {};", XOrYOrZOrU));
EXPECT_TRUE(notMatches("class V {};", XOrYOrZOrU));
DeclarationMatcher XOrYOrZOrUOrV =
recordDecl(anyOf(hasName("X"), hasName("Y"), hasName("Z"), hasName("U"),
hasName("V")));
EXPECT_TRUE(matches("class X {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class Y {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class Z {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class U {};", XOrYOrZOrUOrV));
EXPECT_TRUE(matches("class V {};", XOrYOrZOrUOrV));
EXPECT_TRUE(notMatches("class A {};", XOrYOrZOrUOrV));
StatementMatcher MixedTypes = stmt(anyOf(ifStmt(), binaryOperator()));
EXPECT_TRUE(matches("int F() { return 1 + 2; }", MixedTypes));
EXPECT_TRUE(matches("int F() { if (true) return 1; }", MixedTypes));
EXPECT_TRUE(notMatches("int F() { return 1; }", MixedTypes));
EXPECT_TRUE(
matches("void f() try { } catch (int) { } catch (...) { }",
cxxCatchStmt(anyOf(hasDescendant(varDecl()), isCatchAll()))));
}
TEST(DeclarationMatcher, MatchHas) {
DeclarationMatcher HasClassX = recordDecl(has(recordDecl(hasName("X"))));
EXPECT_TRUE(matches("class Y { class X {}; };", HasClassX));
EXPECT_TRUE(matches("class X {};", HasClassX));
DeclarationMatcher YHasClassX =
recordDecl(hasName("Y"), has(recordDecl(hasName("X"))));
EXPECT_TRUE(matches("class Y { class X {}; };", YHasClassX));
EXPECT_TRUE(notMatches("class X {};", YHasClassX));
EXPECT_TRUE(
notMatches("class Y { class Z { class X {}; }; };", YHasClassX));
}
TEST(DeclarationMatcher, MatchHasRecursiveAllOf) {
DeclarationMatcher Recursive =
recordDecl(
has(recordDecl(
has(recordDecl(hasName("X"))),
has(recordDecl(hasName("Y"))),
hasName("Z"))),
has(recordDecl(
has(recordDecl(hasName("A"))),
has(recordDecl(hasName("B"))),
hasName("C"))),
hasName("F"));
EXPECT_TRUE(matches(
"class F {"
" class Z {"
" class X {};"
" class Y {};"
" };"
" class C {"
" class A {};"
" class B {};"
" };"
"};", Recursive));
EXPECT_TRUE(matches(
"class F {"
" class Z {"
" class A {};"
" class X {};"
" class Y {};"
" };"
" class C {"
" class X {};"
" class A {};"
" class B {};"
" };"
"};", Recursive));
EXPECT_TRUE(matches(
"class O1 {"
" class O2 {"
" class F {"
" class Z {"
" class A {};"
" class X {};"
" class Y {};"
" };"
" class C {"
" class X {};"
" class A {};"
" class B {};"
" };"
" };"
" };"
"};", Recursive));
}
TEST(DeclarationMatcher, MatchHasRecursiveAnyOf) {
DeclarationMatcher Recursive =
recordDecl(
anyOf(
has(recordDecl(
anyOf(
has(recordDecl(
hasName("X"))),
has(recordDecl(
hasName("Y"))),
hasName("Z")))),
has(recordDecl(
anyOf(
hasName("C"),
has(recordDecl(
hasName("A"))),
has(recordDecl(
hasName("B")))))),
hasName("F")));
EXPECT_TRUE(matches("class F {};", Recursive));
EXPECT_TRUE(matches("class Z {};", Recursive));
EXPECT_TRUE(matches("class C {};", Recursive));
EXPECT_TRUE(matches("class M { class N { class X {}; }; };", Recursive));
EXPECT_TRUE(matches("class M { class N { class B {}; }; };", Recursive));
EXPECT_TRUE(
matches("class O1 { class O2 {"
" class M { class N { class B {}; }; }; "
"}; };", Recursive));
}
TEST(DeclarationMatcher, MatchNot) {
DeclarationMatcher NotClassX =
cxxRecordDecl(
isDerivedFrom("Y"),
unless(hasName("X")));
EXPECT_TRUE(notMatches("", NotClassX));
EXPECT_TRUE(notMatches("class Y {};", NotClassX));
EXPECT_TRUE(matches("class Y {}; class Z : public Y {};", NotClassX));
EXPECT_TRUE(notMatches("class Y {}; class X : public Y {};", NotClassX));
EXPECT_TRUE(
notMatches("class Y {}; class Z {}; class X : public Y {};",
NotClassX));
DeclarationMatcher ClassXHasNotClassY =
recordDecl(
hasName("X"),
has(recordDecl(hasName("Z"))),
unless(
has(recordDecl(hasName("Y")))));
EXPECT_TRUE(matches("class X { class Z {}; };", ClassXHasNotClassY));
EXPECT_TRUE(notMatches("class X { class Y {}; class Z {}; };",
ClassXHasNotClassY));
DeclarationMatcher NamedNotRecord =
namedDecl(hasName("Foo"), unless(recordDecl()));
EXPECT_TRUE(matches("void Foo(){}", NamedNotRecord));
EXPECT_TRUE(notMatches("struct Foo {};", NamedNotRecord));
}
TEST(DeclarationMatcher, HasDescendant) {
DeclarationMatcher ZDescendantClassX =
recordDecl(
hasDescendant(recordDecl(hasName("X"))),
hasName("Z"));
EXPECT_TRUE(matches("class Z { class X {}; };", ZDescendantClassX));
EXPECT_TRUE(
matches("class Z { class Y { class X {}; }; };", ZDescendantClassX));
EXPECT_TRUE(
matches("class Z { class A { class Y { class X {}; }; }; };",
ZDescendantClassX));
EXPECT_TRUE(
matches("class Z { class A { class B { class Y { class X {}; }; }; }; };",
ZDescendantClassX));
EXPECT_TRUE(notMatches("class Z {};", ZDescendantClassX));
DeclarationMatcher ZDescendantClassXHasClassY =
recordDecl(
hasDescendant(recordDecl(has(recordDecl(hasName("Y"))),
hasName("X"))),
hasName("Z"));
EXPECT_TRUE(matches("class Z { class X { class Y {}; }; };",
ZDescendantClassXHasClassY));
EXPECT_TRUE(
matches("class Z { class A { class B { class X { class Y {}; }; }; }; };",
ZDescendantClassXHasClassY));
EXPECT_TRUE(notMatches(
"class Z {"
" class A {"
" class B {"
" class X {"
" class C {"
" class Y {};"
" };"
" };"
" }; "
" };"
"};", ZDescendantClassXHasClassY));
DeclarationMatcher ZDescendantClassXDescendantClassY =
recordDecl(
hasDescendant(recordDecl(hasDescendant(recordDecl(hasName("Y"))),
hasName("X"))),
hasName("Z"));
EXPECT_TRUE(
matches("class Z { class A { class X { class B { class Y {}; }; }; }; };",
ZDescendantClassXDescendantClassY));
EXPECT_TRUE(matches(
"class Z {"
" class A {"
" class X {"
" class B {"
" class Y {};"
" };"
" class Y {};"
" };"
" };"
"};", ZDescendantClassXDescendantClassY));
}
TEST(DeclarationMatcher, HasDescendantMemoization) {
DeclarationMatcher CannotMemoize =
decl(hasDescendant(typeLoc().bind("x")), has(decl()));
EXPECT_TRUE(matches("void f() { int i; }", CannotMemoize));
}
TEST(DeclarationMatcher, HasDescendantMemoizationUsesRestrictKind) {
auto Name = hasName("i");
auto VD = internal::Matcher<VarDecl>(Name).dynCastTo<Decl>();
auto RD = internal::Matcher<RecordDecl>(Name).dynCastTo<Decl>();
// Matching VD first should not make a cache hit for RD.
EXPECT_TRUE(notMatches("void f() { int i; }",
decl(hasDescendant(VD), hasDescendant(RD))));
EXPECT_TRUE(notMatches("void f() { int i; }",
decl(hasDescendant(RD), hasDescendant(VD))));
// Not matching RD first should not make a cache hit for VD either.
EXPECT_TRUE(matches("void f() { int i; }",
decl(anyOf(hasDescendant(RD), hasDescendant(VD)))));
}
TEST(DeclarationMatcher, HasAttr) {
EXPECT_TRUE(matches("struct __attribute__((warn_unused)) X {};",
decl(hasAttr(clang::attr::WarnUnused))));
EXPECT_FALSE(matches("struct X {};",
decl(hasAttr(clang::attr::WarnUnused))));
}
TEST(DeclarationMatcher, MatchCudaDecl) {
EXPECT_TRUE(matchesWithCuda("__global__ void f() { }"
"void g() { f<<<1, 2>>>(); }",
cudaKernelCallExpr()));
EXPECT_TRUE(matchesWithCuda("__attribute__((device)) void f() {}",
hasAttr(clang::attr::CUDADevice)));
EXPECT_TRUE(notMatchesWithCuda("void f() {}",
cudaKernelCallExpr()));
EXPECT_FALSE(notMatchesWithCuda("__attribute__((global)) void f() {}",
hasAttr(clang::attr::CUDAGlobal)));
}
// Implements a run method that returns whether BoundNodes contains a
// Decl bound to Id that can be dynamically cast to T.
// Optionally checks that the check succeeded a specific number of times.
template <typename T>
class VerifyIdIsBoundTo : public BoundNodesCallback {
public:
// Create an object that checks that a node of type \c T was bound to \c Id.
// Does not check for a certain number of matches.
explicit VerifyIdIsBoundTo(llvm::StringRef Id)
: Id(Id), ExpectedCount(-1), Count(0) {}
// Create an object that checks that a node of type \c T was bound to \c Id.
// Checks that there were exactly \c ExpectedCount matches.
VerifyIdIsBoundTo(llvm::StringRef Id, int ExpectedCount)
: Id(Id), ExpectedCount(ExpectedCount), Count(0) {}
// Create an object that checks that a node of type \c T was bound to \c Id.
// Checks that there was exactly one match with the name \c ExpectedName.
// Note that \c T must be a NamedDecl for this to work.
VerifyIdIsBoundTo(llvm::StringRef Id, llvm::StringRef ExpectedName,
int ExpectedCount = 1)
: Id(Id), ExpectedCount(ExpectedCount), Count(0),
ExpectedName(ExpectedName) {}
void onEndOfTranslationUnit() override {
if (ExpectedCount != -1)
EXPECT_EQ(ExpectedCount, Count);
if (!ExpectedName.empty())
EXPECT_EQ(ExpectedName, Name);
Count = 0;
Name.clear();
}
~VerifyIdIsBoundTo() override {
EXPECT_EQ(0, Count);
EXPECT_EQ("", Name);
}
bool run(const BoundNodes *Nodes) override {
const BoundNodes::IDToNodeMap &M = Nodes->getMap();
if (Nodes->getNodeAs<T>(Id)) {
++Count;
if (const NamedDecl *Named = Nodes->getNodeAs<NamedDecl>(Id)) {
Name = Named->getNameAsString();
} else if (const NestedNameSpecifier *NNS =
Nodes->getNodeAs<NestedNameSpecifier>(Id)) {
llvm::raw_string_ostream OS(Name);
NNS->print(OS, PrintingPolicy(LangOptions()));
}
BoundNodes::IDToNodeMap::const_iterator I = M.find(Id);
EXPECT_NE(M.end(), I);
if (I != M.end())
EXPECT_EQ(Nodes->getNodeAs<T>(Id), I->second.get<T>());
return true;
}
EXPECT_TRUE(M.count(Id) == 0 ||
M.find(Id)->second.template get<T>() == nullptr);
return false;
}
bool run(const BoundNodes *Nodes, ASTContext *Context) override {
return run(Nodes);
}
private:
const std::string Id;
const int ExpectedCount;
int Count;
const std::string ExpectedName;
std::string Name;
};
TEST(HasDescendant, MatchesDescendantTypes) {
EXPECT_TRUE(matches("void f() { int i = 3; }",
decl(hasDescendant(loc(builtinType())))));
EXPECT_TRUE(matches("void f() { int i = 3; }",
stmt(hasDescendant(builtinType()))));
EXPECT_TRUE(matches("void f() { int i = 3; }",
stmt(hasDescendant(loc(builtinType())))));
EXPECT_TRUE(matches("void f() { int i = 3; }",
stmt(hasDescendant(qualType(builtinType())))));
EXPECT_TRUE(notMatches("void f() { float f = 2.0f; }",
stmt(hasDescendant(isInteger()))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { int a; float c; int d; int e; }",
functionDecl(forEachDescendant(
varDecl(hasDescendant(isInteger())).bind("x"))),
new VerifyIdIsBoundTo<Decl>("x", 3)));
}
TEST(HasDescendant, MatchesDescendantsOfTypes) {
EXPECT_TRUE(matches("void f() { int*** i; }",
qualType(hasDescendant(builtinType()))));
EXPECT_TRUE(matches("void f() { int*** i; }",
qualType(hasDescendant(
pointerType(pointee(builtinType()))))));
EXPECT_TRUE(matches("void f() { int*** i; }",
typeLoc(hasDescendant(loc(builtinType())))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"void f() { int*** i; }",
qualType(asString("int ***"), forEachDescendant(pointerType().bind("x"))),
new VerifyIdIsBoundTo<Type>("x", 2)));
}
TEST(Has, MatchesChildrenOfTypes) {
EXPECT_TRUE(matches("int i;",
varDecl(hasName("i"), has(isInteger()))));
EXPECT_TRUE(notMatches("int** i;",
varDecl(hasName("i"), has(isInteger()))));
EXPECT_TRUE(matchAndVerifyResultTrue(
"int (*f)(float, int);",
qualType(functionType(), forEach(qualType(isInteger()).bind("x"))),
new VerifyIdIsBoundTo<QualType>("x", 2)));
}
TEST(Has, MatchesChildTypes) {
EXPECT_TRUE(matches(
"int* i;",
varDecl(hasName("i"), hasType(qualType(has(builtinType()))))));
EXPECT_TRUE(notMatches(
"int* i;",
varDecl(hasName("i"), hasType(qualType(has(pointerType()))))));
}
TEST(ValueDecl, Matches) {
EXPECT_TRUE(matches("enum EnumType { EnumValue };",
valueDecl(hasType(asString("enum EnumType")))));
EXPECT_TRUE(matches("void FunctionDecl();",
valueDecl(hasType(asString("void (void)")))));
}
TEST(Enum, DoesNotMatchClasses) {
EXPECT_TRUE(notMatches("class X {};", enumDecl(hasName("X"))));
}
TEST(Enum, MatchesEnums) {
EXPECT_TRUE(matches("enum X {};", enumDecl(hasName("X"))));
}
TEST(EnumConstant, Matches) {
DeclarationMatcher Matcher = enumConstantDecl(hasName("A"));
EXPECT_TRUE(matches("enum X{ A };", Matcher));
EXPECT_TRUE(notMatches("enum X{ B };", Matcher));
EXPECT_TRUE(notMatches("enum X {};", Matcher));
}
TEST(StatementMatcher, Has) {
StatementMatcher HasVariableI =
expr(hasType(pointsTo(recordDecl(hasName("X")))),
has(declRefExpr(to(varDecl(hasName("i"))))));
EXPECT_TRUE(matches(
"class X; X *x(int); void c() { int i; x(i); }", HasVariableI));
EXPECT_TRUE(notMatches(
"class X; X *x(int); void c() { int i; x(42); }", HasVariableI));
}
TEST(StatementMatcher, HasDescendant) {
StatementMatcher HasDescendantVariableI =
expr(hasType(pointsTo(recordDecl(hasName("X")))),
hasDescendant(declRefExpr(to(varDecl(hasName("i"))))));
EXPECT_TRUE(matches(
"class X; X *x(bool); bool b(int); void c() { int i; x(b(i)); }",
HasDescendantVariableI));
EXPECT_TRUE(notMatches(
"class X; X *x(bool); bool b(int); void c() { int i; x(b(42)); }",
HasDescendantVariableI));
}
TEST(TypeMatcher, MatchesClassType) {
TypeMatcher TypeA = hasDeclaration(recordDecl(hasName("A")));
EXPECT_TRUE(matches("class A { public: A *a; };", TypeA));
EXPECT_TRUE(notMatches("class A {};", TypeA));
TypeMatcher TypeDerivedFromA =
hasDeclaration(cxxRecordDecl(isDerivedFrom("A")));
EXPECT_TRUE(matches("class A {}; class B : public A { public: B *b; };",
TypeDerivedFromA));
EXPECT_TRUE(notMatches("class A {};", TypeA));
TypeMatcher TypeAHasClassB = hasDeclaration(
recordDecl(hasName("A"), has(recordDecl(hasName("B")))));
EXPECT_TRUE(
matches("class A { public: A *a; class B {}; };", TypeAHasClassB));
EXPECT_TRUE(matchesC("struct S {}; void f(void) { struct S s; }",
varDecl(hasType(namedDecl(hasName("S"))))));
}
TEST(TypeMatcher, MatchesDeclTypes) {
// TypedefType -> TypedefNameDecl
EXPECT_TRUE(matches("typedef int I; void f(I i);",
parmVarDecl(hasType(namedDecl(hasName("I"))))));
// ObjCObjectPointerType
EXPECT_TRUE(matchesObjC("@interface Foo @end void f(Foo *f);",
parmVarDecl(hasType(objcObjectPointerType()))));
// ObjCObjectPointerType -> ObjCInterfaceType -> ObjCInterfaceDecl
EXPECT_TRUE(matchesObjC(
"@interface Foo @end void f(Foo *f);",
parmVarDecl(hasType(pointsTo(objcInterfaceDecl(hasName("Foo")))))));
// TemplateTypeParmType
EXPECT_TRUE(matches("template <typename T> void f(T t);",
parmVarDecl(hasType(templateTypeParmType()))));
// TemplateTypeParmType -> TemplateTypeParmDecl
EXPECT_TRUE(matches("template <typename T> void f(T t);",
parmVarDecl(hasType(namedDecl(hasName("T"))))));
// InjectedClassNameType
EXPECT_TRUE(matches("template <typename T> struct S {"
" void f(S s);"
"};",
parmVarDecl(hasType(injectedClassNameType()))));
EXPECT_TRUE(notMatches("template <typename T> struct S {"
" void g(S<T> s);"
"};",
parmVarDecl(hasType(injectedClassNameType()))));
// InjectedClassNameType -> CXXRecordDecl
EXPECT_TRUE(matches("template <typename T> struct S {"
" void f(S s);"
"};",
parmVarDecl(hasType(namedDecl(hasName("S"))))));
static const char Using[] = "template <typename T>"
"struct Base {"
" typedef T Foo;"
"};"
""
"template <typename T>"
"struct S : private Base<T> {"
" using typename Base<T>::Foo;"
" void f(Foo);"
"};";
// UnresolvedUsingTypenameDecl
EXPECT_TRUE(matches(Using, unresolvedUsingTypenameDecl(hasName("Foo"))));
// UnresolvedUsingTypenameType -> UnresolvedUsingTypenameDecl
EXPECT_TRUE(matches(Using, parmVarDecl(hasType(namedDecl(hasName("Foo"))))));
}
TEST(Matcher, BindMatchedNodes) {
DeclarationMatcher ClassX = has(recordDecl(hasName("::X")).bind("x"));
EXPECT_TRUE(matchAndVerifyResultTrue("class X {};",
ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("x")));
EXPECT_TRUE(matchAndVerifyResultFalse("class X {};",
ClassX, new VerifyIdIsBoundTo<CXXRecordDecl>("other-id")));
TypeMatcher TypeAHasClassB = hasDeclaration(
recordDecl(hasName("A"), has(recordDecl(hasName("B")).bind("b"))));
EXPECT_TRUE(matchAndVerifyResultTrue("class A { public: A *a; class B {}; };",
TypeAHasClassB,
new VerifyIdIsBoundTo<Decl>("b")));
StatementMatcher MethodX =
callExpr(callee(cxxMethodDecl(hasName("x")))).bind("x");
EXPECT_TRUE(matchAndVerifyResultTrue("class A { void x() { x(); } };",
MethodX,
new VerifyIdIsBoundTo<CXXMemberCallExpr>("x")));
}
TEST(Matcher, BindTheSameNameInAlternatives) {
StatementMatcher matcher = anyOf(
binaryOperator(hasOperatorName("+"),
hasLHS(expr().bind("x")),
hasRHS(integerLiteral(equals(0)))),
binaryOperator(hasOperatorName("+"),
hasLHS(integerLiteral(equals(0))),
hasRHS(expr().bind("x"))));
EXPECT_TRUE(matchAndVerifyResultTrue(
// The first branch of the matcher binds x to 0 but then fails.
// The second branch binds x to f() and succeeds.
"int f() { return 0 + f(); }",
matcher,
new VerifyIdIsBoundTo<CallExpr>("x")));
}
TEST(Matcher, BindsIDForMemoizedResults) {
// Using the same matcher in two match expressions will make memoization
// kick in.
DeclarationMatcher ClassX = recordDecl(hasName("X")).bind("x");
EXPECT_TRUE(matchAndVerifyResultTrue(
"class A { class B { class X {}; }; };",
DeclarationMatcher(anyOf(
recordDecl(hasName("A"), hasDescendant(ClassX)),
recordDecl(hasName("B"), hasDescendant(ClassX)))),
new VerifyIdIsBoundTo<Decl>("x", 2)));
}
TEST(HasDeclaration, HasDeclarationOfEnumType) {
EXPECT_TRUE(matches("enum X {}; void y(X *x) { x; }",
expr(hasType(pointsTo(
qualType(hasDeclaration(enumDecl(hasName("X")))))))));
}
TEST(HasDeclaration, HasGetDeclTraitTest) {
EXPECT_TRUE(internal::has_getDecl<TypedefType>::value);
EXPECT_TRUE(internal::has_getDecl<RecordType>::value);
EXPECT_FALSE(internal::has_getDecl<TemplateSpecializationType>::value);
}
TEST(HasDeclaration, HasDeclarationOfTypeWithDecl) {
EXPECT_TRUE(matches("typedef int X; X a;",
varDecl(hasName("a"),
hasType(typedefType(hasDeclaration(decl()))))));
// FIXME: Add tests for other types with getDecl() (e.g. RecordType)
}
TEST(HasDeclaration, HasDeclarationOfTemplateSpecializationType) {
EXPECT_TRUE(matches("template <typename T> class A {}; A<int> a;",
varDecl(hasType(templateSpecializationType(
hasDeclaration(namedDecl(hasName("A"))))))));
}
TEST(HasType, TakesQualTypeMatcherAndMatchesExpr) {
TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
EXPECT_TRUE(
matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y(X *x) { x; }",
expr(hasType(ClassX))));
EXPECT_TRUE(
matches("class X {}; void y(X *x) { x; }",
expr(hasType(pointsTo(ClassX)))));
}
TEST(HasType, TakesQualTypeMatcherAndMatchesValueDecl) {
TypeMatcher ClassX = hasDeclaration(recordDecl(hasName("X")));
EXPECT_TRUE(
matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
EXPECT_TRUE(
matches("class X {}; void y() { X *x; }",
varDecl(hasType(pointsTo(ClassX)))));
}
TEST(HasType, TakesDeclMatcherAndMatchesExpr) {
DeclarationMatcher ClassX = recordDecl(hasName("X"));
EXPECT_TRUE(
matches("class X {}; void y(X &x) { x; }", expr(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y(X *x) { x; }",
expr(hasType(ClassX))));
}
TEST(HasType, TakesDeclMatcherAndMatchesValueDecl) {
DeclarationMatcher ClassX = recordDecl(hasName("X"));
EXPECT_TRUE(
matches("class X {}; void y() { X x; }", varDecl(hasType(ClassX))));
EXPECT_TRUE(
notMatches("class X {}; void y() { X *x; }", varDecl(hasType(ClassX))));
}
TEST(HasTypeLoc, MatchesDeclaratorDecls) {
EXPECT_TRUE(matches("int x;",
varDecl(hasName("x"), hasTypeLoc(loc(asString("int"))))));
// Make sure we don't crash on implicit constructors.
EXPECT_TRUE(notMatches("class X {}; X x;",
declaratorDecl(hasTypeLoc(loc(asString("int"))))));
}
TEST(Matcher, Call) {
// FIXME: Do we want to overload Call() to directly take
// Matcher<Decl>, too?
StatementMatcher MethodX =
callExpr(hasDeclaration(cxxMethodDecl(hasName("x"))));
EXPECT_TRUE(matches("class Y { void x() { x(); } };", MethodX));
EXPECT_TRUE(notMatches("class Y { void x() {} };", MethodX));
StatementMatcher MethodOnY =
cxxMemberCallExpr(on(hasType(recordDecl(hasName("Y")))));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
MethodOnY));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
MethodOnY));
StatementMatcher MethodOnYPointer =
cxxMemberCallExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
MethodOnYPointer));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
MethodOnYPointer));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
MethodOnYPointer));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
MethodOnYPointer));
EXPECT_TRUE(
notMatches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
MethodOnYPointer));
}
TEST(Matcher, Lambda) {
EXPECT_TRUE(matches("auto f = [] (int i) { return i; };",
lambdaExpr()));
}
TEST(Matcher, ForRange) {
EXPECT_TRUE(matches("int as[] = { 1, 2, 3 };"
"void f() { for (auto &a : as); }",
cxxForRangeStmt()));
EXPECT_TRUE(notMatches("void f() { for (int i; i<5; ++i); }",
cxxForRangeStmt()));
}
TEST(Matcher, SubstNonTypeTemplateParm) {
EXPECT_FALSE(matches("template<int N>\n"
"struct A { static const int n = 0; };\n"
"struct B : public A<42> {};",
substNonTypeTemplateParmExpr()));
EXPECT_TRUE(matches("template<int N>\n"
"struct A { static const int n = N; };\n"
"struct B : public A<42> {};",
substNonTypeTemplateParmExpr()));
}
TEST(Matcher, NonTypeTemplateParmDecl) {
EXPECT_TRUE(matches("template <int N> void f();",
nonTypeTemplateParmDecl(hasName("N"))));
EXPECT_TRUE(
notMatches("template <typename T> void f();", nonTypeTemplateParmDecl()));
}
TEST(Matcher, templateTypeParmDecl) {
EXPECT_TRUE(matches("template <typename T> void f();",
templateTypeParmDecl(hasName("T"))));
EXPECT_TRUE(
notMatches("template <int N> void f();", templateTypeParmDecl()));
}
TEST(Matcher, UserDefinedLiteral) {
EXPECT_TRUE(matches("constexpr char operator \"\" _inc (const char i) {"
" return i + 1;"
"}"
"char c = 'a'_inc;",
userDefinedLiteral()));
}
TEST(Matcher, FlowControl) {
EXPECT_TRUE(matches("void f() { while(true) { break; } }", breakStmt()));
EXPECT_TRUE(matches("void f() { while(true) { continue; } }",
continueStmt()));
EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", gotoStmt()));
EXPECT_TRUE(matches("void f() { goto FOO; FOO: ;}", labelStmt()));
EXPECT_TRUE(matches("void f() { return; }", returnStmt()));
}
TEST(HasType, MatchesAsString) {
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() {Y* y; y->x(); }",
cxxMemberCallExpr(on(hasType(asString("class Y *"))))));
EXPECT_TRUE(
matches("class X { void x(int x) {} };",
cxxMethodDecl(hasParameter(0, hasType(asString("int"))))));
EXPECT_TRUE(matches("namespace ns { struct A {}; } struct B { ns::A a; };",
fieldDecl(hasType(asString("ns::A")))));
EXPECT_TRUE(matches("namespace { struct A {}; } struct B { A a; };",
fieldDecl(hasType(asString("struct (anonymous namespace)::A")))));
}
TEST(Matcher, OverloadedOperatorCall) {
StatementMatcher OpCall = cxxOperatorCallExpr();
// Unary operator
EXPECT_TRUE(matches("class Y { }; "
"bool operator!(Y x) { return false; }; "
"Y y; bool c = !y;", OpCall));
// No match -- special operators like "new", "delete"
// FIXME: operator new takes size_t, for which we need stddef.h, for which
// we need to figure out include paths in the test.
// EXPECT_TRUE(NotMatches("#include <stddef.h>\n"
// "class Y { }; "
// "void *operator new(size_t size) { return 0; } "
// "Y *y = new Y;", OpCall));
EXPECT_TRUE(notMatches("class Y { }; "
"void operator delete(void *p) { } "
"void a() {Y *y = new Y; delete y;}", OpCall));
// Binary operator
EXPECT_TRUE(matches("class Y { }; "
"bool operator&&(Y x, Y y) { return true; }; "
"Y a; Y b; bool c = a && b;",
OpCall));
// No match -- normal operator, not an overloaded one.
EXPECT_TRUE(notMatches("bool x = true, y = true; bool t = x && y;", OpCall));
EXPECT_TRUE(notMatches("int t = 5 << 2;", OpCall));
}
TEST(Matcher, HasOperatorNameForOverloadedOperatorCall) {
StatementMatcher OpCallAndAnd =
cxxOperatorCallExpr(hasOverloadedOperatorName("&&"));
EXPECT_TRUE(matches("class Y { }; "
"bool operator&&(Y x, Y y) { return true; }; "
"Y a; Y b; bool c = a && b;", OpCallAndAnd));
StatementMatcher OpCallLessLess =
cxxOperatorCallExpr(hasOverloadedOperatorName("<<"));
EXPECT_TRUE(notMatches("class Y { }; "
"bool operator&&(Y x, Y y) { return true; }; "
"Y a; Y b; bool c = a && b;",
OpCallLessLess));
StatementMatcher OpStarCall =
cxxOperatorCallExpr(hasOverloadedOperatorName("*"));
EXPECT_TRUE(matches("class Y; int operator*(Y &); void f(Y &y) { *y; }",
OpStarCall));
DeclarationMatcher ClassWithOpStar =
cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*")));
EXPECT_TRUE(matches("class Y { int operator*(); };",
ClassWithOpStar));
EXPECT_TRUE(notMatches("class Y { void myOperator(); };",
ClassWithOpStar)) ;
DeclarationMatcher AnyOpStar = functionDecl(hasOverloadedOperatorName("*"));
EXPECT_TRUE(matches("class Y; int operator*(Y &);", AnyOpStar));
EXPECT_TRUE(matches("class Y { int operator*(); };", AnyOpStar));
}
TEST(Matcher, NestedOverloadedOperatorCalls) {
EXPECT_TRUE(matchAndVerifyResultTrue(
"class Y { }; "
"Y& operator&&(Y& x, Y& y) { return x; }; "
"Y a; Y b; Y c; Y d = a && b && c;",
cxxOperatorCallExpr(hasOverloadedOperatorName("&&")).bind("x"),
new VerifyIdIsBoundTo<CXXOperatorCallExpr>("x", 2)));
EXPECT_TRUE(matches("class Y { }; "
"Y& operator&&(Y& x, Y& y) { return x; }; "
"Y a; Y b; Y c; Y d = a && b && c;",
cxxOperatorCallExpr(hasParent(cxxOperatorCallExpr()))));
EXPECT_TRUE(
matches("class Y { }; "
"Y& operator&&(Y& x, Y& y) { return x; }; "
"Y a; Y b; Y c; Y d = a && b && c;",
cxxOperatorCallExpr(hasDescendant(cxxOperatorCallExpr()))));
}
TEST(Matcher, ThisPointerType) {
StatementMatcher MethodOnY =
cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y y; y.x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y &y) { y.x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y *&y) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z(Y y[]) { y->x(); }",
MethodOnY));
EXPECT_TRUE(
matches("class Y { public: void x(); }; void z() { Y *y; y->x(); }",
MethodOnY));
EXPECT_TRUE(matches(
"class Y {"
" public: virtual void x();"
"};"
"class X : public Y {"
" public: virtual void x();"
"};"
"void z() { X *x; x->Y::x(); }", MethodOnY));
}
TEST(Matcher, VariableUsage) {
StatementMatcher Reference =
declRefExpr(to(
varDecl(hasInitializer(
cxxMemberCallExpr(thisPointerType(recordDecl(hasName("Y"))))))));
EXPECT_TRUE(matches(
"class Y {"
" public:"
" bool x() const;"
"};"
"void z(const Y &y) {"
" bool b = y.x();"
" if (b) {}"
"}", Reference));
EXPECT_TRUE(notMatches(
"class Y {"
" public:"
" bool x() const;"
"};"
"void z(const Y &y) {"
" bool b = y.x();"
"}", Reference));
}
TEST(Matcher, VarDecl_Storage) {
auto M = varDecl(hasName("X"), hasLocalStorage());
EXPECT_TRUE(matches("void f() { int X; }", M));
EXPECT_TRUE(notMatches("int X;", M));
EXPECT_TRUE(notMatches("void f() { static int X; }", M));
M = varDecl(hasName("X"), hasGlobalStorage());
EXPECT_TRUE(notMatches("void f() { int X; }", M));
EXPECT_TRUE(matches("int X;", M));
EXPECT_TRUE(matches("void f() { static int X; }", M));
}
TEST(Matcher, FindsVarDeclInFunctionParameter) {
EXPECT_TRUE(matches(
"void f(int i) {}",
varDecl(hasName("i"))));
}
TEST(Matcher, CalledVariable) {
StatementMatcher CallOnVariableY =
cxxMemberCallExpr(on(declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(matches(
"class Y { public: void x() { Y y; y.x(); } };", CallOnVariableY));
EXPECT_TRUE(matches(
"class Y { public: void x() const { Y y; y.x(); } };", CallOnVariableY));
EXPECT_TRUE(matches(
"class Y { public: void x(); };"
"class X : public Y { void z() { X y; y.x(); } };", CallOnVariableY));
EXPECT_TRUE(matches(
"class Y { public: void x(); };"
"class X : public Y { void z() { X *y; y->x(); } };", CallOnVariableY));
EXPECT_TRUE(notMatches(
"class Y { public: void x(); };"
"class X : public Y { void z() { unsigned long y; ((X*)y)->x(); } };",
CallOnVariableY));
}
TEST(UnaryExprOrTypeTraitExpr, MatchesSizeOfAndAlignOf) {
EXPECT_TRUE(matches("void x() { int a = sizeof(a); }",
unaryExprOrTypeTraitExpr()));
EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }",
alignOfExpr(anything())));
// FIXME: Uncomment once alignof is enabled.
// EXPECT_TRUE(matches("void x() { int a = alignof(a); }",
// unaryExprOrTypeTraitExpr()));
// EXPECT_TRUE(notMatches("void x() { int a = alignof(a); }",
// sizeOfExpr()));
}
TEST(UnaryExpressionOrTypeTraitExpression, MatchesCorrectType) {
EXPECT_TRUE(matches("void x() { int a = sizeof(a); }", sizeOfExpr(
hasArgumentOfType(asString("int")))));
EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
hasArgumentOfType(asString("float")))));
EXPECT_TRUE(matches(
"struct A {}; void x() { A a; int b = sizeof(a); }",
sizeOfExpr(hasArgumentOfType(hasDeclaration(recordDecl(hasName("A")))))));
EXPECT_TRUE(notMatches("void x() { int a = sizeof(a); }", sizeOfExpr(
hasArgumentOfType(hasDeclaration(recordDecl(hasName("string")))))));
}
TEST(MemberExpression, DoesNotMatchClasses) {
EXPECT_TRUE(notMatches("class Y { void x() {} };", memberExpr()));
}
TEST(MemberExpression, MatchesMemberFunctionCall) {
EXPECT_TRUE(matches("class Y { void x() { x(); } };", memberExpr()));
}
TEST(MemberExpression, MatchesVariable) {
EXPECT_TRUE(
matches("class Y { void x() { this->y; } int y; };", memberExpr()));
EXPECT_TRUE(
matches("class Y { void x() { y; } int y; };", memberExpr()));
EXPECT_TRUE(
matches("class Y { void x() { Y y; y.y; } int y; };", memberExpr()));
}
TEST(MemberExpression, MatchesStaticVariable) {
EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
memberExpr()));
EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
memberExpr()));
EXPECT_TRUE(notMatches("class Y { void x() { Y::y; } static int y; };",
memberExpr()));
}
TEST(IsInteger, MatchesIntegers) {
EXPECT_TRUE(matches("int i = 0;", varDecl(hasType(isInteger()))));
EXPECT_TRUE(matches(
"long long i = 0; void f(long long) { }; void g() {f(i);}",
callExpr(hasArgument(0, declRefExpr(
to(varDecl(hasType(isInteger()))))))));
}
TEST(IsInteger, ReportsNoFalsePositives) {
EXPECT_TRUE(notMatches("int *i;", varDecl(hasType(isInteger()))));
EXPECT_TRUE(notMatches("struct T {}; T t; void f(T *) { }; void g() {f(&t);}",
callExpr(hasArgument(0, declRefExpr(
to(varDecl(hasType(isInteger()))))))));
}
TEST(IsArrow, MatchesMemberVariablesViaArrow) {
EXPECT_TRUE(matches("class Y { void x() { this->y; } int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(matches("class Y { void x() { y; } int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } int y; };",
memberExpr(isArrow())));
}
TEST(IsArrow, MatchesStaticMemberVariablesViaArrow) {
EXPECT_TRUE(matches("class Y { void x() { this->y; } static int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { y; } static int y; };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { (*this).y; } static int y; };",
memberExpr(isArrow())));
}
TEST(IsArrow, MatchesMemberCallsViaArrow) {
EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
memberExpr(isArrow())));
EXPECT_TRUE(matches("class Y { void x() { x(); } };",
memberExpr(isArrow())));
EXPECT_TRUE(notMatches("class Y { void x() { Y y; y.x(); } };",
memberExpr(isArrow())));
}
TEST(Callee, MatchesDeclarations) {
StatementMatcher CallMethodX = callExpr(callee(cxxMethodDecl(hasName("x"))));
EXPECT_TRUE(matches("class Y { void x() { x(); } };", CallMethodX));
EXPECT_TRUE(notMatches("class Y { void x() {} };", CallMethodX));
CallMethodX = callExpr(callee(cxxConversionDecl()));
EXPECT_TRUE(
matches("struct Y { operator int() const; }; int i = Y();", CallMethodX));
EXPECT_TRUE(notMatches("struct Y { operator int() const; }; Y y = Y();",
CallMethodX));
}
TEST(ConversionDeclaration, IsExplicit) {
EXPECT_TRUE(matches("struct S { explicit operator int(); };",
cxxConversionDecl(isExplicit())));
EXPECT_TRUE(notMatches("struct S { operator int(); };",
cxxConversionDecl(isExplicit())));
}
TEST(Callee, MatchesMemberExpressions) {
EXPECT_TRUE(matches("class Y { void x() { this->x(); } };",
callExpr(callee(memberExpr()))));
EXPECT_TRUE(
notMatches("class Y { void x() { this->x(); } };", callExpr(callee(callExpr()))));
}
TEST(Function, MatchesFunctionDeclarations) {
StatementMatcher CallFunctionF = callExpr(callee(functionDecl(hasName("f"))));
EXPECT_TRUE(matches("void f() { f(); }", CallFunctionF));
EXPECT_TRUE(notMatches("void f() { }", CallFunctionF));
if (llvm::Triple(llvm::sys::getDefaultTargetTriple()).getOS() !=
llvm::Triple::Win32) {
// FIXME: Make this work for MSVC.
// Dependent contexts, but a non-dependent call.
EXPECT_TRUE(matches("void f(); template <int N> void g() { f(); }",
CallFunctionF));
EXPECT_TRUE(
matches("void f(); template <int N> struct S { void g() { f(); } };",
CallFunctionF));
}
// Depedent calls don't match.
EXPECT_TRUE(
notMatches("void f(int); template <typename T> void g(T t) { f(t); }",
CallFunctionF));
EXPECT_TRUE(
notMatches("void f(int);"
"template <typename T> struct S { void g(T t) { f(t); } };",
CallFunctionF));
EXPECT_TRUE(matches("void f(...);", functionDecl(isVariadic())));
EXPECT_TRUE(notMatches("void f(int);", functionDecl(isVariadic())));
EXPECT_TRUE(notMatches("template <typename... Ts> void f(Ts...);",
functionDecl(isVariadic())));
EXPECT_TRUE(notMatches("void f();", functionDecl(isVariadic())));
EXPECT_TRUE(notMatchesC("void f();", functionDecl(isVariadic())));
}
TEST(FunctionTemplate, MatchesFunctionTemplateDeclarations) {
EXPECT_TRUE(
matches("template <typename T> void f(T t) {}",
functionTemplateDecl(hasName("f"))));
}
TEST(FunctionTemplate, DoesNotMatchFunctionDeclarations) {
EXPECT_TRUE(
notMatches("void f(double d); void f(int t) {}",
functionTemplateDecl(hasName("f"))));
}
TEST(FunctionTemplate, DoesNotMatchFunctionTemplateSpecializations) {
EXPECT_TRUE(
notMatches("void g(); template <typename T> void f(T t) {}"
"template <> void f(int t) { g(); }",
functionTemplateDecl(hasName("f"),
hasDescendant(declRefExpr(to(
functionDecl(hasName("g"))))))));
}
TEST(Matcher, Argument) {
StatementMatcher CallArgumentY = callExpr(
hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(matches("void x(int) { int y; x(y); }", CallArgumentY));
EXPECT_TRUE(
matches("class X { void x(int) { int y; x(y); } };", CallArgumentY));
EXPECT_TRUE(notMatches("void x(int) { int z; x(z); }", CallArgumentY));
StatementMatcher WrongIndex = callExpr(
hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(notMatches("void x(int) { int y; x(y); }", WrongIndex));
}
TEST(Matcher, AnyArgument) {
StatementMatcher CallArgumentY = callExpr(
hasAnyArgument(declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(matches("void x(int, int) { int y; x(1, y); }", CallArgumentY));
EXPECT_TRUE(matches("void x(int, int) { int y; x(y, 42); }", CallArgumentY));
EXPECT_TRUE(notMatches("void x(int, int) { x(1, 2); }", CallArgumentY));
}
TEST(Matcher, ArgumentCount) {
StatementMatcher Call1Arg = callExpr(argumentCountIs(1));
EXPECT_TRUE(matches("void x(int) { x(0); }", Call1Arg));
EXPECT_TRUE(matches("class X { void x(int) { x(0); } };", Call1Arg));
EXPECT_TRUE(notMatches("void x(int, int) { x(0, 0); }", Call1Arg));
}
TEST(Matcher, ParameterCount) {
DeclarationMatcher Function1Arg = functionDecl(parameterCountIs(1));
EXPECT_TRUE(matches("void f(int i) {}", Function1Arg));
EXPECT_TRUE(matches("class X { void f(int i) {} };", Function1Arg));
EXPECT_TRUE(notMatches("void f() {}", Function1Arg));
EXPECT_TRUE(notMatches("void f(int i, int j, int k) {}", Function1Arg));
}
TEST(Matcher, References) {
DeclarationMatcher ReferenceClassX = varDecl(
hasType(references(recordDecl(hasName("X")))));
EXPECT_TRUE(matches("class X {}; void y(X y) { X &x = y; }",
ReferenceClassX));
EXPECT_TRUE(
matches("class X {}; void y(X y) { const X &x = y; }", ReferenceClassX));
// The match here is on the implicit copy constructor code for
// class X, not on code 'X x = y'.
EXPECT_TRUE(
matches("class X {}; void y(X y) { X x = y; }", ReferenceClassX));
EXPECT_TRUE(
notMatches("class X {}; extern X x;", ReferenceClassX));
EXPECT_TRUE(
notMatches("class X {}; void y(X *y) { X *&x = y; }", ReferenceClassX));
}
TEST(QualType, hasCanonicalType) {
EXPECT_TRUE(notMatches("typedef int &int_ref;"
"int a;"
"int_ref b = a;",
varDecl(hasType(qualType(referenceType())))));
EXPECT_TRUE(
matches("typedef int &int_ref;"
"int a;"
"int_ref b = a;",
varDecl(hasType(qualType(hasCanonicalType(referenceType()))))));
}
TEST(QualType, hasLocalQualifiers) {
EXPECT_TRUE(notMatches("typedef const int const_int; const_int i = 1;",
varDecl(hasType(hasLocalQualifiers()))));
EXPECT_TRUE(matches("int *const j = nullptr;",
varDecl(hasType(hasLocalQualifiers()))));
EXPECT_TRUE(matches("int *volatile k;",
varDecl(hasType(hasLocalQualifiers()))));
EXPECT_TRUE(notMatches("int m;",
varDecl(hasType(hasLocalQualifiers()))));
}
TEST(HasParameter, CallsInnerMatcher) {
EXPECT_TRUE(matches("class X { void x(int) {} };",
cxxMethodDecl(hasParameter(0, varDecl()))));
EXPECT_TRUE(notMatches("class X { void x(int) {} };",
cxxMethodDecl(hasParameter(0, hasName("x")))));
}
TEST(HasParameter, DoesNotMatchIfIndexOutOfBounds) {
EXPECT_TRUE(notMatches("class X { void x(int) {} };",
cxxMethodDecl(hasParameter(42, varDecl()))));
}
TEST(HasType, MatchesParameterVariableTypesStrictly) {
EXPECT_TRUE(matches(
"class X { void x(X x) {} };",
cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(notMatches(
"class X { void x(const X &x) {} };",
cxxMethodDecl(hasParameter(0, hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(matches("class X { void x(const X *x) {} };",
cxxMethodDecl(hasParameter(
0, hasType(pointsTo(recordDecl(hasName("X"))))))));
EXPECT_TRUE(matches("class X { void x(const X &x) {} };",
cxxMethodDecl(hasParameter(
0, hasType(references(recordDecl(hasName("X"))))))));
}
TEST(HasAnyParameter, MatchesIndependentlyOfPosition) {
EXPECT_TRUE(matches(
"class Y {}; class X { void x(X x, Y y) {} };",
cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
EXPECT_TRUE(matches(
"class Y {}; class X { void x(Y y, X x) {} };",
cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
}
TEST(Returns, MatchesReturnTypes) {
EXPECT_TRUE(matches("class Y { int f() { return 1; } };",
functionDecl(returns(asString("int")))));
EXPECT_TRUE(notMatches("class Y { int f() { return 1; } };",
functionDecl(returns(asString("float")))));
EXPECT_TRUE(matches("class Y { Y getMe() { return *this; } };",
functionDecl(returns(hasDeclaration(
recordDecl(hasName("Y")))))));
}
TEST(IsExternC, MatchesExternCFunctionDeclarations) {
EXPECT_TRUE(matches("extern \"C\" void f() {}", functionDecl(isExternC())));
EXPECT_TRUE(matches("extern \"C\" { void f() {} }",
functionDecl(isExternC())));
EXPECT_TRUE(notMatches("void f() {}", functionDecl(isExternC())));
}
TEST(IsDeleted, MatchesDeletedFunctionDeclarations) {
EXPECT_TRUE(
notMatches("void Func();", functionDecl(hasName("Func"), isDeleted())));
EXPECT_TRUE(matches("void Func() = delete;",
functionDecl(hasName("Func"), isDeleted())));
}
TEST(isConstexpr, MatchesConstexprDeclarations) {
EXPECT_TRUE(matches("constexpr int foo = 42;",
varDecl(hasName("foo"), isConstexpr())));
EXPECT_TRUE(matches("constexpr int bar();",
functionDecl(hasName("bar"), isConstexpr())));
}
TEST(HasAnyParameter, DoesntMatchIfInnerMatcherDoesntMatch) {
EXPECT_TRUE(notMatches(
"class Y {}; class X { void x(int) {} };",
cxxMethodDecl(hasAnyParameter(hasType(recordDecl(hasName("X")))))));
}
TEST(HasAnyParameter, DoesNotMatchThisPointer) {
EXPECT_TRUE(notMatches("class Y {}; class X { void x() {} };",
cxxMethodDecl(hasAnyParameter(
hasType(pointsTo(recordDecl(hasName("X"))))))));
}
TEST(HasName, MatchesParameterVariableDeclarations) {
EXPECT_TRUE(matches("class Y {}; class X { void x(int x) {} };",
cxxMethodDecl(hasAnyParameter(hasName("x")))));
EXPECT_TRUE(notMatches("class Y {}; class X { void x(int) {} };",
cxxMethodDecl(hasAnyParameter(hasName("x")))));
}
TEST(Matcher, MatchesClassTemplateSpecialization) {
EXPECT_TRUE(matches("template<typename T> struct A {};"
"template<> struct A<int> {};",
classTemplateSpecializationDecl()));
EXPECT_TRUE(matches("template<typename T> struct A {}; A<int> a;",
classTemplateSpecializationDecl()));
EXPECT_TRUE(notMatches("template<typename T> struct A {};",
classTemplateSpecializationDecl()));
}
TEST(DeclaratorDecl, MatchesDeclaratorDecls) {
EXPECT_TRUE(matches("int x;", declaratorDecl()));
EXPECT_TRUE(notMatches("class A {};", declaratorDecl()));
}
TEST(ParmVarDecl, MatchesParmVars) {
EXPECT_TRUE(matches("void f(int x);", parmVarDecl()));
EXPECT_TRUE(notMatches("void f();", parmVarDecl()));
}
TEST(Matcher, MatchesTypeTemplateArgument) {
EXPECT_TRUE(matches(
"template<typename T> struct B {};"
"B<int> b;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(refersToType(
asString("int"))))));
}
TEST(Matcher, MatchesDeclarationReferenceTemplateArgument) {
EXPECT_TRUE(matches(
"struct B { int next; };"
"template<int(B::*next_ptr)> struct A {};"
"A<&B::next> a;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToDeclaration(fieldDecl(hasName("next")))))));
EXPECT_TRUE(notMatches(
"template <typename T> struct A {};"
"A<int> a;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToDeclaration(decl())))));
EXPECT_TRUE(matches(
"struct B { int next; };"
"template<int(B::*next_ptr)> struct A {};"
"A<&B::next> a;",
templateSpecializationType(hasAnyTemplateArgument(isExpr(
hasDescendant(declRefExpr(to(fieldDecl(hasName("next"))))))))));
EXPECT_TRUE(notMatches(
"template <typename T> struct A {};"
"A<int> a;",
templateSpecializationType(hasAnyTemplateArgument(
refersToDeclaration(decl())))));
}
TEST(Matcher, MatchesSpecificArgument) {
EXPECT_TRUE(matches(
"template<typename T, typename U> class A {};"
"A<bool, int> a;",
classTemplateSpecializationDecl(hasTemplateArgument(
1, refersToType(asString("int"))))));
EXPECT_TRUE(notMatches(
"template<typename T, typename U> class A {};"
"A<int, bool> a;",
classTemplateSpecializationDecl(hasTemplateArgument(
1, refersToType(asString("int"))))));
EXPECT_TRUE(matches(
"template<typename T, typename U> class A {};"
"A<bool, int> a;",
templateSpecializationType(hasTemplateArgument(
1, refersToType(asString("int"))))));
EXPECT_TRUE(notMatches(
"template<typename T, typename U> class A {};"
"A<int, bool> a;",
templateSpecializationType(hasTemplateArgument(
1, refersToType(asString("int"))))));
}
TEST(TemplateArgument, Matches) {
EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(templateArgument()))));
EXPECT_TRUE(matches(
"template<typename T> struct C {}; C<int> c;",
templateSpecializationType(hasAnyTemplateArgument(templateArgument()))));
}
TEST(TemplateArgumentCountIs, Matches) {
EXPECT_TRUE(
matches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(templateArgumentCountIs(1))));
EXPECT_TRUE(
notMatches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(templateArgumentCountIs(2))));
EXPECT_TRUE(matches("template<typename T> struct C {}; C<int> c;",
templateSpecializationType(templateArgumentCountIs(1))));
EXPECT_TRUE(
notMatches("template<typename T> struct C {}; C<int> c;",
templateSpecializationType(templateArgumentCountIs(2))));
}
TEST(IsIntegral, Matches) {
EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(isIntegral()))));
EXPECT_TRUE(notMatches("template<typename T> struct C {}; C<int> c;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
templateArgument(isIntegral())))));
}
TEST(RefersToIntegralType, Matches) {
EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(refersToIntegralType(
asString("int"))))));
EXPECT_TRUE(notMatches("template<unsigned T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
refersToIntegralType(asString("int"))))));
}
TEST(EqualsIntegralValue, Matches) {
EXPECT_TRUE(matches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(equalsIntegralValue("42")))));
EXPECT_TRUE(matches("template<int T> struct C {}; C<-42> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(equalsIntegralValue("-42")))));
EXPECT_TRUE(matches("template<int T> struct C {}; C<-0042> c;",
classTemplateSpecializationDecl(
hasAnyTemplateArgument(equalsIntegralValue("-34")))));
EXPECT_TRUE(notMatches("template<int T> struct C {}; C<42> c;",
classTemplateSpecializationDecl(hasAnyTemplateArgument(
equalsIntegralValue("0042")))));
}
TEST(Matcher, MatchesAccessSpecDecls) {
EXPECT_TRUE(matches("class C { public: int i; };", accessSpecDecl()));
EXPECT_TRUE(
matches("class C { public: int i; };", accessSpecDecl(isPublic())));
EXPECT_TRUE(
notMatches("class C { public: int i; };", accessSpecDecl(isProtected())));
EXPECT_TRUE(
notMatches("class C { public: int i; };", accessSpecDecl(isPrivate())));
EXPECT_TRUE(notMatches("class C { int i; };", accessSpecDecl()));
}
TEST(Matcher, MatchesFinal) {
EXPECT_TRUE(matches("class X final {};", cxxRecordDecl(isFinal())));
EXPECT_TRUE(matches("class X { virtual void f() final; };",
cxxMethodDecl(isFinal())));
EXPECT_TRUE(notMatches("class X {};", cxxRecordDecl(isFinal())));
EXPECT_TRUE(
notMatches("class X { virtual void f(); };", cxxMethodDecl(isFinal())));
}
TEST(Matcher, MatchesVirtualMethod) {
EXPECT_TRUE(matches("class X { virtual int f(); };",
cxxMethodDecl(isVirtual(), hasName("::X::f"))));
EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isVirtual())));
}
TEST(Matcher, MatchesPureMethod) {
EXPECT_TRUE(matches("class X { virtual int f() = 0; };",
cxxMethodDecl(isPure(), hasName("::X::f"))));
EXPECT_TRUE(notMatches("class X { int f(); };", cxxMethodDecl(isPure())));
}
TEST(Matcher, MatchesCopyAssignmentOperator) {
EXPECT_TRUE(matches("class X { X &operator=(X); };",
cxxMethodDecl(isCopyAssignmentOperator())));
EXPECT_TRUE(matches("class X { X &operator=(X &); };",
cxxMethodDecl(isCopyAssignmentOperator())));
EXPECT_TRUE(matches("class X { X &operator=(const X &); };",
cxxMethodDecl(isCopyAssignmentOperator())));
EXPECT_TRUE(matches("class X { X &operator=(volatile X &); };",
cxxMethodDecl(isCopyAssignmentOperator())));
EXPECT_TRUE(matches("class X { X &operator=(const volatile X &); };",
cxxMethodDecl(isCopyAssignmentOperator())));
EXPECT_TRUE(notMatches("class X { X &operator=(X &&); };",
cxxMethodDecl(isCopyAssignmentOperator())));
}
TEST(Matcher, MatchesConstMethod) {
EXPECT_TRUE(
matches("struct A { void foo() const; };", cxxMethodDecl(isConst())));
EXPECT_TRUE(
notMatches("struct A { void foo(); };", cxxMethodDecl(isConst())));
}
TEST(Matcher, MatchesOverridingMethod) {
EXPECT_TRUE(matches("class X { virtual int f(); }; "
"class Y : public X { int f(); };",
cxxMethodDecl(isOverride(), hasName("::Y::f"))));
EXPECT_TRUE(notMatches("class X { virtual int f(); }; "
"class Y : public X { int f(); };",
cxxMethodDecl(isOverride(), hasName("::X::f"))));
EXPECT_TRUE(notMatches("class X { int f(); }; "
"class Y : public X { int f(); };",
cxxMethodDecl(isOverride())));
EXPECT_TRUE(notMatches("class X { int f(); int f(int); }; ",
cxxMethodDecl(isOverride())));
EXPECT_TRUE(
matches("template <typename Base> struct Y : Base { void f() override;};",
cxxMethodDecl(isOverride(), hasName("::Y::f"))));
}
TEST(Matcher, ConstructorCall) {
StatementMatcher Constructor = cxxConstructExpr();
EXPECT_TRUE(
matches("class X { public: X(); }; void x() { X x; }", Constructor));
EXPECT_TRUE(
matches("class X { public: X(); }; void x() { X x = X(); }",
Constructor));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x = 0; }",
Constructor));
EXPECT_TRUE(matches("class X {}; void x(int) { X x; }", Constructor));
}
TEST(Matcher, ConstructorArgument) {
StatementMatcher Constructor = cxxConstructExpr(
hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; X x(y); }",
Constructor));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; X x = X(y); }",
Constructor));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; X x = y; }",
Constructor));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int z; X x(z); }",
Constructor));
StatementMatcher WrongIndex = cxxConstructExpr(
hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int y; X x(y); }",
WrongIndex));
}
TEST(Matcher, ConstructorArgumentCount) {
StatementMatcher Constructor1Arg = cxxConstructExpr(argumentCountIs(1));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x(0); }",
Constructor1Arg));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x = X(0); }",
Constructor1Arg));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x = 0; }",
Constructor1Arg));
EXPECT_TRUE(
notMatches("class X { public: X(int, int); }; void x() { X x(0, 0); }",
Constructor1Arg));
}
TEST(Matcher, ConstructorListInitialization) {
StatementMatcher ConstructorListInit =
cxxConstructExpr(isListInitialization());
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { X x{0}; }",
ConstructorListInit));
EXPECT_FALSE(
matches("class X { public: X(int); }; void x() { X x(0); }",
ConstructorListInit));
}
TEST(Matcher,ThisExpr) {
EXPECT_TRUE(
matches("struct X { int a; int f () { return a; } };", cxxThisExpr()));
EXPECT_TRUE(
notMatches("struct X { int f () { int a; return a; } };", cxxThisExpr()));
}
TEST(Matcher, BindTemporaryExpression) {
StatementMatcher TempExpression = cxxBindTemporaryExpr();
std::string ClassString = "class string { public: string(); ~string(); }; ";
EXPECT_TRUE(
matches(ClassString +
"string GetStringByValue();"
"void FunctionTakesString(string s);"
"void run() { FunctionTakesString(GetStringByValue()); }",
TempExpression));
EXPECT_TRUE(
notMatches(ClassString +
"string* GetStringPointer(); "
"void FunctionTakesStringPtr(string* s);"
"void run() {"
" string* s = GetStringPointer();"
" FunctionTakesStringPtr(GetStringPointer());"
" FunctionTakesStringPtr(s);"
"}",
TempExpression));
EXPECT_TRUE(
notMatches("class no_dtor {};"
"no_dtor GetObjByValue();"
"void ConsumeObj(no_dtor param);"
"void run() { ConsumeObj(GetObjByValue()); }",
TempExpression));
}
TEST(MaterializeTemporaryExpr, MatchesTemporary) {
std::string ClassString =
"class string { public: string(); int length(); }; ";
EXPECT_TRUE(
matches(ClassString +
"string GetStringByValue();"
"void FunctionTakesString(string s);"
"void run() { FunctionTakesString(GetStringByValue()); }",
materializeTemporaryExpr()));
EXPECT_TRUE(
notMatches(ClassString +
"string* GetStringPointer(); "
"void FunctionTakesStringPtr(string* s);"
"void run() {"
" string* s = GetStringPointer();"
" FunctionTakesStringPtr(GetStringPointer());"
" FunctionTakesStringPtr(s);"
"}",
materializeTemporaryExpr()));
EXPECT_TRUE(
notMatches(ClassString +
"string GetStringByValue();"
"void run() { int k = GetStringByValue().length(); }",
materializeTemporaryExpr()));
EXPECT_TRUE(
notMatches(ClassString +
"string GetStringByValue();"
"void run() { GetStringByValue(); }",
materializeTemporaryExpr()));
}
TEST(ConstructorDeclaration, SimpleCase) {
EXPECT_TRUE(matches("class Foo { Foo(int i); };",
cxxConstructorDecl(ofClass(hasName("Foo")))));
EXPECT_TRUE(notMatches("class Foo { Foo(int i); };",
cxxConstructorDecl(ofClass(hasName("Bar")))));
}
TEST(ConstructorDeclaration, IsImplicit) {
// This one doesn't match because the constructor is not added by the
// compiler (it is not needed).
EXPECT_TRUE(notMatches("class Foo { };",
cxxConstructorDecl(isImplicit())));
// The compiler added the implicit default constructor.
EXPECT_TRUE(matches("class Foo { }; Foo* f = new Foo();",
cxxConstructorDecl(isImplicit())));
EXPECT_TRUE(matches("class Foo { Foo(){} };",
cxxConstructorDecl(unless(isImplicit()))));
// The compiler added an implicit assignment operator.
EXPECT_TRUE(matches("struct A { int x; } a = {0}, b = a; void f() { a = b; }",
cxxMethodDecl(isImplicit(), hasName("operator="))));
}
TEST(ConstructorDeclaration, IsExplicit) {
EXPECT_TRUE(matches("struct S { explicit S(int); };",
cxxConstructorDecl(isExplicit())));
EXPECT_TRUE(notMatches("struct S { S(int); };",
cxxConstructorDecl(isExplicit())));
}
TEST(ConstructorDeclaration, Kinds) {
EXPECT_TRUE(matches("struct S { S(); };",
cxxConstructorDecl(isDefaultConstructor())));
EXPECT_TRUE(notMatches("struct S { S(); };",
cxxConstructorDecl(isCopyConstructor())));
EXPECT_TRUE(notMatches("struct S { S(); };",
cxxConstructorDecl(isMoveConstructor())));
EXPECT_TRUE(notMatches("struct S { S(const S&); };",
cxxConstructorDecl(isDefaultConstructor())));
EXPECT_TRUE(matches("struct S { S(const S&); };",
cxxConstructorDecl(isCopyConstructor())));
EXPECT_TRUE(notMatches("struct S { S(const S&); };",
cxxConstructorDecl(isMoveConstructor())));
EXPECT_TRUE(notMatches("struct S { S(S&&); };",
cxxConstructorDecl(isDefaultConstructor())));
EXPECT_TRUE(notMatches("struct S { S(S&&); };",
cxxConstructorDecl(isCopyConstructor())));
EXPECT_TRUE(matches("struct S { S(S&&); };",
cxxConstructorDecl(isMoveConstructor())));
}
TEST(DestructorDeclaration, MatchesVirtualDestructor) {
EXPECT_TRUE(matches("class Foo { virtual ~Foo(); };",
cxxDestructorDecl(ofClass(hasName("Foo")))));
}
TEST(DestructorDeclaration, DoesNotMatchImplicitDestructor) {
EXPECT_TRUE(notMatches("class Foo {};",
cxxDestructorDecl(ofClass(hasName("Foo")))));
}
TEST(HasAnyConstructorInitializer, SimpleCase) {
EXPECT_TRUE(
notMatches("class Foo { Foo() { } };",
cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
EXPECT_TRUE(
matches("class Foo {"
" Foo() : foo_() { }"
" int foo_;"
"};",
cxxConstructorDecl(hasAnyConstructorInitializer(anything()))));
}
TEST(HasAnyConstructorInitializer, ForField) {
static const char Code[] =
"class Baz { };"
"class Foo {"
" Foo() : foo_() { }"
" Baz foo_;"
" Baz bar_;"
"};";
EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
forField(hasType(recordDecl(hasName("Baz"))))))));
EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
forField(hasName("foo_"))))));
EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
forField(hasType(recordDecl(hasName("Bar"))))))));
}
TEST(HasAnyConstructorInitializer, WithInitializer) {
static const char Code[] =
"class Foo {"
" Foo() : foo_(0) { }"
" int foo_;"
"};";
EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
withInitializer(integerLiteral(equals(0)))))));
EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
withInitializer(integerLiteral(equals(1)))))));
}
TEST(HasAnyConstructorInitializer, IsWritten) {
static const char Code[] =
"struct Bar { Bar(){} };"
"class Foo {"
" Foo() : foo_() { }"
" Bar foo_;"
" Bar bar_;"
"};";
EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
allOf(forField(hasName("foo_")), isWritten())))));
EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
allOf(forField(hasName("bar_")), isWritten())))));
EXPECT_TRUE(matches(Code, cxxConstructorDecl(hasAnyConstructorInitializer(
allOf(forField(hasName("bar_")), unless(isWritten()))))));
}
TEST(HasAnyConstructorInitializer, IsBaseInitializer) {
static const char Code[] =
"struct B {};"
"struct D : B {"
" int I;"
" D(int i) : I(i) {}"
"};"
"struct E : B {"
" E() : B() {}"
"};";
EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
hasName("E")))));
EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
hasAnyConstructorInitializer(allOf(isBaseInitializer(), isWritten())),
hasName("D")))));
EXPECT_TRUE(matches(Code, cxxConstructorDecl(allOf(
hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
hasName("D")))));
EXPECT_TRUE(notMatches(Code, cxxConstructorDecl(allOf(
hasAnyConstructorInitializer(allOf(isMemberInitializer(), isWritten())),
hasName("E")))));
}
TEST(Matcher, NewExpression) {
StatementMatcher New = cxxNewExpr();
EXPECT_TRUE(matches("class X { public: X(); }; void x() { new X; }", New));
EXPECT_TRUE(
matches("class X { public: X(); }; void x() { new X(); }", New));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { new X(0); }", New));
EXPECT_TRUE(matches("class X {}; void x(int) { new X; }", New));
}
TEST(Matcher, NewExpressionArgument) {
StatementMatcher New = cxxConstructExpr(
hasArgument(0, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; new X(y); }",
New));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { int y; new X(y); }",
New));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int z; new X(z); }",
New));
StatementMatcher WrongIndex = cxxConstructExpr(
hasArgument(42, declRefExpr(to(varDecl(hasName("y"))))));
EXPECT_TRUE(
notMatches("class X { public: X(int); }; void x() { int y; new X(y); }",
WrongIndex));
}
TEST(Matcher, NewExpressionArgumentCount) {
StatementMatcher New = cxxConstructExpr(argumentCountIs(1));
EXPECT_TRUE(
matches("class X { public: X(int); }; void x() { new X(0); }", New));
EXPECT_TRUE(
notMatches("class X { public: X(int, int); }; void x() { new X(0, 0); }",
New));
}
TEST(Matcher, DeleteExpression) {
EXPECT_TRUE(matches("struct A {}; void f(A* a) { delete a; }",
cxxDeleteExpr()));
}
TEST(Matcher, DefaultArgument) {
StatementMatcher Arg = cxxDefaultArgExpr();
EXPECT_TRUE(matches("void x(int, int = 0) { int y; x(y); }", Arg));
EXPECT_TRUE(
matches("class X { void x(int, int = 0) { int y; x(y); } };", Arg));
EXPECT_TRUE(notMatches("void x(int, int = 0) { int y; x(y, 0); }", Arg));
}
TEST(Matcher, StringLiterals) {
StatementMatcher Literal = stringLiteral();
EXPECT_TRUE(matches("const char *s = \"string\";", Literal));
// wide string
EXPECT_TRUE(matches("const wchar_t *s = L\"string\";", Literal));
// with escaped characters
EXPECT_TRUE(matches("const char *s = \"\x05five\";", Literal));
// no matching -- though the data type is the same, there is no string literal
EXPECT_TRUE(notMatches("const char s[1] = {'a'};", Literal));
}
TEST(Matcher, CharacterLiterals) {
StatementMatcher CharLiteral = characterLiteral();
EXPECT_TRUE(matches("const char c = 'c';", CharLiteral));
// wide character
EXPECT_TRUE(matches("const char c = L'c';", CharLiteral));
// wide character, Hex encoded, NOT MATCHED!
EXPECT_TRUE(notMatches("const wchar_t c = 0x2126;", CharLiteral));
EXPECT_TRUE(notMatches("const char c = 0x1;", CharLiteral));
}
TEST(Matcher, IntegerLiterals) {
StatementMatcher HasIntLiteral = integerLiteral();
EXPECT_TRUE(matches("int i = 10;", HasIntLiteral));
EXPECT_TRUE(matches("int i = 0x1AB;", HasIntLiteral));
EXPECT_TRUE(matches("int i = 10L;", HasIntLiteral));
EXPECT_TRUE(matches("int i = 10U;", HasIntLiteral));
// Non-matching cases (character literals, float and double)
EXPECT_TRUE(notMatches("int i = L'a';",
HasIntLiteral)); // this is actually a character
// literal cast to int
EXPECT_TRUE(notMatches("int i = 'a';", HasIntLiteral));
EXPECT_TRUE(notMatches("int i = 1e10;", HasIntLiteral));
EXPECT_TRUE(notMatches("int i = 10.0;", HasIntLiteral));
}
TEST(Matcher, FloatLiterals) {
StatementMatcher HasFloatLiteral = floatLiteral();
EXPECT_TRUE(matches("float i = 10.0;", HasFloatLiteral));
EXPECT_TRUE(matches("float i = 10.0f;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 10.0;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 10.0L;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 1e10;", HasFloatLiteral));
EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0))));
EXPECT_TRUE(matches("double i = 5.0;", floatLiteral(equals(5.0f))));
EXPECT_TRUE(
matches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(5.0)))));
EXPECT_TRUE(notMatches("float i = 10;", HasFloatLiteral));
EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0))));
EXPECT_TRUE(notMatches("double i = 5.0;", floatLiteral(equals(6.0f))));
EXPECT_TRUE(
notMatches("double i = 5.0;", floatLiteral(equals(llvm::APFloat(6.0)))));
}
TEST(Matcher, NullPtrLiteral) {
EXPECT_TRUE(matches("int* i = nullptr;", cxxNullPtrLiteralExpr()));
}
TEST(Matcher, GNUNullExpr) {
EXPECT_TRUE(matches("int* i = __null;", gnuNullExpr()));
}
TEST(Matcher, AsmStatement) {
EXPECT_TRUE(matches("void foo() { __asm(\"mov al, 2\"); }", asmStmt()));
}
TEST(Matcher, Conditions) {
StatementMatcher Condition =
ifStmt(hasCondition(cxxBoolLiteral(equals(true))));
EXPECT_TRUE(matches("void x() { if (true) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { if (false) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { bool a = true; if (a) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { if (true || false) {} }", Condition));
EXPECT_TRUE(notMatches("void x() { if (1) {} }", Condition));
}
TEST(IfStmt, ChildTraversalMatchers) {
EXPECT_TRUE(matches("void f() { if (false) true; else false; }",
ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
EXPECT_TRUE(notMatches("void f() { if (false) false; else true; }",
ifStmt(hasThen(cxxBoolLiteral(equals(true))))));
EXPECT_TRUE(matches("void f() { if (false) false; else true; }",
ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
EXPECT_TRUE(notMatches("void f() { if (false) true; else false; }",
ifStmt(hasElse(cxxBoolLiteral(equals(true))))));
}
TEST(MatchBinaryOperator, HasOperatorName) {
StatementMatcher OperatorOr = binaryOperator(hasOperatorName("||"));
EXPECT_TRUE(matches("void x() { true || false; }", OperatorOr));
EXPECT_TRUE(notMatches("void x() { true && false; }", OperatorOr));
}
TEST(MatchBinaryOperator, HasLHSAndHasRHS) {
StatementMatcher OperatorTrueFalse =
binaryOperator(hasLHS(cxxBoolLiteral(equals(true))),
hasRHS(cxxBoolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true || false; }", OperatorTrueFalse));
EXPECT_TRUE(matches("void x() { true && false; }", OperatorTrueFalse));
EXPECT_TRUE(notMatches("void x() { false || true; }", OperatorTrueFalse));
StatementMatcher OperatorIntPointer = arraySubscriptExpr(
hasLHS(hasType(isInteger())), hasRHS(hasType(pointsTo(qualType()))));
EXPECT_TRUE(matches("void x() { 1[\"abc\"]; }", OperatorIntPointer));
EXPECT_TRUE(notMatches("void x() { \"abc\"[1]; }", OperatorIntPointer));
}
TEST(MatchBinaryOperator, HasEitherOperand) {
StatementMatcher HasOperand =
binaryOperator(hasEitherOperand(cxxBoolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true || false; }", HasOperand));
EXPECT_TRUE(matches("void x() { false && true; }", HasOperand));
EXPECT_TRUE(notMatches("void x() { true || true; }", HasOperand));
}
TEST(Matcher, BinaryOperatorTypes) {
// Integration test that verifies the AST provides all binary operators in
// a way we expect.
// FIXME: Operator ','
EXPECT_TRUE(
matches("void x() { 3, 4; }", binaryOperator(hasOperatorName(","))));
EXPECT_TRUE(
matches("bool b; bool c = (b = true);",
binaryOperator(hasOperatorName("="))));
EXPECT_TRUE(
matches("bool b = 1 != 2;", binaryOperator(hasOperatorName("!="))));
EXPECT_TRUE(
matches("bool b = 1 == 2;", binaryOperator(hasOperatorName("=="))));
EXPECT_TRUE(matches("bool b = 1 < 2;", binaryOperator(hasOperatorName("<"))));
EXPECT_TRUE(
matches("bool b = 1 <= 2;", binaryOperator(hasOperatorName("<="))));
EXPECT_TRUE(
matches("int i = 1 << 2;", binaryOperator(hasOperatorName("<<"))));
EXPECT_TRUE(
matches("int i = 1; int j = (i <<= 2);",
binaryOperator(hasOperatorName("<<="))));
EXPECT_TRUE(matches("bool b = 1 > 2;", binaryOperator(hasOperatorName(">"))));
EXPECT_TRUE(
matches("bool b = 1 >= 2;", binaryOperator(hasOperatorName(">="))));
EXPECT_TRUE(
matches("int i = 1 >> 2;", binaryOperator(hasOperatorName(">>"))));
EXPECT_TRUE(
matches("int i = 1; int j = (i >>= 2);",
binaryOperator(hasOperatorName(">>="))));
EXPECT_TRUE(
matches("int i = 42 ^ 23;", binaryOperator(hasOperatorName("^"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i ^= 42);",
binaryOperator(hasOperatorName("^="))));
EXPECT_TRUE(
matches("int i = 42 % 23;", binaryOperator(hasOperatorName("%"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i %= 42);",
binaryOperator(hasOperatorName("%="))));
EXPECT_TRUE(
matches("bool b = 42 &23;", binaryOperator(hasOperatorName("&"))));
EXPECT_TRUE(
matches("bool b = true && false;",
binaryOperator(hasOperatorName("&&"))));
EXPECT_TRUE(
matches("bool b = true; bool c = (b &= false);",
binaryOperator(hasOperatorName("&="))));
EXPECT_TRUE(
matches("bool b = 42 | 23;", binaryOperator(hasOperatorName("|"))));
EXPECT_TRUE(
matches("bool b = true || false;",
binaryOperator(hasOperatorName("||"))));
EXPECT_TRUE(
matches("bool b = true; bool c = (b |= false);",
binaryOperator(hasOperatorName("|="))));
EXPECT_TRUE(
matches("int i = 42 *23;", binaryOperator(hasOperatorName("*"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i *= 23);",
binaryOperator(hasOperatorName("*="))));
EXPECT_TRUE(
matches("int i = 42 / 23;", binaryOperator(hasOperatorName("/"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i /= 23);",
binaryOperator(hasOperatorName("/="))));
EXPECT_TRUE(
matches("int i = 42 + 23;", binaryOperator(hasOperatorName("+"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i += 23);",
binaryOperator(hasOperatorName("+="))));
EXPECT_TRUE(
matches("int i = 42 - 23;", binaryOperator(hasOperatorName("-"))));
EXPECT_TRUE(
matches("int i = 42; int j = (i -= 23);",
binaryOperator(hasOperatorName("-="))));
EXPECT_TRUE(
matches("struct A { void x() { void (A::*a)(); (this->*a)(); } };",
binaryOperator(hasOperatorName("->*"))));
EXPECT_TRUE(
matches("struct A { void x() { void (A::*a)(); ((*this).*a)(); } };",
binaryOperator(hasOperatorName(".*"))));
// Member expressions as operators are not supported in matches.
EXPECT_TRUE(
notMatches("struct A { void x(A *a) { a->x(this); } };",
binaryOperator(hasOperatorName("->"))));
// Initializer assignments are not represented as operator equals.
EXPECT_TRUE(
notMatches("bool b = true;", binaryOperator(hasOperatorName("="))));
// Array indexing is not represented as operator.
EXPECT_TRUE(notMatches("int a[42]; void x() { a[23]; }", unaryOperator()));
// Overloaded operators do not match at all.
EXPECT_TRUE(notMatches(
"struct A { bool operator&&(const A &a) const { return false; } };"
"void x() { A a, b; a && b; }",
binaryOperator()));
}
TEST(MatchUnaryOperator, HasOperatorName) {
StatementMatcher OperatorNot = unaryOperator(hasOperatorName("!"));
EXPECT_TRUE(matches("void x() { !true; } ", OperatorNot));
EXPECT_TRUE(notMatches("void x() { true; } ", OperatorNot));
}
TEST(MatchUnaryOperator, HasUnaryOperand) {
StatementMatcher OperatorOnFalse =
unaryOperator(hasUnaryOperand(cxxBoolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { !false; }", OperatorOnFalse));
EXPECT_TRUE(notMatches("void x() { !true; }", OperatorOnFalse));
}
TEST(Matcher, UnaryOperatorTypes) {
// Integration test that verifies the AST provides all unary operators in
// a way we expect.
EXPECT_TRUE(matches("bool b = !true;", unaryOperator(hasOperatorName("!"))));
EXPECT_TRUE(
matches("bool b; bool *p = &b;", unaryOperator(hasOperatorName("&"))));
EXPECT_TRUE(matches("int i = ~ 1;", unaryOperator(hasOperatorName("~"))));
EXPECT_TRUE(
matches("bool *p; bool b = *p;", unaryOperator(hasOperatorName("*"))));
EXPECT_TRUE(
matches("int i; int j = +i;", unaryOperator(hasOperatorName("+"))));
EXPECT_TRUE(
matches("int i; int j = -i;", unaryOperator(hasOperatorName("-"))));
EXPECT_TRUE(
matches("int i; int j = ++i;", unaryOperator(hasOperatorName("++"))));
EXPECT_TRUE(
matches("int i; int j = i++;", unaryOperator(hasOperatorName("++"))));
EXPECT_TRUE(
matches("int i; int j = --i;", unaryOperator(hasOperatorName("--"))));
EXPECT_TRUE(
matches("int i; int j = i--;", unaryOperator(hasOperatorName("--"))));
// We don't match conversion operators.
EXPECT_TRUE(notMatches("int i; double d = (double)i;", unaryOperator()));
// Function calls are not represented as operator.
EXPECT_TRUE(notMatches("void f(); void x() { f(); }", unaryOperator()));
// Overloaded operators do not match at all.
// FIXME: We probably want to add that.
EXPECT_TRUE(notMatches(
"struct A { bool operator!() const { return false; } };"
"void x() { A a; !a; }", unaryOperator(hasOperatorName("!"))));
}
TEST(Matcher, ConditionalOperator) {
StatementMatcher Conditional = conditionalOperator(
hasCondition(cxxBoolLiteral(equals(true))),
hasTrueExpression(cxxBoolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true ? false : true; }", Conditional));
EXPECT_TRUE(notMatches("void x() { false ? false : true; }", Conditional));
EXPECT_TRUE(notMatches("void x() { true ? true : false; }", Conditional));
StatementMatcher ConditionalFalse = conditionalOperator(
hasFalseExpression(cxxBoolLiteral(equals(false))));
EXPECT_TRUE(matches("void x() { true ? true : false; }", ConditionalFalse));
EXPECT_TRUE(
notMatches("void x() { true ? false : true; }", ConditionalFalse));
}
TEST(ArraySubscriptMatchers, ArraySubscripts) {
EXPECT_TRUE(matches("int i[2]; void f() { i[1] = 1; }",
arraySubscriptExpr()));
EXPECT_TRUE(notMatches("int i; void f() { i = 1; }",
arraySubscriptExpr()));
}
TEST(ArraySubscriptMatchers, ArrayIndex) {
EXPECT_TRUE(matches(
"int i[2]; void f() { i[1] = 1; }",
arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
EXPECT_TRUE(matches(
"int i[2]; void f() { 1[i] = 1; }",
arraySubscriptExpr(hasIndex(integerLiteral(equals(1))))));
EXPECT_TRUE(notMatches(
"int i[2]; void f() { i[1] = 1; }",
arraySubscriptExpr(hasIndex(integerLiteral(equals(0))))));
}
TEST(ArraySubscriptMatchers, MatchesArrayBase) {
EXPECT_TRUE(matches(
"int i[2]; void f() { i[1] = 2; }",
arraySubscriptExpr(hasBase(implicitCastExpr(
hasSourceExpression(declRefExpr()))))));
}
TEST(Matcher, HasNameSupportsNamespaces) {
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a::b::C"))));
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("::a::b::C"))));
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("b::C"))));
EXPECT_TRUE(matches("namespace a { namespace b { class C; } }",
recordDecl(hasName("C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("c::b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a::c::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a::b::A"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("::b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("z::a::b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class C; } }",
recordDecl(hasName("a+b::C"))));
EXPECT_TRUE(notMatches("namespace a { namespace b { class AC; } }",
recordDecl(hasName("C"))));
}
TEST(Matcher, HasNameSupportsOuterClasses) {
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("A::B::C"))));
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("::A::B::C"))));
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("B::C"))));
EXPECT_TRUE(
matches("class A { class B { class C; }; };",
recordDecl(hasName("C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("c::B::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("A::c::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("A::B::A"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("::B::C"))));
EXPECT_TRUE(notMatches("class A { class B { class C; }; };",
recordDecl(hasName("z::A::B::C"))));
EXPECT_TRUE(
notMatches("class A { class B { class C; }; };",
recordDecl(hasName("A+B::C"))));
}
TEST(Matcher, IsDefinition) {
DeclarationMatcher DefinitionOfClassA =
recordDecl(hasName("A"), isDefinition());
EXPECT_TRUE(matches("class A {};", DefinitionOfClassA));
EXPECT_TRUE(notMatches("class A;", DefinitionOfClassA));
DeclarationMatcher DefinitionOfVariableA =
varDecl(hasName("a"), isDefinition());
EXPECT_TRUE(matches("int a;", DefinitionOfVariableA));
EXPECT_TRUE(notMatches("extern int a;", DefinitionOfVariableA));
DeclarationMatcher DefinitionOfMethodA =
cxxMethodDecl(hasName("a"), isDefinition());
EXPECT_TRUE(matches("class A { void a() {} };", DefinitionOfMethodA));
EXPECT_TRUE(notMatches("class A { void a(); };", DefinitionOfMethodA));
}
TEST(Matcher, OfClass) {
StatementMatcher Constructor = cxxConstructExpr(hasDeclaration(cxxMethodDecl(
ofClass(hasName("X")))));
EXPECT_TRUE(
matches("class X { public: X(); }; void x(int) { X x; }", Constructor));
EXPECT_TRUE(
matches("class X { public: X(); }; void x(int) { X x = X(); }",
Constructor));
EXPECT_TRUE(