diff --git a/README.md b/README.md index 88886c5c..2adbc365 100644 --- a/README.md +++ b/README.md @@ -478,7 +478,7 @@ In addition, it supports the following custom containers: - `rfl::Result`: Allows for exception-free programming. - `rfl::TaggedUnion`: Similar to `std::variant`, but with explicit tags that make parsing more efficient. - `rfl::Validator`: Allows for automatic input validation. -- `rfl::Variant`: An alternative to `std::variant`. +- `rfl::Variant`: An alternative to `std::variant` that compiles considerably faster. ### Custom classes diff --git a/docs/variants_and_tagged_unions.md b/docs/variants_and_tagged_unions.md index dc878330..b534161e 100644 --- a/docs/variants_and_tagged_unions.md +++ b/docs/variants_and_tagged_unions.md @@ -1,10 +1,19 @@ # `std::variant`, `rfl::Variant` and `rfl::TaggedUnion` -## `std::variant` or `rfl::Variant` (untagged) +## `rfl::Variant` (untagged) Sometimes you know that the JSON object can be one of several alternatives. For example, you might have several shapes like `Circle`, `Rectangle` or `Square`. For these kind of -cases, the C++ standard library contains `std::variant`, even though we we recommend you to use `rfl::Variant` instead: +cases, the C++ standard library contains `std::variant` and it is supported by reflect-cpp. + +However, we recommend you use `rfl::Variant` instead. + +`rfl::Variant` behaves just like `std::variant`, but it compiles considerably faster, +particularly for variants with many alternatives. + +You can use the functions `rfl::get`, `rfl::get_if`, `rfl::holds_alternative`, `rfl::visit`, +`rfl::variant_alternative_t` and `rfl::variant_size_v` to access the variant and they work +the same way as their equivalents in the standard library. ```cpp struct Circle { @@ -34,7 +43,7 @@ several problems with this: 1) It is in inefficient: The parser has to read the fields for all of the different alternatives until it can't find a required field in the JSON object. It will then move on to the next alternative. 2) It leads to confusing error messages: If none of the alternatives can be matched, you will get an error message telling you why each of the alternatives couldn't be matched. Such error messages are very long-winding and hard to read. -3) It is dangerous. Imagine we had written `std::variant` instead of `std::variant`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs. +3) It is dangerous. Imagine we had written `rfl::Variant` instead of `rfl::Variant`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs. ## `rfl::TaggedUnion` (internally tagged) @@ -196,7 +205,7 @@ Because the tag is external, this is called *externally tagged*. It is the stand ## The visitor pattern -In C++, the idiomatic way to handle `std::variant` and `rfl::TaggedUnion` is the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit). +In C++, the idiomatic way to handle `std::variant`, `rfl::Variant` and `rfl::TaggedUnion` is the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit). For instance, the externally tagged `rfl::Variant` from the example above could be handled like this: @@ -223,10 +232,13 @@ const auto handle_shapes = [](const auto& field) { } }; -std::visit(handle_shapes, my_shape.variant()); +rfl::visit(handle_shapes, my_shape); // OK + +my_shape.visit(handle_shapes); // also OK + ``` -Likewise, `rfl::TaggedUnion` contains `std::variant` under-the-hood. The original variant can be +You can also apply `rfl::visit` to `rfl::TaggedUnion`. The underlying `rfl::Variant` can be retrieved using `.variant()`: ```cpp @@ -247,7 +259,7 @@ const auto handle_shapes = [](const auto& s) { } }; -std::visit(handle_shapes, my_shape.variant()); +rfl::visit(handle_shapes, my_shape); // OK + +my_shape.visit(handle_shapes); // also OK ``` - - diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 49857152..b273dc08 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -13,6 +13,7 @@ #include "Result.hpp" #include "internal/StringLiteral.hpp" #include "internal/no_duplicate_field_names.hpp" +#include "internal/nth_tuple_element_t.hpp" namespace rfl { @@ -182,7 +183,7 @@ class Literal { #if __cpp_lib_three_way_comparison >= 201907L return name() <=> _str; #else - auto const &const_name = name(); + auto const& const_name = name(); if (const_name < _str) { return std::strong_ordering::less; } @@ -199,7 +200,7 @@ class Literal { #if __cpp_lib_three_way_comparison >= 201907L return name() <=> _str; #else - auto const &const_name = name(); + auto const& const_name = name(); if (const_name < _str) { return std::strong_ordering::less; } @@ -268,7 +269,7 @@ class Literal { template static void allowed_strings_vec_add_one(std::vector* _values) { - using FieldType = typename std::tuple_element<_i, FieldsType>::type; + using FieldType = internal::nth_tuple_element_t<_i, FieldsType>; _values->emplace_back(FieldType::name_.str()); } @@ -288,7 +289,7 @@ class Literal { template void find_name_set_if_matches(std::string* _name) const { if (_i == value_) { - using FieldType = typename std::tuple_element_t<_i, FieldsType>; + using FieldType = internal::nth_tuple_element_t<_i, FieldsType>; *_name = FieldType::name_.str(); } } @@ -297,7 +298,7 @@ class Literal { /// the string at compile time within the Literal's own fields. template constexpr static auto find_name_within_own_fields() { - return std::tuple_element_t<_i, FieldsType>::name_; + return internal::nth_tuple_element_t<_i, FieldsType>::name_; } /// Finds the correct value associated with @@ -325,7 +326,7 @@ class Literal { template static void find_value_set_if_matches(const std::string& _str, bool* _found, int* _idx) { - using FieldType = typename std::tuple_element<_i, FieldsType>::type; + using FieldType = internal::nth_tuple_element_t<_i, FieldsType>; if (!*_found && FieldType::name_.string_view() == _str) { *_idx = _i; *_found = true; @@ -338,7 +339,7 @@ class Literal { if constexpr (_i == num_fields_) { return -1; } else { - using FieldType = typename std::tuple_element<_i, FieldsType>::type; + using FieldType = internal::nth_tuple_element_t<_i, FieldsType>; if constexpr (FieldType::name_ == _name) { return _i; } else { diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 516491d0..69ad53bf 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -14,6 +14,7 @@ #include "internal/find_index.hpp" #include "internal/is_extra_fields.hpp" #include "internal/no_duplicate_field_names.hpp" +#include "internal/nth_tuple_element_t.hpp" namespace rfl { @@ -444,7 +445,7 @@ class NamedTuple { if constexpr (_i == size()) { return _idx; } else { - using FieldType = typename std::tuple_element_t<_i, Fields>; + using FieldType = internal::nth_element_t<_i, FieldTypes...>; constexpr bool is_extra_fields = internal::is_extra_fields_v; static_assert(_idx == -1 || !is_extra_fields, @@ -472,7 +473,7 @@ class NamedTuple { } else { // When we add additional fields, it is more intuitive to add // them to the end, that is why we do it like this. - using FieldType = typename std::tuple_element_t; + using FieldType = internal::nth_element_t; using T = std::remove_cvref_t; return make_fields( FieldType(std::forward(std::get(values_))), @@ -494,7 +495,7 @@ class NamedTuple { } else { // When we add additional fields, it is more intuitive to add // them to the end, that is why we do it like this. - using FieldType = typename std::tuple_element::type; + using FieldType = internal::nth_element_t; return make_fields(FieldType(std::get(values_)), std::move(_args)...); } @@ -510,7 +511,7 @@ class NamedTuple { if constexpr (retrieved_all_fields) { return NamedTuple(std::forward(_args)...); } else { - using FieldType = typename std::tuple_element::type; + using FieldType = internal::nth_element_t; if constexpr (size == _index) { return make_replaced<_index, V, T>( @@ -581,12 +582,13 @@ class NamedTuple { if constexpr (retrieved_all_fields) { return std::make_tuple(std::forward(_args)...); } else { - constexpr auto field_name = std::tuple_element::type::name_; + constexpr auto field_name = + internal::nth_element_t::name_; constexpr auto index = internal::find_index>(); - using FieldType = typename std::tuple_element::type; + using FieldType = internal::nth_element_t; using T = std::remove_cvref_t; diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 56289fca..4e36838c 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -1,6 +1,7 @@ #ifndef RFL_RESULT_HPP_ #define RFL_RESULT_HPP_ +#include #include #include #include @@ -327,7 +328,7 @@ class Result { return *(reinterpret_cast(t_or_err_.data())); } - void move_from_other(Result& _other) { + void move_from_other(Result& _other) noexcept { if (success_) { new (&get_t()) T(std::move(_other.get_t())); } else { diff --git a/include/rfl/TaggedUnion.hpp b/include/rfl/TaggedUnion.hpp index 09448837..e65e260c 100644 --- a/include/rfl/TaggedUnion.hpp +++ b/include/rfl/TaggedUnion.hpp @@ -1,8 +1,7 @@ #ifndef RFL_TAGGEDUNION_HPP_ #define RFL_TAGGEDUNION_HPP_ -#include - +#include "Variant.hpp" #include "define_literal.hpp" #include "internal/Getter.hpp" #include "internal/StringLiteral.hpp" @@ -16,7 +15,7 @@ struct TaggedUnion { static constexpr internal::StringLiteral discrimininator_ = _discriminator; /// The type of the underlying variant. - using VariantType = std::variant; + using VariantType = rfl::Variant; /// A literal containing all the tags that are possible using PossibleTags = define_literal_t...>; @@ -88,6 +87,30 @@ struct TaggedUnion { /// Returns the underlying variant. const VariantType& variant() const { return variant_; } + /// Applies function _f to all underlying alternatives. + template + auto visit(F& _f) { + return variant_.visit(_f); + } + + /// Applies function _f to all underlying alternatives. + template + auto visit(F& _f) const { + return variant_.visit(_f); + } + + /// Applies function _f to all underlying alternatives. + template + auto visit(const F& _f) { + return variant_.visit(_f); + } + + /// Applies function _f to all underlying alternatives. + template + auto visit(const F& _f) const { + return variant_.visit(_f); + } + static_assert(!PossibleTags::has_duplicates(), "Duplicate tags are not allowed inside tagged unions."); @@ -96,62 +119,6 @@ struct TaggedUnion { VariantType variant_; }; -namespace internal { - -template -struct Getter> { - public: - /// Retrieves the indicated value from the tuple. - template - static inline auto& get( - TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) { - return Getter>::template get<_index>( - _tu.variant_); - } - - /// Gets a field by name. - template - static inline auto& get( - TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) { - return Getter>::template get<_field_name>( - _tu.variant_); - } - - /// Gets a field by the field type. - template - static inline auto& get( - TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) { - return Getter>::template get( - _tu.variant_); - } - - /// Retrieves the indicated value from the tuple. - template - static inline const auto& get_const( - const TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) { - return Getter>::template get_const<_index>( - _tu.variant_); - } - - /// Gets a field by name. - template - static inline const auto& get_const( - const TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) { - return Getter>::template get_const< - _field_name>(_tu.variant_); - } - - /// Gets a field by the field type. - template - static inline const auto& get_const( - const TaggedUnion<_discriminator, NamedTupleTypes...>& _tu) { - return Getter>::template get_const( - _tu.variant_); - } -}; - -} // namespace internal - } // namespace rfl #endif // RFL_TAGGEDUNION_HPP_ diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index b9e4b118..5191b016 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -1,84 +1,515 @@ #ifndef RFL_VARIANT_HPP_ #define RFL_VARIANT_HPP_ -#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "internal/element_index.hpp" +#include "internal/nth_element_t.hpp" +#include "internal/variant/find_max_size.hpp" +#include "internal/variant/is_alternative_type.hpp" namespace rfl { template -struct Variant { - /// The type of the underlying variant. - using VariantType = std::variant; +class Variant { + static constexpr auto max_size_wrapper_ = + internal::variant::find_max_size(); - Variant(const VariantType& _variant) : variant_(_variant) {} + static constexpr unsigned long num_bytes_ = max_size_wrapper_.size_; - Variant(VariantType&& _variant) noexcept : variant_(std::move(_variant)) {} + using LargestType = typename decltype(max_size_wrapper_)::Type; - Variant(const Variant& _variant) = default; + using DataType = std::array; - Variant(Variant&& _variant) noexcept = default; + using IndexType = + std::conditional_t::max(), + std::uint8_t, std::uint16_t>; - template , - bool>::type = true> - Variant(const T& _t) : variant_(_t) {} + static constexpr IndexType size_ = sizeof...(AlternativeTypes); - template , - bool>::type = true> - Variant(T&& _t) noexcept : variant_(std::forward(_t)) {} + template + struct Index {}; - ~Variant() = default; - - /// Assigns the underlying object. - Variant& operator=(const VariantType& _variant) { - variant_ = _variant; - return *this; + public: + Variant() { + using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; + move_from_type(FirstAlternative()); } + Variant(const Variant& _other) { + copy_from_other(_other); + } + + Variant(Variant&& _other) noexcept { + move_from_other(std::move(_other)); + } + + template (), + bool>::type = true> + Variant(const T& _t) { + copy_from_type(_t); + } + + template (), + bool>::type = true> + Variant(T&& _t) noexcept { + move_from_type(std::forward(_t)); + } + + ~Variant() { destroy_if_necessary(); } + + /// Emplaces a new element into the variant. + template + constexpr T& emplace(Args&&... _args) { + auto t = T{std::forward(_args)...}; + destroy_if_necessary(); + move_from_type(std::move(t)); + return *(reinterpret_cast(data_.data())); + } + + /// Emplaces a new element into the variant. + template + constexpr auto& emplace(Args&&... _args) { + using T = internal::nth_element_t<_i, AlternativeTypes...>; + return emplace(std::move(_args)...); + } + + /// Returns the index of the element currently held. + constexpr int index() const noexcept { return index_; } + /// Assigns the underlying object. - Variant& operator=(VariantType&& _variant) { - variant_ = std::move(_variant); + template (), + bool>::type = true> + Variant& operator=(const T& _t) { + auto temp = Variant(_t); + destroy_if_necessary(); + move_from_other(std::move(temp)); return *this; } /// Assigns the underlying object. template , + typename std::enable_if(), bool>::type = true> - Variant& operator=(T&& _variant) { - variant_ = std::forward(_variant); - return *this; - } - - /// Assigns the underlying object. - template , - bool>::type = true> - Variant& operator=(const T& _variant) { - variant_ = _variant; + Variant& operator=(T&& _t) noexcept { + destroy_if_necessary(); + move_from_type(std::forward(_t)); return *this; } /// Assigns the underlying object. Variant& operator=( - const Variant& _other) = default; + const Variant& _other) { + if (this == &_other) { + return *this; + } + auto temp = Variant(_other); + destroy_if_necessary(); + move_from_other(std::move(temp)); + return *this; + } /// Assigns the underlying object. Variant& operator=( - Variant&& _other) = default; + Variant&& _other) noexcept { + if (this == &_other) { + return *this; + } + destroy_if_necessary(); + move_from_other(std::move(_other)); + return *this; + } - /// Returns the underlying variant. - VariantType& variant() { return variant_; } + /// Swaps the content with the other variant. + void swap(Variant& _other) noexcept { + if (this == &_other) { + return; + } + auto temp = Variant(std::move(*this)); + move_from_other(std::move(_other)); + _other = std::move(temp); + } - /// Returns the underlying variant. - const VariantType& variant() const { return variant_; } + template + auto visit(F& _f) { + using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; + using ResultType = std::remove_cvref_t< + std::invoke_result_t, FirstAlternative&>>; + if constexpr (std::is_same_v) { + bool visited = false; + do_visit_no_result(_f, &visited, + std::make_integer_sequence()); + } else { + auto res = std::optional(); + do_visit_with_result(_f, &res, + std::make_integer_sequence()); + return std::move(*res); + } + } - /// The underlying variant - a Variant is a thin wrapper - /// around a variant that is mainly used for parsing. - VariantType variant_; + template + auto visit(F& _f) const { + using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; + using ResultType = std::remove_cvref_t< + std::invoke_result_t, FirstAlternative&>>; + if constexpr (std::is_same_v) { + bool visited = false; + do_visit_no_result(_f, &visited, + std::make_integer_sequence()); + } else { + auto res = std::optional(); + do_visit_with_result(_f, &res, + std::make_integer_sequence()); + return std::move(*res); + } + } + + template + auto visit(const F& _f) { + using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; + using ResultType = std::remove_cvref_t< + std::invoke_result_t, FirstAlternative&>>; + if constexpr (std::is_same_v) { + bool visited = false; + do_visit_no_result(_f, &visited, + std::make_integer_sequence()); + } else { + auto res = std::optional(); + do_visit_with_result(_f, &res, + std::make_integer_sequence()); + return std::move(*res); + } + } + + template + auto visit(const F& _f) const { + using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; + using ResultType = std::remove_cvref_t< + std::invoke_result_t, FirstAlternative&>>; + if constexpr (std::is_same_v) { + bool visited = false; + do_visit_no_result(_f, &visited, + std::make_integer_sequence()); + } else { + auto res = std::optional(); + do_visit_with_result(_f, &res, + std::make_integer_sequence()); + return std::move(*res); + } + } + + private: + void copy_from_other(const Variant& _other) { + const auto copy_one = [this](const auto& _t) { this->copy_from_type(_t); }; + _other.visit(copy_one); + } + + template + void copy_from_type(const T& _t) noexcept { + using CurrentType = std::remove_cvref_t; + index_ = + internal::element_index...>(); + new (reinterpret_cast(data_.data())) CurrentType(_t); + } + + void destroy_if_necessary() { + const auto destroy_one = [](auto& _t) { + using T = std::remove_cvref_t; + if constexpr (std::is_destructible_v) { + _t.~T(); + } + }; + visit(destroy_one); + } + + template + void do_visit_no_result(F& _f, bool* _visited, + std::integer_sequence) { + auto visit_one = [this](const F& _f, bool* _visited, + Index<_i>) { + if (!*_visited && index_ == _i) { + _f(get_alternative<_i>()); + *_visited = true; + } + }; + (visit_one(_f, _visited, Index<_is>{}), ...); + } + + template + void do_visit_no_result(F& _f, bool* _visited, + std::integer_sequence) const { + auto visit_one = [this](const F& _f, bool* _visited, + Index<_i>) { + if (!*_visited && index_ == _i) { + _f(get_alternative<_i>()); + *_visited = true; + } + }; + (visit_one(_f, _visited, Index<_is>{}), ...); + } + + template + void do_visit_with_result(F& _f, std::optional* _res, + std::integer_sequence) { + auto visit_one = [this](const F& _f, + std::optional* _res, + Index<_i>) { + if (!*_res && index_ == _i) { + *_res = _f(get_alternative<_i>()); + } + }; + (visit_one(_f, _res, Index<_is>{}), ...); + } + + template + void do_visit_with_result(F& _f, std::optional* _res, + std::integer_sequence) const { + auto visit_one = [this](const F& _f, + std::optional* _res, + Index<_i>) { + if (!*_res && index_ == _i) { + *_res = _f(get_alternative<_i>()); + } + }; + (visit_one(_f, _res, Index<_is>{}), ...); + } + + template + void do_visit_no_result(const F& _f, bool* _visited, + std::integer_sequence) { + const auto visit_one = [this](const F& _f, bool* _visited, + Index<_i>) { + if (!*_visited && index_ == _i) { + _f(get_alternative<_i>()); + *_visited = true; + } + }; + (visit_one(_f, _visited, Index<_is>{}), ...); + } + + template + void do_visit_no_result(const F& _f, bool* _visited, + std::integer_sequence) const { + const auto visit_one = [this](const F& _f, bool* _visited, + Index<_i>) { + if (!*_visited && index_ == _i) { + _f(get_alternative<_i>()); + *_visited = true; + } + }; + (visit_one(_f, _visited, Index<_is>{}), ...); + } + + template + void do_visit_with_result(const F& _f, std::optional* _res, + std::integer_sequence) { + const auto visit_one = [this](const F& _f, + std::optional* _res, + Index<_i>) { + if (!*_res && index_ == _i) { + *_res = _f(get_alternative<_i>()); + } + }; + (visit_one(_f, _res, Index<_is>{}), ...); + } + + template + void do_visit_with_result(const F& _f, std::optional* _res, + std::integer_sequence) const { + const auto visit_one = [this](const F& _f, + std::optional* _res, + Index<_i>) { + if (!*_res && index_ == _i) { + *_res = _f(get_alternative<_i>()); + } + }; + (visit_one(_f, _res, Index<_is>{}), ...); + } + + template + auto& get_alternative() noexcept { + using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>; + return *(reinterpret_cast(data_.data())); + } + + template + const auto& get_alternative() const noexcept { + using CurrentType = internal::nth_element_t<_i, AlternativeTypes...>; + return *(reinterpret_cast(data_.data())); + } + + void move_from_other(Variant&& _other) noexcept { + const auto move_one = [this](auto&& _t) { + this->move_from_type(std::forward>(_t)); + }; + std::forward>(_other).visit(move_one); + } + + template + void move_from_type(T&& _t) noexcept { + using CurrentType = std::remove_cvref_t; + index_ = + internal::element_index...>(); + new (reinterpret_cast(data_.data())) + CurrentType(std::forward(_t)); + } + + private: + /// Index indicating which of the alternatives is currently contained in the + /// variant. + IndexType index_; + + /// The underlying data, can be any of the underlying types. + alignas(LargestType) DataType data_; }; +template +constexpr T* get_if(Variant& _v) noexcept { + const auto get = [](auto& _v) -> T* { + using Type = std::remove_cvref_t; + if constexpr (std::is_same>()) { + return &_v; + } else { + return nullptr; + } + }; + return _v.visit(get); +} + +template +constexpr const T* get_if(const Variant& _v) noexcept { + const auto get = [](const auto& _v) -> const T* { + using Type = std::remove_cvref_t; + if constexpr (std::is_same>()) { + return &_v; + } else { + return nullptr; + } + }; + return _v.visit(get); +} + +template +constexpr auto* get_if(Variant& _v) noexcept { + using T = internal::nth_element_t<_i, Types...>; + return get_if(_v); +} + +template +constexpr auto* get_if(const Variant& _v) noexcept { + using T = internal::nth_element_t<_i, Types...>; + return get_if(_v); +} + +template +constexpr T& get(Variant& _v) { + auto ptr = get_if(_v); + if (!ptr) { + throw std::runtime_error("Variant does not contain signified type."); + } + return *ptr; +} + +template +constexpr T&& get(Variant&& _v) { + auto ptr = get_if(_v); + if (!ptr) { + throw std::runtime_error("Variant does not contain signified type."); + } + return std::move(*ptr); +} + +template +constexpr const T& get(const Variant& _v) { + auto ptr = get_if(_v); + if (!ptr) { + throw std::runtime_error("Variant does not contain signified type."); + } + return *ptr; +} + +template +constexpr auto& get(Variant& _v) { + auto ptr = get_if<_i>(_v); + if (!ptr) { + throw std::runtime_error("Variant does not contain signified type."); + } + return *ptr; +} + +template +constexpr auto&& get(Variant&& _v) { + auto ptr = get_if<_i>(_v); + if (!ptr) { + throw std::runtime_error("Variant does not contain signified type."); + } + return std::move(*ptr); +} + +template +constexpr const auto& get(const Variant& _v) { + auto ptr = get_if<_i>(_v); + if (!ptr) { + throw std::runtime_error("Variant does not contain signified type."); + } + return *ptr; +} + +template +constexpr bool holds_alternative(const Variant& _v) noexcept { + constexpr auto ix = internal::element_index, + std::remove_cvref_t...>(); + static_assert(ix != -1, "Type not supported."); + return ix == _v.index(); +} + +template +struct variant_alternative; + +template +struct variant_alternative> { + using type = internal::nth_element_t; +}; + +template +using variant_alternative_t = + typename variant_alternative>::type; + +template +struct variant_size; + +template +struct variant_size> + : std::integral_constant {}; + +template +constexpr size_t variant_size_v = + variant_size>(); + } // namespace rfl +namespace std { +template +void swap(rfl::Variant& _lhs, rfl::Variant& _rhs) noexcept { + _lhs.swap(_rhs); +}; +} // namespace std + #endif diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 7f7367fc..30ca1aa0 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -26,8 +26,8 @@ struct EqualTo { using ValidationType = parsing::schema::ValidationType; const auto value = std::is_floating_point_v - ? std::variant(static_cast(_threshold)) - : std::variant(static_cast(_threshold)); + ? rfl::Variant(static_cast(_threshold)) + : rfl::Variant(static_cast(_threshold)); return ValidationType{ValidationType::EqualTo{.value_ = value}}; } }; @@ -50,8 +50,8 @@ struct Minimum { using ValidationType = parsing::schema::ValidationType; const auto value = std::is_floating_point_v - ? std::variant(static_cast(_threshold)) - : std::variant(static_cast(_threshold)); + ? rfl::Variant(static_cast(_threshold)) + : rfl::Variant(static_cast(_threshold)); return ValidationType{ValidationType::Minimum{.value_ = value}}; } }; @@ -74,8 +74,8 @@ struct ExclusiveMinimum { using ValidationType = parsing::schema::ValidationType; const auto value = std::is_floating_point_v - ? std::variant(static_cast(_threshold)) - : std::variant(static_cast(_threshold)); + ? rfl::Variant(static_cast(_threshold)) + : rfl::Variant(static_cast(_threshold)); return ValidationType{ValidationType::ExclusiveMinimum{.value_ = value}}; } }; @@ -98,8 +98,8 @@ struct Maximum { using ValidationType = parsing::schema::ValidationType; const auto value = std::is_floating_point_v - ? std::variant(static_cast(_threshold)) - : std::variant(static_cast(_threshold)); + ? rfl::Variant(static_cast(_threshold)) + : rfl::Variant(static_cast(_threshold)); return ValidationType{ValidationType::Maximum{.value_ = value}}; } }; @@ -122,8 +122,8 @@ struct ExclusiveMaximum { using ValidationType = parsing::schema::ValidationType; const auto value = std::is_floating_point_v - ? std::variant(static_cast(_threshold)) - : std::variant(static_cast(_threshold)); + ? rfl::Variant(static_cast(_threshold)) + : rfl::Variant(static_cast(_threshold)); return ValidationType{ValidationType::ExclusiveMaximum{.value_ = value}}; } }; @@ -146,8 +146,8 @@ struct NotEqualTo { using ValidationType = parsing::schema::ValidationType; const auto value = std::is_floating_point_v - ? std::variant(static_cast(_threshold)) - : std::variant(static_cast(_threshold)); + ? rfl::Variant(static_cast(_threshold)) + : rfl::Variant(static_cast(_threshold)); return ValidationType{ValidationType::NotEqualTo{.value_ = value}}; } }; diff --git a/include/rfl/internal/Getter.hpp b/include/rfl/internal/Getter.hpp index 03824624..d65a3f52 100644 --- a/include/rfl/internal/Getter.hpp +++ b/include/rfl/internal/Getter.hpp @@ -6,6 +6,7 @@ #include "StringLiteral.hpp" #include "find_index.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl::internal { @@ -40,8 +41,8 @@ struct Getter { constexpr auto index = find_index(); static_assert( - std::is_same::type::Type, + std::is_same::Type, typename Field::Type>(), "If two fields have the same name, " "their type must be the same as " @@ -69,8 +70,8 @@ struct Getter { constexpr auto index = find_index(); static_assert( - std::is_same::type::Type, + std::is_same::Type, typename Field::Type>(), "If two fields have the same name, " "their type must be the same as " @@ -81,76 +82,6 @@ struct Getter { // ---------------------------------------------------------------------------- -/// For handling std::variant. -template -struct Getter> { - public: - /// Retrieves the indicated value from the tuple. - template - static inline auto& get(std::variant& _tup) { - const auto apply = [](auto& _t) -> auto& { - using NamedTupleType = std::remove_cvref_t; - return Getter::template get<_index>(_t); - }; - return std::visit(apply, _tup); - } - - /// Gets a field by name. - template - static inline auto& get(std::variant& _tup) { - const auto apply = [](auto& _t) -> auto& { - using NamedTupleType = std::remove_cvref_t; - return Getter::template get<_field_name>(_t); - }; - return std::visit(apply, _tup); - } - - /// Gets a field by the field type. - template - static inline auto& get(std::variant& _tup) { - const auto apply = [](auto& _t) -> auto& { - using NamedTupleType = std::remove_cvref_t; - return Getter::template get(_t); - }; - return std::visit(apply, _tup); - } - - /// Retrieves the indicated value from the tuple. - template - static inline const auto& get_const( - const std::variant& _tup) { - const auto apply = [](const auto& _tup) -> const auto& { - using NamedTupleType = std::remove_cvref_t; - return Getter::template get_const<_index>(_tup); - }; - return std::visit(apply, _tup); - } - - /// Gets a field by name. - template - static inline const auto& get_const( - const std::variant& _tup) { - const auto apply = [](const auto& _t) -> const auto& { - using NamedTupleType = std::remove_cvref_t; - return Getter::template get_const<_field_name>(_t); - }; - return std::visit(apply, _tup); - } - - /// Gets a field by the field type. - template - static inline const auto& get_const( - const std::variant& _tup) { - const auto apply = [](const auto& _t) -> const auto& { - using NamedTupleType = std::remove_cvref_t; - return Getter::template get_const(_t); - }; - return std::visit(apply, _tup); - } -}; - -// ---------------------------------------------------------------------------- - } // namespace rfl::internal #endif diff --git a/include/rfl/internal/all_fields.hpp b/include/rfl/internal/all_fields.hpp index 58c887c4..9eef8856 100644 --- a/include/rfl/internal/all_fields.hpp +++ b/include/rfl/internal/all_fields.hpp @@ -6,18 +6,19 @@ #include #include "is_field.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { template constexpr bool all_fields() { - if constexpr (_i == std::tuple_size_v) { - return true; - } else { - using T = std::tuple_element_t<_i, TupleType>; - return is_field_v && all_fields(); - } + if constexpr (_i == std::tuple_size_v) { + return true; + } else { + using T = nth_tuple_element_t<_i, TupleType>; + return is_field_v && all_fields(); + } } } // namespace internal diff --git a/include/rfl/internal/element_index.hpp b/include/rfl/internal/element_index.hpp new file mode 100644 index 00000000..c02b5a29 --- /dev/null +++ b/include/rfl/internal/element_index.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_INTERNAL_ELEMENT_INDEX_HPP_ +#define RFL_INTERNAL_ELEMENT_INDEX_HPP_ + +#include + +namespace rfl::internal { + +template +consteval int find_element_index() { + return -1; +} + +template +consteval int find_element_index() { + if constexpr (std::is_same_v) { + return _i; + } else { + return find_element_index<_i + 1, T, Tail...>(); + } +} + +template +consteval int element_index() { + return find_element_index<0, T, AlternativeTypes...>(); +} + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/field_type.hpp b/include/rfl/internal/field_type.hpp index c195a801..0f8f9633 100644 --- a/include/rfl/internal/field_type.hpp +++ b/include/rfl/internal/field_type.hpp @@ -7,9 +7,10 @@ #include "../NamedTuple.hpp" #include "../TaggedUnion.hpp" +#include "../named_tuple_t.hpp" #include "StringLiteral.hpp" #include "find_index.hpp" -#include "../named_tuple_t.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -24,13 +25,14 @@ struct FieldType; /// Default option - for named tuples. template struct FieldType { - using NamedTupleType = named_tuple_t; + using NamedTupleType = named_tuple_t; - static constexpr int field_ix_ = - internal::find_index<_field_name, typename NamedTupleType::Fields>(); + static constexpr int field_ix_ = + internal::find_index<_field_name, typename NamedTupleType::Fields>(); - using Type = typename std::tuple_element< - field_ix_, typename NamedTupleType::Fields>::type::Type; + using Type = + typename nth_tuple_element_t::Type; }; /// For variants - in this case the FieldType returned by all options must be @@ -39,22 +41,23 @@ template struct FieldType<_field_name, std::variant> { - constexpr static bool all_types_match = std::conjunction_v::Type, - typename FieldType<_field_name, OtherAlternativeTypes>::Type>...>; + constexpr static bool all_types_match = std::conjunction_v::Type, + typename FieldType<_field_name, OtherAlternativeTypes>::Type>...>; - static_assert(all_types_match, "All field types must be the same."); + static_assert(all_types_match, "All field types must be the same."); - using Type = typename FieldType<_field_name, FirstAlternativeType>::Type; + using Type = typename FieldType<_field_name, FirstAlternativeType>::Type; }; /// For tagged union - just defers to the variant. template struct FieldType<_field_name, TaggedUnion<_discriminator_name, VarTypes...>> { - using Type = typename FieldType< - _field_name, typename TaggedUnion<_discriminator_name, - VarTypes...>::VariantType>::Type; + using Type = + typename FieldType<_field_name, + typename TaggedUnion<_discriminator_name, + VarTypes...>::VariantType>::Type; }; } // namespace internal diff --git a/include/rfl/internal/find_index.hpp b/include/rfl/internal/find_index.hpp index fa028781..b04c5a8d 100644 --- a/include/rfl/internal/find_index.hpp +++ b/include/rfl/internal/find_index.hpp @@ -1,10 +1,10 @@ #ifndef RFL_FIND_INDEX_HPP_ #define RFL_FIND_INDEX_HPP_ -#include #include #include "StringLiteral.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -12,8 +12,7 @@ namespace internal { /// Finds the index of the field signified by _field_name template constexpr static int find_index() { - using FieldType = - std::remove_cvref_t::type>; + using FieldType = std::remove_cvref_t>; constexpr bool name_i_matches = (FieldType::name_ == _field_name); diff --git a/include/rfl/internal/get_field_names.hpp b/include/rfl/internal/get_field_names.hpp index 39fdcc86..af383e59 100644 --- a/include/rfl/internal/get_field_names.hpp +++ b/include/rfl/internal/get_field_names.hpp @@ -95,19 +95,28 @@ auto get_field_name() { } } +// We don't want the operator+ to apply to normal literals, +// so we introduce this wrapper. +template +struct LiteralWrapper { + Literal<_names...> literal_; +}; + +template +auto wrap_literal(const Literal<_names...>& _literal) { + return LiteralWrapper<_names...>{_literal}; +} + template -auto concat_two_literals(const rfl::Literal<_names1...>&, - const rfl::Literal<_names2...>&) { - return rfl::Literal<_names1..., _names2...>::template from_value<0>(); +auto operator+(const LiteralWrapper<_names1...>&, + const LiteralWrapper<_names2...>&) { + return LiteralWrapper<_names1..., _names2...>{ + rfl::Literal<_names1..., _names2...>::template from_value<0>()}; } template auto concat_literals(const Head& _head, const Tail&... _tail) { - if constexpr (sizeof...(_tail) == 0) { - return _head; - } else { - return concat_two_literals(_head, concat_literals(_tail...)); - } + return (wrap_literal(_head) + ... + wrap_literal(_tail)).literal_; } inline auto concat_literals() { return rfl::Literal<>(); } diff --git a/include/rfl/internal/get_meta_fields.hpp b/include/rfl/internal/get_meta_fields.hpp index c40cdc77..f3d3a290 100644 --- a/include/rfl/internal/get_meta_fields.hpp +++ b/include/rfl/internal/get_meta_fields.hpp @@ -7,6 +7,7 @@ #include "../MetaField.hpp" #include "../type_name_t.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -17,7 +18,7 @@ auto get_meta_fields(AlreadyExtracted&&... _already_extracted) { if constexpr (NamedTupleType::size() == i) { return std::array{std::move(_already_extracted)...}; } else { - using FieldType = std::tuple_element_t; + using FieldType = nth_tuple_element_t; auto name = typename FieldType::Name().str(); auto type = type_name_t().str(); return get_meta_fields( diff --git a/include/rfl/internal/has_fields.hpp b/include/rfl/internal/has_fields.hpp index 1f4e2f5d..51923bce 100644 --- a/include/rfl/internal/has_fields.hpp +++ b/include/rfl/internal/has_fields.hpp @@ -8,6 +8,7 @@ #include "all_fields.hpp" #include "is_field.hpp" #include "is_flatten_field.hpp" +#include "nth_tuple_element_t.hpp" #include "ptr_tuple_t.hpp" namespace rfl { @@ -18,7 +19,7 @@ constexpr bool all_fields_or_flatten() { if constexpr (_i == std::tuple_size_v) { return true; } else { - using T = std::remove_cvref_t>; + using T = std::remove_cvref_t>; if constexpr (is_flatten_field_v) { return all_fields_or_flatten< ptr_tuple_t::Type>>() && @@ -34,7 +35,7 @@ constexpr bool some_fields_or_flatten() { if constexpr (_i == std::tuple_size_v) { return false; } else { - using T = std::remove_cvref_t>; + using T = std::remove_cvref_t>; if constexpr (is_flatten_field_v) { return some_fields_or_flatten< ptr_tuple_t::Type>>() || diff --git a/include/rfl/internal/has_flatten_fields.hpp b/include/rfl/internal/has_flatten_fields.hpp index 19241d95..976e26cf 100644 --- a/include/rfl/internal/has_flatten_fields.hpp +++ b/include/rfl/internal/has_flatten_fields.hpp @@ -6,6 +6,7 @@ #include #include "is_flatten_field.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -15,7 +16,7 @@ constexpr bool has_flatten_fields() { if constexpr (_i == std::tuple_size_v) { return false; } else { - using T = std::remove_cvref_t>; + using T = std::remove_cvref_t>; return is_flatten_field_v || has_flatten_fields(); } } diff --git a/include/rfl/internal/move_and_flatten_field_tuple.hpp b/include/rfl/internal/move_and_flatten_field_tuple.hpp index 1df49854..fd7338c6 100644 --- a/include/rfl/internal/move_and_flatten_field_tuple.hpp +++ b/include/rfl/internal/move_and_flatten_field_tuple.hpp @@ -5,6 +5,7 @@ #include "is_flatten_field.hpp" #include "move_to_field_tuple.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -15,7 +16,7 @@ auto move_and_flatten_field_tuple(FieldTuple&& _t, Args&&... _args) { if constexpr (i == std::tuple_size_v>) { return std::tuple_cat(std::move(_args)...); } else { - using T = std::tuple_element_t>; + using T = nth_tuple_element_t>; if constexpr (is_flatten_field::value) { return move_and_flatten_field_tuple( std::move(_t), std::move(_args)..., diff --git a/include/rfl/internal/move_from_named_tuple.hpp b/include/rfl/internal/move_from_named_tuple.hpp index b01930c1..3b14824c 100644 --- a/include/rfl/internal/move_from_named_tuple.hpp +++ b/include/rfl/internal/move_from_named_tuple.hpp @@ -4,11 +4,12 @@ #include #include +#include "../named_tuple_t.hpp" #include "is_field.hpp" #include "is_named_tuple.hpp" #include "nt_to_ptr_named_tuple.hpp" +#include "nth_tuple_element_t.hpp" #include "ptr_field_tuple_t.hpp" -#include "../named_tuple_t.hpp" namespace rfl { namespace internal { @@ -24,7 +25,7 @@ auto make_ptr_fields(PtrNamedTupleType& _n, Args... _args) { return std::make_tuple(_args...); } else { using Field = - std::remove_cvref_t>; + std::remove_cvref_t>; using T = std::remove_cvref_t>; if constexpr (is_named_tuple_v) { @@ -54,7 +55,7 @@ auto move_from_ptr_fields(Pointers& _ptrs, Args&&... _args) { if constexpr (i == std::tuple_size_v>) { return T{std::move(_args)...}; } else { - using FieldType = std::tuple_element_t>; + using FieldType = nth_tuple_element_t>; if constexpr (is_field_v) { return move_from_ptr_fields( @@ -66,7 +67,7 @@ auto move_from_ptr_fields(Pointers& _ptrs, Args&&... _args) { using PtrFieldTupleType = std::remove_cvref_t>; using U = std::remove_cvref_t::Type>>; + typename nth_tuple_element_t::Type>>; return move_from_ptr_fields( _ptrs, std::move(_args)..., diff --git a/include/rfl/internal/move_from_tuple.hpp b/include/rfl/internal/move_from_tuple.hpp index 02b4d217..5d288cd6 100644 --- a/include/rfl/internal/move_from_tuple.hpp +++ b/include/rfl/internal/move_from_tuple.hpp @@ -19,7 +19,7 @@ constexpr int calc_flattened_size() { if constexpr (_i == std::tuple_size_v) { return 0; } else { - using T = std::remove_pointer_t>; + using T = std::remove_pointer_t>; if constexpr (is_flatten_field_v) { return calc_flattened_size>() + calc_flattened_size(); @@ -39,7 +39,7 @@ auto unflatten_ptr_tuple(PtrTupleType& _t, Args... _args) { return std::make_tuple(_args...); } else { using T = std::remove_cvref_t< - std::remove_pointer_t>>; + std::remove_pointer_t>>; if constexpr (is_flatten_field_v) { using SubTargetTupleType = @@ -65,7 +65,7 @@ auto move_from_pointers(Pointers& _ptrs, Args&&... _args) { if constexpr (i == std::tuple_size_v>) { return std::remove_cvref_t{std::move(_args)...}; } else { - using FieldType = std::tuple_element_t>; + using FieldType = nth_tuple_element_t>; if constexpr (std::is_pointer_v) { return move_from_pointers(_ptrs, std::move(_args)..., @@ -75,7 +75,7 @@ auto move_from_pointers(Pointers& _ptrs, Args&&... _args) { using PtrTupleType = ptr_tuple_t>; using U = std::remove_cvref_t>::Type>; + nth_tuple_element_t>::Type>; return move_from_pointers(_ptrs, std::move(_args)..., move_from_pointers(std::get(_ptrs))); diff --git a/include/rfl/internal/no_duplicate_field_names.hpp b/include/rfl/internal/no_duplicate_field_names.hpp index 734dacc9..a24c8cb3 100644 --- a/include/rfl/internal/no_duplicate_field_names.hpp +++ b/include/rfl/internal/no_duplicate_field_names.hpp @@ -3,6 +3,8 @@ #include +#include "nth_tuple_element_t.hpp" + namespace rfl { namespace internal { @@ -11,10 +13,8 @@ namespace no_duplicate_field_names_helpers { template constexpr inline void compare_two_fields() { if constexpr (_j < _i) { - using FieldType1 = - std::remove_cvref_t::type>; - using FieldType2 = - std::remove_cvref_t::type>; + using FieldType1 = std::remove_cvref_t>; + using FieldType2 = std::remove_cvref_t>; constexpr auto field_name_i = FieldType1::name_; constexpr auto field_name_j = FieldType2::name_; diff --git a/include/rfl/internal/nt_to_ptr_named_tuple.hpp b/include/rfl/internal/nt_to_ptr_named_tuple.hpp index 4eac64c2..51dff6ae 100644 --- a/include/rfl/internal/nt_to_ptr_named_tuple.hpp +++ b/include/rfl/internal/nt_to_ptr_named_tuple.hpp @@ -5,6 +5,7 @@ #include "../Field.hpp" #include "../make_named_tuple.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -21,7 +22,7 @@ auto nt_to_ptr_named_tuple(NamedTupleType& _nt, AlreadyExtracted... _a) { if constexpr (i == num_fields) { return make_named_tuple(_a...); } else { - using FieldType = typename std::tuple_element::type; + using FieldType = nth_tuple_element_t; using T = std::remove_cvref_t; return nt_to_ptr_named_tuple( _nt, _a..., Field(&std::get(_nt.values()))); @@ -40,7 +41,7 @@ auto nt_to_ptr_named_tuple(const NamedTupleType& _nt, AlreadyExtracted... _a) { if constexpr (i == num_fields) { return make_named_tuple(_a...); } else { - using FieldType = typename std::tuple_element::type; + using FieldType = nth_tuple_element_t; using T = std::remove_cvref_t; return nt_to_ptr_named_tuple( _nt, _a..., diff --git a/include/rfl/internal/nth_element_t.hpp b/include/rfl/internal/nth_element_t.hpp new file mode 100644 index 00000000..dafcd120 --- /dev/null +++ b/include/rfl/internal/nth_element_t.hpp @@ -0,0 +1,73 @@ +#ifndef RFL_INTERNAL_NTH_ELEMENT_T_HPP_ +#define RFL_INTERNAL_NTH_ELEMENT_T_HPP_ + +#include + +namespace rfl::internal { + +#if defined(__clang__) + +template +using nth_element_t = __type_pack_element; + +#else + +template +struct NthElement; + +template +struct NthElement { + using Type = typename NthElement::Type; +}; + +template +struct NthElement<0, T0, Ts...> { + using Type = T0; +}; + +template +struct NthElement<1, T0, T1, Ts...> { + using Type = T1; +}; + +template +struct NthElement<2, T0, T1, T2, Ts...> { + using Type = T2; +}; + +template +struct NthElement<3, T0, T1, T2, T3, Ts...> { + using Type = T3; +}; + +template +struct NthElement<4, T0, T1, T2, T3, T4, Ts...> { + using Type = T4; +}; + +template +struct NthElement<5, T0, T1, T2, T3, T4, T5, Ts...> { + using Type = T5; +}; + +template +struct NthElement<6, T0, T1, T2, T3, T4, T5, T6, Ts...> { + using Type = T6; +}; + +template +struct NthElement<7, T0, T1, T2, T3, T4, T5, T6, T7, Ts...> { + using Type = T7; +}; + +template +using nth_element_t = typename NthElement::Type; + +#endif + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/nth_tuple_element_t.hpp b/include/rfl/internal/nth_tuple_element_t.hpp new file mode 100644 index 00000000..913c8455 --- /dev/null +++ b/include/rfl/internal/nth_tuple_element_t.hpp @@ -0,0 +1,23 @@ +#ifndef RFL_INTERNAL_NTH_TUPLE_ELEMENT_T_HPP_ +#define RFL_INTERNAL_NTH_TUPLE_ELEMENT_T_HPP_ + +#include + +#include "nth_element_t.hpp" + +namespace rfl::internal { + +template +struct nth_tuple_element; + +template +struct nth_tuple_element> { + using Type = nth_element_t; +}; + +template +using nth_tuple_element_t = typename nth_tuple_element::Type; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/remove_fields.hpp b/include/rfl/internal/remove_fields.hpp index 49b28a0d..efa6d011 100644 --- a/include/rfl/internal/remove_fields.hpp +++ b/include/rfl/internal/remove_fields.hpp @@ -8,6 +8,7 @@ #include "../NamedTuple.hpp" #include "../define_named_tuple.hpp" #include "StringLiteral.hpp" +#include "nth_tuple_element_t.hpp" namespace rfl { namespace internal { @@ -34,8 +35,8 @@ struct remove_single_field { constexpr static int num_fields = std::tuple_size_v; - using FieldType = std::remove_cvref_t::type>; + using FieldType = std::remove_cvref_t< + nth_tuple_element_t>; using NewNamedTupleType = std::conditional_t<_name == FieldType::name_, _NewNamedTupleType, diff --git a/include/rfl/internal/to_flattened_ptr_tuple.hpp b/include/rfl/internal/to_flattened_ptr_tuple.hpp index eaf9de03..a003448b 100644 --- a/include/rfl/internal/to_flattened_ptr_tuple.hpp +++ b/include/rfl/internal/to_flattened_ptr_tuple.hpp @@ -5,6 +5,7 @@ #include "has_flatten_fields.hpp" #include "is_flatten_field.hpp" +#include "nth_tuple_element_t.hpp" #include "to_ptr_tuple.hpp" namespace rfl { @@ -18,7 +19,7 @@ auto flatten_ptr_tuple(PtrTuple&& _t, Args... _args) { } else if constexpr (i == std::tuple_size_v>) { return std::tuple_cat(std::forward(_args)...); } else { - using T = std::tuple_element_t>; + using T = nth_tuple_element_t>; if constexpr (is_flatten_field_v) { return flatten_ptr_tuple( std::forward(_t), std::forward(_args)..., diff --git a/include/rfl/internal/to_ptr_named_tuple.hpp b/include/rfl/internal/to_ptr_named_tuple.hpp index c6fab6eb..1286f8d1 100644 --- a/include/rfl/internal/to_ptr_named_tuple.hpp +++ b/include/rfl/internal/to_ptr_named_tuple.hpp @@ -13,6 +13,7 @@ #include "is_empty.hpp" #include "is_field.hpp" #include "is_named_tuple.hpp" +#include "nth_tuple_element_t.hpp" #include "to_flattened_ptr_tuple.hpp" #include "to_ptr_field_tuple.hpp" @@ -25,7 +26,7 @@ auto flatten_ptr_field_tuple(PtrFieldTuple& _t, Args&&... _args) { if constexpr (i == std::tuple_size_v>) { return std::tuple_cat(std::forward(_args)...); } else { - using T = std::tuple_element_t>; + using T = nth_tuple_element_t>; if constexpr (internal::is_flatten_field::value) { auto subtuple = internal::to_ptr_field_tuple(*std::get(_t).get()); return flatten_ptr_field_tuple(_t, std::forward(_args)..., diff --git a/include/rfl/internal/variant/find_max_size.hpp b/include/rfl/internal/variant/find_max_size.hpp new file mode 100644 index 00000000..c43ed669 --- /dev/null +++ b/include/rfl/internal/variant/find_max_size.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_INTERNAL_VARIANT_FIND_MAX_SIZE_HPP_ +#define RFL_INTERNAL_VARIANT_FIND_MAX_SIZE_HPP_ + +namespace rfl::internal::variant { + +template +struct SizeWrapper { + using Type = T; + static constexpr unsigned long size_ = sizeof(T); +}; + +template +consteval auto operator|(const SizeWrapper& _s1, + const SizeWrapper& _s2) { + if constexpr (sizeof(T2) > sizeof(T1)) { + return _s2; + } else { + return _s1; + } +} + +template +consteval auto find_max_size() { + return (SizeWrapper{} | ... | SizeWrapper{}); +} + +} // namespace rfl::internal::variant + +#endif diff --git a/include/rfl/internal/variant/is_alternative_type.hpp b/include/rfl/internal/variant/is_alternative_type.hpp new file mode 100644 index 00000000..af8e9525 --- /dev/null +++ b/include/rfl/internal/variant/is_alternative_type.hpp @@ -0,0 +1,19 @@ +#ifndef RFL_INTERNAL_VARIANT_IS_ALTERNATIVE_TYPE_HPP_ +#define RFL_INTERNAL_VARIANT_IS_ALTERNATIVE_TYPE_HPP_ + +#include + +#include "../element_index.hpp" + +namespace rfl::internal::variant { + +template +static constexpr bool is_alternative_type() { + return internal::element_index, + std::remove_cvref_t...>() != + -1; +} + +} // namespace rfl::internal::variant + +#endif diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp index 5563d771..849ce452 100644 --- a/include/rfl/json/schema/Type.hpp +++ b/include/rfl/json/schema/Type.hpp @@ -5,10 +5,10 @@ #include #include #include -#include #include "../../Literal.hpp" #include "../../Rename.hpp" +#include "../../Variant.hpp" namespace rfl::json::schema { @@ -36,7 +36,7 @@ struct Type { rfl::Rename<"maxLength", std::optional> maxSize; }; - using NumericType = std::variant; + using NumericType = rfl::Variant; struct AllOf { std::optional description; @@ -50,13 +50,13 @@ struct Type { struct ExclusiveMaximum { std::optional description; - std::variant exclusiveMaximum; + rfl::Variant exclusiveMaximum; std::string type; }; struct ExclusiveMinimum { std::optional description; - std::variant exclusiveMinimum; + rfl::Variant exclusiveMinimum; std::string type; }; @@ -70,13 +70,13 @@ struct Type { struct Maximum { std::optional description; - std::variant maximum; + rfl::Variant maximum; std::string type; }; struct Minimum { std::optional description; - std::variant minimum; + rfl::Variant minimum; std::string type; }; @@ -137,7 +137,7 @@ struct Type { }; using ReflectionType = - std::variant; diff --git a/include/rfl/json/to_schema.hpp b/include/rfl/json/to_schema.hpp index e33f56c2..8203f065 100644 --- a/include/rfl/json/to_schema.hpp +++ b/include/rfl/json/to_schema.hpp @@ -10,10 +10,10 @@ #include #include #include -#include #include "../Literal.hpp" #include "../Processors.hpp" +#include "../Variant.hpp" #include "../parsing/schema/Type.hpp" #include "../parsing/schema/ValidationType.hpp" #include "../parsing/schema/make.hpp" @@ -31,8 +31,8 @@ template struct TypeHelper {}; template -struct TypeHelper> { - using JSONSchemaType = std::variant...>; +struct TypeHelper> { + using JSONSchemaType = rfl::Variant...>; }; /// Returns the JSON schema for a class. @@ -52,7 +52,7 @@ std::string to_schema(const yyjson_write_flag _flag = 0) { .definitions = definitions}; }; auto root = type_to_json_schema_type(internal_schema.root_); - const auto json_schema = std::visit(to_schema, std::move(root.value)); + const auto json_schema = rfl::visit(to_schema, std::move(root.value)); return write(json_schema, _flag); } } // namespace rfl::json diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index e52d4c17..24272224 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -5,10 +5,11 @@ #include #include #include -#include #include "../Result.hpp" +#include "../Variant.hpp" #include "../always_false.hpp" +#include "../visit.hpp" #include "FieldVariantReader.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -19,9 +20,9 @@ namespace parsing { /// To be used when all options of the variants are rfl::Field. Essentially, /// this is an externally tagged union. template - requires AreReaderAndWriter> +requires AreReaderAndWriter> struct FieldVariantParser { - using FieldVariantType = std::variant; + using FieldVariantType = rfl::Variant; using ResultType = Result; public: @@ -58,7 +59,7 @@ struct FieldVariantParser { } template - static void write(const W& _w, const std::variant& _v, + static void write(const W& _w, const rfl::Variant& _v, const P& _parent) noexcept { static_assert( internal::no_duplicate_field_names>(), @@ -72,13 +73,13 @@ struct FieldVariantParser { _parent); }; - std::visit(handle, _v); + rfl::visit(handle, _v); } static schema::Type to_schema( std::map* _definitions, - [[maybe_unused]] std::vector _types = {}) { - using VariantType = std::variant...>; + std::vector _types = {}) { + using VariantType = rfl::Variant...>; return Parser::to_schema(_definitions); } }; diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index 275b6a60..58ed8459 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -5,11 +5,13 @@ #include #include #include -#include +#include #include #include "../Result.hpp" +#include "../Variant.hpp" #include "../internal/is_array.hpp" +#include "../internal/nth_element_t.hpp" namespace rfl::parsing { @@ -17,7 +19,7 @@ template class FieldVariantReader { private: using InputVarType = typename R::InputVarType; - using FieldVariantType = std::variant; + using FieldVariantType = rfl::Variant; using ResultType = Result; public: @@ -27,50 +29,48 @@ class FieldVariantReader { ~FieldVariantReader() = default; - template void read(const std::string_view& _disc_value, const InputVarType& _var) const noexcept { - if constexpr (_i < sizeof...(FieldTypes)) { - if constexpr (_i == 0) { - if (*field_variant_) { - *field_variant_ = Error( - "Could not parse: Expected the object to have " - "exactly one field, but found more than one."); - return; - } - } - - using FieldType = std::remove_cvref_t< - typename std::tuple_element<_i, std::tuple>::type>; - - using ValueType = std::remove_cvref_t; - - constexpr auto key = FieldType::name_.string_view(); - - if (key == _disc_value) { - const auto to_variant = [](ValueType&& _val) { - return std::variant(FieldType(std::move(_val))); - }; - const auto embellish_error = [&](const Error& _e) { - return Error("Could not parse std::variant with field '" + - std::string(_disc_value) + "': " + _e.what()); - }; - *field_variant_ = - Parser::read(*r_, _var) - .transform(to_variant) - .or_else(embellish_error); - return; - } else { - read<_i + 1>(_disc_value, _var); - } - } else { + try_matching_fields( + _disc_value, _var, + std::make_integer_sequence()); + if (!*field_variant_) { *field_variant_ = Error( - "Could not parse std::variant, could not match field named " + "Could not parse rfl::Variant, could not match field named " "'" + std::string(_disc_value) + "'."); } } + private: + template + void try_matching_fields(const std::string_view& _disc_value, + const InputVarType& _var, + std::integer_sequence) const noexcept { + (try_one<_is>(_disc_value, _var), ...); + } + + template + void try_one(const std::string_view& _disc_value, + const InputVarType& _var) const noexcept { + using FieldType = + std::remove_cvref_t>; + using ValueType = std::remove_cvref_t; + constexpr auto key = FieldType::name_.string_view(); + if (key == _disc_value) { + const auto to_variant = [](ValueType&& _val) { + return rfl::Variant(FieldType(std::move(_val))); + }; + const auto embellish_error = [&](const Error& _e) { + return Error("Could not parse rfl::Variant with field '" + + std::string(_disc_value) + "': " + _e.what()); + }; + *field_variant_ = Parser::read(*r_, _var) + .transform(to_variant) + .or_else(embellish_error); + } + } + private: /// The underlying reader. const R* r_; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index a2dc35af..3d84fd36 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -16,6 +16,7 @@ #include "../internal/is_basic_type.hpp" #include "../internal/is_extra_fields.hpp" #include "../internal/is_skip.hpp" +#include "../internal/nth_element_t.hpp" #include "../internal/strings/replace_all.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" @@ -129,8 +130,7 @@ struct NamedTupleParser { static void add_field_to_object(const W& _w, const NamedTuple& _tup, OutputObjectOrArrayType* _ptr) noexcept { - using FieldType = - typename std::tuple_element<_i, std::tuple>::type; + using FieldType = internal::nth_element_t<_i, FieldTypes...>; using ValueType = std::remove_cvref_t; const auto value = rfl::get<_i>(_tup); if constexpr (internal::is_extra_fields_v) { @@ -167,8 +167,7 @@ struct NamedTupleParser { static void add_field_to_schema( std::map* _definitions, SchemaType* _schema) noexcept { - using F = - std::tuple_element_t<_i, typename NamedTuple::Fields>; + using F = internal::nth_element_t<_i, FieldTypes...>; using U = std::remove_cvref_t; if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { auto s = Parser::to_schema(_definitions); @@ -194,9 +193,8 @@ struct NamedTupleParser { (add_field_to_schema<_is>(_definitions, _schema), ...); if constexpr (NamedTupleType::pos_extra_fields() != -1) { - using F = - std::tuple_element_t::Fields>; + using F = internal::nth_element_t; using ExtraFieldsType = std::remove_cvref_t; using U = std::remove_cvref_t; _schema->additional_properties_ = std::make_shared( @@ -210,7 +208,7 @@ struct NamedTupleParser { const NamedTupleType& _view, std::array* _set, std::vector* _errors) noexcept { - using FieldType = std::tuple_element_t<_i, typename NamedTupleType::Fields>; + using FieldType = internal::nth_element_t<_i, FieldTypes...>; using ValueType = std::remove_reference_t< std::remove_pointer_t>; @@ -220,7 +218,7 @@ struct NamedTupleParser { (_all_required || is_required()); if constexpr (is_required_field) { constexpr auto current_name = - std::tuple_element_t<_i, typename NamedTupleType::Fields>::name(); + internal::nth_element_t<_i, FieldTypes...>::name(); _errors->emplace_back(Error( "Field named '" + std::string(current_name) + "' not found.")); } else { diff --git a/include/rfl/parsing/Parser_rfl_variant.hpp b/include/rfl/parsing/Parser_rfl_variant.hpp index 2fb1a15e..d05553a8 100644 --- a/include/rfl/parsing/Parser_rfl_variant.hpp +++ b/include/rfl/parsing/Parser_rfl_variant.hpp @@ -8,46 +8,118 @@ #include "../Result.hpp" #include "../Variant.hpp" #include "../always_false.hpp" +#include "../internal/nth_element_t.hpp" #include "FieldVariantParser.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" -namespace rfl { -namespace parsing { +namespace rfl::parsing { -template -requires AreReaderAndWriter> -struct Parser, ProcessorsType> { +template +requires AreReaderAndWriter> +class Parser, ProcessorsType> { + public: using InputVarType = typename R::InputVarType; using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read( + static Result> read( const R& _r, const InputVarType& _var) noexcept { - const auto to_rfl_variant = [](auto&& _var) { - return rfl::Variant( - std::forward>(_var)); - }; - return Parser, ProcessorsType>::read(_r, - _var) - .transform(to_rfl_variant); + if constexpr (internal::all_fields>()) { + return FieldVariantParser::read(_r, _var); + } else { + std::optional> result; + std::vector errors; + read_variant( + _r, _var, &result, &errors, + std::make_integer_sequence()); + if (result) { + return std::move(*result); + } else { + return Error( + to_single_error_message(errors, + "Could not parse the variant. Each of the " + "possible alternatives failed " + "for the following reasons: ", + 100000)); + } + } } template - static void write(const W& _w, const rfl::Variant& _variant, + static void write(const W& _w, + const rfl::Variant& _variant, const P& _parent) noexcept { - Parser, ProcessorsType>::write( - _w, _variant.variant(), _parent); + if constexpr (internal::all_fields>()) { + FieldVariantParser::write( + _w, _variant, _parent); + } else { + const auto handle = [&](const auto& _v) { + using Type = std::remove_cvref_t; + Parser::write(_w, _v, _parent); + }; + return rfl::visit(handle, _variant); + } } static schema::Type to_schema( std::map* _definitions) { - return Parser, ProcessorsType>::to_schema( - _definitions); + if constexpr (internal::all_fields>()) { + return FieldVariantParser::to_schema(_definitions); + } else { + std::vector types; + build_schema( + _definitions, &types, + std::make_integer_sequence()); + return schema::Type{schema::Type::AnyOf{.types_ = std::move(types)}}; + } + } + + private: + template + static void add_to_schema(std::map* _definitions, + std::vector* _types) noexcept { + using AltType = + std::remove_cvref_t>; + _types->push_back( + Parser::to_schema(_definitions)); + } + + template + static void build_schema(std::map* _definitions, + std::vector* _types, + std::integer_sequence) noexcept { + (add_to_schema<_is>(_definitions, _types), ...); + } + + template + static void read_one_alternative( + const R& _r, const InputVarType& _var, + std::optional>* _result, + std::vector* _errors) noexcept { + if (!*_result) { + using AltType = + std::remove_cvref_t>; + auto res = Parser::read(_r, _var); + if (res) { + *_result = std::move(*res); + } else { + _errors->emplace_back(*res.error()); + } + } + } + + template + static void read_variant( + const R& _r, const InputVarType& _var, + std::optional>* _result, + std::vector* _errors, + std::integer_sequence) noexcept { + (read_one_alternative<_is>(_r, _var, _result, _errors), ...); } }; -} // namespace parsing -} // namespace rfl +} // namespace rfl::parsing #endif diff --git a/include/rfl/parsing/Parser_tagged_union.hpp b/include/rfl/parsing/Parser_tagged_union.hpp index 48ae92f1..e56b89fd 100644 --- a/include/rfl/parsing/Parser_tagged_union.hpp +++ b/include/rfl/parsing/Parser_tagged_union.hpp @@ -67,7 +67,7 @@ struct Parser, const auto handle = [&](const auto& _val) { write_wrapped(_w, _val, _parent); }; - std::visit(handle, _tagged_union.variant_); + rfl::visit(handle, _tagged_union.variant_); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_variant.hpp b/include/rfl/parsing/Parser_variant.hpp index e6749f70..284b74bd 100644 --- a/include/rfl/parsing/Parser_variant.hpp +++ b/include/rfl/parsing/Parser_variant.hpp @@ -8,7 +8,9 @@ #include "../Ref.hpp" #include "../Result.hpp" +#include "../Variant.hpp" #include "../always_false.hpp" +#include "../internal/to_ptr_field.hpp" #include "FieldVariantParser.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" @@ -17,22 +19,35 @@ namespace rfl { namespace parsing { -template -requires AreReaderAndWriter> -class Parser, ProcessorsType> { +template +requires AreReaderAndWriter> +class Parser, ProcessorsType> { + template + using ptr_field_t = + decltype(internal::to_ptr_field(std::declval())); + public: using InputVarType = typename R::InputVarType; using OutputVarType = typename W::OutputVarType; - static Result> read( + static Result> read( const R& _r, const InputVarType& _var) noexcept { - if constexpr (internal::all_fields>()) { - return FieldVariantParser::read( - _r, _var); + if constexpr (internal::all_fields>()) { + const auto wrap = [](auto&& _v) { + return std::variant(std::move(_v)); + }; + const auto to_std_variant = [&](auto&& _v) { + return rfl::visit(wrap, std::move(_v)); + }; + return FieldVariantParser::read(_r, _var) + .transform(to_std_variant); } else { - std::optional> result; + std::optional> result; std::vector errors; - read_variant(_r, _var, &result, &errors); + read_variant( + _r, _var, &result, &errors, + std::make_integer_sequence()); if (result) { return std::move(*result); } else { @@ -47,11 +62,21 @@ class Parser, ProcessorsType> { } template - static void write(const W& _w, const std::variant& _variant, + static void write(const W& _w, + const std::variant& _variant, const P& _parent) noexcept { - if constexpr (internal::all_fields>()) { - FieldVariantParser::write( - _w, _variant, _parent); + if constexpr (internal::all_fields>()) { + const auto wrap = [](const auto& _v) { + return rfl::Variant...>( + internal::to_ptr_field(_v)); + }; + const auto to_rfl_variant = [&](const auto& _v) { + return std::visit(wrap, _v); + }; + FieldVariantParser< + R, W, ProcessorsType, + ptr_field_t...>::write(_w, to_rfl_variant(_variant), + _parent); } else { const auto handle = [&](const auto& _v) { using Type = std::remove_cvref_t; @@ -63,13 +88,14 @@ class Parser, ProcessorsType> { static schema::Type to_schema( std::map* _definitions) { - if constexpr (internal::all_fields>()) { - return FieldVariantParser::to_schema( - _definitions); + if constexpr (internal::all_fields>()) { + return FieldVariantParser::to_schema(_definitions); } else { std::vector types; - build_schema(_definitions, &types, - std::make_integer_sequence()); + build_schema( + _definitions, &types, + std::make_integer_sequence()); return schema::Type{schema::Type::AnyOf{.types_ = std::move(types)}}; } } @@ -79,7 +105,7 @@ class Parser, ProcessorsType> { static void add_to_schema(std::map* _definitions, std::vector* _types) noexcept { using U = std::remove_cvref_t< - std::variant_alternative_t<_i, std::variant>>; + std::variant_alternative_t<_i, std::variant>>; _types->push_back(Parser::to_schema(_definitions)); } @@ -90,24 +116,31 @@ class Parser, ProcessorsType> { (add_to_schema<_is>(_definitions, _types), ...); } - template - static void read_variant(const R& _r, const InputVarType& _var, - std::optional>* _result, - std::vector* _errors) noexcept { - constexpr size_t size = sizeof...(FieldTypes); - if constexpr (_i < size) { - using AltType = std::remove_cvref_t< - std::variant_alternative_t<_i, std::variant>>; + template + static void read_one_alternative( + const R& _r, const InputVarType& _var, + std::optional>* _result, + std::vector* _errors) noexcept { + if (!*_result) { + using AltType = + std::remove_cvref_t>; auto res = Parser::read(_r, _var); if (res) { *_result = std::move(*res); - return; } else { _errors->emplace_back(*res.error()); - return read_variant<_i + 1>(_r, _var, _result, _errors); } } } + + template + static void read_variant( + const R& _r, const InputVarType& _var, + std::optional>* _result, + std::vector* _errors, + std::integer_sequence) noexcept { + (read_one_alternative<_is>(_r, _var, _result, _errors), ...); + } }; } // namespace parsing diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index 3b4004e2..6c3c5c35 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -7,6 +7,7 @@ #include "../Result.hpp" #include "../always_false.hpp" +#include "../internal/nth_element_t.hpp" #include "Parent.hpp" #include "TupleReader.hpp" #include "schema/Type.hpp" @@ -87,8 +88,8 @@ struct TupleParser { static void to_array(const W& _w, const std::tuple& _tup, const P& _parent) noexcept { if constexpr (_i < sizeof...(Ts)) { - using NewFieldType = std::remove_cvref_t< - typename std::tuple_element_t<_i, std::tuple>>; + using NewFieldType = + std::remove_cvref_t>; Parser::write(_w, std::get<_i>(_tup), _parent); to_array<_i + 1>(_w, _tup, _parent); diff --git a/include/rfl/parsing/TupleReader.hpp b/include/rfl/parsing/TupleReader.hpp index 3726afc5..a94fe446 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -8,6 +8,7 @@ #include "../Result.hpp" #include "../internal/is_array.hpp" +#include "../internal/nth_tuple_element_t.hpp" namespace rfl::parsing { @@ -46,7 +47,7 @@ class TupleReader { return; } using CurrentType = - std::remove_cvref_t>; + std::remove_cvref_t>; if constexpr (!std::is_array_v && std::is_pointer_v && std::is_destructible_v) { @@ -65,7 +66,7 @@ class TupleReader { if constexpr (_i < size_) { if (i_ == _i) { using CurrentType = - std::remove_cvref_t>; + std::remove_cvref_t>; if constexpr (_all_required || is_required()) { @@ -86,7 +87,7 @@ class TupleReader { if constexpr (_i < size_) { if (i_ == _i) { using CurrentType = - std::remove_cvref_t>; + std::remove_cvref_t>; auto res = Parser::read(*r_, _var); diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index bb77840c..46991bcb 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -9,6 +9,7 @@ #include "../Result.hpp" #include "../internal/is_array.hpp" +#include "../internal/nth_tuple_element_t.hpp" namespace rfl::parsing { @@ -48,7 +49,8 @@ class ViewReader { const auto& _var, auto* _view, auto* _errors, auto* _found, auto* _set, bool* _already_assigned) { - using FieldType = std::tuple_element_t; + using FieldType = + internal::nth_tuple_element_t; using OriginalType = typename FieldType::Type; using T = std::remove_cvref_t>; @@ -132,7 +134,8 @@ class ViewReader { template void call_destructor_on_one_if_necessary() const { - using FieldType = std::tuple_element_t<_i, typename ViewType::Fields>; + using FieldType = + internal::nth_tuple_element_t<_i, typename ViewType::Fields>; using OriginalType = std::remove_cvref_t; using ValueType = std::remove_cvref_t>; diff --git a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp index 89ec151a..f19d08c9 100644 --- a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp @@ -9,6 +9,7 @@ #include "../Result.hpp" #include "../internal/is_array.hpp" +#include "../internal/nth_tuple_element_t.hpp" namespace rfl::parsing { @@ -59,7 +60,8 @@ class ViewReaderWithStrippedFieldNames { static void assign_if_field_is_field_i(const R& _r, const auto& _var, auto* _view, auto* _errors, auto* _found, auto* _set, int _i) { - using FieldType = std::tuple_element_t; + using FieldType = + internal::nth_tuple_element_t; using OriginalType = typename FieldType::Type; using T = std::remove_cvref_t>; @@ -105,7 +107,8 @@ class ViewReaderWithStrippedFieldNames { // TODO: Unnecessary code duplication. template void call_destructor_on_one_if_necessary() const { - using FieldType = std::tuple_element_t<_i, typename ViewType::Fields>; + using FieldType = + internal::nth_tuple_element_t<_i, typename ViewType::Fields>; using OriginalType = std::remove_cvref_t; using ValueType = std::remove_cvref_t>; diff --git a/include/rfl/parsing/schema/Type.hpp b/include/rfl/parsing/schema/Type.hpp index f8dfea0a..5b2d27d3 100644 --- a/include/rfl/parsing/schema/Type.hpp +++ b/include/rfl/parsing/schema/Type.hpp @@ -5,10 +5,10 @@ #include #include #include -#include #include #include "../../Ref.hpp" +#include "../../Variant.hpp" #include "ValidationType.hpp" namespace rfl::parsing::schema { @@ -86,7 +86,7 @@ struct Type { }; using VariantType = - std::variant; diff --git a/include/rfl/parsing/schema/ValidationType.hpp b/include/rfl/parsing/schema/ValidationType.hpp index fec2540c..dab04df5 100644 --- a/include/rfl/parsing/schema/ValidationType.hpp +++ b/include/rfl/parsing/schema/ValidationType.hpp @@ -4,10 +4,10 @@ #include #include #include -#include #include #include "../../Ref.hpp" +#include "../../Variant.hpp" namespace rfl::parsing::schema { @@ -21,27 +21,27 @@ struct ValidationType { }; struct EqualTo { - std::variant value_; + rfl::Variant value_; }; struct ExclusiveMaximum { - std::variant value_; + rfl::Variant value_; }; struct ExclusiveMinimum { - std::variant value_; + rfl::Variant value_; }; struct Maximum { - std::variant value_; + rfl::Variant value_; }; struct Minimum { - std::variant value_; + rfl::Variant value_; }; struct NotEqualTo { - std::variant value_; + rfl::Variant value_; }; struct OneOf { @@ -57,7 +57,7 @@ struct ValidationType { }; using VariantType = - std::variant; /// A type can be determined to be any of the above. diff --git a/include/rfl/visit.hpp b/include/rfl/visit.hpp index 64262aed..a2f78618 100644 --- a/include/rfl/visit.hpp +++ b/include/rfl/visit.hpp @@ -11,22 +11,96 @@ namespace rfl { -/// Implements the visitor pattern for Literals. template inline auto visit(const Visitor& _visitor, const Literal<_fields...> _literal, const Args&... _args) { - constexpr int size = sizeof...(_fields); - using WrapperType = internal::VisitorWrapper; - const auto wrapper = WrapperType{&_visitor}; - return internal::VisitTree::visit<0, size, WrapperType>( - wrapper, _literal.value(), _args...); + constexpr int size = sizeof...(_fields); + using WrapperType = internal::VisitorWrapper; + const auto wrapper = WrapperType{&_visitor}; + return internal::VisitTree::visit<0, size, WrapperType>( + wrapper, _literal.value(), _args...); } -/// Implements the visitor pattern for TaggedUnions. -template -inline auto visit(const Visitor& _visitor, +template +inline auto visit(F& _f, Variant& _v) { + return _v.visit(_f); +} + +template +inline auto visit(F& _f, Variant&& _v) { + return _v.visit(_f); +} + +template +inline auto visit(F& _f, const Variant& _v) { + return _v.visit(_f); +} + +template +inline auto visit(const F& _f, Variant& _v) { + return _v.visit(_f); +} + +template +inline auto visit(const F& _f, Variant&& _v) { + return _v.visit(_f); +} + +template +inline auto visit(const F& _f, const Variant& _v) { + return _v.visit(_f); +} + +template +inline auto visit(F& _f, TaggedUnion<_discriminator, Args...>& _tagged_union) { + return _tagged_union.variant().visit(_f); +} + +template +inline auto visit(F& _f, TaggedUnion<_discriminator, Args...>&& _tagged_union) { + return _tagged_union.variant().visit(_f); +} + +template +inline auto visit(F& _f, const TaggedUnion<_discriminator, Args...>& _tagged_union) { - return std::visit(_visitor, _tagged_union.variant()); + return _tagged_union.variant().visit(_f); +} + +template +inline auto visit(const F& _f, + TaggedUnion<_discriminator, Args...>& _tagged_union) { + return _tagged_union.variant().visit(_f); +} + +template +inline auto visit(const F& _f, + TaggedUnion<_discriminator, Args...>&& _tagged_union) { + return _tagged_union.variant().visit(_f); +} + +template +inline auto visit(const F& _f, + const TaggedUnion<_discriminator, Args...>& _tagged_union) { + return _tagged_union.variant().visit(_f); +} + +template +inline auto visit(F& _f, Head& _head, Tail&... _tail) { + const auto f_outer = [&](auto& _h) { + const auto f_inner = [&](auto&... _t) { return _f(_h, _t...); }; + return visit(f_inner, _tail...); + }; + return _head.visit(f_outer); +} + +template +inline auto visit(const F& _f, Head& _head, Tail&... _tail) { + const auto f_outer = [&](auto& _h) { + const auto f_inner = [&](auto&... _t) { return _f(_h, _t...); }; + return visit(f_inner, _tail...); + }; + return _head.visit(f_outer); } } // namespace rfl diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index 8d218077..b6adc401 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -128,7 +128,7 @@ bool is_optional(const parsing::schema::Type& _t) { using T = std::remove_cvref_t; return std::is_same(); }; - return std::visit(handle, _t.variant_); + return rfl::visit(handle, _t.variant_); } std::string numeric_type_to_string(const parsing::schema::Type& _type) { @@ -145,13 +145,13 @@ std::string numeric_type_to_string(const parsing::schema::Type& _type) { return schema::Type::Number{}.type.str(); } }; - return std::visit(handle_variant, _type.variant_); + return rfl::visit(handle_variant, _type.variant_); } schema::Type handle_validation_type( const parsing::schema::Type& _type, const parsing::schema::ValidationType& _validation_type) { - const auto handle_variant = [&](const auto& _v) -> schema::Type { + auto handle_variant = [&](const auto& _v) -> schema::Type { using T = std::remove_cvref_t; using ValidationType = parsing::schema::ValidationType; if constexpr (std::is_same()) { @@ -180,22 +180,25 @@ schema::Type handle_validation_type( } else if constexpr (std::is_same()) { auto t = type_to_json_schema_type(_type); + const auto to_size = [](const auto _v) { + return static_cast(_v); + }; auto handle_size_variant = [&](auto& _t, const auto& _size_limit) { using U = std::remove_cvref_t; using V = std::remove_cvref_t; if constexpr (std::is_same() || std::is_same()) { if constexpr (std::is_same()) { - _t.minSize = std::get(_size_limit.value_); + _t.minSize = _size_limit.value_.visit(to_size); return t; - + } else if constexpr (std::is_same()) { - _t.maxSize = std::get(_size_limit.value_); + _t.maxSize = _size_limit.value_.visit(to_size); return t; } else if constexpr (std::is_same()) { - _t.minSize = std::get(_size_limit.value_); - _t.maxSize = std::get(_size_limit.value_); + _t.minSize = _size_limit.value_.visit(to_size); + _t.maxSize = _size_limit.value_.visit(to_size); return t; } else if constexpr (std::is_same() || @@ -210,7 +213,8 @@ schema::Type handle_validation_type( } return t; }; - return std::visit(handle_size_variant, t.value, _v.size_limit_->variant_); + + return rfl::visit(handle_size_variant, t.value, _v.size_limit_->variant_); } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::ExclusiveMaximum{ @@ -259,11 +263,11 @@ schema::Type handle_validation_type( } }; - return std::visit(handle_variant, _validation_type.variant_); + return rfl::visit(handle_variant, _validation_type.variant_); } schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) { - const auto handle_variant = [](const auto& _t) -> schema::Type { + auto handle_variant = [](const auto& _t) -> schema::Type { using T = std::remove_cvref_t; using Type = parsing::schema::Type; if constexpr (std::is_same()) { @@ -296,7 +300,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) { _v.description = _t.description_; return schema::Type{_v}; }; - return std::visit(update_prediction, res.value); + return rfl::visit(update_prediction, res.value); } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::FixedSizeTypedArray{ @@ -362,7 +366,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) { } }; - return std::visit(handle_variant, _type.variant_); + return rfl::visit(handle_variant, _type.variant_); } } // namespace rfl::json diff --git a/tests/json/test_field_variant_std.cpp b/tests/json/test_field_variant_std.cpp new file mode 100644 index 00000000..f5e14b3a --- /dev/null +++ b/tests/json/test_field_variant_std.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_field_variant_std { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = std::variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>>; + +TEST(json, test_field_variant_std) { + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read(r, R"({"rectangle":{"height":10.0,"width":5.0}})"); +} +} // namespace test_field_variant_std diff --git a/tests/json/test_rfl_variant.cpp b/tests/json/test_rfl_variant.cpp new file mode 100644 index 00000000..eb43aed9 --- /dev/null +++ b/tests/json/test_rfl_variant.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read(r, R"({"height":10.0,"width":5.0})"); +} +} // namespace test_rfl_variant diff --git a/tests/json/test_rfl_variant_emplace.cpp b/tests/json/test_rfl_variant_emplace.cpp new file mode 100644 index 00000000..cec11f00 --- /dev/null +++ b/tests/json/test_rfl_variant_emplace.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant_emplace { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant_emplace) { + Shapes r; + r.emplace<1>(10.0, 5.0); + write_and_read(r, R"({"height":10.0,"width":5.0})"); +} +} // namespace test_rfl_variant_emplace diff --git a/tests/json/test_rfl_variant_get_if.cpp b/tests/json/test_rfl_variant_get_if.cpp new file mode 100644 index 00000000..3339a339 --- /dev/null +++ b/tests/json/test_rfl_variant_get_if.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant_get_if { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant_get_if) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + EXPECT_TRUE(rfl::get_if<1>(r) && true); + EXPECT_FALSE(rfl::get_if<0>(r) && true); +} +} // namespace test_rfl_variant_get_if diff --git a/tests/json/test_rfl_variant_holds_alternative.cpp b/tests/json/test_rfl_variant_holds_alternative.cpp new file mode 100644 index 00000000..be1936dc --- /dev/null +++ b/tests/json/test_rfl_variant_holds_alternative.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant_holds_alternative { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant_holds_alternative) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + EXPECT_TRUE(rfl::holds_alternative(r)); + EXPECT_FALSE(rfl::holds_alternative(r)); +} +} // namespace test_rfl_variant_holds_alternative diff --git a/tests/json/test_rfl_variant_swap.cpp b/tests/json/test_rfl_variant_swap.cpp new file mode 100644 index 00000000..894ec1a9 --- /dev/null +++ b/tests/json/test_rfl_variant_swap.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant_swap { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant_swap) { + Shapes r = Rectangle{.height = 10, .width = 5}; + Shapes c = Circle{.radius = 3}; + r.swap(c); + write_and_read(c, R"({"height":10.0,"width":5.0})"); + write_and_read(r, R"({"radius":3.0})"); +} +} // namespace test_rfl_variant_swap diff --git a/tests/json/test_rfl_variant_visit.cpp b/tests/json/test_rfl_variant_visit.cpp new file mode 100644 index 00000000..9d05cba6 --- /dev/null +++ b/tests/json/test_rfl_variant_visit.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant_visit { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant_visit) { + Shapes r = Rectangle{.height = 10, .width = 5}; + Shapes c = Circle{.radius = 3}; + Shapes s = std::make_unique(Square{.width = 3.0}); + const auto f = [](const auto& _r, const auto& _c, const auto& _s) { + return rfl::json::write(_r) + ", " + rfl::json::write(_c) + ", " + + rfl::json::write(_s); + }; + const auto str = rfl::visit(f, r, c, s); + EXPECT_TRUE(str == + R"({"height":10.0,"width":5.0}, {"radius":3.0}, {"width":3.0})"); +} +} // namespace test_rfl_variant_visit diff --git a/tests/json/test_rfl_variant_visit_in_place.cpp b/tests/json/test_rfl_variant_visit_in_place.cpp new file mode 100644 index 00000000..bafee19a --- /dev/null +++ b/tests/json/test_rfl_variant_visit_in_place.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_variant_visit_in_place { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant>; + +TEST(json, test_rfl_variant_visit) { + Shapes r = Rectangle{.height = 10, .width = 5}; + Shapes c = Circle{.radius = 3}; + Shapes s = std::make_unique(Square{.width = 3.0}); + const auto str = rfl::visit( + [](const auto& _r, const auto& _c, const auto& _s) { + return rfl::json::write(_r) + ", " + rfl::json::write(_c) + ", " + + rfl::json::write(_s); + }, + r, c, s); + EXPECT_TRUE(str == + R"({"height":10.0,"width":5.0}, {"radius":3.0}, {"width":3.0})"); +} +} // namespace test_rfl_variant_visit_in_place