diff --git a/docs/processors.md b/docs/processors.md index cebafe38..14b43d8a 100644 --- a/docs/processors.md +++ b/docs/processors.md @@ -34,6 +34,7 @@ The resulting JSON string looks like this: reflect-cpp currently supports the following processors: - `rfl::AddStructName` +- `rfl::AddTagsToVariants` - `rfl::AllowRawPtrs` - `rfl::DefaultIfMissing` - `rfl::NoExtraFields` @@ -61,6 +62,58 @@ The resulting JSON string looks like this: {"type":"Person","first_name":"Homer","last_name":"Simpson","age":45} ``` +### `rfl::AddStructsToVariants` + +This processor automatically adds structs to variants. Consider the following example: + +```cpp +struct button_pressed_t {}; + +struct button_released_t {}; + +struct key_pressed_t { + char key; +}; + +using my_event_type_t = + std::variant; +``` + +The problem here is that `button_pressed_t` and `butten_released_t` virtually look +indistinguishable. The will both be serialized to `{}`. + +But you can add this processor to automatically add tags and avoid the problem: + +```cpp +const auto vec = std::vector( + {button_pressed_t{}, button_released_t{}, key_pressed_t{'c'}, 3}); + +const auto json_string = rfl::json::write(vec); + +rfl::json::write, rfl::AddTagsToVariants>(json_string); +``` + +`vec` will now be serialized as follows: + +```json +[{"button_pressed_t":{}},{"button_released_t":{}},{"key_pressed_t":{"key":99}},{"int":3}] +``` + +You can also set your own custom tags like this: + +```cpp +struct key_pressed_t { + using Tag = rfl::Literal<"your_custom_tag">; + char key; +}; +``` + +`key_pressed_t` will now be serialized as follows: + +```json +{"your_custom_tag":{"key":99}} +``` + ### `rfl::AllowRawPtrs` By default, reflect-cpp does not allow *reading into* raw pointers. (*Writing from* raw pointers is never a problem.) This is because reading into raw pointers means that the library will allocate memory that the user then has to manually delete. This can lead to misunderstandings and memory leaks. diff --git a/docs/variants_and_tagged_unions.md b/docs/variants_and_tagged_unions.md index b534161e..4c327d77 100644 --- a/docs/variants_and_tagged_unions.md +++ b/docs/variants_and_tagged_unions.md @@ -45,9 +45,21 @@ several problems with this: 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 `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. +## Automatic tags + +The easiest way to solve this problem is to simply add tags automatically. You can do so by using `rfl::AddTagsToVariants`: + +```cpp +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +Please refer to the section on processors in this documentation for more information. + ## `rfl::TaggedUnion` (internally tagged) -One way to solve this problem is to add a tag inside the class. That is why we have provided a helper class for these purposes: `rfl::TaggedUnion`. +Another way to solve this problem is to add a tag inside the class. That is why we have provided a helper class for these purposes: `rfl::TaggedUnion`. TaggedUnions use the name of the struct as an identifying tag. It will then try to take that field from the JSON object, match it to the correct alternative and then only parse the correct alternative. diff --git a/include/rfl.hpp b/include/rfl.hpp index 9b290516..7c1e1f1e 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -8,6 +8,7 @@ #endif #include "rfl/AddStructName.hpp" +#include "rfl/AddTagsToVariants.hpp" #include "rfl/AllOf.hpp" #include "rfl/AllowRawPtrs.hpp" #include "rfl/AnyOf.hpp" diff --git a/include/rfl/AddTagsToVariants.hpp b/include/rfl/AddTagsToVariants.hpp new file mode 100644 index 00000000..09b9d867 --- /dev/null +++ b/include/rfl/AddTagsToVariants.hpp @@ -0,0 +1,19 @@ +#ifndef RFL_ADDTAGSTOVARIANTS_HPP_ +#define RFL_ADDTAGSTOVARIANTS_HPP_ + +namespace rfl { + +/// This is a "fake" processor - it doesn't do much in itself, but its +/// inclusion instructs the parsers to automatically add tags to the variants +/// they might encounter. +struct AddTagsToVariants { + public: + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Processors.hpp b/include/rfl/Processors.hpp index f2d95d30..2284eb96 100644 --- a/include/rfl/Processors.hpp +++ b/include/rfl/Processors.hpp @@ -3,6 +3,7 @@ #include +#include "internal/is_add_tags_to_variants_v.hpp" #include "internal/is_allow_raw_ptrs_v.hpp" #include "internal/is_default_if_missing_v.hpp" #include "internal/is_no_extra_fields_v.hpp" @@ -17,6 +18,7 @@ struct Processors; template <> struct Processors<> { + static constexpr bool add_tags_to_variants_ = false; static constexpr bool allow_raw_ptrs_ = false; static constexpr bool all_required_ = false; static constexpr bool default_if_missing_ = false; @@ -32,6 +34,10 @@ struct Processors<> { template struct Processors { + static constexpr bool add_tags_to_variants_ = + std::disjunction_v, + internal::is_add_tags_to_variants...>; + static constexpr bool allow_raw_ptrs_ = std::disjunction_v, internal::is_allow_raw_ptrs...>; diff --git a/include/rfl/internal/is_add_tags_to_variants_v.hpp b/include/rfl/internal/is_add_tags_to_variants_v.hpp new file mode 100644 index 00000000..a756eb47 --- /dev/null +++ b/include/rfl/internal/is_add_tags_to_variants_v.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_INTERNAL_ISADDTAGSTOVARIANTS_HPP_ +#define RFL_INTERNAL_ISADDTAGSTOVARIANTS_HPP_ + +#include +#include +#include + +#include "../AddTagsToVariants.hpp" + +namespace rfl ::internal { + +template +class is_add_tags_to_variants; + +template +class is_add_tags_to_variants : public std::false_type {}; + +template <> +class is_add_tags_to_variants : public std::true_type {}; + +template +constexpr bool is_add_tags_to_variants_v = is_add_tags_to_variants< + std::remove_cvref_t>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/tag_t.hpp b/include/rfl/internal/tag_t.hpp index 02278c82..4ce5e0d1 100644 --- a/include/rfl/internal/tag_t.hpp +++ b/include/rfl/internal/tag_t.hpp @@ -9,8 +9,7 @@ namespace rfl::internal { template -using tag_t = - typename std::invoke_result), T>::type; +using tag_t = std::invoke_result_t), T>; } // namespace rfl::internal diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 59238516..2929e4d8 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -64,14 +64,12 @@ struct FieldVariantParser { "Externally tagged variants cannot have duplicate field " "names."); - const auto handle = [&](const auto& _field) { + _v.visit([&](const auto& _field) { const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); using NamedTupleType = std::remove_cvref_t; Parser::write(_w, named_tuple, _parent); - }; - - rfl::visit(handle, _v); + }); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_rfl_variant.hpp b/include/rfl/parsing/Parser_rfl_variant.hpp index 28b0d90c..a80a7391 100644 --- a/include/rfl/parsing/Parser_rfl_variant.hpp +++ b/include/rfl/parsing/Parser_rfl_variant.hpp @@ -11,6 +11,7 @@ #include "../internal/nth_element_t.hpp" #include "FieldVariantParser.hpp" #include "Parser_base.hpp" +#include "VariantAlternativeWrapper.hpp" #include "schema/Type.hpp" namespace rfl::parsing { @@ -26,6 +27,19 @@ class Parser, ProcessorsType> { if constexpr (internal::all_fields>()) { return FieldVariantParser::read(_r, _var); + + } else if constexpr (ProcessorsType::add_tags_to_variants_) { + using FieldVariantType = + rfl::Variant...>; + const auto from_field_variant = + [](const auto& _field) -> rfl::Variant { + return std::move(_field.value()); + }; + return Parser::read(_r, _var) + .transform([&](FieldVariantType&& _f) { + return _f.visit(from_field_variant); + }); + } else { std::optional> result; std::vector errors; @@ -52,6 +66,17 @@ class Parser, ProcessorsType> { if constexpr (internal::all_fields>()) { FieldVariantParser::write( _w, _variant, _parent); + + } else if constexpr (ProcessorsType::add_tags_to_variants_) { + using FieldVariantType = + rfl::Variant...>; + const auto to_field_variant = + [](const T& _t) -> FieldVariantType { + return VariantAlternativeWrapper(&_t); + }; + Parser::write( + _w, _variant.visit(to_field_variant), _parent); + } else { const auto handle = [&](const auto& _v) { using Type = std::remove_cvref_t; @@ -66,6 +91,13 @@ class Parser, ProcessorsType> { if constexpr (internal::all_fields>()) { return FieldVariantParser::to_schema(_definitions); + + } else if constexpr (ProcessorsType::add_tags_to_variants_) { + using FieldVariantType = + rfl::Variant...>; + return Parser::to_schema( + _definitions); + } else { std::vector types; build_schema( diff --git a/include/rfl/parsing/Parser_variant.hpp b/include/rfl/parsing/Parser_variant.hpp index 84150971..e60dc9d8 100644 --- a/include/rfl/parsing/Parser_variant.hpp +++ b/include/rfl/parsing/Parser_variant.hpp @@ -13,11 +13,11 @@ #include "../internal/to_ptr_field.hpp" #include "FieldVariantParser.hpp" #include "Parser_base.hpp" +#include "VariantAlternativeWrapper.hpp" #include "schema/Type.hpp" #include "to_single_error_message.hpp" -namespace rfl { -namespace parsing { +namespace rfl::parsing { template requires AreReaderAndWriter> @@ -41,6 +41,19 @@ class Parser, ProcessorsType> { return FieldVariantParser::read(_r, _var) .transform(to_std_variant); + + } else if constexpr (ProcessorsType::add_tags_to_variants_) { + using FieldVariantType = + rfl::Variant...>; + const auto from_field_variant = + [](auto&& _field) -> std::variant { + return std::move(_field.value()); + }; + return Parser::read(_r, _var) + .transform([&](FieldVariantType&& _f) { + return _f.visit(from_field_variant); + }); + } else { std::optional> result; std::vector errors; @@ -76,6 +89,16 @@ class Parser, ProcessorsType> { R, W, ProcessorsType, ptr_field_t...>::write(_w, to_rfl_variant(_variant), _parent); + } else if constexpr (ProcessorsType::add_tags_to_variants_) { + using FieldVariantType = + rfl::Variant...>; + const auto to_field_variant = + [](const T& _t) -> FieldVariantType { + return VariantAlternativeWrapper(&_t); + }; + Parser::write( + _w, std::visit(to_field_variant, _variant), _parent); + } else { const auto handle = [&](const auto& _v) { using Type = std::remove_cvref_t; @@ -90,6 +113,13 @@ class Parser, ProcessorsType> { if constexpr (internal::all_fields>()) { return FieldVariantParser::to_schema(_definitions); + + } else if constexpr (ProcessorsType::add_tags_to_variants_) { + using FieldVariantType = + rfl::Variant...>; + return Parser::to_schema( + _definitions); + } else { std::vector types; build_schema( @@ -142,7 +172,6 @@ class Parser, ProcessorsType> { } }; -} // namespace parsing -} // namespace rfl +} // namespace rfl::parsing #endif diff --git a/include/rfl/parsing/VariantAlternativeWrapper.hpp b/include/rfl/parsing/VariantAlternativeWrapper.hpp new file mode 100644 index 00000000..924b711f --- /dev/null +++ b/include/rfl/parsing/VariantAlternativeWrapper.hpp @@ -0,0 +1,46 @@ +#ifndef RFL_PARSING_VARIANTALTERNATIVEWRAPPER_HPP_ +#define RFL_PARSING_VARIANTALTERNATIVEWRAPPER_HPP_ + +#include + +#include "../Field.hpp" +#include "../Literal.hpp" +#include "../internal/StringLiteral.hpp" +#include "../internal/get_type_name.hpp" +#include "../internal/has_tag_v.hpp" +#include "../internal/remove_namespaces.hpp" + +namespace rfl::parsing { + +namespace vaw { + +template +struct GetName {}; + +template +struct GetName> { + constexpr static internal::StringLiteral name_ = _name; +}; + +template +consteval auto make_tag() { + if constexpr (internal::has_tag_v) { + return typename T::Tag(); + } else { + return Literal< + internal::remove_namespaces()>()>(); + } +} + +template +using tag_t = std::invoke_result_t< + decltype(make_tag>>)>; + +} // namespace vaw + +template +using VariantAlternativeWrapper = Field>::name_, T>; + +} // namespace rfl::parsing + +#endif diff --git a/tests/json/test_add_tag_to_rfl_variant.cpp b/tests/json/test_add_tag_to_rfl_variant.cpp new file mode 100644 index 00000000..66c7d7e9 --- /dev/null +++ b/tests/json/test_add_tag_to_rfl_variant.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_add_tag_to_rfl_variant { + +struct button_pressed_t {}; + +struct button_released_t {}; + +struct key_pressed_t { + using Tag = rfl::Literal<"key_pressed">; + char key; +}; + +using my_event_type_t = + rfl::Variant; + +TEST(json, test_add_tag_to_rfl_variant) { + const auto vec = std::vector( + {button_pressed_t{}, button_released_t{}, key_pressed_t{'c'}, 3}); + + write_and_read( + vec, + R"([{"button_pressed_t":{}},{"button_released_t":{}},{"key_pressed":{"key":99}},{"int":3}])"); +} +} // namespace test_add_tag_to_rfl_variant diff --git a/tests/json/test_add_tag_to_variant.cpp b/tests/json/test_add_tag_to_variant.cpp new file mode 100644 index 00000000..5ce9a953 --- /dev/null +++ b/tests/json/test_add_tag_to_variant.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_add_tag_to_variant { + +struct button_pressed_t {}; + +struct button_released_t {}; + +struct key_pressed_t { + using Tag = rfl::Literal<"key_pressed">; + char key; +}; + +using my_event_type_t = + std::variant; + +TEST(json, test_add_tag_to_variant) { + const auto vec = std::vector( + {button_pressed_t{}, button_released_t{}, key_pressed_t{'c'}, 3}); + + write_and_read( + vec, + R"([{"button_pressed_t":{}},{"button_released_t":{}},{"key_pressed":{"key":99}},{"int":3}])"); +} +} // namespace test_add_tag_to_variant