diff --git a/README.md b/README.md index 0c7b6c00..14153ee5 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,29 @@ Found 5 errors: 5) Field named 'children' not found. ``` +## Enums + +reflect-cpp supports scoped enumerations: + +```cpp +enum class Color { red, green, blue, yellow }; + +struct Circle { + float radius; + Color color; +}; + +const auto circle = Circle{.radius = 2.0, .color = Color::green}; + +rfl::json::write(circle); +``` + +This results in the following JSON string: + +```json +{"radius":2.0,"color":"green"} +``` + ## Algebraic data types reflect-cpp supports Pydantic-style tagged unions, which allow you to form algebraic data types: diff --git a/docs/enums.md b/docs/enums.md new file mode 100644 index 00000000..edd1530b --- /dev/null +++ b/docs/enums.md @@ -0,0 +1,55 @@ +# Enums + +reflect-cpp supports scoped enumerations. + +Example: + +```cpp +enum class Color { red, green, blue, yellow }; + +struct Circle { + float radius; + Color color; +}; + +const auto circle = Circle{.radius = 2.0, .color = Color::green}; + +rfl::json::write(circle); +``` + +This results in the following JSON string: + +```json +{"radius":2.0,"color":"green"} +``` + +However, some limitations apply: + +1. They must be be scoped enumerations. + +```cpp +/// OK - scoped enumeration +enum class Color1 { red, green, blue, yellow }; + +/// OK - scoped enumeration +enum struct Color2 { red, green, blue, yellow }; + +/// unsupported - unscoped enumerations +enum Color3 { red, green, blue, yellow }; +``` + +2. You cannot have more than 100 values and if you explicitly assign values, they must be between 0 and 99. + +```cpp +/// OK +enum class Color1 { red, green, blue, yellow }; + +/// OK +enum struct Color2 { red, green, blue = 50, yellow }; + +/// unsupported - red is a negative value +enum Color3 { red = -10, green, blue, yellow }; + +/// unsupported - red is greater than 99 +enum Color3 { red = 200, green, blue, yellow }; +``` \ No newline at end of file diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index c882fe23..8c7969e5 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -73,6 +73,14 @@ class Literal { return Literal(_value); } + /// Constructs a new Literal. + static Result> from_value(ValueType _value) { + if (_value >= num_fields_) { + return Error("Value cannot exceed number of fields."); + } + return Literal(_value); + } + /// Determines whether the literal contains the string. static bool contains(const std::string& _str) { return has_value(_str); } diff --git a/include/rfl/internal/enums/EnumLiteralConverter.hpp b/include/rfl/internal/enums/EnumLiteralConverter.hpp new file mode 100644 index 00000000..a881fe8e --- /dev/null +++ b/include/rfl/internal/enums/EnumLiteralConverter.hpp @@ -0,0 +1,38 @@ +#ifndef RFL_INTERNAL_ENUMS_LITERAL_CONVERTER_HPP_ +#define RFL_INTERNAL_ENUMS_LITERAL_CONVERTER_HPP_ + +#include +#include +#include +#include +#include + +#include "rfl/Literal.hpp" + +namespace rfl { +namespace internal { +namespace enums { + +template +struct Names { + /// Contains a collection of enums as compile-time strings. + using Names = LiteralType; + + /// The number of possible values + constexpr static size_t size = N; + + /// A list of all the possible enums + std::array enums_; + + /// The integer values underlying the enum. + std::array, N> integers_; + + static_assert(LiteralType::size() == N, + "Size of literal and enum do not match."); +}; + +} // namespace enums +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/enums/LiteralConverter.hpp b/include/rfl/internal/enums/LiteralConverter.hpp new file mode 100644 index 00000000..74e13560 --- /dev/null +++ b/include/rfl/internal/enums/LiteralConverter.hpp @@ -0,0 +1,59 @@ +#ifndef RFL_INTERNAL_ENUMS_LITERAL_CONVERTER_HPP_ +#define RFL_INTERNAL_ENUMS_LITERAL_CONVERTER_HPP_ + +#include +#include +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/internal/enums/get_enum_names.hpp" +#include "rfl/type_name_t.hpp" + +namespace rfl { +namespace internal { +namespace enums { + +template +struct LiteralConverter { + static constexpr auto names_ = get_enum_names(); + + using NamesLiteral = typename decltype(names_)::Literal; + + static Result enum_to_literal(const EnumType _enum) { + for (size_t i = 0; i < names_.size; ++i) { + if (names_.enums_[i] == _enum) { + return NamesLiteral::from_value( + static_cast(i)); + } + } + return Error( + "Something went wrong when parsing the enum type '" + + type_name_t().str() + + "'. An integer representation of the enum type is " + + std::to_string(static_cast>(_enum)) + + ". Is it possible that some of the values are negative or " + "greater than 99? This is unsupported (as is explicitly " + "stated in the documentation)."); + } + + static Result enum_to_string(const EnumType _enum) { + const auto to_str = [](const auto _l) { return _l.str(); }; + return enum_to_literal(_enum).transform(to_str); + } + + static EnumType literal_to_enum(const NamesLiteral _lit) { + return names_.enums_[_lit.value()]; + } + + static Result string_to_enum(const std::string& _str) { + return NamesLiteral::from_string(_str).transform(literal_to_enum); + } +}; + +} // namespace enums +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/enums/Names.hpp b/include/rfl/internal/enums/Names.hpp new file mode 100644 index 00000000..0b61e804 --- /dev/null +++ b/include/rfl/internal/enums/Names.hpp @@ -0,0 +1,38 @@ +#ifndef RFL_INTERNAL_ENUMS_NAMES_HPP_ +#define RFL_INTERNAL_ENUMS_NAMES_HPP_ + +#include +#include +#include +#include +#include + +#include "rfl/Literal.hpp" + +namespace rfl { +namespace internal { +namespace enums { + +template +struct Names { + /// Contains a collection of enums as compile-time strings. + using Literal = LiteralType; + + /// The number of possible values + constexpr static size_t size = N; + + /// A list of all the possible enums + std::array enums_; + + /// The integer values underlying the enum. + std::array, N> integers_; + + static_assert(N == 0 || LiteralType::size() == N, + "Size of literal and enum do not match."); +}; + +} // namespace enums +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/enums/get_enum_names.hpp b/include/rfl/internal/enums/get_enum_names.hpp new file mode 100644 index 00000000..4fa5c7ef --- /dev/null +++ b/include/rfl/internal/enums/get_enum_names.hpp @@ -0,0 +1,130 @@ +#ifndef RFL_INTERNAL_ENUMS_GET_ENUM_NAMES_HPP_ +#define RFL_INTERNAL_ENUMS_GET_ENUM_NAMES_HPP_ + +#include +#include +#include + +#include "rfl/Literal.hpp" +#include "rfl/define_literal.hpp" +#include "rfl/internal/enums/Names.hpp" +#include "rfl/internal/remove_namespaces.hpp" + +// https://en.cppreference.com/w/cpp/language/static_cast: + +// 8) A value of integer or enumeration type can be converted to any complete +// enumeration type. + +// If the underlying type is not fixed, the behavior is undefined if the value +// of expression is out of range (the range is all values possible for the +// smallest bit-field large enough to hold all enumerators of the target +// enumeration). If the underlying type is fixed, the result is the same as +// converting the original value first to the underlying type of the enumeration +// and then to the enumeration type. + +// https://en.cppreference.com/w/cpp/language/enum + +// enum struct|class name { enumerator = constexpr , enumerator = constexpr , +// ... } (1) +// ... +// 1) declares a scoped enumeration type whose underlying type is int (the +// keywords class and struct are exactly equivalent) +// +// --> These rules taken together imply that if you EITHER fix the type OR you +// use a scoped integer, static_cast(some_integer_value) will always be +// defined. + +namespace rfl { +namespace internal { +namespace enums { + +template +consteval auto get_enum_name_str_view() { + const auto func_name = + std::string_view{std::source_location::current().function_name()}; +#if defined(__clang__) + const auto split = func_name.substr(0, func_name.size() - 1); + return split.substr(split.find("e = ") + 4); +#elif defined(__GNUC__) + const auto split = func_name.substr(0, func_name.size() - 1); + return split.substr(split.find("e = ") + 4); +#elif defined(_MSC_VER) + const auto split = func_name.substr(0, func_name.size() - 7); + return split.substr(split.find("get_enum_name_str_view<") + 23); +#else + static_assert(false, + "You are using an unsupported compiler. Please use GCC, Clang " + "or MSVC or use rfl::Literal."); +#endif +} + +template +consteval auto get_enum_name() { + constexpr auto name = get_enum_name_str_view(); + const auto to_str_lit = [&](std::index_sequence) { + return StringLiteral{name[Ns]...}; + }; + return to_str_lit(std::make_index_sequence{}); +} + +template +constexpr auto start_value = Names, 0>{ + .enums_ = std::array{}, + .integers_ = std::array, 0>{}}; + +template , int _i = 0> +consteval auto get_enum_names() { + static_assert( + std::is_enum_v && + !std::is_convertible_v>, + "You must use scoped enums (using class or struct) for the " + "parsing to work!"); + + static_assert(std::is_integral_v>, + "The underlying type of any Enum must be integral!"); + + constexpr auto max = + std::numeric_limits>::max(); + + if constexpr (_i == 100 || _i > max) { + return _names; + } else { + constexpr auto name = get_enum_name(_i)>(); + if constexpr (std::get<0>(name.arr_) == '(') { + return get_enum_names(); + } else { + const auto update_enums = [&](std::index_sequence) { + return std::array{ + _names.enums_[Ns]..., static_cast(_i)}; + }; + + const auto update_integers = [&](std::index_sequence) { + return std::array, sizeof...(Ns) + 1>{ + _names.integers_[Ns]..., + static_cast>(_i)}; + }; + + using NewNames = std::conditional_t< + decltype(_names)::size == 0, + Names()>, 1>, + Names()>>, + decltype(_names)::size + 1>>; + + constexpr auto new_names = NewNames{ + .enums_ = + update_enums(std::make_index_sequence{}), + .integers_ = update_integers( + std::make_index_sequence{})}; + + return get_enum_names(); + } + } +} + +} // namespace enums +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index e1ca4130..23ffd226 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -35,6 +35,7 @@ #include "rfl/internal/Memoization.hpp" #include "rfl/internal/StringLiteral.hpp" #include "rfl/internal/all_fields.hpp" +#include "rfl/internal/enums/LiteralConverter.hpp" #include "rfl/internal/flattened_ptr_tuple_t.hpp" #include "rfl/internal/flattened_tuple_t.hpp" #include "rfl/internal/get_field_names.hpp" @@ -104,6 +105,10 @@ struct Parser { } }; return Parser::read(_r, _var).and_then(to_struct); + } else if constexpr (std::is_enum_v) { + using LiteralConverter = internal::enums::LiteralConverter; + return _r.template to_basic_type(_var).and_then( + LiteralConverter::string_to_enum); } else if constexpr (internal::is_basic_type_v) { return _r.template to_basic_type>(_var); } else { @@ -130,6 +135,14 @@ struct Parser { const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var); using PtrNamedTupleType = std::decay_t; return Parser::write(_w, ptr_named_tuple); + } else if constexpr (std::is_enum_v) { + using LiteralConverter = internal::enums::LiteralConverter; + const auto handle_error = [](const auto& _err) -> std::string { + return _err.what(); + }; + const auto str = + LiteralConverter::enum_to_string(_var).or_else(handle_error).value(); + return _w.from_basic_type(str); } else if constexpr (internal::is_basic_type_v) { return _w.from_basic_type(_var); } else { diff --git a/tests/json/CMakeLists.txt b/tests/json/CMakeLists.txt index 7ba5a0f5..ccaac37b 100644 --- a/tests/json/CMakeLists.txt +++ b/tests/json/CMakeLists.txt @@ -27,6 +27,7 @@ add_executable( "test_default_values.cpp" "test_deque.cpp" "test_email.cpp" + "test_enum.cpp" "test_error_messages.cpp" "test_field_variant.cpp" "test_flatten.cpp" diff --git a/tests/json/test_enum.cpp b/tests/json/test_enum.cpp new file mode 100644 index 00000000..21010052 --- /dev/null +++ b/tests/json/test_enum.cpp @@ -0,0 +1,30 @@ +#include "test_enum.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_enum { + +enum class Color { red, green, blue, yellow }; + +struct Circle { + float radius; + Color color; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto circle = Circle{.radius = 2.0, .color = Color::green}; + + write_and_read(circle, R"({"radius":2.0,"color":"green"})"); +} + +} // namespace test_enum diff --git a/tests/json/test_enum.hpp b/tests/json/test_enum.hpp new file mode 100644 index 00000000..2e2e0b3d --- /dev/null +++ b/tests/json/test_enum.hpp @@ -0,0 +1,4 @@ +namespace test_enum { +void test(); +} + diff --git a/tests/json/tests.cpp b/tests/json/tests.cpp index b3e1d272..6ead366c 100644 --- a/tests/json/tests.cpp +++ b/tests/json/tests.cpp @@ -16,6 +16,7 @@ #include "test_default_values.hpp" #include "test_deque.hpp" #include "test_email.hpp" +#include "test_enum.hpp" #include "test_error_messages.hpp" #include "test_field_variant.hpp" #include "test_flatten.hpp" @@ -65,6 +66,7 @@ int main() { test_unique_ptr::test(); test_unique_ptr2::test(); test_literal::test(); + test_enum::test(); test_variant::test(); test_tagged_union::test(); test_tagged_union2::test();