Files
Library/tests/standalone/Core/Meta.cpp
T

100 lines
2.8 KiB
C++

// @requires-reflection
#include <Void/Core/Meta.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
namespace M = Void::Meta;
namespace
{
struct Point {
int x = 1;
int y = 2;
};
struct Nest {
Point p;
std::string tag = "z";
};
enum class Color { Red, Green, Blue };
} // namespace
Void::Testing::Test meta_field_walk()
{
Void::Testing::expect_eq(M::field_count<Point>(), std::size_t{2});
const auto names = M::field_names<Point>();
Void::Testing::expect_eq(names.size(), std::size_t{2});
Void::Testing::expect(names[0] == "x" && names[1] == "y");
Point p{3, 4};
int sum = 0;
M::for_each_field(p, [&](std::string_view, auto& f) { sum += f; });
Void::Testing::expect_eq(sum, 7);
// mutate through for_each_field
M::for_each_field(p, [](std::string_view, auto& f) { f += 1; });
Void::Testing::expect(p.x == 4 && p.y == 5);
}
Void::Testing::Test meta_equal_compare_hash()
{
Point a{3, 4};
Point b{3, 4};
Point c{3, 5};
Void::Testing::expect(M::equal(a, b));
Void::Testing::expect(!M::equal(a, c));
Void::Testing::expect(M::compare(a, c) == std::strong_ordering::less);
Void::Testing::expect(M::compare(a, b) == std::strong_ordering::equal);
Void::Testing::expect_eq(M::hash(a), M::hash(b));
Void::Testing::expect(M::hash(a) != M::hash(c));
}
Void::Testing::Test meta_repr_nested()
{
Point p{5, 6};
Void::Testing::expect_eq(M::repr(p), std::string{"Point{x: 5, y: 6}"});
Nest n{Point{1, 2}, "hi"};
Void::Testing::expect_eq(
M::repr(n), std::string{"Nest{p: Point{x: 1, y: 2}, tag: hi}"});
}
Void::Testing::Test meta_enum_utilities()
{
Void::Testing::expect_eq(M::enum_count<Color>, std::size_t{3});
constexpr auto vals = M::enum_values<Color>();
Void::Testing::expect(vals[0] == Color::Red && vals[2] == Color::Blue);
const auto entries = M::enum_entries<Color>();
Void::Testing::expect(entries[1].first == Color::Green &&
entries[1].second == "Green");
Void::Testing::expect(M::enum_name(Color::Blue) == "Blue");
Void::Testing::expect(M::enum_parse<Color>("Green").value() ==
Color::Green);
Void::Testing::expect(!M::enum_parse<Color>("Nope").has_value());
}
namespace
{
struct Marker {
};
struct Annotated {
[[= Marker{}]] int tagged = 0;
int plain = 0;
};
} // namespace
Void::Testing::Test meta_member_annotations()
{
static constexpr auto members = M::members_v<Annotated>;
static_assert(M::has_annotation<Marker>(members[0]));
static_assert(!M::has_annotation<Marker>(members[1]));
Void::Testing::expect(M::has_annotation<Marker>(members[0]));
Void::Testing::expect(!M::has_annotation<Marker>(members[1]));
}
Void::Testing::Test meta_type_name()
{
Void::Testing::expect_eq(M::type_name<Point>(), std::string{"Point"});
Void::Testing::expect_eq(M::type_name<Nest>(), std::string{"Nest"});
}