From 745c7ead2c56e09de6aa2a3cc6128be9afb84c59 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Mon, 9 Oct 2023 21:08:05 +0200 Subject: [PATCH 01/48] Added support for clang --- include/rfl/NamedTuple.hpp | 34 +++---------------- include/rfl/Result.hpp | 23 ++++++++++--- .../rfl/internal/move_from_named_tuple.hpp | 2 +- include/rfl/json/Reader.hpp | 21 ++---------- include/rfl/json/Writer.hpp | 2 ++ include/rfl/parsing/Parser.hpp | 34 ++++++++++++------- tests/test_box.hpp | 8 ++--- tests/test_ref.hpp | 8 ++--- tests/test_unique_ptr2.hpp | 8 ++--- 9 files changed, 61 insertions(+), 79 deletions(-) diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 14f7f811..d1dd877d 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -149,17 +149,6 @@ class NamedTuple { } } - /// Template specialization for std::tuple, so we can pass fields from other - /// named tuples. - template - auto add(const std::tuple& _tuple, Tail&&... _tail) const { - if constexpr (sizeof...(Tail) > 0) { - return add_tuple(_tuple).add(std::forward(_tail)...); - } else { - return add_tuple(std::forward>(_tuple)); - } - } - /// Template specialization for NamedTuple, so we can pass fields from other /// named tuples. template @@ -178,21 +167,6 @@ class NamedTuple { std::forward(_tail)...); } - /// Template specialization for NamedTuple, so we can pass fields from other - /// named tuples. - template - auto add(const NamedTuple& _named_tuple, Tail&&... _tail) { - return add(_named_tuple.fields(), std::forward(_tail)...); - } - - /// Template specialization for NamedTuple, so we can pass fields from other - /// named tuples. - template - auto add(const NamedTuple& _named_tuple, - Tail&&... _tail) const { - return add(_named_tuple.fields(), std::forward(_tail)...); - } - /// Returns a tuple containing the fields. Fields fields() { return make_fields(); } @@ -345,7 +319,7 @@ class NamedTuple { template constexpr auto add_tuple(std::tuple&& _tuple) { const auto a = [this](auto&&... _fields) { - return add(std::forward(_fields)...); + return this->add(std::forward(_fields)...); }; return std::apply(a, std::forward>(_tuple)); } @@ -355,7 +329,7 @@ class NamedTuple { template constexpr auto add_tuple(std::tuple&& _tuple) const { const auto a = [this](auto&&... _fields) { - return add(std::forward(_fields)...); + return this->add(std::forward(_fields)...); }; return std::apply(a, std::forward>(_tuple)); } @@ -458,7 +432,7 @@ class NamedTuple { template auto replace_tuple(std::tuple&& _tuple) { const auto r = [this](auto&&... _fields) { - return replace(std::forward(_fields)...); + return this->replace(std::forward(_fields)...); }; return std::apply(r, std::forward>(_tuple)); } @@ -468,7 +442,7 @@ class NamedTuple { template auto replace_tuple(std::tuple&& _tuple) const { const auto r = [this](auto&&... _fields) { - return replace(std::forward(_fields)...); + return this->replace(std::forward(_fields)...); }; return std::apply(r, std::forward>(_tuple)); } diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index d12b6b19..9400e20e 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -144,7 +144,7 @@ class Result { /// them within a std::range. const T* end() const noexcept { const auto get_ptr = - [this](const TOrError& _t_or_err) -> const T* { + [](const TOrError& _t_or_err) -> const T* { if constexpr (!std::is_same()) { return &_t_or_err + 1; } else { @@ -158,7 +158,7 @@ class Result { /// or std::nullopt otherwise. std::optional error() const noexcept { const auto get_err = - [this]( + []( const TOrError& _t_or_err) -> std::optional { if constexpr (!std::is_same()) { return std::nullopt; @@ -284,11 +284,11 @@ class Result { /// Returns the value if the result does not contain an error, throws an /// exceptions if not. Similar to .unwrap() in Rust. - T& value() { + T value() { const auto handle_variant = - [&](TOrError& _t_or_err) -> T& { + [&](TOrError& _t_or_err) -> T { if constexpr (!std::is_same()) { - return _t_or_err; + return std::forward(_t_or_err); } else { throw std::runtime_error(_t_or_err.what()); } @@ -310,6 +310,19 @@ class Result { return std::visit(handle_variant, t_or_err_); } + /// Returns the value or a default. + T value_or(const T& _default) noexcept { + const auto handle_variant = + [&](const TOrError& _t_or_err) -> T { + if constexpr (!std::is_same()) { + return std::forward(_t_or_err); + } else { + return _default; + } + }; + return std::visit(handle_variant, t_or_err_); + } + /// Returns the value or a default. T value_or(const T& _default) const noexcept { const auto handle_variant = diff --git a/include/rfl/internal/move_from_named_tuple.hpp b/include/rfl/internal/move_from_named_tuple.hpp index 8f09a016..821c5c0b 100644 --- a/include/rfl/internal/move_from_named_tuple.hpp +++ b/include/rfl/internal/move_from_named_tuple.hpp @@ -50,7 +50,7 @@ template auto move_from_pointers(Pointers& _ptrs, Args&&... _args) { constexpr auto i = sizeof...(Args); if constexpr (i == std::tuple_size_v>) { - return T(std::move(_args)...); + return T{std::move(_args)...}; } else { using FieldType = std::tuple_element_t>; diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index 7a3e5ba8..03fd8bfe 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -18,34 +18,19 @@ namespace rfl { namespace json { -struct YYJSONOutputArray { - yyjson_mut_val* val_; -}; - -struct YYJSONOutputObject { - yyjson_mut_val* val_; -}; - -struct YYJSONOutputVar { - YYJSONOutputVar(yyjson_mut_val* _val) : val_(_val) {} - - YYJSONOutputVar(YYJSONOutputArray _arr) : val_(_arr.val_) {} - - YYJSONOutputVar(YYJSONOutputObject _obj) : val_(_obj.val_) {} - - yyjson_mut_val* val_; -}; - struct Reader { struct YYJSONInputArray { + YYJSONInputArray(yyjson_val* _val) : val_(_val) {} yyjson_val* val_; }; struct YYJSONInputObject { + YYJSONInputObject(yyjson_val* _val) : val_(_val) {} yyjson_val* val_; }; struct YYJSONInputVar { + YYJSONInputVar(yyjson_val* _val) : val_(_val) {} yyjson_val* val_; }; diff --git a/include/rfl/json/Writer.hpp b/include/rfl/json/Writer.hpp index 2bc1e83d..bd26e0fe 100644 --- a/include/rfl/json/Writer.hpp +++ b/include/rfl/json/Writer.hpp @@ -19,10 +19,12 @@ namespace json { struct Writer { struct YYJSONOutputArray { + YYJSONOutputArray(yyjson_mut_val* _val) : val_(_val) {} yyjson_mut_val* val_; }; struct YYJSONOutputObject { + YYJSONOutputObject(yyjson_mut_val* _val) : val_(_val) {} yyjson_mut_val* val_; }; diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index fda9f122..d0769427 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -221,7 +221,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const ReaderType& _r, InputVarType* _var) noexcept { - const auto to_box = [&](auto&& _t) { + const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; return Parser>::read(_r, _var) @@ -444,9 +444,7 @@ struct Parser> { if (_r.is_empty(_var)) { return std::optional(); } - const auto to_opt = [&_r](auto&& _t) { - return std::make_optional(_t); - }; + const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; return Parser>::read(_r, _var) .transform(to_opt); } @@ -922,7 +920,8 @@ struct Parser> { // ---------------------------------------------------------------------------- /// This can be used for data structures that would be expressed as array in -/// serialized format (std::vector, std::set, std::deque, ...). +/// serialized format (std::vector, std::set, std::deque, ...), +/// but also includes map-like types, when the key is not of type std::string. template struct VectorParser { public: @@ -938,23 +937,32 @@ struct VectorParser { InputVarType* _var) noexcept { using namespace std::ranges::views; - const auto get_result = [&](auto& _v) { - return std::move( - Parser>::read(_r, &_v) - .value()); + const auto get_elem = [&](auto& _v) { + return Parser>::read(_r, + &_v) + .value(); }; - const auto to_vec = [&](InputArrayType _arr) -> Result { + const auto to_container = + [&](InputArrayType&& _arr) -> Result { auto input_vars = _r.to_vec(&_arr); - auto range = input_vars | transform(get_result); + VecType vec; + for (auto it = input_vars.begin(); it != input_vars.end(); ++it) { + vec.emplace_back(get_elem(*it)); + } + return vec; + }; + + const auto to_result = [&](InputArrayType&& _arr) -> Result { try { - return Result(VecType(range.begin(), range.end())); + return Result( + to_container(std::forward(_arr))); } catch (std::exception& e) { return Error(e.what()); } }; - return _r.to_array(_var).and_then(to_vec); + return _r.to_array(_var).and_then(to_result); } static OutputVarType write(const WriterType& _w, diff --git a/tests/test_box.hpp b/tests/test_box.hpp index 1ff2730c..9317efdd 100644 --- a/tests/test_box.hpp +++ b/tests/test_box.hpp @@ -32,10 +32,10 @@ void test_box() { auto leaf2 = DecisionTree::Leaf{.value = 5.0}; - auto node = - DecisionTree::Node{.critical_value = 10.0, - .lesser = rfl::make_box(leaf1), - .greater = rfl::make_box(leaf2)}; + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_box(DecisionTree{leaf1}), + .greater = rfl::make_box(DecisionTree{leaf2})}; const DecisionTree tree{.leaf_or_node = std::move(node)}; diff --git a/tests/test_ref.hpp b/tests/test_ref.hpp index 8c353f5d..b7fe3e90 100644 --- a/tests/test_ref.hpp +++ b/tests/test_ref.hpp @@ -32,10 +32,10 @@ void test_ref() { const auto leaf2 = DecisionTree::Leaf{.value = 5.0}; - auto node = - DecisionTree::Node{.critical_value = 10.0, - .lesser = rfl::make_ref(leaf1), - .greater = rfl::make_ref(leaf2)}; + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_ref(DecisionTree{leaf1}), + .greater = rfl::make_ref(DecisionTree{leaf2})}; const DecisionTree tree{.leaf_or_node = std::move(node)}; diff --git a/tests/test_unique_ptr2.hpp b/tests/test_unique_ptr2.hpp index aae61b15..4fab614c 100644 --- a/tests/test_unique_ptr2.hpp +++ b/tests/test_unique_ptr2.hpp @@ -32,10 +32,10 @@ void test_unique_ptr2() { auto leaf2 = DecisionTree::Leaf{.value = 5.0}; - auto node = - DecisionTree::Node{.critical_value = 10.0, - .lesser = std::make_unique(leaf1), - .greater = std::make_unique(leaf2)}; + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = std::make_unique(DecisionTree{leaf1}), + .greater = std::make_unique(DecisionTree{leaf2})}; const DecisionTree tree{.leaf_or_node = std::move(node)}; From 23922db9c59c22e576d1267631d22f81ec0e3c73 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Mon, 9 Oct 2023 22:32:37 +0200 Subject: [PATCH 02/48] Added tests for various containers --- include/rfl/parsing/Parser.hpp | 43 ++++++++++++++++++++----- include/rfl/parsing/is_forward_list.hpp | 22 +++++++++++++ include/rfl/parsing/is_map_like.hpp | 26 +++++++++++++++ tests/test_deque.hpp | 30 +++++++++++++++++ tests/test_forward_list.hpp | 30 +++++++++++++++++ tests/test_list.hpp | 30 +++++++++++++++++ tests/test_map.hpp | 30 +++++++++++++++++ tests/test_unordered_map.hpp | 32 ++++++++++++++++++ tests/tests.cpp | 10 ++++++ 9 files changed, 245 insertions(+), 8 deletions(-) create mode 100644 include/rfl/parsing/is_forward_list.hpp create mode 100644 include/rfl/parsing/is_map_like.hpp create mode 100644 tests/test_deque.hpp create mode 100644 tests/test_forward_list.hpp create mode 100644 tests/test_list.hpp create mode 100644 tests/test_map.hpp create mode 100644 tests/test_unordered_map.hpp diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index d0769427..3967108b 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -34,6 +34,8 @@ #include "rfl/internal/no_duplicate_field_names.hpp" #include "rfl/internal/to_ptr_named_tuple.hpp" #include "rfl/named_tuple_t.hpp" +#include "rfl/parsing/is_forward_list.hpp" +#include "rfl/parsing/is_map_like.hpp" #include "rfl/parsing/is_required.hpp" #include "rfl/to_named_tuple.hpp" @@ -533,9 +535,10 @@ struct Parser> { static OutputVarType write( const WriterType& _w, const std::pair& _p) noexcept { - const auto tup = std::make_tuple(_p.first, _p.second); - return Parser>::write(_w, tup); + const auto tup = std::make_tuple(&_p.first, &_p.second); + return Parser< + ReaderType, WriterType, + std::tuple>::write(_w, tup); } }; @@ -699,7 +702,8 @@ struct Parser> { AlreadyExtracted&&... _already_extracted) noexcept { constexpr size_t i = sizeof...(AlreadyExtracted); if constexpr (i == sizeof...(Ts)) { - return std::tuple(std::make_tuple(_already_extracted...)); + return std::tuple( + std::make_tuple(std::move(_already_extracted)...)); } else { const auto extract_next = [&](auto&& new_entry) { return extract_field_by_field(_r, std::move(_vec), @@ -943,12 +947,35 @@ struct VectorParser { .value(); }; + const auto get_pair = [&](auto& _v) { + if constexpr (is_map_like()) { + using K = std::decay_t; + using V = std::decay_t; + return Parser>>::read(_r, &_v) + .value(); + } + }; + const auto to_container = [&](InputArrayType&& _arr) -> Result { auto input_vars = _r.to_vec(&_arr); VecType vec; - for (auto it = input_vars.begin(); it != input_vars.end(); ++it) { - vec.emplace_back(get_elem(*it)); + if constexpr (is_forward_list()) { + for (auto it = input_vars.rbegin(); it != input_vars.rend(); + ++it) { + vec.emplace_front(get_elem(*it)); + } + } else if constexpr (is_map_like()) { + for (auto it = input_vars.begin(); it != input_vars.end(); + ++it) { + vec.insert(get_pair(*it)); + } + } else { + for (auto it = input_vars.begin(); it != input_vars.end(); + ++it) { + vec.emplace_back(get_elem(*it)); + } } return vec; }; @@ -968,9 +995,9 @@ struct VectorParser { static OutputVarType write(const WriterType& _w, const VecType& _vec) noexcept { auto arr = _w.new_array(); - for (auto it = _vec.begin(); it != _vec.end(); ++it) { + for (const auto& v : _vec) { _w.add( - Parser>::write(_w, *it), + Parser>::write(_w, v), &arr); } return OutputVarType(arr); diff --git a/include/rfl/parsing/is_forward_list.hpp b/include/rfl/parsing/is_forward_list.hpp new file mode 100644 index 00000000..2ac6fe79 --- /dev/null +++ b/include/rfl/parsing/is_forward_list.hpp @@ -0,0 +1,22 @@ +#ifndef RFL_PARSING_IS_FORWARD_LIST_HPP_ +#define RFL_PARSING_IS_FORWARD_LIST_HPP_ + +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_forward_list; + +template +class is_forward_list : public std::false_type {}; + +template +class is_forward_list> : public std::true_type {}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/is_map_like.hpp b/include/rfl/parsing/is_map_like.hpp new file mode 100644 index 00000000..c0679bfc --- /dev/null +++ b/include/rfl/parsing/is_map_like.hpp @@ -0,0 +1,26 @@ +#ifndef RFL_PARSING_IS_MAP_LIKE_HPP_ +#define RFL_PARSING_IS_MAP_LIKE_HPP_ + +#include +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_map_like; + +template +class is_map_like : public std::false_type {}; + +template +class is_map_like> : public std::true_type {}; + +template +class is_map_like> : public std::true_type {}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/tests/test_deque.hpp b/tests/test_deque.hpp new file mode 100644 index 00000000..78e8fec5 --- /dev/null +++ b/tests/test_deque.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_deque() { + std::cout << "test_deque" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + children->emplace_back(Person{.first_name = "Bart"}); + children->emplace_back(Person{.first_name = "Lisa"}); + children->emplace_back(Person{.first_name = "Maggie"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]})"); +} diff --git a/tests/test_forward_list.hpp b/tests/test_forward_list.hpp new file mode 100644 index 00000000..8ccfdb21 --- /dev/null +++ b/tests/test_forward_list.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_forward_list() { + std::cout << "test_forward_list" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + children->emplace_front(Person{.first_name = "Maggie"}); + children->emplace_front(Person{.first_name = "Lisa"}); + children->emplace_front(Person{.first_name = "Bart"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]})"); +} diff --git a/tests/test_list.hpp b/tests/test_list.hpp new file mode 100644 index 00000000..06de7e72 --- /dev/null +++ b/tests/test_list.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_list() { + std::cout << "test_list" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + children->emplace_back(Person{.first_name = "Bart"}); + children->emplace_back(Person{.first_name = "Lisa"}); + children->emplace_back(Person{.first_name = "Maggie"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]})"); +} diff --git a/tests/test_map.hpp b/tests/test_map.hpp new file mode 100644 index 00000000..efb793bf --- /dev/null +++ b/tests/test_map.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_map() { + std::cout << "test_map" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + children->insert(std::make_pair(1, Person{.first_name = "Bart"})); + children->insert(std::make_pair(2, Person{.first_name = "Lisa"})); + children->insert(std::make_pair(3, Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":[[1,{"firstName":"Bart","lastName":"Simpson"}],[2,{"firstName":"Lisa","lastName":"Simpson"}],[3,{"firstName":"Maggie","lastName":"Simpson"}]]})"); +} diff --git a/tests/test_unordered_map.hpp b/tests/test_unordered_map.hpp new file mode 100644 index 00000000..b91940b1 --- /dev/null +++ b/tests/test_unordered_map.hpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_unordered_map() { + std::cout << "test_unordered_map" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + children->insert(std::make_pair(1, Person{.first_name = "Bart"})); + children->insert(std::make_pair(2, Person{.first_name = "Lisa"})); + children->insert(std::make_pair(3, Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + // Unordered maps are unpredictable. We therefore only make sure that this + // compiles. + const auto json_string = rfl::json::write(homer); + const auto homer2 = rfl::json::read(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/tests.cpp b/tests/tests.cpp index 5be0b764..8e458819 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -7,9 +7,13 @@ #include "test_custom_class3.hpp" #include "test_custom_class4.hpp" #include "test_default_values.hpp" +#include "test_deque.hpp" #include "test_field_variant.hpp" #include "test_flatten.hpp" +#include "test_forward_list.hpp" +#include "test_list.hpp" #include "test_literal.hpp" +#include "test_map.hpp" #include "test_optional_fields.hpp" #include "test_readme_example.hpp" #include "test_ref.hpp" @@ -20,6 +24,7 @@ #include "test_timestamp.hpp" #include "test_unique_ptr.hpp" #include "test_unique_ptr2.hpp" +#include "test_unordered_map.hpp" #include "test_variant.hpp" int main() { @@ -37,6 +42,11 @@ int main() { test_array(); test_timestamp(); test_flatten(); + test_deque(); + test_forward_list(); + test_list(); + test_map(); + test_unordered_map(); test_custom_class1(); test_custom_class2(); From c94992591d343dd9f210e1d505bea774f8094dc4 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Mon, 9 Oct 2023 22:36:29 +0200 Subject: [PATCH 03/48] Update README.md to include compilers --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8fa70e5a..194d5682 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) [![Generic badge](https://img.shields.io/badge/C++-20-blue.svg)](https://shields.io/) [![Generic badge](https://img.shields.io/badge/gcc-10+-blue.svg)](https://shields.io/) -[![Generic badge](https://img.shields.io/badge/clang-TODO-red.svg)](https://shields.io/) +[![Generic badge](https://img.shields.io/badge/clang-10+-blue.svg)](https://shields.io/) [![Generic badge](https://img.shields.io/badge/MSVC-TODO-red.svg)](https://shields.io/) ![image](banner1.png) @@ -149,10 +149,15 @@ At the moment, this is work-in-progress. Here are some things that are still mis - Benchmarks and optimization - Documentation is unfinished (missing rfl::Result, rfl::NamedTuple as well as extension to other serialization formats) -- Support for Clang and MSVC +- Support for MSVC ## Installation +The following compilers are supported: +- GCC 11.4 or higher +- Clang 14.0 or higher +- MSVC (TODO) + ### Option 1: Header-only If you **do not** need JSON support, then reflect-cpp is header-only. Simply copy the contents of the folder `include` into your source repository or add it to your include path. From 0c0e09cd283bca396655964a0ae2113dae8fe8ef Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Mon, 9 Oct 2023 22:36:59 +0200 Subject: [PATCH 04/48] Fixed typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 194d5682..225b9864 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) [![Generic badge](https://img.shields.io/badge/C++-20-blue.svg)](https://shields.io/) [![Generic badge](https://img.shields.io/badge/gcc-10+-blue.svg)](https://shields.io/) -[![Generic badge](https://img.shields.io/badge/clang-10+-blue.svg)](https://shields.io/) +[![Generic badge](https://img.shields.io/badge/clang-14+-blue.svg)](https://shields.io/) [![Generic badge](https://img.shields.io/badge/MSVC-TODO-red.svg)](https://shields.io/) ![image](banner1.png) From 9039f55ce79f088f912e4eba91bafe178761729c Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Mon, 9 Oct 2023 22:37:50 +0200 Subject: [PATCH 05/48] Updated gcc --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 225b9864..a291ed83 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) [![Generic badge](https://img.shields.io/badge/C++-20-blue.svg)](https://shields.io/) -[![Generic badge](https://img.shields.io/badge/gcc-10+-blue.svg)](https://shields.io/) +[![Generic badge](https://img.shields.io/badge/gcc-11+-blue.svg)](https://shields.io/) [![Generic badge](https://img.shields.io/badge/clang-14+-blue.svg)](https://shields.io/) [![Generic badge](https://img.shields.io/badge/MSVC-TODO-red.svg)](https://shields.io/) From 5198a446aa5d877822eb550984e1bd7483c63e7c Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Tue, 10 Oct 2023 21:37:02 +0200 Subject: [PATCH 06/48] Added support for various containers --- include/rfl/parsing/Parser.hpp | 33 +++++++++++++++++++++++------ include/rfl/parsing/is_map_like.hpp | 6 ++++++ include/rfl/parsing/is_set_like.hpp | 32 ++++++++++++++++++++++++++++ tests/test_multimap.hpp | 30 ++++++++++++++++++++++++++ tests/test_multiset.hpp | 28 ++++++++++++++++++++++++ tests/test_set.hpp | 28 ++++++++++++++++++++++++ tests/test_unordered_multimap.hpp | 33 +++++++++++++++++++++++++++++ tests/test_unordered_multiset.hpp | 31 +++++++++++++++++++++++++++ tests/test_unordered_set.hpp | 30 ++++++++++++++++++++++++++ tests/tests.cpp | 12 +++++++++++ 10 files changed, 257 insertions(+), 6 deletions(-) create mode 100644 include/rfl/parsing/is_set_like.hpp create mode 100644 tests/test_multimap.hpp create mode 100644 tests/test_multiset.hpp create mode 100644 tests/test_set.hpp create mode 100644 tests/test_unordered_multimap.hpp create mode 100644 tests/test_unordered_multiset.hpp create mode 100644 tests/test_unordered_set.hpp diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 3967108b..1d84a2db 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -37,6 +37,7 @@ #include "rfl/parsing/is_forward_list.hpp" #include "rfl/parsing/is_map_like.hpp" #include "rfl/parsing/is_required.hpp" +#include "rfl/parsing/is_set_like.hpp" #include "rfl/to_named_tuple.hpp" namespace rfl { @@ -967,14 +968,16 @@ struct VectorParser { vec.emplace_front(get_elem(*it)); } } else if constexpr (is_map_like()) { - for (auto it = input_vars.begin(); it != input_vars.end(); - ++it) { - vec.insert(get_pair(*it)); + for (auto& v : input_vars) { + vec.insert(get_pair(v)); + } + } else if constexpr (is_set_like()) { + for (auto& v : input_vars) { + vec.insert(get_elem(v)); } } else { - for (auto it = input_vars.begin(); it != input_vars.end(); - ++it) { - vec.emplace_back(get_elem(*it)); + for (auto& v : input_vars) { + vec.emplace_back(get_elem(v)); } } return vec; @@ -1020,6 +1023,14 @@ template struct Parser> : public VectorParser> {}; +template +struct Parser> + : public VectorParser> {}; + +template +struct Parser> + : public VectorParser> {}; + template struct Parser> : public VectorParser> {}; @@ -1028,6 +1039,16 @@ template struct Parser> : public VectorParser> {}; +template +struct Parser> + : public VectorParser> {}; + +template +struct Parser> + : public VectorParser> {}; + template struct Parser> : public VectorParser> {}; diff --git a/include/rfl/parsing/is_map_like.hpp b/include/rfl/parsing/is_map_like.hpp index c0679bfc..34249982 100644 --- a/include/rfl/parsing/is_map_like.hpp +++ b/include/rfl/parsing/is_map_like.hpp @@ -17,9 +17,15 @@ class is_map_like : public std::false_type {}; template class is_map_like> : public std::true_type {}; +template +class is_map_like> : public std::true_type {}; + template class is_map_like> : public std::true_type {}; +template +class is_map_like> : public std::true_type {}; + } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/is_set_like.hpp b/include/rfl/parsing/is_set_like.hpp new file mode 100644 index 00000000..9801c750 --- /dev/null +++ b/include/rfl/parsing/is_set_like.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_PARSING_IS_SET_LIKE_HPP_ +#define RFL_PARSING_IS_SET_LIKE_HPP_ + +#include +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_set_like; + +template +class is_set_like : public std::false_type {}; + +template +class is_set_like> : public std::true_type {}; + +template +class is_set_like> : public std::true_type {}; + +template +class is_set_like> : public std::true_type {}; + +template +class is_set_like> : public std::true_type {}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/tests/test_multimap.hpp b/tests/test_multimap.hpp new file mode 100644 index 00000000..6746613e --- /dev/null +++ b/tests/test_multimap.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_multimap() { + std::cout << "test_multimap" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + children->insert(std::make_pair(1, Person{.first_name = "Bart"})); + children->insert(std::make_pair(2, Person{.first_name = "Lisa"})); + children->insert(std::make_pair(3, Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":[[1,{"firstName":"Bart","lastName":"Simpson"}],[2,{"firstName":"Lisa","lastName":"Simpson"}],[3,{"firstName":"Maggie","lastName":"Simpson"}]]})"); +} diff --git a/tests/test_multiset.hpp b/tests/test_multiset.hpp new file mode 100644 index 00000000..21d7062e --- /dev/null +++ b/tests/test_multiset.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_multiset() { + std::cout << "test_multiset" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::multiset({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":["Bart","Lisa","Maggie"]})"); +} diff --git a/tests/test_set.hpp b/tests/test_set.hpp new file mode 100644 index 00000000..97e3834b --- /dev/null +++ b/tests/test_set.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_set() { + std::cout << "test_set" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::set({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":["Bart","Lisa","Maggie"]})"); +} diff --git a/tests/test_unordered_multimap.hpp b/tests/test_unordered_multimap.hpp new file mode 100644 index 00000000..757118df --- /dev/null +++ b/tests/test_unordered_multimap.hpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_unordered_multimap() { + std::cout << "test_unordered_multimap" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", + std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + children->insert(std::make_pair(1, Person{.first_name = "Bart"})); + children->insert(std::make_pair(2, Person{.first_name = "Lisa"})); + children->insert(std::make_pair(3, Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + // Unordered maps are unpredictable. We therefore only make sure that this + // compiles. + const auto json_string = rfl::json::write(homer); + const auto homer2 = rfl::json::read(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_unordered_multiset.hpp b/tests/test_unordered_multiset.hpp new file mode 100644 index 00000000..11591da4 --- /dev/null +++ b/tests/test_unordered_multiset.hpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_unordered_multiset() { + std::cout << "test_unordered_multiset" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", + std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::unordered_multiset({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + // Unordered multisets are unpredictable. We therefore only make sure that + // this compiles. + const auto json_string = rfl::json::write(homer); + const auto homer2 = rfl::json::read(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_unordered_set.hpp b/tests/test_unordered_set.hpp new file mode 100644 index 00000000..f4602a64 --- /dev/null +++ b/tests/test_unordered_set.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_unordered_set() { + std::cout << "test_unordered_set" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::unique_ptr>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::unordered_set({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + // Unordered sets are unpredictable. We therefore only make sure that this + // compiles. + const auto json_string = rfl::json::write(homer); + const auto homer2 = rfl::json::read(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/tests.cpp b/tests/tests.cpp index 8e458819..c196fea9 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -14,17 +14,23 @@ #include "test_list.hpp" #include "test_literal.hpp" #include "test_map.hpp" +#include "test_multimap.hpp" +#include "test_multiset.hpp" #include "test_optional_fields.hpp" #include "test_readme_example.hpp" #include "test_ref.hpp" #include "test_replace.hpp" #include "test_replace_flatten.hpp" #include "test_replace_with_other_struct.hpp" +#include "test_set.hpp" #include "test_tagged_union.hpp" #include "test_timestamp.hpp" #include "test_unique_ptr.hpp" #include "test_unique_ptr2.hpp" #include "test_unordered_map.hpp" +#include "test_unordered_multimap.hpp" +#include "test_unordered_multiset.hpp" +#include "test_unordered_set.hpp" #include "test_variant.hpp" int main() { @@ -47,6 +53,12 @@ int main() { test_list(); test_map(); test_unordered_map(); + test_set(); + test_unordered_set(); + test_multimap(); + test_unordered_multimap(); + test_multiset(); + test_unordered_multiset(); test_custom_class1(); test_custom_class2(); From 94b8ab368be1f2fe29771c621750ff6a629c0726 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Tue, 10 Oct 2023 23:14:25 +0200 Subject: [PATCH 07/48] Added tests for string map and string unordered map --- include/rfl/parsing/Parser.hpp | 43 ++++++++++++++++++----------- tests/test_string_map.hpp | 20 ++++++++++++++ tests/test_string_unordered_map.hpp | 25 +++++++++++++++++ tests/tests.cpp | 4 +++ 4 files changed, 76 insertions(+), 16 deletions(-) create mode 100644 tests/test_string_map.hpp create mode 100644 tests/test_string_unordered_map.hpp diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 1d84a2db..081ae0f4 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -272,8 +272,10 @@ struct Parser> { // ---------------------------------------------------------------------------- -template -struct Parser> { +/// Used for maps for which the key type is std::string. These are represented +/// as objects. +template +struct MapParser { public: using InputObjectType = typename ReaderType::InputObjectType; using InputVarType = typename ReaderType::InputVarType; @@ -281,12 +283,13 @@ struct Parser> { using OutputObjectType = typename WriterType::OutputObjectType; using OutputVarType = typename WriterType::OutputVarType; - /// Expresses the variables as a std::map. - static Result> read( - const ReaderType& _r, InputVarType* _var) noexcept { + using ValueType = std::decay_t; + + static Result read(const ReaderType& _r, + InputVarType* _var) noexcept { const auto get_pair = [&](auto _pair) { - const auto to_pair = [&](const ValueType& _val) { - return std::make_pair(_pair.first, _val); + const auto to_pair = [&](ValueType&& _val) { + return std::make_pair(_pair.first, std::move(_val)); }; return Parser>::read(_r, &_pair.second) @@ -294,25 +297,24 @@ struct Parser> { .value(); }; - const auto to_map = [&_r, get_pair](auto _obj) { - using namespace std::ranges::views; + const auto to_map = [&_r, get_pair](auto _obj) -> Result { auto m = _r.to_map(&_obj); - auto range = m | transform(get_pair); + MapType res; try { - return std::map(range.begin(), - range.end()); + for (const auto& p : m) { + res.insert(get_pair(p)); + } } catch (std::exception& e) { return Error(e.what()); } + return res; }; return _r.to_object(_var).and_then(to_map); } - /// Transform a std::map into an object - static OutputVarType write( - const WriterType& _w, - const std::map& _m) noexcept { + static OutputVarType write(const WriterType& _w, + const MapType& _m) noexcept { auto obj = _w.new_object(); for (const auto& [k, v] : _m) { _w.set_field( @@ -325,6 +327,15 @@ struct Parser> { } }; +template +struct Parser> + : public MapParser> {}; + +template +struct Parser> + : public MapParser> {}; + // ---------------------------------------------------------------------------- template diff --git a/tests/test_string_map.hpp b/tests/test_string_map.hpp new file mode 100644 index 00000000..b06cabf8 --- /dev/null +++ b/tests/test_string_map.hpp @@ -0,0 +1,20 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_string_map() { + std::cout << "test_string_map" << std::endl; + + std::map> homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + write_and_read(homer, R"({"firstName":"Homer","lastName":"Simpson"})"); +} diff --git a/tests/test_string_unordered_map.hpp b/tests/test_string_unordered_map.hpp new file mode 100644 index 00000000..54238ec2 --- /dev/null +++ b/tests/test_string_unordered_map.hpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_string_unordered_map() { + std::cout << "test_string_unordered_map" << std::endl; + + using Map = std::unordered_map>; + Map homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + // Unordered maps are unpredictable. We therefore only make sure that this + // compiles. + const auto json_string = rfl::json::write(homer); + const auto homer2 = rfl::json::read(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/tests.cpp b/tests/tests.cpp index c196fea9..6f6afdd6 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -23,6 +23,8 @@ #include "test_replace_flatten.hpp" #include "test_replace_with_other_struct.hpp" #include "test_set.hpp" +#include "test_string_map.hpp" +#include "test_string_unordered_map.hpp" #include "test_tagged_union.hpp" #include "test_timestamp.hpp" #include "test_unique_ptr.hpp" @@ -59,6 +61,8 @@ int main() { test_unordered_multimap(); test_multiset(); test_unordered_multiset(); + test_string_map(); + test_string_unordered_map(); test_custom_class1(); test_custom_class2(); From 6715854d1a43425521f80fed0a9ec516860573f3 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Tue, 10 Oct 2023 23:17:11 +0200 Subject: [PATCH 08/48] Updated list of containers --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a291ed83..59fb3049 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,9 @@ reflect-cpp supports the following containers from the C++ standard library: - `std::array` - `std::deque` - `std::forward_list` -- `std::map` +- `std::map` +- `std::multimap` +- `std::multiset` - `std::list` - `std::optional` - `std::pair` @@ -110,7 +112,9 @@ reflect-cpp supports the following containers from the C++ standard library: - `std::string` - `std::tuple` - `std::unique_ptr` -- `std::unordered_map` +- `std::unordered_map` +- `std::unordered_multimap` +- `std::unordered_multiset` - `std::unordered_set` - `std::variant` - `std::vector` From 88a010c4f1aba1f8a04474747d1b3f94bf68727e Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 11 Oct 2023 00:01:09 +0200 Subject: [PATCH 09/48] Create standard_containers.md --- docs/standard_containers.md | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 docs/standard_containers.md diff --git a/docs/standard_containers.md b/docs/standard_containers.md new file mode 100644 index 00000000..bd8bb819 --- /dev/null +++ b/docs/standard_containers.md @@ -0,0 +1,41 @@ +# Support for standard containers + +The serialization and deserialization of containers is handled as follows: + +`std::map` and `std::unordered_map` are treated +as objects. + +Consider the following map: + +```cpp +std::map homer; +homer["firstName"] = "Homer"; +homer["lastName"] = "Simpson"; +``` + +This will be represented as follows: + +```json +{"firstName":"Homer","lastName":"Simpson"} +``` + +All other supported standard containers +(other than `std::variant`, `std::optional`, `std::unique_ptr` and `std::shared_ptr`) +will be represented as arrays. Containers for which the `value_type` +is a key-value-pair, will be represented as arrays of pairs. + +Consider the following map: + +```cpp +std::map children; +children[1] = Person{.first_name = "Bart", .last_name = "Simpson"}; +children[2] = Person{.first_name = "Lisa", .last_name = "Simpson"}; +children[3] = Person{.first_name = "Maggie", .last_name = "Simpson"}; +``` + +This will be represented as follows: + +```json +[[1,{"firstName":"Bart","lastName":"Simpson"}],[2,{"firstName":"Lisa","lastName":"Simpson"}],[3,{"firstName":"Maggie","lastName":"Simpson"}]] +``` + From 8909b6411318621f49efb1a612795afbcd4ba76b Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 11 Oct 2023 00:02:05 +0200 Subject: [PATCH 10/48] Update README.md --- docs/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/README.md b/docs/README.md index 649a67f6..5849f23d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,6 +18,8 @@ 1.7) [rfl::Timestamp](https://github.com/getml/reflect-cpp/blob/main/docs/timestamps.md) - For serializing and deserializing timestamps. +1.8) [Standard containers](https://github.com/getml/reflect-cpp/blob/main/docs/standard_containers.md) - Describes how reflect-cpp treats containers in the standard library. + ## 2) Custom classes 2.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields. From 823f796519616c24705ec53d89f0511a65b5d038 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Wed, 11 Oct 2023 21:49:50 +0200 Subject: [PATCH 11/48] Added move constructor for different type to result --- include/rfl/Result.hpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 9400e20e..9e84d24f 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -45,6 +45,14 @@ class Result { Result(Error&& _err) noexcept : t_or_err_(std::move(_err)) {} + template , + bool>::type = true> + Result(Result&& _other) + : t_or_err_( + std::forward>(_other) + .transform([](U&& _u) { return T(std::forward(_u)); }) + .t_or_err_) {} + template , bool>::type = true> Result(const Result& _other) From 3db0bbb065519ace692b9e7066baa24e8340b5e8 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Wed, 11 Oct 2023 21:50:05 +0200 Subject: [PATCH 12/48] Build NamedTuple non-recursively --- include/rfl/parsing/Parser.hpp | 65 ++++++++++++++++------------------ 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 081ae0f4..0a1c5a90 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -352,7 +352,7 @@ struct Parser> { InputVarType* _var) noexcept { const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; const auto build = [&](auto _map) { - return build_named_tuple_recursively(_r, _map); + return build_named_tuple(_r, _map); }; return _r.to_object(_var).transform(to_map).and_then(build); } @@ -368,42 +368,39 @@ struct Parser> { private: /// Builds the named tuple field by field. template - static Result> build_named_tuple_recursively( - const ReaderType& _r, const std::map& _map, - Args&&... _args) noexcept { - const auto size = sizeof...(Args); - - if constexpr (size == sizeof...(FieldTypes)) { - return NamedTuple(std::move(_args)...); - } else { - using FieldType = typename std::tuple_element< - size, typename NamedTuple::Fields>::type; - - using ValueType = std::decay_t; - - const auto key = FieldType::name_.str(); - - const auto it = _map.find(key); - - if (it == _map.end()) { - if constexpr (is_required()) { - return Error("Field named '" + key + "' not found!"); - } else { - return build_named_tuple_recursively( - _r, _map, std::move(_args)..., FieldType(ValueType())); - } - } - - const auto build = [&](auto&& _value) { - return build_named_tuple_recursively( - _r, _map, std::move(_args)..., - FieldType(std::move(_value))); - }; - - return get_value(_r, *it).and_then(build); + static Result> build_named_tuple( + const ReaderType& _r, + const std::map& _map) noexcept { + try { + return NamedTuple( + build_one_field(_r, _map).value()...); + } catch (std::exception& e) { + return Error(e.what()); } } + /// Builds a single field for the named tuple. + template + static Result build_one_field( + const ReaderType& _r, + const std::map& _map) noexcept { + using ValueType = std::decay_t; + + const auto key = FieldType::name_.str(); + + const auto it = _map.find(key); + + if (it == _map.end()) { + if constexpr (is_required()) { + return Error("Field named '" + key + "' not found!"); + } else { + return FieldType(ValueType()); + } + } + + return get_value(_r, *it); + } + /// Builds the object field by field. template static void build_object_recursively(const WriterType& _w, From 7129e5a2ce56b3a18fdd60e6045efbc73c762838 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Wed, 11 Oct 2023 21:54:05 +0200 Subject: [PATCH 13/48] Revert "Build NamedTuple non-recursively" This reverts commit 3db0bbb065519ace692b9e7066baa24e8340b5e8. --- include/rfl/parsing/Parser.hpp | 55 ++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 0a1c5a90..081ae0f4 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -352,7 +352,7 @@ struct Parser> { InputVarType* _var) noexcept { const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; const auto build = [&](auto _map) { - return build_named_tuple(_r, _map); + return build_named_tuple_recursively(_r, _map); }; return _r.to_object(_var).transform(to_map).and_then(build); } @@ -368,37 +368,40 @@ struct Parser> { private: /// Builds the named tuple field by field. template - static Result> build_named_tuple( - const ReaderType& _r, - const std::map& _map) noexcept { - try { - return NamedTuple( - build_one_field(_r, _map).value()...); - } catch (std::exception& e) { - return Error(e.what()); - } - } + static Result> build_named_tuple_recursively( + const ReaderType& _r, const std::map& _map, + Args&&... _args) noexcept { + const auto size = sizeof...(Args); - /// Builds a single field for the named tuple. - template - static Result build_one_field( - const ReaderType& _r, - const std::map& _map) noexcept { - using ValueType = std::decay_t; + if constexpr (size == sizeof...(FieldTypes)) { + return NamedTuple(std::move(_args)...); + } else { + using FieldType = typename std::tuple_element< + size, typename NamedTuple::Fields>::type; - const auto key = FieldType::name_.str(); + using ValueType = std::decay_t; - const auto it = _map.find(key); + const auto key = FieldType::name_.str(); - if (it == _map.end()) { - if constexpr (is_required()) { - return Error("Field named '" + key + "' not found!"); - } else { - return FieldType(ValueType()); + const auto it = _map.find(key); + + if (it == _map.end()) { + if constexpr (is_required()) { + return Error("Field named '" + key + "' not found!"); + } else { + return build_named_tuple_recursively( + _r, _map, std::move(_args)..., FieldType(ValueType())); + } } - } - return get_value(_r, *it); + const auto build = [&](auto&& _value) { + return build_named_tuple_recursively( + _r, _map, std::move(_args)..., + FieldType(std::move(_value))); + }; + + return get_value(_r, *it).and_then(build); + } } /// Builds the object field by field. From 19b8130ad709741ef394752e52d948722bc774a5 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Thu, 12 Oct 2023 17:36:53 +0200 Subject: [PATCH 14/48] Fixed typo --- docs/custom_parser.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/custom_parser.md b/docs/custom_parser.md index 83f1a1c2..1a045a12 100644 --- a/docs/custom_parser.md +++ b/docs/custom_parser.md @@ -96,7 +96,7 @@ const auto people = rfl::json::read>(json_str).value(); ``` As we have noted, in this particular example, the `Person` class can be constructed from the field values in -`PersonImpl` in the exact same order they were declaced in `PersonImpl`. So we can drop the `.to_class` method: +`PersonImpl` in the exact same order they were declared in `PersonImpl`. So we can drop the `.to_class` method: ```cpp struct PersonImpl { From f267bfa1542e394e194b2aa82a3f324fdfcd446e Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 14 Oct 2023 00:04:17 +0200 Subject: [PATCH 15/48] Added load and save --- include/rfl/json.hpp | 2 ++ include/rfl/json/load.hpp | 31 +++++++++++++++++++++++++++++++ include/rfl/json/save.hpp | 30 ++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 include/rfl/json/load.hpp create mode 100644 include/rfl/json/save.hpp diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index 9dce6813..bc8cec2a 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -4,7 +4,9 @@ #include "rfl/json/Parser.hpp" #include "rfl/json/Reader.hpp" #include "rfl/json/Writer.hpp" +#include "rfl/json/load.hpp" #include "rfl/json/read.hpp" +#include "rfl/json/save.hpp" #include "rfl/json/write.hpp" #endif diff --git a/include/rfl/json/load.hpp b/include/rfl/json/load.hpp new file mode 100644 index 00000000..a0813c07 --- /dev/null +++ b/include/rfl/json/load.hpp @@ -0,0 +1,31 @@ +#ifndef RFL_JSON_LOAD_HPP_ +#define RFL_JSON_LOAD_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/json/read.hpp" + +namespace rfl { +namespace json { + +template +Result load(const std::string& _fname) { + std::ifstream infile(_fname); + if (infile.is_open()) { + auto r = read(std::string(std::istreambuf_iterator(infile), + std::istreambuf_iterator())); + infile.close(); + return r; + } else { + return Error("Unable to open file '" + _fname + + "' or file could not be found."); + } +} + +} // namespace json +} // namespace rfl + +#endif diff --git a/include/rfl/json/save.hpp b/include/rfl/json/save.hpp new file mode 100644 index 00000000..4dfb77f6 --- /dev/null +++ b/include/rfl/json/save.hpp @@ -0,0 +1,30 @@ +#ifndef RFL_JSON_SAVE_HPP_ +#define RFL_JSON_SAVE_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/json/write.hpp" + +namespace rfl { +namespace json { + +template +Result save(const std::string& _fname, const T& _obj) { + try { + std::ofstream outfile; + outfile.open(_fname); + outfile << write(_obj); + outfile.close(); + } catch (std::exception& e) { + return Error(e.what()); + } + return Nothing{}; +} + +} // namespace json +} // namespace rfl + +#endif From a0d17bd3c59b9cb523dcf2b40209733233633d03 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 14 Oct 2023 18:59:54 +0200 Subject: [PATCH 16/48] load_string and save_string in separate files --- include/rfl/io/load_string.hpp | 29 +++++++++++++++++++++++++++++ include/rfl/io/save_string.hpp | 29 +++++++++++++++++++++++++++++ include/rfl/json/load.hpp | 16 ++-------------- include/rfl/json/save.hpp | 11 ++--------- 4 files changed, 62 insertions(+), 23 deletions(-) create mode 100644 include/rfl/io/load_string.hpp create mode 100644 include/rfl/io/save_string.hpp diff --git a/include/rfl/io/load_string.hpp b/include/rfl/io/load_string.hpp new file mode 100644 index 00000000..4a8c28d0 --- /dev/null +++ b/include/rfl/io/load_string.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_IO_LOAD_STRING_HPP_ +#define RFL_IO_LOAD_STRING_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace io { + +Result load_string(const std::string& _fname) { + std::ifstream infile(_fname); + if (infile.is_open()) { + auto r = std::string(std::istreambuf_iterator(infile), + std::istreambuf_iterator()); + infile.close(); + return r; + } else { + return Error("Unable to open file '" + _fname + + "' or file could not be found."); + } +} + +} // namespace io +} // namespace rfl + +#endif diff --git a/include/rfl/io/save_string.hpp b/include/rfl/io/save_string.hpp new file mode 100644 index 00000000..dcef60ed --- /dev/null +++ b/include/rfl/io/save_string.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_IO_SAVE_STRING_HPP_ +#define RFL_IO_SAVE_STRING_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace io { + +Result save_string(const std::string& _fname, + const std::string& _str) { + try { + std::ofstream outfile; + outfile.open(_fname); + outfile << _str; + outfile.close(); + } catch (std::exception& e) { + return Error(e.what()); + } + return Nothing{}; +} + +} // namespace io +} // namespace rfl + +#endif diff --git a/include/rfl/json/load.hpp b/include/rfl/json/load.hpp index a0813c07..2f34febf 100644 --- a/include/rfl/json/load.hpp +++ b/include/rfl/json/load.hpp @@ -1,11 +1,8 @@ #ifndef RFL_JSON_LOAD_HPP_ #define RFL_JSON_LOAD_HPP_ -#include -#include -#include - #include "rfl/Result.hpp" +#include "rfl/io/load_string.hpp" #include "rfl/json/read.hpp" namespace rfl { @@ -13,16 +10,7 @@ namespace json { template Result load(const std::string& _fname) { - std::ifstream infile(_fname); - if (infile.is_open()) { - auto r = read(std::string(std::istreambuf_iterator(infile), - std::istreambuf_iterator())); - infile.close(); - return r; - } else { - return Error("Unable to open file '" + _fname + - "' or file could not be found."); - } + return rfl::io::load_string(_fname).and_then(read); } } // namespace json diff --git a/include/rfl/json/save.hpp b/include/rfl/json/save.hpp index 4dfb77f6..614f3917 100644 --- a/include/rfl/json/save.hpp +++ b/include/rfl/json/save.hpp @@ -6,6 +6,7 @@ #include #include "rfl/Result.hpp" +#include "rfl/io/save_string.hpp" #include "rfl/json/write.hpp" namespace rfl { @@ -13,15 +14,7 @@ namespace json { template Result save(const std::string& _fname, const T& _obj) { - try { - std::ofstream outfile; - outfile.open(_fname); - outfile << write(_obj); - outfile.close(); - } catch (std::exception& e) { - return Error(e.what()); - } - return Nothing{}; + return rfl::io::save_string(write(_obj)); } } // namespace json From f34bdd76b96d5f42a4183d30f31e75c26d7e3b3d Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 14 Oct 2023 20:35:59 +0200 Subject: [PATCH 17/48] Optimized the reading of the named tuples using field indices --- include/rfl/json/Reader.hpp | 18 +++++++++ include/rfl/parsing/Parser.hpp | 71 +++++++++++++++++++++++++--------- 2 files changed, 70 insertions(+), 19 deletions(-) diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index 03fd8bfe..fcbc6a8f 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -5,11 +5,13 @@ #include #include +#include #include #include #include #include #include +#include #include #include "rfl/Result.hpp" @@ -100,6 +102,22 @@ struct Reader { return InputArrayType(_var->val_); } + std::vector> to_fields_vec( + const std::unordered_map& _field_indices, + InputObjectType* _obj) const noexcept { + std::vector> f_vec(_field_indices.size()); + yyjson_obj_iter iter; + yyjson_obj_iter_init(_obj->val_, &iter); + yyjson_val* key; + while ((key = yyjson_obj_iter_next(&iter))) { + const auto it = _field_indices.find(yyjson_get_str(key)); + if (it != _field_indices.end()) { + f_vec[it->second] = InputVarType(yyjson_obj_iter_get_val(key)); + } + } + return f_vec; + } + std::map to_map( InputObjectType* _obj) const noexcept { std::map m; diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 081ae0f4..75ec9afa 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -350,11 +350,13 @@ struct Parser> { /// Generates a NamedTuple from a JSON Object. static Result> read(const ReaderType& _r, InputVarType* _var) noexcept { - const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; - const auto build = [&](auto _map) { - return build_named_tuple_recursively(_r, _map); + const auto to_fields_vec = [&](auto _obj) { + return _r.to_fields_vec(field_indices(), &_obj); }; - return _r.to_object(_var).transform(to_map).and_then(build); + const auto build = [&](auto _fields_vec) { + return build_named_tuple_recursively(_r, _fields_vec); + }; + return _r.to_object(_var).transform(to_fields_vec).and_then(build); } /// Transforms a NamedTuple into a JSON object. @@ -369,7 +371,8 @@ struct Parser> { /// Builds the named tuple field by field. template static Result> build_named_tuple_recursively( - const ReaderType& _r, const std::map& _map, + const ReaderType& _r, + const std::vector>& _fields_vec, Args&&... _args) noexcept { const auto size = sizeof...(Args); @@ -381,26 +384,26 @@ struct Parser> { using ValueType = std::decay_t; - const auto key = FieldType::name_.str(); + const auto& f = _fields_vec[size]; - const auto it = _map.find(key); - - if (it == _map.end()) { + if (!f) { if constexpr (is_required()) { + const auto key = FieldType::name_.str(); return Error("Field named '" + key + "' not found!"); } else { return build_named_tuple_recursively( - _r, _map, std::move(_args)..., FieldType(ValueType())); + _r, _fields_vec, std::move(_args)..., + FieldType(ValueType())); } } const auto build = [&](auto&& _value) { return build_named_tuple_recursively( - _r, _map, std::move(_args)..., + _r, _fields_vec, std::move(_args)..., FieldType(std::move(_value))); }; - return get_value(_r, *it).and_then(build); + return get_value(_r, *f).and_then(build); } } @@ -430,19 +433,49 @@ struct Parser> { } } + /// Uses a memoization pattern to retrieve the field indices. + /// There are some objects that we are likely to parse many times, + /// so we only calculate these indices once. + static const auto& field_indices() noexcept { + if (field_indices_.size() == 0) { + set_field_indices(); + } + return Parser>::field_indices_; + } + /// Retrieves the value from the object. This is mainly needed to generate a /// better error message. - template - static auto get_value(const ReaderType& _r, - std::pair _pair) noexcept { + template + static auto get_value(const ReaderType& _r, InputVarType _var) noexcept { const auto embellish_error = [&](const Error& _e) { - return Error("Failed to parse field '" + _pair.first + - "': " + _e.what()); + const auto key = FieldType::name_.str(); + return Error("Failed to parse field '" + key + "': " + _e.what()); }; - return Parser::read(_r, - &_pair.second) + using ValueType = std::decay_t; + return Parser::read(_r, &_var) .or_else(embellish_error); } + + /// Builds the object field by field. + template + static void set_field_indices() noexcept { + if constexpr (_i >= sizeof...(FieldTypes)) { + return; + } else { + using FieldType = + typename std::tuple_element<_i, + std::tuple>::type; + const auto name = FieldType::name_.str(); + Parser>::field_indices_[name] = _i; + set_field_indices<_i + 1>(); + } + } + + private: + /// Maps each of the field names to an index signifying their order. + static inline std::unordered_map field_indices_; }; // ---------------------------------------------------------------------------- From 383dde14f502f599b158fc3e4e61266370f0be13 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sun, 15 Oct 2023 13:45:07 +0200 Subject: [PATCH 18/48] Use string_view to compare the fields --- include/rfl/internal/StringLiteral.hpp | 5 +++++ include/rfl/json/Reader.hpp | 5 +++-- include/rfl/parsing/Parser.hpp | 5 +++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/include/rfl/internal/StringLiteral.hpp b/include/rfl/internal/StringLiteral.hpp index daa7a046..c5cfc7b2 100644 --- a/include/rfl/internal/StringLiteral.hpp +++ b/include/rfl/internal/StringLiteral.hpp @@ -21,6 +21,11 @@ struct StringLiteral { /// Returns the value as a string. std::string str() const { return std::string(value_); } + + /// Returns the value as a string. + std::string_view string_view() const { + return std::string_view(value_, N - 1); + } }; template diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index fcbc6a8f..cb9b0484 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -103,14 +103,15 @@ struct Reader { } std::vector> to_fields_vec( - const std::unordered_map& _field_indices, + const std::unordered_map& _field_indices, InputObjectType* _obj) const noexcept { std::vector> f_vec(_field_indices.size()); yyjson_obj_iter iter; yyjson_obj_iter_init(_obj->val_, &iter); yyjson_val* key; while ((key = yyjson_obj_iter_next(&iter))) { - const auto it = _field_indices.find(yyjson_get_str(key)); + const char* k = yyjson_get_str(key); + const auto it = _field_indices.find(std::string_view(k, strlen(k))); if (it != _field_indices.end()) { f_vec[it->second] = InputVarType(yyjson_obj_iter_get_val(key)); } diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 75ec9afa..fd07516d 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -466,7 +467,7 @@ struct Parser> { using FieldType = typename std::tuple_element<_i, std::tuple>::type; - const auto name = FieldType::name_.str(); + const auto name = FieldType::name_.string_view(); Parser>::field_indices_[name] = _i; set_field_indices<_i + 1>(); @@ -475,7 +476,7 @@ struct Parser> { private: /// Maps each of the field names to an index signifying their order. - static inline std::unordered_map field_indices_; + static inline std::unordered_map field_indices_; }; // ---------------------------------------------------------------------------- From 4c020e7e82d29276044d7cdfb3b9972ff564f0c6 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sun, 15 Oct 2023 14:29:41 +0200 Subject: [PATCH 19/48] Using std::array instead of std::vector for retrieving the fields --- include/rfl/json/Reader.hpp | 10 ++++++---- include/rfl/parsing/Parser.hpp | 18 ++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index cb9b0484..c3096789 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -3,6 +3,7 @@ #include +#include #include #include #include @@ -102,10 +103,11 @@ struct Reader { return InputArrayType(_var->val_); } - std::vector> to_fields_vec( + template + std::array, size> to_fields_array( const std::unordered_map& _field_indices, InputObjectType* _obj) const noexcept { - std::vector> f_vec(_field_indices.size()); + std::array, size> f_arr; yyjson_obj_iter iter; yyjson_obj_iter_init(_obj->val_, &iter); yyjson_val* key; @@ -113,10 +115,10 @@ struct Reader { const char* k = yyjson_get_str(key); const auto it = _field_indices.find(std::string_view(k, strlen(k))); if (it != _field_indices.end()) { - f_vec[it->second] = InputVarType(yyjson_obj_iter_get_val(key)); + f_arr[it->second] = InputVarType(yyjson_obj_iter_get_val(key)); } } - return f_vec; + return f_arr; } std::map to_map( diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index fd07516d..e8dc0bcb 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -351,13 +351,14 @@ struct Parser> { /// Generates a NamedTuple from a JSON Object. static Result> read(const ReaderType& _r, InputVarType* _var) noexcept { - const auto to_fields_vec = [&](auto _obj) { - return _r.to_fields_vec(field_indices(), &_obj); + const auto to_fields_array = [&](auto _obj) { + return _r.template to_fields_array( + field_indices(), &_obj); }; const auto build = [&](auto _fields_vec) { return build_named_tuple_recursively(_r, _fields_vec); }; - return _r.to_object(_var).transform(to_fields_vec).and_then(build); + return _r.to_object(_var).transform(to_fields_array).and_then(build); } /// Transforms a NamedTuple into a JSON object. @@ -373,19 +374,20 @@ struct Parser> { template static Result> build_named_tuple_recursively( const ReaderType& _r, - const std::vector>& _fields_vec, + const std::array, sizeof...(FieldTypes)>& + _fields_vec, Args&&... _args) noexcept { - const auto size = sizeof...(Args); + constexpr auto i = sizeof...(Args); - if constexpr (size == sizeof...(FieldTypes)) { + if constexpr (i == sizeof...(FieldTypes)) { return NamedTuple(std::move(_args)...); } else { using FieldType = typename std::tuple_element< - size, typename NamedTuple::Fields>::type; + i, typename NamedTuple::Fields>::type; using ValueType = std::decay_t; - const auto& f = _fields_vec[size]; + const auto& f = std::get(_fields_vec); if (!f) { if constexpr (is_required()) { From 013708b77cb346070237ff33083fec8dae2b23dd Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sun, 15 Oct 2023 17:58:37 +0200 Subject: [PATCH 20/48] Removed unnecessary boilerplate code --- include/rfl/Box.hpp | 19 +++++------ include/rfl/Field.hpp | 45 ++++++++++---------------- include/rfl/Flatten.hpp | 40 +++++++++-------------- include/rfl/Literal.hpp | 63 ++++++++++++++----------------------- include/rfl/NamedTuple.hpp | 37 +++++++--------------- include/rfl/Ref.hpp | 26 +++++---------- include/rfl/Result.hpp | 16 ++-------- include/rfl/TaggedUnion.hpp | 40 +++++++++-------------- 8 files changed, 97 insertions(+), 189 deletions(-) diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index bb628334..dd107edd 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -20,32 +20,27 @@ class Box { Box(const Box& _other) = delete; - Box(Box&& _other) : ptr_(std::move(_other.ptr_)) {} + Box(Box&& _other) = default; ~Box() = default; /// Returns a pointer to the underlying object - inline T* get() const { return ptr_.get(); } + T* get() const { return ptr_.get(); } /// Copy assignment operator - inline Box& operator=(const Box& _other) = delete; + Box& operator=(const Box& _other) = delete; /// Move assignment operator - inline Box& operator=(Box&& _other) noexcept { - if (&_other != this) { - ptr_ = std::move(_other.ptr_); - } - return *this; - } + Box& operator=(Box&& _other) noexcept = default; /// Returns the underlying object. - inline T& operator*() const { return *ptr_; } + T& operator*() const { return *ptr_; } /// Returns the underlying object. - inline T* operator->() const { return ptr_.get(); } + T* operator->() const { return ptr_.get(); } /// Returns the underlying unique_ptr - inline const std::unique_ptr& ptr() const { return ptr_; } + const std::unique_ptr& ptr() const { return ptr_; } private: /// Only make is allowed to use this constructor. diff --git a/include/rfl/Field.hpp b/include/rfl/Field.hpp index 2a19a923..77249f76 100644 --- a/include/rfl/Field.hpp +++ b/include/rfl/Field.hpp @@ -26,10 +26,9 @@ struct Field { Field(Type&& _value) noexcept : value_(std::move(_value)) {} - Field(Field<_name, _Type>&& _field) noexcept - : value_(std::move(_field.value_)) {} + Field(Field<_name, _Type>&& _field) noexcept = default; - Field(const Field<_name, Type>& _field) : value_(_field.get()) {} + Field(const Field<_name, Type>& _field) = default; template Field(const Field<_name, T>& _field) : value_(_field.get()) {} @@ -61,22 +60,22 @@ struct Field { constexpr static const internal::StringLiteral name_ = _name; /// Returns the underlying object. - inline const Type& get() const { return value_; } + const Type& get() const { return value_; } /// Returns the underlying object. - inline Type& operator()() { return value_; } + Type& operator()() { return value_; } /// Returns the underlying object. - inline const Type& operator()() const { return value_; } + const Type& operator()() const { return value_; } /// Assigns the underlying object. - inline auto& operator=(const Type& _value) { + auto& operator=(const Type& _value) { value_ = _value; return *this; } /// Assigns the underlying object. - inline auto& operator=(Type&& _value) noexcept { + auto& operator=(Type&& _value) noexcept { value_ = std::move(_value); return *this; } @@ -84,7 +83,7 @@ struct Field { /// Assigns the underlying object. template , bool>::type = true> - inline auto& operator=(const T& _value) { + auto& operator=(const T& _value) { value_ = _value; return *this; } @@ -93,51 +92,41 @@ struct Field { template , bool>::type = true> - inline auto& operator=(const Default& _default) { + auto& operator=(const Default& _default) { value_ = Type(); return *this; } /// Assigns the underlying object. - inline Field<_name, _Type>& operator=(const Field<_name, _Type>& _field) { - if (&_field != this) { - value_ = _field.get(); - } - return *this; - } + Field<_name, _Type>& operator=(const Field<_name, _Type>& _field) = default; /// Assigns the underlying object. - inline Field<_name, _Type>& operator=(Field<_name, _Type>&& _field) { - if (&_field != this) { - value_ = std::move(_field.value_); - } - return *this; - } + Field<_name, _Type>& operator=(Field<_name, _Type>&& _field) = default; /// Assigns the underlying object. template - inline auto& operator=(const Field<_name, T>& _field) { + auto& operator=(const Field<_name, T>& _field) { value_ = _field.get(); return *this; } /// Assigns the underlying object. template - inline auto& operator=(Field<_name, T>&& _field) { + auto& operator=(Field<_name, T>&& _field) { value_ = std::forward(_field.value_); return *this; } /// Assigns the underlying object. - inline void set(const Type& _value) { value_ = _value; } + void set(const Type& _value) { value_ = _value; } /// Assigns the underlying object. - inline void set(Type&& _value) { value_ = std::move(_value); } + void set(Type&& _value) { value_ = std::move(_value); } /// Returns the underlying object. - inline Type& value() { return value_; } + Type& value() { return value_; } /// Returns the underlying object. - inline const Type& value() const { return value_; } + const Type& value() const { return value_; } /// The underlying value. Type value_; diff --git a/include/rfl/Flatten.hpp b/include/rfl/Flatten.hpp index ca13d944..5d7028e8 100644 --- a/include/rfl/Flatten.hpp +++ b/include/rfl/Flatten.hpp @@ -19,10 +19,9 @@ struct Flatten { Flatten(Type&& _value) noexcept : value_(std::forward(_value)) {} - Flatten(const Flatten<_Type>& _f) : value_(_f.get()) {} + Flatten(const Flatten<_Type>& _f) = default; - Flatten(Flatten<_Type>&& _f) noexcept - : value_(std::forward(_f.value_)) {} + Flatten(Flatten<_Type>&& _f) noexcept = default; template Flatten(const Flatten& _f) : value_(_f.get()) {} @@ -41,22 +40,22 @@ struct Flatten { ~Flatten() = default; /// Returns the underlying object. - inline const Type& get() const { return value_; } + const Type& get() const { return value_; } /// Returns the underlying object. - inline Type& operator()() { return value_; } + Type& operator()() { return value_; } /// Returns the underlying object. - inline const Type& operator()() const { return value_; } + const Type& operator()() const { return value_; } /// Assigns the underlying object. - inline Flatten<_Type>& operator=(const _Type& _value) { + Flatten<_Type>& operator=(const _Type& _value) { value_ = _value; return *this; } /// Assigns the underlying object. - inline Flatten<_Type>& operator=(_Type&& _value) { + Flatten<_Type>& operator=(_Type&& _value) { value_ = std::forward(_value); return *this; } @@ -64,46 +63,35 @@ struct Flatten { /// Assigns the underlying object. template , bool>::type = true> - inline Flatten<_Type>& operator=(const T& _value) { + Flatten<_Type>& operator=(const T& _value) { value_ = _value; return *this; } /// Assigns the underlying object. - inline Flatten<_Type>& operator=(const Flatten<_Type>& _f) { - if (&_f != this) { - value_ = _f.get(); - } - return *this; - } + Flatten<_Type>& operator=(const Flatten<_Type>& _f) = default; /// Assigns the underlying object. - inline Flatten<_Type>& operator=(Flatten<_Type>&& _f) { - if (&_f != this) { - value_ = std::move(_f.value_); - } - return *this; - } - + Flatten<_Type>& operator=(Flatten<_Type>&& _f) = default; /// Assigns the underlying object. template - inline Flatten<_Type>& operator=(const Flatten& _f) { + Flatten<_Type>& operator=(const Flatten& _f) { value_ = _f.get(); return *this; } /// Assigns the underlying object. template - inline Flatten<_Type>& operator=(Flatten&& _f) { + Flatten<_Type>& operator=(Flatten&& _f) { value_ = std::forward(_f); return *this; } /// Assigns the underlying object. - inline void set(const Type& _value) { value_ = _value; } + void set(const Type& _value) { value_ = _value; } /// Assigns the underlying object. - inline void set(Type&& _value) { value_ = std::forward(_value); } + void set(Type&& _value) { value_ = std::forward(_value); } /// The underlying value. Type value_; diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index f1019fd5..9661f3f5 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -34,10 +34,10 @@ class Literal { static constexpr ValueType num_fields_ = sizeof...(fields_); /// Constructs a Literal from another literal. - Literal(const Literal& _other) : value_(_other.value_) {} + Literal(const Literal& _other) = default; /// Constructs a Literal from another literal. - Literal(Literal&& _other) noexcept : value_(_other.value_) {} + Literal(Literal&& _other) noexcept = default; /// A single-field literal is special because it /// can also have a default constructor. @@ -48,20 +48,18 @@ class Literal { ~Literal() = default; /// Determines whether the literal contains the string. - inline static bool contains(const std::string& _str) { - return has_value(_str); - } + static bool contains(const std::string& _str) { return has_value(_str); } /// Determines whether the literal contains the string at compile time. template - inline static constexpr bool contains() { + static constexpr bool contains() { return find_value_of<_name>() != -1; } /// Determines whether the literal contains any of the strings in the other /// literal at compile time. template - inline static constexpr bool contains_any() { + static constexpr bool contains_any() { if constexpr (_i == num_fields_) { return false; } else { @@ -74,7 +72,7 @@ class Literal { /// Determines whether the literal contains all of the strings in the other /// literal at compile time. template - inline static constexpr bool contains_all() { + static constexpr bool contains_all() { if constexpr (_i == num_fields_) { return _n_found == OtherLiteralType::num_fields_; } else { @@ -89,9 +87,7 @@ class Literal { /// Determines whether the literal has duplicate strings at compile time. /// These is useful for checking collections of strings in other contexts. - inline static constexpr bool has_duplicates() { - return has_duplicate_strings(); - } + static constexpr bool has_duplicates() { return has_duplicate_strings(); } /// Constructs a Literal from a string. Returns an error if the string /// cannot be found. @@ -113,26 +109,17 @@ class Literal { /// Helper function to retrieve a name at compile time. template - inline constexpr static auto name_of() { + constexpr static auto name_of() { constexpr auto name = find_name_within_own_fields<_value>(); return Literal(); } /// Assigns from another literal. - Literal& operator=(const Literal& _other) { - if (this != &_other) { - value_ = _other.value_; - } - return *this; - } + Literal& operator=(const Literal& _other) = default; /// Assigns from another literal. - Literal& operator=(Literal&& _other) noexcept { - if (this != &_other) { - value_ = _other.value_; - } - return *this; - } + Literal& operator=(Literal&& _other) noexcept = + default; /// Assigns the literal from a string Literal& operator=(const std::string& _str) { @@ -141,37 +128,33 @@ class Literal { } /// Equality operator other Literals. - inline bool operator==(const Literal& _other) const { + bool operator==(const Literal& _other) const { return value() == _other.value(); } /// Equality operator other Literals with different fields. template - inline bool operator==(const Literal& _other) const { + bool operator==(const Literal& _other) const { return name() == _other.name(); } /// Inequality operator for other Literals. template - inline bool operator!=(const Literal& _other) const { + bool operator!=(const Literal& _other) const { return !(*this == _other); } /// Equality operator for strings. - inline bool operator==(const std::string& _str) const { - return name() == _str; - } + bool operator==(const std::string& _str) const { return name() == _str; } /// Inequality operator for strings. - inline bool operator!=(const std::string& _str) const { - return name() != _str; - } + bool operator!=(const std::string& _str) const { return name() != _str; } /// Alias for .name(). std::string str() const { return name(); } /// Returns the value actually contained in the Literal. - inline ValueType value() const { return value_; } + ValueType value() const { return value_; } /// Returns the value of the string literal in the template. template @@ -187,7 +170,7 @@ class Literal { /// Returns all of the allowed fields. template - inline static std::string allowed_strings(const std::string& _values = "") { + static std::string allowed_strings(const std::string& _values = "") { using FieldType = typename std::tuple_element<_i, FieldsType>::type; const auto head = "'" + FieldType::field_.str() + "'"; const auto values = _values.size() == 0 ? head : _values + ", " + head; @@ -200,7 +183,7 @@ class Literal { /// Whether the Literal contains duplicate strings. template - inline constexpr static bool has_duplicate_strings() { + constexpr static bool has_duplicate_strings() { if constexpr (_i >= num_fields_) { return false; } else { @@ -209,7 +192,7 @@ class Literal { } template - inline constexpr static bool is_duplicate() { + constexpr static bool is_duplicate() { using FieldType1 = typename std::tuple_element<_i, FieldsType>::type; using FieldType2 = typename std::tuple_element<_j, FieldsType>::type; if constexpr (FieldType1::field_ == FieldType2::field_) { @@ -239,7 +222,7 @@ class Literal { /// Finds the correct index associated with /// the string at compile time within the Literal's own fields. template - inline constexpr static auto find_name_within_own_fields() { + constexpr static auto find_name_within_own_fields() { using FieldType = typename std::tuple_element<_i, FieldsType>::type; return FieldType::field_; } @@ -247,7 +230,7 @@ class Literal { /// Finds the correct value associated with /// the string at run time. template - inline static Result find_value(const std::string& _str) { + static Result find_value(const std::string& _str) { using FieldType = typename std::tuple_element<_i, FieldsType>::type; if (FieldType::field_.str() == _str) { return _i; @@ -276,7 +259,7 @@ class Literal { /// Whether the literal contains this string. template - inline static bool has_value(const std::string& _str) { + static bool has_value(const std::string& _str) { using FieldType = typename std::tuple_element<_i, FieldsType>::type; if (FieldType::field_.str() == _str) { return true; diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index d1dd877d..350e0f4e 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -70,16 +70,10 @@ class NamedTuple { } /// Copy constructor. - NamedTuple(const NamedTuple& _other) - : values_(_other.values_) { - // Duplicate field checks not required - has already been checked. - } + NamedTuple(const NamedTuple& _other) = default; /// Move constructor. - NamedTuple(NamedTuple&& _other) - : values_(std::move(_other.values_)) { - // Duplicate field checks not required - has already been checked. - } + NamedTuple(NamedTuple&& _other) = default; /// Copy constructor. template @@ -175,62 +169,53 @@ class NamedTuple { /// Gets a field by index. template - inline auto& get() { + auto& get() { return rfl::get<_index>(*this); } /// Gets a field by name. template - inline auto& get() { + auto& get() { return rfl::get<_field_name>(*this); } /// Gets a field by the field type. template - inline auto& get() { + auto& get() { return rfl::get(*this); } /// Gets a field by index. template - inline const auto& get() const { + const auto& get() const { return rfl::get<_index>(*this); } /// Gets a field by name. template - inline const auto& get() const { + const auto& get() const { return rfl::get<_field_name>(*this); } /// Gets a field by the field type. template - inline const auto& get() const { + const auto& get() const { return rfl::get(*this); } /// Returns the results wrapped in a field. template - inline auto get_field() const { + auto get_field() const { return rfl::make_field<_field_name>(rfl::get<_field_name>(*this)); } /// Copy assignment operator. NamedTuple& operator=( - const NamedTuple& _other) { - values_ = _other.values_; - return *this; - } + const NamedTuple& _other) = default; /// Move assignment operator. NamedTuple& operator=( - NamedTuple&& _other) noexcept { - if (this == &_other) { - return *this; - } - values_ = std::move(_other.values_); - return *this; - } + NamedTuple&& _other) noexcept = default; /// Replaces one or several fields, returning a new version /// with the non-replaced fields left unchanged. diff --git a/include/rfl/Ref.hpp b/include/rfl/Ref.hpp index 229ec0ce..866791ea 100644 --- a/include/rfl/Ref.hpp +++ b/include/rfl/Ref.hpp @@ -18,9 +18,9 @@ class Ref { return Ref(std::make_shared(std::forward(_args)...)); } - Ref(const Ref& _other) : ptr_(_other.ptr_){}; + Ref(const Ref& _other) = default; - Ref(Ref&& _other) : ptr_(std::move(_other.ptr_)) {} + Ref(Ref&& _other) = default; template Ref(const Ref& _other) : ptr_(_other.ptr()) {} @@ -28,16 +28,16 @@ class Ref { ~Ref() = default; /// Returns a pointer to the underlying object - inline T* get() const { return ptr_.get(); } + T* get() const { return ptr_.get(); } /// Returns the underlying object. - inline T& operator*() const { return *ptr_; } + T& operator*() const { return *ptr_; } /// Returns the underlying object. - inline T* operator->() const { return ptr_.get(); } + T* operator->() const { return ptr_.get(); } /// Returns the underlying shared_ptr - inline const std::shared_ptr& ptr() const { return ptr_; } + const std::shared_ptr& ptr() const { return ptr_; } /// Copy assignment operator. template @@ -47,20 +47,10 @@ class Ref { } /// Move assignment operator - inline Ref& operator=(Ref&& _other) noexcept { - if (&_other != this) { - ptr_ = std::move(_other.ptr_); - } - return *this; - } + Ref& operator=(Ref&& _other) noexcept = default; /// Copy assignment operator - inline Ref& operator=(const Ref& _other) { - if (&_other != this) { - ptr_ = _other.ptr_; - } - return *this; - } + Ref& operator=(const Ref& _other) = default; private: /// Only make is allowed to use this constructor. diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 9e84d24f..5423fd1e 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -191,25 +191,15 @@ class Result { const T& operator*() const { return *std::get_if(&t_or_err_); } /// Assigns the underlying object. - inline Result& operator=(const Result& _other) { - if (this != &_other) { - t_or_err_ = _other.t_or_err_; - } - return *this; - } + Result& operator=(const Result& _other) = default; /// Assigns the underlying object. - inline Result& operator=(Result&& _other) { - if (this != &_other) { - t_or_err_ = std::move(_other.t_or_err_); - } - return *this; - } + Result& operator=(Result&& _other) = default; /// Assigns the underlying object. template , bool>::type = true> - inline auto& operator=(const Result& _other) { + auto& operator=(const Result& _other) { const auto to_t = [](const U& _u) -> T { return _u; }; t_or_err_ = _other.transform(to_t).t_or_err_; return *this; diff --git a/include/rfl/TaggedUnion.hpp b/include/rfl/TaggedUnion.hpp index c832c456..7d3a9d8b 100644 --- a/include/rfl/TaggedUnion.hpp +++ b/include/rfl/TaggedUnion.hpp @@ -20,13 +20,11 @@ struct TaggedUnion { TaggedUnion(VariantType&& _variant) noexcept : variant_(std::move(_variant)) {} - TaggedUnion( - const TaggedUnion<_discriminator, NamedTupleTypes...>& _tagged_union) - : variant_(_tagged_union.variant_) {} + TaggedUnion(const TaggedUnion<_discriminator, NamedTupleTypes...>& + _tagged_union) = default; TaggedUnion(TaggedUnion<_discriminator, NamedTupleTypes...>&& - _tagged_union) noexcept - : variant_(std::move(_tagged_union.variant_)) {} + _tagged_union) noexcept = default; template , @@ -41,14 +39,14 @@ struct TaggedUnion { ~TaggedUnion() = default; /// Assigns the underlying object. - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( const VariantType& _variant) { variant_ = _variant; return *this; } /// Assigns the underlying object. - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( VariantType&& _variant) { variant_ = std::move(_variant); return *this; @@ -58,8 +56,7 @@ struct TaggedUnion { template , bool>::type = true> - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( - T&& _variant) { + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=(T&& _variant) { variant_ = std::forward(_variant); return *this; } @@ -68,35 +65,26 @@ struct TaggedUnion { template , bool>::type = true> - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( const T& _variant) { variant_ = _variant; return *this; } /// Assigns the underlying object. - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( - const TaggedUnion<_discriminator, NamedTupleTypes...>& _other) { - if (this != &_other) { - variant_ = _other.get(); - } - return *this; - } + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( + const TaggedUnion<_discriminator, NamedTupleTypes...>& _other) = + default; /// Assigns the underlying object. - inline TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( - TaggedUnion<_discriminator, NamedTupleTypes...>&& _other) { - if (this != &_other) { - variant_ = std::move(_other.variant_); - } - return *this; - } + TaggedUnion<_discriminator, NamedTupleTypes...>& operator=( + TaggedUnion<_discriminator, NamedTupleTypes...>&& _other) = default; /// Returns the underlying variant. - inline VariantType& variant() { return variant_; } + VariantType& variant() { return variant_; } /// Returns the underlying variant. - inline const VariantType& variant() const { return variant_; } + const VariantType& variant() const { return variant_; } /// The underlying variant - a TaggedUnion is a thin wrapper /// around a variant that is mainly used for parsing. From 278071f2c00f563707b34553539325d1a9f7fdf2 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Mon, 16 Oct 2023 22:22:54 +0200 Subject: [PATCH 21/48] Replaced map with vector of key-value-pairs --- include/rfl/json/Reader.hpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index c3096789..1e43f489 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -113,7 +113,7 @@ struct Reader { yyjson_val* key; while ((key = yyjson_obj_iter_next(&iter))) { const char* k = yyjson_get_str(key); - const auto it = _field_indices.find(std::string_view(k, strlen(k))); + const auto it = _field_indices.find(std::string_view(k)); if (it != _field_indices.end()) { f_arr[it->second] = InputVarType(yyjson_obj_iter_get_val(key)); } @@ -121,17 +121,16 @@ struct Reader { return f_arr; } - std::map to_map( + std::vector> to_map( InputObjectType* _obj) const noexcept { - std::map m; + std::vector> m; yyjson_obj_iter iter; yyjson_obj_iter_init(_obj->val_, &iter); yyjson_val* key; while ((key = yyjson_obj_iter_next(&iter))) { - const auto p = - std::make_pair(yyjson_get_str(key), - InputVarType(yyjson_obj_iter_get_val(key))); - m.emplace(std::move(p)); + auto p = std::make_pair(yyjson_get_str(key), + InputVarType(yyjson_obj_iter_get_val(key))); + m.emplace_back(std::move(p)); } return m; } From d6c4622b55149a23647e10acb607519b7b993fb3 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Tue, 17 Oct 2023 00:30:26 +0200 Subject: [PATCH 22/48] Move keys --- include/rfl/parsing/Parser.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index e8dc0bcb..d850b041 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -288,9 +288,9 @@ struct MapParser { static Result read(const ReaderType& _r, InputVarType* _var) noexcept { - const auto get_pair = [&](auto _pair) { + const auto get_pair = [&](auto& _pair) { const auto to_pair = [&](ValueType&& _val) { - return std::make_pair(_pair.first, std::move(_val)); + return std::make_pair(std::move(_pair.first), std::move(_val)); }; return Parser>::read(_r, &_pair.second) @@ -302,7 +302,7 @@ struct MapParser { auto m = _r.to_map(&_obj); MapType res; try { - for (const auto& p : m) { + for (auto& p : m) { res.insert(get_pair(p)); } } catch (std::exception& e) { From d72047111b51cfd84b21fb8cd6c21ec6340f79ab Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 18 Oct 2023 20:36:04 +0200 Subject: [PATCH 23/48] Create named_tuple.md --- docs/named_tuple.md | 76 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/named_tuple.md diff --git a/docs/named_tuple.md b/docs/named_tuple.md new file mode 100644 index 00000000..1feec936 --- /dev/null +++ b/docs/named_tuple.md @@ -0,0 +1,76 @@ +# `rfl::NamedTuple` + +`rfl::NamedTuple` is very similar to `std::tuple`, but unlike `std::tuple` the fields have names. + +In other words, consider the following struct: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; +}; +``` + +You might as well define the following `rfl::NamedTuple`: + +```cpp +using Person = rfl::NamedTuple< + rfl::Field<"firstName", std::string>, + rfl::Field<"lastName", std::string>, + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>>; +``` + +From the point-of-view of serialization/deserialization, the two definitions are equivalent. +The resulting JSON strings (or any other format) will be the same. + + +## Structural typing + +From the point-of-view of programming, there is an important difference: Structs are *nominally typed* +and named tuples are *structurally typed* (confusingly, structs are not structurally typed). + +In plain language, that means that the compiler will regard this as absolutely equivalent to `Person`, the named tuple: + +```cpp +using Person2 = rfl::NamedTuple< + rfl::Field<"firstName", std::string>, + rfl::Field<"lastName", std::string>, + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>>; +``` + +However, this will be seen as a type that is different from `Person`, the struct: + +```cpp +struct Person2 { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; +}; +``` + +Structural typing also means that you can declare new types on-the-fly. For instance, in order +to create a `Person` named tuple, you don't actually have to declare it at all. The following will do: + +```cpp +const auto person = rfl::Field<"firstName", std::string>("Homer") * + rfl::Field<"firstName", std::string>("Simpson") * + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19"); +``` + +The type of `person` will now be equivalent to the definition of `Person`, the named tuple, +regardless of whether you have actually declared it anywhere. + +On the other hand, structural typing also means that recursive definitions are impossible. +For instance, consider something like this: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"children", std::vector> children; +}; +``` + +In this example, `Person` is recursively defined (because of the field `children`). +This is impossible to accomplish using structural typing and `rfl::NamedTuple`, just like it is impossible to have a recursively defined lambda function. From 22498861dd7c17bff6137394f8838a37ba2a469c Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 18 Oct 2023 22:48:57 +0200 Subject: [PATCH 24/48] Added more documentation for rfl::NamedTuple --- docs/named_tuple.md | 176 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 175 insertions(+), 1 deletion(-) diff --git a/docs/named_tuple.md b/docs/named_tuple.md index 1feec936..406c568d 100644 --- a/docs/named_tuple.md +++ b/docs/named_tuple.md @@ -54,7 +54,7 @@ to create a `Person` named tuple, you don't actually have to declare it at all. ```cpp const auto person = rfl::Field<"firstName", std::string>("Homer") * - rfl::Field<"firstName", std::string>("Simpson") * + rfl::Field<"lastName", std::string>("Simpson") * rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19"); ``` @@ -74,3 +74,177 @@ struct Person { In this example, `Person` is recursively defined (because of the field `children`). This is impossible to accomplish using structural typing and `rfl::NamedTuple`, just like it is impossible to have a recursively defined lambda function. + +## Accessing fields + +Fields inside the named tuple can be accessed using `rfl::get` or the `.get` method: + +```cpp +const auto person = rfl::Field<"firstName", std::string>("Homer") * + rfl::Field<"lastName", std::string>("Simpson") * + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19"); + +// OK in most circumstances (there are restrictions +// due to the way C++ templates work). +const auto first_name = person.get<"firstName">(); + +// Always OK +const auto first_name = person.template get<"firstName">(); + +// Always OK +const auto first_name = rfl::get<"firstName">(person); +``` + +## Similarity to structs + +Most of the functionality we have described also work for `rfl::NamedTuple`. +It should be noted that you are free to mix `rfl::NamedTuple` and structs. +For instance, you can build a `rfl::TaggedUnion` from a combination of +`rfl::NamedTuple` and structs or you could construct a struct from named tuples using +`rfl::as`. + +### `std::variant` and `rfl::TaggedUnion` + +`rfl::NamedTuple`s can be inserted into `std::variant`: + +```cpp +using Circle = rfl::NamedTuple>; + +using Rectangle = rfl::NamedTuple< + rfl::Field<"height", double>, + rfl::Field<"width", double>>; + +using Square rfl::NamedTuple>; + +// Untagged variant - OK +using Shapes = std::variant; + +// Externally tagged variant - also OK: +using Shapes = std::variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", Square>>; +``` + +They can also be inserted into `rfl::TaggedUnion`: + +```cpp +using Circle = rfl::NamedTuple< + rfl::Field<"shape", rfl::Literal<"Circle">>, + rfl::Field<"radius", double>>; + +using Rectangle = rfl::NamedTuple< + rfl::Field<"shape", rfl::Literal<"Rectangle">>, + rfl::Field<"height", double>, + rfl::Field<"width", double>>; + +using Square rfl::NamedTuple< + rfl::Field<"shape", rfl::Literal<"Square">>, + rfl::Field<"width", double>>; + +// Tell rfl::TaggedUnion that you want it to look for the field "shape". +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; +``` + +### `rfl::replace` + +`rfl::replace` works for `rfl::NamedTuple` as well: + +```cpp +const auto lisa = rfl::Field<"firstName", std::string>("Lisa") * + rfl::Field<"lastName", std::string>("Simpson"); + +// Returns a deep copy of the original object, +// replacing first_name. +const auto maggie = + rfl::replace(lisa, rfl::make_field<"firstName">(std::string("Maggie"))); + +// Also OK +const auto bart = lisa.replace(rfl::make_field<"firstName">(std::string("Bart"))); +``` + +### `rfl::as` + +So does `rfl::as`: + +```cpp +using C = rfl::NamedTuple< + rfl::Field<"f1", std::string>, + rfl::Field<"f2", std::string>, + rfl::Field<"f4", std::string>>; + +const auto a = rfl::Field<"f1", std::string>("Hello") * + rfl::Field<"f2", std::string>("World"); + +const auto b = rfl::Field<"f3", std::string>("Hello") * + rfl::Field<"f4", std::string>("World"); + +const auto c = rfl::as(a, b); +``` + +However, you do not really have to use `rfl::as` here. This will work as well: + +```cpp +// Same as rfl::as(a, b) +const auto c = C(a * b); +``` + +(in fact, this is how `rfl::as` is implemented in the first place). + +## Defining named tuples using other named tuples + +`rfl::Flatten` is not supported inside named tuples. Instead, you can use `rfl::define_named_tuple_t<...>` +to achieve the same goal: + +```cpp +using Person = rfl::NamedTuple< + rfl::Field<"firstName", std::string>, + rfl::Field<"lastName", std::string>, + rfl::Field<"age", int>>; + +using Employee = rfl::define_named_tuple_t< + Person, + rfl::Field<"salary", float>>; + +const auto employee = Employee( + rfl::Field<"firstName", std::string>("Homer"), + rfl::Field<"lastName", std::string>("Simpson"), + rfl::make_field<"age">(45), + rfl::make_field<"salary">(60000.0)); +``` + +## Transforming structs to named tuples and vice versa + +You can transform structs to named tuples and vice versa: + +```cpp +auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .birthday = "1987-04-19"}; + +// bart_nt is a named tuple +const auto bart_nt = rfl::to_named_tuple(bart); + +// You can also retrieve the equivalent named tuple +// type to a struct: +using PersonNamedTuple = rfl::named_tuple_t; + +// rfl::to_named_tuple also supports move semantics +PersonNamedTuple bart_nt = rfl::to_named_tuple(std::move(bart_nt)); + +// You can also go the other way +const auto bart_struct = rfl::from_named_tuple(bart_nt); +const auto bart_struct = rfl::from_named_tuple(std::move(bart_nt)); +``` + +## rfl::NamedTuple is central to reflect-cpp + +`rfl::NamedTuple` is basically at the heart of how the reflect-cpp reflection +is actually implemented. If you look at how reflect-cpp is implemented you will find that +structs are transformed from and to `rfl::NamedTuple`s +all the time (using zero-copy operations wherever possible). +That is because `rfl::NamedTuple` actually support reflection, +where as structs don't. + + + + From 4cce20d38c99e7dc35467a6ce6617d5cfedf7952 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 18 Oct 2023 22:49:59 +0200 Subject: [PATCH 25/48] Update README.md --- docs/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/README.md b/docs/README.md index 5849f23d..50b37df7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,3 +31,5 @@ 3.1) [rfl::replace](https://github.com/getml/reflect-cpp/blob/main/docs/replace.md) - For replacing one or several fields in a struct. 3.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs. + +3.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing From 21d09d106c17ceb9152b57020227bb6525911c44 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Thu, 19 Oct 2023 22:25:45 +0200 Subject: [PATCH 26/48] Added documentation for rfl::Result --- docs/result.md | 138 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 docs/result.md diff --git a/docs/result.md b/docs/result.md new file mode 100644 index 00000000..8e22cc05 --- /dev/null +++ b/docs/result.md @@ -0,0 +1,138 @@ +# `rfl::Result` + +In this documentation, we have, on several occasions, read a JSON string like this: + +```cpp +const auto homer = rfl::json::read(json_string).value(); +``` + +However, so far we have not elaborated on why `.value()` is necessary. Why can't we just do this? + +```cpp +const auto homer = rfl::json::read(json_string); +``` + +The reason is that parsing a JSON string is something that might fail. We do not know much about +the string that put into there. It might not be a valid JSON. And even if it is a valid JSON, then it +might not conform to the assumptions that we have made about it and laid out in the type system +in the form of various structs and containers. + +`rfl::json::read` handles this by returning an `rfl::Result` type. `rfl::Result` is a way of error +handling without exceptions. Exceptions are controversial, because they add another, hidden control +path to your program that it hard to follow or predict. For this reasons, and others, the Google +C++ style guide [disallows exceptions altogether](https://google.github.io/styleguide/cppguide.html#Exceptions). +Modern programming languages like Go and Rust don't even support them in the first place. The C++ +standards committee has recognized this and introduced [std::expected](https://en.cppreference.com/w/cpp/utility/expected) +in C++-23. + +However, reflect-cpp is a library for C++-20 and until that changes, we need to implement our own result type. + +If you do not care about these objections to exceptions, you can just call `rfl::json::read<...>(json_string).value()`, +which throws an exception, if the result type contains an error and be done with it. + +## What is `rfl::Result`? + +`rfl::Result` is similar to `std::optional` it that it contains an object that may or may not be there. However, +unlike `std::optional`, it does not simply contain `std::nullopt` if the operation has not been successful. Instead, +it contains an `rfl::Error` with a clear error message. + +In laying out our structs an containers, about the the type system, we are making *requirements* about the +JSON input we are expecting from the outside world. `rfl::json::read(...)` checks whether these requirements are met. +If the requirements are met, `rfl::json::read` returns T wrapped inside `rfl::Result`. If they are not met, it returns +`rfl::Error` containing an error message explaining what went wrong. + +## Monadic operations + +From the point of view of category theory, `rfl::Result` is both a functor and a monad (actually, all monads are functors). + +This is reflected in its member functions `.transform(...)` and `.and_then(...)`. + +`.transform(...)` requires a function `F` of the type `T -> U`. If the `rfl::Result` contains a type `T`, +then `r.transform(f)` *will* return an `rfl::Result` containing a type `U`, otherwise it will return an `rfl::Result` +containing an error. + +`.and_then(...)` requires a function `F` of the type `T -> rfl::Result`. If the `rfl::Result` contains a type `T`, +then `r.and_then(f)` *might* return an `rfl::Result` containing a type `U`, depending on whether `f` failed. +If `r` already contained an error, then `r.and_then(f)` will surely return an `rfl::Result` containing an error. +containing an error. + +Throughout reflect-cpp's code, these functions are widely used by the parser. For instance, consider how we are reading +`std::unique_ptr` (note that this is somewhat simplified): + +```cpp +const auto to_ptr = [](auto&& _t) { + return std::make_unique(std::move(_t)); +}; + +return Parser::read(_r, _var).transform(to_ptr); +``` + +This code works as follows: First, we read in a type `T`, which is something that might fail. However, we know 100% that +once we have `T` we can surely wrap it inside a pointer, so we can call `.transform(...)`. + +On the other hand, consider the implementation of `rfl::json::load`, which loads a JSON from a file: + +```cpp +template +Result load(const std::string& _fname) { + return rfl::io::load_string(_fname).and_then(read); +} +``` + +This code works as follows: First, we read in the text file using `rfl::io::load_string`. This an operation that might fail (maybe +the file doesn't exist, maybe it isn't readable, ...). Then we have to to parse its contents using `rfl::json::read`. Again, +this is an operation that might fail (might not be a proper JSON, might not conform to our requirements, ...). Therefore, we +have to call `.and_then(...)`. + +## Retrieving values or errors + +If you want the underlying value of type T, you can use `.value(...)`. Note that this throws an exception, if `rfl::Result` contains +an error. + +If you are 100% sure that the result does not contain error, you can also call the operator `*`. This will lead to undefined behavior, +if you are wrong. + +If you want the underlying value of type T or some kind of default value, you can call `.value_or(your_default_value)`. + +If you want to retrieve the error, you can call `.error()`, which will return a value of type `std::optional`. + +If you want to check whether the result contains an error, you can just use the bool operator: + +```cpp +if (my_result) { + // my_result cannot contain an error, + // so it is okay to call operator *. + auto v = *my_result; +} else { + // my_result must contain an error. + auto err = my_result.error().value(); +} +``` + +## Iterating over `rfl::Result` + +`rfl::Result` can be iterated over, as it contains either zero or one values of type `T`: + +```cpp +for (const auto& v: my_result) { + // If you are inside this loop, then my_result did not contain an error. +} +``` + +## `.and_other(...)`, `.or_else(...)`, `.or_other(...)` + +`r1.and_other(r2)` expects an `r2` or type `rfl::Result`. It returns an error, if `r1` contains an error and `r2` otherwise. + +`r.or_else(f)` expects a function `f` for type `Error -> rfl::Result`. It returns `r` if `r` did not contain an error and the results of `f` otherwise. + +This is often used to produce better error messages: + +```cpp +const auto embellish_error = [&](const Error& _e) -> rfl::Result { + return Error("Failed to parse field '" + key + "': " + _e.what()); +}; +return Parser::read(_r, &_var).or_else(embellish_error); +``` + +`r1.or_other(r2)` expects an `r2` or type `rfl::Result`. It returns an `r1`, if `r1` does not contain an error and `r2` otherwise. + From d78aa01f7cab86af1e90d9aaea1524fec412c670 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Thu, 19 Oct 2023 22:33:09 +0200 Subject: [PATCH 27/48] Update README.md --- docs/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/README.md b/docs/README.md index 50b37df7..d4d33f91 100644 --- a/docs/README.md +++ b/docs/README.md @@ -33,3 +33,6 @@ 3.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs. 3.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing + +3.4) [rfl::Result](https://github.com/getml/reflect-cpp/blob/main/docs/result.md) - For error handling without exceptions + From 2d3d6340eb2abc6af2429c1e516b0e8e5e201810 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Thu, 19 Oct 2023 22:35:18 +0200 Subject: [PATCH 28/48] Use move semantics for std::shared_ptr and rfl::Box --- include/rfl/parsing/Parser.hpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index d850b041..c8d35ca0 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -519,7 +519,9 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const ReaderType& _r, InputVarType* _var) noexcept { - const auto to_ref = [&](auto&& _t) { return Ref::make(_t); }; + const auto to_ref = [&](auto&& _t) { + return Ref::make(std::move(_t)); + }; return Parser>::read(_r, _var) .transform(to_ref); } @@ -545,7 +547,9 @@ struct Parser> { if (_r.is_empty(_var)) { return std::shared_ptr(); } - const auto to_ptr = [](auto&& _t) { return std::make_shared(_t); }; + const auto to_ptr = [](auto&& _t) { + return std::make_shared(std::move(_t)); + }; return Parser>::read(_r, _var) .transform(to_ptr); } From 3730f2cb04a99afe597f328a6ff14fb6e656c758 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Fri, 20 Oct 2023 23:06:01 +0200 Subject: [PATCH 29/48] Added documentation on json --- docs/json.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 docs/json.md diff --git a/docs/json.md b/docs/json.md new file mode 100644 index 00000000..db5c91e1 --- /dev/null +++ b/docs/json.md @@ -0,0 +1,39 @@ +# JSON + +For JSON support, you must also include the header ``. + +Suppose you have a struct like this: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + rfl::Field<"children", std::vector> children; +}; +``` + +You can parse JSON strings like this: + +```cpp +const rfl::Result result = rfl::json::read(json_string); +``` + +A person can be turned into a JSON string like this: + +```cpp +const auto person = Person{...}; +const std::string json_string = rfl::json::write(person); +``` + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::json::load("/path/to/file.json"); + +const auto person = Person{...}; +rfl::json::save("/path/to/file.json", person); +``` + + + From bfef536f371f48c6c037249c9508adfcbbd007fe Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Fri, 20 Oct 2023 23:07:23 +0200 Subject: [PATCH 30/48] Update README.md --- docs/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/README.md b/docs/README.md index d4d33f91..bb1f70ec 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,3 +36,7 @@ 3.4) [rfl::Result](https://github.com/getml/reflect-cpp/blob/main/docs/result.md) - For error handling without exceptions +## 4) Supported formats + +4.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md) + From ea3ce3632cec598c14d9389b06739c89521940e4 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 21 Oct 2023 14:19:32 +0200 Subject: [PATCH 31/48] Added support for better error messages --- include/rfl/Result.hpp | 6 +-- include/rfl/parsing/Parser.hpp | 83 ++++++++++++++++++++++++++++++---- tests/test_error_messages.hpp | 42 +++++++++++++++++ tests/tests.cpp | 2 + 4 files changed, 121 insertions(+), 12 deletions(-) create mode 100644 tests/test_error_messages.hpp diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 5423fd1e..2c84ffc4 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -211,10 +211,10 @@ class Result { Result or_else(const F& _f) { const auto handle_variant = [&](TOrError&& _t_or_err) -> Result { - if constexpr (std::is_same()) { - return _f(std::forward(_t_or_err)); + if constexpr (std::is_same, Error>()) { + return _f(std::forward(_t_or_err)); } else { - return std::forward(_t_or_err); + return std::forward(_t_or_err); } }; return std::visit(handle_variant, diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index c8d35ca0..aeb4fb3a 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -392,7 +392,10 @@ struct Parser> { if (!f) { if constexpr (is_required()) { const auto key = FieldType::name_.str(); - return Error("Field named '" + key + "' not found!"); + return collect_errors( + _r, _fields_vec, + std::vector( + {Error("Field named '" + key + "' not found!")})); } else { return build_named_tuple_recursively( _r, _fields_vec, std::move(_args)..., @@ -406,7 +409,64 @@ struct Parser> { FieldType(std::move(_value))); }; - return get_value(_r, *f).and_then(build); + const auto handle_error = [&](Error&& _error) { + return collect_errors( + _r, _fields_vec, std::vector({std::move(_error)})); + }; + + return get_value(_r, *f) + .or_else(handle_error) + .and_then(build); + } + } + + /// If something went wrong, we want to collect all of the errors - it's + /// just good UX. + template + static Error collect_errors( + const ReaderType& _r, + const std::array, sizeof...(FieldTypes)>& + _fields_vec, + std::vector _errors) noexcept { + if constexpr (_i == sizeof...(FieldTypes)) { + if (_errors.size() == 1) { + return std::move(_errors[0]); + } else { + std::string msg = + "Found " + std::to_string(_errors.size()) + " errors:"; + for (size_t i = 0; i < _errors.size(); ++i) { + msg += "\n" + std::to_string(i + 1) + ") " + + _errors.at(i).what(); + } + return Error(msg); + } + } else { + using FieldType = typename std::tuple_element< + _i, typename NamedTuple::Fields>::type; + + using ValueType = std::decay_t; + + const auto& f = std::get<_i>(_fields_vec); + + if (!f) { + if constexpr (is_required()) { + const auto key = FieldType::name_.str(); + _errors.emplace_back( + Error("Field named '" + key + "' not found.")); + } + return collect_errors<_i + 1>(_r, _fields_vec, + std::move(_errors)); + } + + const auto add_error_if_applicable = + [&](Error&& _error) -> Result { + _errors.emplace_back(std::move(_error)); + return _error; + }; + + get_value(_r, *f).or_else(add_error_if_applicable); + + return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors)); } } @@ -447,8 +507,8 @@ struct Parser> { NamedTuple>::field_indices_; } - /// Retrieves the value from the object. This is mainly needed to generate a - /// better error message. + /// Retrieves the value from the object. This is mainly needed to + /// generate a better error message. template static auto get_value(const ReaderType& _r, InputVarType _var) noexcept { const auto embellish_error = [&](const Error& _e) { @@ -654,7 +714,8 @@ struct Parser>(), - "Externally tagged variants cannot have duplicate field names."); + "Externally tagged variants cannot have duplicate field " + "names."); const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; @@ -867,7 +929,8 @@ struct FieldVariantParser { const std::variant& _v) noexcept { static_assert( internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field names."); + "Externally tagged variants cannot have duplicate field " + "names."); const auto handle = [&](const auto& _field) { const auto named_tuple = @@ -887,7 +950,8 @@ struct FieldVariantParser { InputVarType* _var) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { return Error( - "Could not parse std::variant, could not match field named '" + + "Could not parse std::variant, could not match field named " + "'" + _disc_value + "'."); } else { using FieldType = std::decay_t> { /// This can be used for data structures that would be expressed as array in /// serialized format (std::vector, std::set, std::deque, ...), -/// but also includes map-like types, when the key is not of type std::string. +/// but also includes map-like types, when the key is not of type +/// std::string. template struct VectorParser { public: diff --git a/tests/test_error_messages.hpp b/tests/test_error_messages.hpp new file mode 100644 index 00000000..139c9dc0 --- /dev/null +++ b/tests/test_error_messages.hpp @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_error_messages() { + std::cout << "test_error_messages" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + rfl::Field<"children", std::vector> children; + }; + + const std::string faulty_string = + R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})"; + + const auto result = rfl::json::read(faulty_string); + + const std::string expected = R"(Found 3 errors: +1) Failed to parse field 'lastName': Could not cast to string. +2) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'. +3) Field named 'children' not found.)"; + + if (!result.error()) { + std::cout << "Expected an error, got none." << std::endl << std::endl; + } + + if (result.error().value().what() != expected) { + std::cout << "Expected: " << std::endl + << expected << std::endl + << "Got:" << std::endl + << result.error().value().what() << std::endl + << std::endl; + } + + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/tests.cpp b/tests/tests.cpp index 6f6afdd6..871285c4 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -8,6 +8,7 @@ #include "test_custom_class4.hpp" #include "test_default_values.hpp" #include "test_deque.hpp" +#include "test_error_messages.hpp" #include "test_field_variant.hpp" #include "test_flatten.hpp" #include "test_forward_list.hpp" @@ -63,6 +64,7 @@ int main() { test_unordered_multiset(); test_string_map(); test_string_unordered_map(); + test_error_messages(); test_custom_class1(); test_custom_class2(); From d2d918c5955c15b8110044ce5223c562e00d30be Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sat, 21 Oct 2023 14:24:16 +0200 Subject: [PATCH 32/48] Documented good error messages --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 59fb3049..146d2aec 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,23 @@ std::cout << "Hello, my name is " << homer2.first_name() << " " << homer2.last_name() << "." << std::endl; ``` +reflect-cpp returns clear and comprehensive error messages: + +```cpp +const std::string faulty_json_string = + R"({"firstName":"Homer","lastName":12345,"birthday":"04/19/1987"})"; +const auto result = rfl::json::read(faulty_json_string); +``` + +Yields the following error message: + +``` +Found 3 errors: +1) Failed to parse field 'lastName': Could not cast to string. +2) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'. +3) Field named 'children' not found. +``` + ## Support for containers ### C++ standard library From fa5c8fd9986b4a65eeacea4640b9bd509a281841 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 21 Oct 2023 18:24:44 +0200 Subject: [PATCH 33/48] Added concepts and constraints for the Parser --- include/rfl/parsing/AreReaderAndWriter.hpp | 16 + include/rfl/parsing/IsReader.hpp | 41 ++ include/rfl/parsing/IsWriter.hpp | 32 ++ include/rfl/parsing/Parser.hpp | 527 ++++++++++----------- 4 files changed, 351 insertions(+), 265 deletions(-) create mode 100644 include/rfl/parsing/AreReaderAndWriter.hpp create mode 100644 include/rfl/parsing/IsReader.hpp create mode 100644 include/rfl/parsing/IsWriter.hpp diff --git a/include/rfl/parsing/AreReaderAndWriter.hpp b/include/rfl/parsing/AreReaderAndWriter.hpp new file mode 100644 index 00000000..962f6390 --- /dev/null +++ b/include/rfl/parsing/AreReaderAndWriter.hpp @@ -0,0 +1,16 @@ +#ifndef RFL_PARSING_AREREADERANDWRITER_HPP_ +#define RFL_PARSING_AREREADERANDWRITER_HPP_ + +#include "rfl/parsing/IsReader.hpp" +#include "rfl/parsing/IsWriter.hpp" + +namespace rfl { +namespace parsing { + +template +concept AreReaderAndWriter = IsReader && IsWriter; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp new file mode 100644 index 00000000..99c1fcbd --- /dev/null +++ b/include/rfl/parsing/IsReader.hpp @@ -0,0 +1,41 @@ +#ifndef RFL_PARSING_ISREADER_HPP_ +#define RFL_PARSING_ISREADER_HPP_ + +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace parsing { + +template +concept IsReader = requires(R r, typename R::InputArrayType arr, + typename R::InputObjectType obj, + typename R::InputVarType var) { + { r.template to_basic_type(&var) } -> std::same_as>; + + { + r.to_array(&var) + } -> std::same_as>; + + { + r.to_map(&obj) + } -> std::same_as< + std::vector>>; + + { + r.to_object(&var) + } -> std::same_as>; + + { r.to_vec(&arr) } -> std::same_as>; + + { + r.template use_custom_constructor(&var) + } -> std::same_as>; +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/IsWriter.hpp b/include/rfl/parsing/IsWriter.hpp new file mode 100644 index 00000000..11c89a2f --- /dev/null +++ b/include/rfl/parsing/IsWriter.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_PARSING_ISWRITER_HPP_ +#define RFL_PARSING_ISWRITER_HPP_ + +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace parsing { + +template +concept IsWriter = requires(W w, std::string name, + typename W::OutputArrayType arr, + typename W::OutputObjectType obj, + typename W::OutputVarType var) { + { w.add(var, &arr) } -> std::same_as; + + { w.empty_var() } -> std::same_as; + + { w.new_array() } -> std::same_as; + + { w.new_object() } -> std::same_as; + + { w.is_empty(&var) } -> std::same_as; + + { w.set_field(name, var, &obj) } -> std::same_as; +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index aeb4fb3a..cf28477a 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -35,6 +35,7 @@ #include "rfl/internal/no_duplicate_field_names.hpp" #include "rfl/internal/to_ptr_named_tuple.hpp" #include "rfl/named_tuple_t.hpp" +#include "rfl/parsing/AreReaderAndWriter.hpp" #include "rfl/parsing/is_forward_list.hpp" #include "rfl/parsing/is_map_like.hpp" #include "rfl/parsing/is_required.hpp" @@ -46,20 +47,22 @@ namespace parsing { // ---------------------------------------------------------------------------- -template +template +requires AreReaderAndWriter struct Parser; // ---------------------------------------------------------------------------- /// Default case - anything that cannot be explicitly matched. -template +template +requires AreReaderAndWriter struct Parser { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result read(const ReaderType& _r, InputVarType* _var) noexcept { - if constexpr (ReaderType::template has_custom_constructor) { + static Result read(const R& _r, InputVarType* _var) noexcept { + if constexpr (R::template has_custom_constructor) { return _r.template use_custom_constructor(_var); } else { if constexpr (internal::has_reflection_type_v) { @@ -71,9 +74,8 @@ struct Parser { return Error(e.what()); } }; - return Parser::read( - _r, _var) - .and_then(wrap_in_t); + return Parser::read(_r, _var).and_then( + wrap_in_t); } else if constexpr (std::is_class_v && !std::is_same()) { using NamedTupleType = named_tuple_t; @@ -84,9 +86,8 @@ struct Parser { return Error(e.what()); } }; - return Parser::read( - _r, _var) - .and_then(to_struct); + return Parser::read(_r, _var).and_then( + to_struct); } else { return _r.template to_basic_type>(_var); } @@ -94,36 +95,35 @@ struct Parser { } /// Converts the variable to a JSON type. - static auto write(const WriterType& _w, const T& _var) noexcept { + static auto write(const W& _w, const T& _var) noexcept { if constexpr (internal::has_reflection_type_v) { using ReflectionType = std::decay_t; if constexpr (internal::has_reflection_method_v) { - return Parser::write( - _w, _var.reflection()); + return Parser::write(_w, + _var.reflection()); } else { const auto& [r] = _var; - return Parser::write(_w, - r); + return Parser::write(_w, r); } } else if constexpr (std::is_class_v && !std::is_same()) { const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var); using PtrNamedTupleType = std::decay_t; - return Parser::write( - _w, ptr_named_tuple); + return Parser::write(_w, ptr_named_tuple); } else { return _w.from_basic_type(_var); } } }; -template -struct Parser { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter +struct Parser { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result read(const ReaderType& _r, InputVarType* _var) noexcept { + static Result read(const R& _r, InputVarType* _var) noexcept { static_assert( always_false_v, "Reading into raw pointers is dangerous and therefore unsupported. " @@ -133,27 +133,27 @@ struct Parser { } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, const T* _ptr) noexcept { + static OutputVarType write(const W& _w, const T* _ptr) noexcept { if (!_ptr) { return _w.empty_var(); } - return Parser>::write(_w, - *_ptr); + return Parser>::write(_w, *_ptr); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { +template +requires AreReaderAndWriter> +struct Parser> { public: - using InputArrayType = typename ReaderType::InputArrayType; - using InputVarType = typename ReaderType::InputVarType; + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename WriterType::OutputArrayType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { const auto to_vec = [&](auto _arr) { return _r.to_vec(&_arr); }; @@ -177,13 +177,11 @@ struct Parser> { .and_then(extract); } - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::array& _arr) noexcept { auto arr = _w.new_array(); for (auto it = _arr.begin(); it != _arr.end(); ++it) { - _w.add( - Parser>::write(_w, *it), - &arr); + _w.add(Parser>::write(_w, *it), &arr); } return OutputVarType(arr); } @@ -192,7 +190,7 @@ struct Parser> { /// Extracts values from the array, field by field. template static Result> extract_field_by_field( - const ReaderType& _r, std::vector _vec, + const R& _r, std::vector _vec, AlreadyExtracted&&... _already_extracted) noexcept { constexpr size_t i = sizeof...(AlreadyExtracted); if constexpr (i == _size) { @@ -209,47 +207,44 @@ struct Parser> { /// Extracts a single field from a JSON. template - static auto extract_single_field(const ReaderType& _r, + static auto extract_single_field(const R& _r, std::vector* _vec) noexcept { - return Parser::read(_r, &((*_vec)[_i])); + return Parser::read(_r, &((*_vec)[_i])); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result> read(const R& _r, InputVarType* _var) noexcept { const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; - return Parser>::read(_r, _var) - .transform(to_box); + return Parser>::read(_r, _var).transform(to_box); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, - const Box& _box) noexcept { - return Parser>::write(_w, - *_box); + static OutputVarType write(const W& _w, const Box& _box) noexcept { + return Parser>::write(_w, *_box); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { const auto to_type = [](const auto& _str) { return Literal<_fields...>::from_string(_str); @@ -265,7 +260,7 @@ struct Parser> { } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const Literal<_fields...>& _literal) noexcept { return _w.from_basic_type(_literal.name()); } @@ -275,25 +270,25 @@ struct Parser> { /// Used for maps for which the key type is std::string. These are represented /// as objects. -template +template +requires AreReaderAndWriter struct MapParser { public: - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; using ValueType = std::decay_t; - static Result read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result read(const R& _r, InputVarType* _var) noexcept { const auto get_pair = [&](auto& _pair) { const auto to_pair = [&](ValueType&& _val) { return std::make_pair(std::move(_pair.first), std::move(_val)); }; - return Parser>::read(_r, &_pair.second) + return Parser>::read(_r, + &_pair.second) .transform(to_pair) .value(); }; @@ -314,42 +309,42 @@ struct MapParser { return _r.to_object(_var).and_then(to_map); } - static OutputVarType write(const WriterType& _w, - const MapType& _m) noexcept { + static OutputVarType write(const W& _w, const MapType& _m) noexcept { auto obj = _w.new_object(); for (const auto& [k, v] : _m) { - _w.set_field( - k, - Parser>::write( - _w, v), - &obj); + _w.set_field(k, Parser>::write(_w, v), + &obj); } return obj; } }; -template -struct Parser> - : public MapParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public MapParser> { +}; -template -struct Parser> - : public MapParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public MapParser> { +}; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; public: /// Generates a NamedTuple from a JSON Object. - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { const auto to_fields_array = [&](auto _obj) { return _r.template to_fields_array( @@ -362,7 +357,7 @@ struct Parser> { } /// Transforms a NamedTuple into a JSON object. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const NamedTuple& _tup) noexcept { auto obj = _w.new_object(); build_object_recursively(_w, _tup, &obj); @@ -373,7 +368,7 @@ struct Parser> { /// Builds the named tuple field by field. template static Result> build_named_tuple_recursively( - const ReaderType& _r, + const R& _r, const std::array, sizeof...(FieldTypes)>& _fields_vec, Args&&... _args) noexcept { @@ -424,7 +419,7 @@ struct Parser> { /// just good UX. template static Error collect_errors( - const ReaderType& _r, + const R& _r, const std::array, sizeof...(FieldTypes)>& _fields_vec, std::vector _errors) noexcept { @@ -472,7 +467,7 @@ struct Parser> { /// Builds the object field by field. template - static void build_object_recursively(const WriterType& _w, + static void build_object_recursively(const W& _w, const NamedTuple& _tup, OutputObjectType* _ptr) noexcept { if constexpr (_i >= sizeof...(FieldTypes)) { @@ -482,8 +477,7 @@ struct Parser> { typename std::tuple_element<_i, std::tuple>::type; using ValueType = std::decay_t; - auto value = Parser::write( - _w, rfl::get<_i>(_tup)); + auto value = Parser::write(_w, rfl::get<_i>(_tup)); const auto name = FieldType::name_.str(); if constexpr (!is_required()) { if (!_w.is_empty(&value)) { @@ -503,21 +497,20 @@ struct Parser> { if (field_indices_.size() == 0) { set_field_indices(); } - return Parser>::field_indices_; + return Parser>::field_indices_; } /// Retrieves the value from the object. This is mainly needed to /// generate a better error message. template - static auto get_value(const ReaderType& _r, InputVarType _var) noexcept { + static auto get_value(const R& _r, InputVarType _var) noexcept { const auto embellish_error = [&](const Error& _e) { const auto key = FieldType::name_.str(); return Error("Failed to parse field '" + key + "': " + _e.what()); }; using ValueType = std::decay_t; - return Parser::read(_r, &_var) - .or_else(embellish_error); + return Parser::read(_r, &_var).or_else( + embellish_error); } /// Builds the object field by field. @@ -530,8 +523,7 @@ struct Parser> { typename std::tuple_element<_i, std::tuple>::type; const auto name = FieldType::name_.string_view(); - Parser>::field_indices_[name] = _i; + Parser>::field_indices_[name] = _i; set_field_indices<_i + 1>(); } } @@ -543,66 +535,64 @@ struct Parser> { // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { if (_r.is_empty(_var)) { return std::optional(); } const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; - return Parser>::read(_r, _var) - .transform(to_opt); + return Parser>::read(_r, _var).transform(to_opt); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::optional& _o) noexcept { if (!_o) { return _w.empty_var(); } - return Parser>::write(_w, *_o); + return Parser>::write(_w, *_o); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result> read(const R& _r, InputVarType* _var) noexcept { const auto to_ref = [&](auto&& _t) { return Ref::make(std::move(_t)); }; - return Parser>::read(_r, _var) - .transform(to_ref); + return Parser>::read(_r, _var).transform(to_ref); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, - const Ref& _ref) noexcept { - return Parser>::write(_w, - *_ref); + static OutputVarType write(const W& _w, const Ref& _ref) noexcept { + return Parser>::write(_w, *_ref); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { if (_r.is_empty(_var)) { return std::shared_ptr(); @@ -610,67 +600,66 @@ struct Parser> { const auto to_ptr = [](auto&& _t) { return std::make_shared(std::move(_t)); }; - return Parser>::read(_r, _var) - .transform(to_ptr); + return Parser>::read(_r, _var).transform(to_ptr); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::shared_ptr& _s) noexcept { if (!_s) { return _w.empty_var(); } - return Parser>::write(_w, *_s); + return Parser>::write(_w, *_s); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. static Result> read( - const ReaderType& _r, InputVarType* _var) noexcept { + const R& _r, InputVarType* _var) noexcept { const auto to_pair = [&](auto&& _t) { return std::make_pair(std::move(std::get<0>(_t)), std::move(std::get<1>(_t))); }; - return Parser>::read(_r, _var) + return Parser>::read(_r, _var) .transform(to_pair); } /// Transform a std::pair into an array static OutputVarType write( - const WriterType& _w, - const std::pair& _p) noexcept { + const W& _w, const std::pair& _p) noexcept { const auto tup = std::make_tuple(&_p.first, &_p.second); return Parser< - ReaderType, WriterType, - std::tuple>::write(_w, tup); + R, W, std::tuple>::write(_w, + tup); } }; // ---------------------------------------------------------------------------- -template -struct Parser> { +template +requires AreReaderAndWriter> +struct Parser> { using ResultType = Result>; public: - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static ResultType read(const ReaderType& _r, InputVarType* _var) noexcept { + static ResultType read(const R& _r, InputVarType* _var) noexcept { const auto get_disc = [&_r](auto _obj) { return get_discriminator(_r, &_obj); }; @@ -684,19 +673,17 @@ struct Parser& - _tagged_union) noexcept { + const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>& + _tagged_union) noexcept { using VariantType = typename TaggedUnion<_discriminator, AlternativeTypes...>::VariantType; - return Parser::write( - _w, _tagged_union.variant_); + return Parser::write(_w, _tagged_union.variant_); } private: template - static ResultType find_matching_alternative(const ReaderType& _r, + static ResultType find_matching_alternative(const R& _r, const std::string& _disc_value, InputVarType* _var) noexcept { if constexpr (_i == sizeof...(AlternativeTypes)) { @@ -720,8 +707,7 @@ struct Parser::read( - _r, _var) + return Parser::read(_r, _var) .transform(to_tagged_union) .or_else(embellish_error); @@ -733,7 +719,7 @@ struct Parser get_discriminator( - const ReaderType& _r, InputObjectType* _obj) noexcept { + const R& _r, InputObjectType* _obj) noexcept { const auto embellish_error = [](const auto& _err) { return Error( "Could not parse tagged union: Could not find field '" + @@ -767,16 +753,17 @@ struct Parser -struct Parser> { +template +requires AreReaderAndWriter> +struct Parser> { public: - using InputArrayType = typename ReaderType::InputArrayType; - using InputVarType = typename ReaderType::InputVarType; + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename WriterType::OutputArrayType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { const auto to_vec = [&](auto _arr) { return _r.to_vec(&_arr); }; @@ -800,7 +787,7 @@ struct Parser> { .and_then(extract); } - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::tuple& _tup) noexcept { auto arr = _w.new_array(); to_array<0>(_w, _tup, &arr); @@ -811,7 +798,7 @@ struct Parser> { /// Extracts values from the array, field by field. template static Result> extract_field_by_field( - const ReaderType& _r, std::vector _vec, + const R& _r, std::vector _vec, AlreadyExtracted&&... _already_extracted) noexcept { constexpr size_t i = sizeof...(AlreadyExtracted); if constexpr (i == sizeof...(Ts)) { @@ -829,25 +816,23 @@ struct Parser> { /// Extracts a single field from a JSON. template - static auto extract_single_field(const ReaderType& _r, + static auto extract_single_field(const R& _r, std::vector* _vec) noexcept { using NewFieldType = std::decay_t< typename std::tuple_element<_i, std::tuple>::type>; - return Parser::read( - _r, &((*_vec)[_i])); + return Parser::read(_r, &((*_vec)[_i])); } /// Transforms a tuple to an array. template - static void to_array(const WriterType& _w, const std::tuple& _tup, + static void to_array(const W& _w, const std::tuple& _tup, OutputArrayType* _ptr) noexcept { if constexpr (_i < sizeof...(Ts)) { using NewFieldType = std::decay_t< typename std::tuple_element<_i, std::tuple>::type>; const auto val = - Parser::write( - _w, std::get<_i>(_tup)); + Parser::write(_w, std::get<_i>(_tup)); _w.add(val, _ptr); to_array<_i + 1>(_w, _tup, _ptr); } @@ -856,13 +841,14 @@ struct Parser> { // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const ReaderType& _r, + static Result> read(const R& _r, InputVarType* _var) noexcept { if (_r.is_empty(_var)) { return std::unique_ptr(); @@ -870,17 +856,16 @@ struct Parser> { const auto to_ptr = [](auto&& _t) { return std::make_unique(std::move(_t)); }; - return Parser>::read(_r, _var) - .transform(to_ptr); + return Parser>::read(_r, _var).transform(to_ptr); } /// Expresses the variable a a JSON. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::unique_ptr& _s) noexcept { if (!_s) { return _w.empty_var(); } - return Parser>::write(_w, *_s); + return Parser>::write(_w, *_s); } }; @@ -888,19 +873,20 @@ struct Parser> { /// To be used when all options of the variants are rfl::Field. Essentially, /// this is an externally tagged union. -template +template +requires AreReaderAndWriter> struct FieldVariantParser { using ResultType = Result>; public: - using InputObjectType = typename ReaderType::InputObjectType; - using InputVarType = typename ReaderType::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename WriterType::OutputObjectType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static ResultType read(const ReaderType& _r, InputVarType* _var) noexcept { + static ResultType read(const R& _r, InputVarType* _var) noexcept { static_assert( internal::no_duplicate_field_names>(), "Externally tagged variants cannot have duplicate field " @@ -925,7 +911,7 @@ struct FieldVariantParser { } /// Expresses the variables as a JSON type. - static OutputVarType write(const WriterType& _w, + static OutputVarType write(const W& _w, const std::variant& _v) noexcept { static_assert( internal::no_duplicate_field_names>(), @@ -936,8 +922,7 @@ struct FieldVariantParser { const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); using NamedTupleType = std::decay_t; - return Parser::write( - _w, named_tuple); + return Parser::write(_w, named_tuple); }; return std::visit(handle, _v); @@ -945,7 +930,7 @@ struct FieldVariantParser { private: template - static ResultType find_matching_alternative(const ReaderType& _r, + static ResultType find_matching_alternative(const R& _r, const std::string& _disc_value, InputVarType* _var) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { @@ -972,7 +957,7 @@ struct FieldVariantParser { _disc_value + "': " + _e.what()); }; - return Parser::read(_r, _var) + return Parser::read(_r, _var) .transform(to_variant) .or_else(embellish_error); } else { @@ -984,20 +969,20 @@ struct FieldVariantParser { // ---------------------------------------------------------------------------- -template -struct Parser> { - using InputVarType = typename ReaderType::InputVarType; - using OutputVarType = typename WriterType::OutputVarType; +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. template static Result> read( - const ReaderType& _r, InputVarType* _var, + const R& _r, InputVarType* _var, const std::string _errors = "") noexcept { if constexpr (_i == 0 && internal::all_fields>()) { - return FieldVariantParser::read(_r, _var); + return FieldVariantParser::read(_r, _var); } else if constexpr (_i == sizeof...(FieldTypes)) { return Error("Could not parse variant: " + _errors); } else { @@ -1014,7 +999,7 @@ struct Parser> { using AltType = std::decay_t< std::variant_alternative_t<_i, std::variant>>; - return Parser::read(_r, _var) + return Parser::read(_r, _var) .transform(to_variant) .or_else(try_next); } @@ -1022,15 +1007,13 @@ struct Parser> { /// Expresses the variables as a JSON type. static OutputVarType write( - const WriterType& _w, - const std::variant& _variant) noexcept { + const W& _w, const std::variant& _variant) noexcept { if constexpr (internal::all_fields>()) { - return FieldVariantParser::write(_w, _variant); + return FieldVariantParser::write(_w, _variant); } else { const auto handle = [&](const auto& _v) { using Type = std::decay_t; - return Parser::write(_w, _v); + return Parser::write(_w, _v); }; return std::visit(handle, _variant); } @@ -1043,33 +1026,31 @@ struct Parser> { /// serialized format (std::vector, std::set, std::deque, ...), /// but also includes map-like types, when the key is not of type /// std::string. -template +template +requires AreReaderAndWriter struct VectorParser { public: - using InputArrayType = typename ReaderType::InputArrayType; - using InputVarType = typename ReaderType::InputVarType; + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename WriterType::OutputArrayType; - using OutputVarType = typename WriterType::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; using T = typename VecType::value_type; - static Result read(const ReaderType& _r, - InputVarType* _var) noexcept { + static Result read(const R& _r, InputVarType* _var) noexcept { using namespace std::ranges::views; const auto get_elem = [&](auto& _v) { - return Parser>::read(_r, - &_v) - .value(); + return Parser>::read(_r, &_v).value(); }; const auto get_pair = [&](auto& _v) { if constexpr (is_map_like()) { using K = std::decay_t; using V = std::decay_t; - return Parser>>::read(_r, &_v) + return Parser>>::read(_r, + &_v) .value(); } }; @@ -1111,67 +1092,83 @@ struct VectorParser { return _r.to_array(_var).and_then(to_result); } - static OutputVarType write(const WriterType& _w, - const VecType& _vec) noexcept { + static OutputVarType write(const W& _w, const VecType& _vec) noexcept { auto arr = _w.new_array(); for (const auto& v : _vec) { - _w.add( - Parser>::write(_w, v), - &arr); + _w.add(Parser>::write(_w, v), &arr); } return OutputVarType(arr); } }; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; -template -struct Parser> - : public VectorParser> {}; +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; } // namespace parsing } // namespace rfl From 4fb6243d6facfb5a54b3a13819414fedaddf62e3 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 21 Oct 2023 21:58:45 +0200 Subject: [PATCH 34/48] Refined the concepts and added comments --- include/rfl/json/Reader.hpp | 20 +++++----- include/rfl/json/Writer.hpp | 11 ++++-- include/rfl/parsing/AreReaderAndWriter.hpp | 2 +- include/rfl/parsing/IsReader.hpp | 46 +++++++++++++++++++++- include/rfl/parsing/IsWriter.hpp | 24 +++++++++-- include/rfl/parsing/Parser.hpp | 39 ++++++++++-------- 6 files changed, 106 insertions(+), 36 deletions(-) diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index 1e43f489..e4f7e527 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -33,6 +33,7 @@ struct Reader { }; struct YYJSONInputVar { + YYJSONInputVar() : val_(nullptr) {} YYJSONInputVar(yyjson_val* _val) : val_(_val) {} yyjson_val* val_; }; @@ -64,8 +65,8 @@ struct Reader { return var; } - bool is_empty(InputVarType* _var) const noexcept { - return !_var->val_ || yyjson_is_null(_var->val_); + bool is_empty(const InputVarType& _var) const noexcept { + return !_var.val_ || yyjson_is_null(_var.val_); } template @@ -103,19 +104,18 @@ struct Reader { return InputArrayType(_var->val_); } - template - std::array, size> to_fields_array( - const std::unordered_map& _field_indices, - InputObjectType* _obj) const noexcept { - std::array, size> f_arr; + template + std::array to_fields_array( + const FunctionType _fct, InputObjectType* _obj) const noexcept { + std::array f_arr; yyjson_obj_iter iter; yyjson_obj_iter_init(_obj->val_, &iter); yyjson_val* key; while ((key = yyjson_obj_iter_next(&iter))) { const char* k = yyjson_get_str(key); - const auto it = _field_indices.find(std::string_view(k)); - if (it != _field_indices.end()) { - f_arr[it->second] = InputVarType(yyjson_obj_iter_get_val(key)); + const auto ix = _fct(std::string_view(k)); + if (ix != -1) { + f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key)); } } return f_arr; diff --git a/include/rfl/json/Writer.hpp b/include/rfl/json/Writer.hpp index bd26e0fe..f628b5d2 100644 --- a/include/rfl/json/Writer.hpp +++ b/include/rfl/json/Writer.hpp @@ -13,6 +13,7 @@ #include #include "rfl/Result.hpp" +#include "rfl/always_false.hpp" namespace rfl { namespace json { @@ -55,7 +56,7 @@ struct Writer { } template - OutputVarType from_basic_type(const T _var) const noexcept { + OutputVarType from_basic_type(const T& _var) const noexcept { if constexpr (std::is_same, std::string>()) { return OutputVarType(yyjson_mut_strcpy(doc_, _var.c_str())); } else if constexpr (std::is_same, bool>()) { @@ -63,8 +64,10 @@ struct Writer { } else if constexpr (std::is_floating_point>()) { return OutputVarType( yyjson_mut_real(doc_, static_cast(_var))); - } else { + } else if constexpr (std::is_integral>()) { return OutputVarType(yyjson_mut_int(doc_, static_cast(_var))); + } else { + static_assert(rfl::always_false_v, "Unsupported type."); } } @@ -76,8 +79,8 @@ struct Writer { return OutputObjectType(yyjson_mut_obj(doc_)); } - bool is_empty(OutputVarType* _var) const noexcept { - return yyjson_mut_is_null(_var->val_); + bool is_empty(const OutputVarType& _var) const noexcept { + return yyjson_mut_is_null(_var.val_); } void set_field(const std::string& _name, const OutputVarType& _var, diff --git a/include/rfl/parsing/AreReaderAndWriter.hpp b/include/rfl/parsing/AreReaderAndWriter.hpp index 962f6390..70648a3c 100644 --- a/include/rfl/parsing/AreReaderAndWriter.hpp +++ b/include/rfl/parsing/AreReaderAndWriter.hpp @@ -8,7 +8,7 @@ namespace rfl { namespace parsing { template -concept AreReaderAndWriter = IsReader && IsWriter; +concept AreReaderAndWriter = IsReader && IsWriter; } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp index 99c1fcbd..ce95d882 100644 --- a/include/rfl/parsing/IsReader.hpp +++ b/include/rfl/parsing/IsReader.hpp @@ -1,8 +1,12 @@ #ifndef RFL_PARSING_ISREADER_HPP_ #define RFL_PARSING_ISREADER_HPP_ +#include #include -#include +#include +#include +#include +#include #include "rfl/Result.hpp" @@ -10,26 +14,64 @@ namespace rfl { namespace parsing { template -concept IsReader = requires(R r, typename R::InputArrayType arr, +concept IsReader = requires(R r, std::string name, + std::function fct, + typename R::InputArrayType arr, typename R::InputObjectType obj, typename R::InputVarType var) { + /// Any Reader needs to define the following: + /// + /// 1) An InputArrayType, which must be an array-like data structure. + /// 2) An InputObjectType, which must contain key-value pairs. + /// 3) An InputVarType, which must be able to represent either + /// InputArrayType, InputObjectType or a basic type (bool, integral, + /// floating point, std::string). + /// 4) A static constexpr bool has_custom_constructor, that determines + /// whether the class in question as a custom constructor, which might + /// be called something like from_json_obj(...). + + /// Retrieves a particular field from an object. + { + r.get_field(name, &obj) + } -> std::same_as>; + + /// Determines whether a variable is empty (the NULL type). + { r.is_empty(var) } -> std::same_as; + + /// Transforms var to a basic type (bool, integral, + /// floating point, std::string) { r.template to_basic_type(&var) } -> std::same_as>; + /// fct is a function that turns the field name into the field index of the + /// struct. It returns -1, if the fields does not exist on the struct. This + /// returns an std::array that can be used to build up the struct. + { + r.template to_fields_array<6>(fct, &obj) + } -> std::same_as>; + + /// Casts var as an InputArrayType. { r.to_array(&var) } -> std::same_as>; + /// Iterates through an object and writes the contained key-value pairs into + /// a vector. { r.to_map(&obj) } -> std::same_as< std::vector>>; + /// Casts var as an InputObjectType. { r.to_object(&var) } -> std::same_as>; + /// Iterates through an array and writes the contained vars into + /// a vector. { r.to_vec(&arr) } -> std::same_as>; + /// Uses the custom constructor, if it has been determined that T has one + /// (see above). { r.template use_custom_constructor(&var) } -> std::same_as>; diff --git a/include/rfl/parsing/IsWriter.hpp b/include/rfl/parsing/IsWriter.hpp index 11c89a2f..351f114f 100644 --- a/include/rfl/parsing/IsWriter.hpp +++ b/include/rfl/parsing/IsWriter.hpp @@ -8,21 +8,39 @@ namespace rfl { namespace parsing { -template -concept IsWriter = requires(W w, std::string name, +template +concept IsWriter = requires(W w, T t, std::string name, typename W::OutputArrayType arr, typename W::OutputObjectType obj, typename W::OutputVarType var) { + /// Any Writer needs to define the following: + /// + /// 1) An OutputArrayType, which must be an array-like data structure. + /// 2) An OutputObjectType, which must contain key-value pairs. + /// 3) An OutputVarType, which must be able to represent either + /// OutputArrayType, OutputObjectType or a basic type (bool, integral, + /// floating point, std::string). + + /// Appends var to the end of arr, thus mutating it. { w.add(var, &arr) } -> std::same_as; + /// Returns an empty var (usually the NULL type). { w.empty_var() } -> std::same_as; + /// Generates a var from a basic type (std::string, bool, floating point or + /// integral). + { w.from_basic_type(t) } -> std::same_as; + + /// Generates a new, empty array. { w.new_array() } -> std::same_as; + /// Generates a new, empty object. { w.new_object() } -> std::same_as; - { w.is_empty(&var) } -> std::same_as; + /// Determines whether the var is empty (the NULL type). + { w.is_empty(var) } -> std::same_as; + /// Adds a new field to obj, thus mutating it. { w.set_field(name, var, &obj) } -> std::same_as; }; diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index cf28477a..fc2a9da3 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -346,9 +347,15 @@ struct Parser> { /// Generates a NamedTuple from a JSON Object. static Result> read(const R& _r, InputVarType* _var) noexcept { + const auto& indices = field_indices(); + const auto fct = [&](const std::string_view& _str) -> std::int16_t { + const auto it = indices.find(_str); + return it != indices.end() ? it->second + : static_cast(-1); + }; const auto to_fields_array = [&](auto _obj) { - return _r.template to_fields_array( - field_indices(), &_obj); + return _r.template to_fields_array(fct, + &_obj); }; const auto build = [&](auto _fields_vec) { return build_named_tuple_recursively(_r, _fields_vec); @@ -369,8 +376,7 @@ struct Parser> { template static Result> build_named_tuple_recursively( const R& _r, - const std::array, sizeof...(FieldTypes)>& - _fields_vec, + const std::array& _fields_vec, Args&&... _args) noexcept { constexpr auto i = sizeof...(Args); @@ -384,7 +390,7 @@ struct Parser> { const auto& f = std::get(_fields_vec); - if (!f) { + if (_r.is_empty(f)) { if constexpr (is_required()) { const auto key = FieldType::name_.str(); return collect_errors( @@ -409,7 +415,7 @@ struct Parser> { _r, _fields_vec, std::vector({std::move(_error)})); }; - return get_value(_r, *f) + return get_value(_r, f) .or_else(handle_error) .and_then(build); } @@ -420,8 +426,7 @@ struct Parser> { template static Error collect_errors( const R& _r, - const std::array, sizeof...(FieldTypes)>& - _fields_vec, + const std::array& _fields_vec, std::vector _errors) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { if (_errors.size() == 1) { @@ -443,7 +448,7 @@ struct Parser> { const auto& f = std::get<_i>(_fields_vec); - if (!f) { + if (_r.is_empty(f)) { if constexpr (is_required()) { const auto key = FieldType::name_.str(); _errors.emplace_back( @@ -459,7 +464,7 @@ struct Parser> { return _error; }; - get_value(_r, *f).or_else(add_error_if_applicable); + get_value(_r, f).or_else(add_error_if_applicable); return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors)); } @@ -480,7 +485,7 @@ struct Parser> { auto value = Parser::write(_w, rfl::get<_i>(_tup)); const auto name = FieldType::name_.str(); if constexpr (!is_required()) { - if (!_w.is_empty(&value)) { + if (!_w.is_empty(value)) { _w.set_field(name, value, _ptr); } } else { @@ -523,14 +528,16 @@ struct Parser> { typename std::tuple_element<_i, std::tuple>::type; const auto name = FieldType::name_.string_view(); - Parser>::field_indices_[name] = _i; + Parser>::field_indices_[name] = + static_cast(_i); set_field_indices<_i + 1>(); } } private: /// Maps each of the field names to an index signifying their order. - static inline std::unordered_map field_indices_; + static inline std::unordered_map + field_indices_; }; // ---------------------------------------------------------------------------- @@ -544,7 +551,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, InputVarType* _var) noexcept { - if (_r.is_empty(_var)) { + if (_r.is_empty(*_var)) { return std::optional(); } const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; @@ -594,7 +601,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, InputVarType* _var) noexcept { - if (_r.is_empty(_var)) { + if (_r.is_empty(*_var)) { return std::shared_ptr(); } const auto to_ptr = [](auto&& _t) { @@ -850,7 +857,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, InputVarType* _var) noexcept { - if (_r.is_empty(_var)) { + if (_r.is_empty(*_var)) { return std::unique_ptr(); } const auto to_ptr = [](auto&& _t) { From fe1b2d141e05217e4b0e3a0109f2e027f0b6bc71 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sat, 21 Oct 2023 22:41:36 +0200 Subject: [PATCH 35/48] Removed unnecessary indirection --- include/rfl/json/Reader.hpp | 56 ++++++------- include/rfl/json/read.hpp | 4 +- include/rfl/parsing/CustomParser.hpp | 2 +- include/rfl/parsing/IsReader.hpp | 16 ++-- include/rfl/parsing/Parser.hpp | 113 ++++++++++++++------------- 5 files changed, 97 insertions(+), 94 deletions(-) diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index e4f7e527..e5ddf40e 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -54,10 +54,9 @@ struct Reader { template static constexpr bool has_custom_constructor = has_from_json_obj::value; - rfl::Result get_field(const std::string& _name, - InputObjectType* _obj) const noexcept { - const auto var = - InputVarType(yyjson_obj_get(_obj->val_, _name.c_str())); + rfl::Result get_field( + const std::string& _name, const InputObjectType _obj) const noexcept { + const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str())); if (!var.val_) { return rfl::Error("Object contains no field named '" + _name + "'."); @@ -65,51 +64,52 @@ struct Reader { return var; } - bool is_empty(const InputVarType& _var) const noexcept { + bool is_empty(const InputVarType _var) const noexcept { return !_var.val_ || yyjson_is_null(_var.val_); } template - rfl::Result to_basic_type(InputVarType* _var) const noexcept { + rfl::Result to_basic_type(const InputVarType _var) const noexcept { if constexpr (std::is_same, std::string>()) { - const auto r = yyjson_get_str(_var->val_); + const auto r = yyjson_get_str(_var.val_); if (r == NULL) { return rfl::Error("Could not cast to string."); } return std::string(r); } else if constexpr (std::is_same, bool>()) { - if (!yyjson_is_bool(_var->val_)) { + if (!yyjson_is_bool(_var.val_)) { return rfl::Error("Could not cast to boolean."); } - return yyjson_get_bool(_var->val_); + return yyjson_get_bool(_var.val_); } else if constexpr (std::is_floating_point>()) { - if (!yyjson_is_num(_var->val_)) { + if (!yyjson_is_num(_var.val_)) { return rfl::Error("Could not cast to double."); } - return static_cast(yyjson_get_num(_var->val_)); + return static_cast(yyjson_get_num(_var.val_)); } else if constexpr (std::is_integral>()) { - if (!yyjson_is_int(_var->val_)) { + if (!yyjson_is_int(_var.val_)) { return rfl::Error("Could not cast to int."); } - return static_cast(yyjson_get_int(_var->val_)); + return static_cast(yyjson_get_int(_var.val_)); } else { static_assert(rfl::always_false_v, "Unsupported type."); } } - rfl::Result to_array(InputVarType* _var) const noexcept { - if (!yyjson_is_arr(_var->val_)) { + rfl::Result to_array( + const InputVarType _var) const noexcept { + if (!yyjson_is_arr(_var.val_)) { return rfl::Error("Could not cast to array!"); } - return InputArrayType(_var->val_); + return InputArrayType(_var.val_); } template std::array to_fields_array( - const FunctionType _fct, InputObjectType* _obj) const noexcept { + const FunctionType _fct, const InputObjectType _obj) const noexcept { std::array f_arr; yyjson_obj_iter iter; - yyjson_obj_iter_init(_obj->val_, &iter); + yyjson_obj_iter_init(_obj.val_, &iter); yyjson_val* key; while ((key = yyjson_obj_iter_next(&iter))) { const char* k = yyjson_get_str(key); @@ -122,10 +122,10 @@ struct Reader { } std::vector> to_map( - InputObjectType* _obj) const noexcept { + const InputObjectType _obj) const noexcept { std::vector> m; yyjson_obj_iter iter; - yyjson_obj_iter_init(_obj->val_, &iter); + yyjson_obj_iter_init(_obj.val_, &iter); yyjson_val* key; while ((key = yyjson_obj_iter_next(&iter))) { auto p = std::make_pair(yyjson_get_str(key), @@ -135,18 +135,19 @@ struct Reader { return m; } - rfl::Result to_object(InputVarType* _var) const noexcept { - if (!yyjson_is_obj(_var->val_)) { + rfl::Result to_object( + const InputVarType _var) const noexcept { + if (!yyjson_is_obj(_var.val_)) { return rfl::Error("Could not cast to object!"); } - return InputObjectType(_var->val_); + return InputObjectType(_var.val_); } - std::vector to_vec(InputArrayType* _arr) const noexcept { + std::vector to_vec(const InputArrayType _arr) const noexcept { std::vector vec; yyjson_val* val; yyjson_arr_iter iter; - yyjson_arr_iter_init(_arr->val_, &iter); + yyjson_arr_iter_init(_arr.val_, &iter); while ((val = yyjson_arr_iter_next(&iter))) { vec.push_back(InputVarType(val)); } @@ -154,9 +155,10 @@ struct Reader { } template - rfl::Result use_custom_constructor(InputVarType* _var) const noexcept { + rfl::Result use_custom_constructor( + const InputVarType _var) const noexcept { try { - return T::from_json_obj(*_var); + return T::from_json_obj(_var); } catch (std::exception& e) { return rfl::Error(e.what()); } diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index 0f5ca6d5..82a041e2 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -20,9 +20,9 @@ Result read(const std::string& _json_str) { using PtrType = std::unique_ptr; yyjson_doc* doc = yyjson_read(_json_str.c_str(), _json_str.size(), 0); const auto ptr = PtrType(doc, yyjson_doc_free); - InputVarType root = InputVarType(yyjson_doc_get_root(doc)); + const auto root = InputVarType(yyjson_doc_get_root(doc)); const auto r = Reader(); - return Parser::read(r, &root); + return Parser::read(r, root); } } // namespace json diff --git a/include/rfl/parsing/CustomParser.hpp b/include/rfl/parsing/CustomParser.hpp index bbe3424e..6c26fc20 100644 --- a/include/rfl/parsing/CustomParser.hpp +++ b/include/rfl/parsing/CustomParser.hpp @@ -15,7 +15,7 @@ template struct CustomParser { static Result read(const ReaderType& _r, - auto* _var) noexcept { + const auto& _var) noexcept { const auto to_class = [](auto&& _h) -> Result { try { if constexpr (internal::has_to_class_method_v) { diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp index ce95d882..d3db7adc 100644 --- a/include/rfl/parsing/IsReader.hpp +++ b/include/rfl/parsing/IsReader.hpp @@ -32,7 +32,7 @@ concept IsReader = requires(R r, std::string name, /// Retrieves a particular field from an object. { - r.get_field(name, &obj) + r.get_field(name, obj) } -> std::same_as>; /// Determines whether a variable is empty (the NULL type). @@ -40,40 +40,40 @@ concept IsReader = requires(R r, std::string name, /// Transforms var to a basic type (bool, integral, /// floating point, std::string) - { r.template to_basic_type(&var) } -> std::same_as>; + { r.template to_basic_type(var) } -> std::same_as>; /// fct is a function that turns the field name into the field index of the /// struct. It returns -1, if the fields does not exist on the struct. This /// returns an std::array that can be used to build up the struct. { - r.template to_fields_array<6>(fct, &obj) + r.template to_fields_array<6>(fct, obj) } -> std::same_as>; /// Casts var as an InputArrayType. { - r.to_array(&var) + r.to_array(var) } -> std::same_as>; /// Iterates through an object and writes the contained key-value pairs into /// a vector. { - r.to_map(&obj) + r.to_map(obj) } -> std::same_as< std::vector>>; /// Casts var as an InputObjectType. { - r.to_object(&var) + r.to_object(var) } -> std::same_as>; /// Iterates through an array and writes the contained vars into /// a vector. - { r.to_vec(&arr) } -> std::same_as>; + { r.to_vec(arr) } -> std::same_as>; /// Uses the custom constructor, if it has been determined that T has one /// (see above). { - r.template use_custom_constructor(&var) + r.template use_custom_constructor(var) } -> std::same_as>; }; diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index fc2a9da3..d6395ab0 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -62,7 +62,7 @@ struct Parser { using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result read(const R& _r, InputVarType* _var) noexcept { + static Result read(const R& _r, const InputVarType& _var) noexcept { if constexpr (R::template has_custom_constructor) { return _r.template use_custom_constructor(_var); } else { @@ -124,7 +124,7 @@ struct Parser { using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result read(const R& _r, InputVarType* _var) noexcept { + static Result read(const R& _r, const InputVarType& _var) noexcept { static_assert( always_false_v, "Reading into raw pointers is dangerous and therefore unsupported. " @@ -154,9 +154,9 @@ struct Parser> { using OutputArrayType = typename W::OutputArrayType; using OutputVarType = typename W::OutputVarType; - static Result> read(const R& _r, - InputVarType* _var) noexcept { - const auto to_vec = [&](auto _arr) { return _r.to_vec(&_arr); }; + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto to_vec = [&](const auto& _arr) { return _r.to_vec(_arr); }; const auto check_size = [](auto _vec) -> Result> { @@ -202,15 +202,15 @@ struct Parser> { std::move(_already_extracted)..., std::move(new_entry)); }; - return extract_single_field(_r, &_vec).and_then(extract_next); + return extract_single_field(_r, _vec).and_then(extract_next); } } /// Extracts a single field from a JSON. template - static auto extract_single_field(const R& _r, - std::vector* _vec) noexcept { - return Parser::read(_r, &((*_vec)[_i])); + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { + return Parser::read(_r, _vec[_i]); } }; @@ -223,7 +223,7 @@ struct Parser> { using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const R& _r, InputVarType* _var) noexcept { + static Result> read(const R& _r, const InputVarType& _var) noexcept { const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; @@ -246,7 +246,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, - InputVarType* _var) noexcept { + const InputVarType& _var) noexcept { const auto to_type = [](const auto& _str) { return Literal<_fields...>::from_string(_str); }; @@ -283,19 +283,20 @@ struct MapParser { using ValueType = std::decay_t; - static Result read(const R& _r, InputVarType* _var) noexcept { + static Result read(const R& _r, + const InputVarType& _var) noexcept { const auto get_pair = [&](auto& _pair) { const auto to_pair = [&](ValueType&& _val) { return std::make_pair(std::move(_pair.first), std::move(_val)); }; - return Parser>::read(_r, - &_pair.second) + return Parser>::read(_r, _pair.second) .transform(to_pair) .value(); }; - const auto to_map = [&_r, get_pair](auto _obj) -> Result { - auto m = _r.to_map(&_obj); + const auto to_map = [&_r, + get_pair](const auto& _obj) -> Result { + auto m = _r.to_map(_obj); MapType res; try { for (auto& p : m) { @@ -345,8 +346,8 @@ struct Parser> { public: /// Generates a NamedTuple from a JSON Object. - static Result> read(const R& _r, - InputVarType* _var) noexcept { + static Result> read( + const R& _r, const InputVarType& _var) noexcept { const auto& indices = field_indices(); const auto fct = [&](const std::string_view& _str) -> std::int16_t { const auto it = indices.find(_str); @@ -355,7 +356,7 @@ struct Parser> { }; const auto to_fields_array = [&](auto _obj) { return _r.template to_fields_array(fct, - &_obj); + _obj); }; const auto build = [&](auto _fields_vec) { return build_named_tuple_recursively(_r, _fields_vec); @@ -508,14 +509,13 @@ struct Parser> { /// Retrieves the value from the object. This is mainly needed to /// generate a better error message. template - static auto get_value(const R& _r, InputVarType _var) noexcept { + static auto get_value(const R& _r, const InputVarType _var) noexcept { const auto embellish_error = [&](const Error& _e) { const auto key = FieldType::name_.str(); return Error("Failed to parse field '" + key + "': " + _e.what()); }; using ValueType = std::decay_t; - return Parser::read(_r, &_var).or_else( - embellish_error); + return Parser::read(_r, _var).or_else(embellish_error); } /// Builds the object field by field. @@ -550,8 +550,8 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, - InputVarType* _var) noexcept { - if (_r.is_empty(*_var)) { + const InputVarType& _var) noexcept { + if (_r.is_empty(_var)) { return std::optional(); } const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; @@ -577,7 +577,7 @@ struct Parser> { using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static Result> read(const R& _r, InputVarType* _var) noexcept { + static Result> read(const R& _r, const InputVarType& _var) noexcept { const auto to_ref = [&](auto&& _t) { return Ref::make(std::move(_t)); }; @@ -600,7 +600,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, - InputVarType* _var) noexcept { + const InputVarType& _var) noexcept { if (_r.is_empty(*_var)) { return std::shared_ptr(); } @@ -630,7 +630,7 @@ struct Parser> { /// Expresses the variables as type T. static Result> read( - const R& _r, InputVarType* _var) noexcept { + const R& _r, const InputVarType& _var) noexcept { const auto to_pair = [&](auto&& _t) { return std::make_pair(std::move(std::get<0>(_t)), std::move(std::get<1>(_t))); @@ -666,9 +666,9 @@ struct Parser> { using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static ResultType read(const R& _r, InputVarType* _var) noexcept { + static ResultType read(const R& _r, const InputVarType& _var) noexcept { const auto get_disc = [&_r](auto _obj) { - return get_discriminator(_r, &_obj); + return get_discriminator(_r, _obj); }; const auto to_result = [&_r, _var](const std::string& _disc_value) { @@ -690,9 +690,9 @@ struct Parser> { private: template - static ResultType find_matching_alternative(const R& _r, - const std::string& _disc_value, - InputVarType* _var) noexcept { + static ResultType find_matching_alternative( + const R& _r, const std::string& _disc_value, + const InputVarType& _var) noexcept { if constexpr (_i == sizeof...(AlternativeTypes)) { return Error("Could not parse tagged union, could not match " + _discriminator.str() + " '" + _disc_value + "'."); @@ -726,7 +726,7 @@ struct Parser> { /// Retrieves the discriminator. static Result get_discriminator( - const R& _r, InputObjectType* _obj) noexcept { + const R& _r, const InputObjectType& _obj) noexcept { const auto embellish_error = [](const auto& _err) { return Error( "Could not parse tagged union: Could not find field '" + @@ -734,7 +734,7 @@ struct Parser> { }; const auto to_type = [&_r](auto _var) { - return _r.template to_basic_type(&_var); + return _r.template to_basic_type(_var); }; return _r.get_field(_discriminator.str(), _obj) @@ -771,8 +771,8 @@ struct Parser> { using OutputVarType = typename W::OutputVarType; static Result> read(const R& _r, - InputVarType* _var) noexcept { - const auto to_vec = [&](auto _arr) { return _r.to_vec(&_arr); }; + const InputVarType& _var) noexcept { + const auto to_vec = [&](auto _arr) { return _r.to_vec(_arr); }; const auto check_size = [](auto _vec) -> Result> { @@ -817,17 +817,17 @@ struct Parser> { std::move(_already_extracted)..., std::move(new_entry)); }; - return extract_single_field(_r, &_vec).and_then(extract_next); + return extract_single_field(_r, _vec).and_then(extract_next); } } /// Extracts a single field from a JSON. template - static auto extract_single_field(const R& _r, - std::vector* _vec) noexcept { + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { using NewFieldType = std::decay_t< typename std::tuple_element<_i, std::tuple>::type>; - return Parser::read(_r, &((*_vec)[_i])); + return Parser::read(_r, _vec[_i]); } /// Transforms a tuple to an array. @@ -856,8 +856,8 @@ struct Parser> { /// Expresses the variables as type T. static Result> read(const R& _r, - InputVarType* _var) noexcept { - if (_r.is_empty(*_var)) { + const InputVarType& _var) noexcept { + if (_r.is_empty(_var)) { return std::unique_ptr(); } const auto to_ptr = [](auto&& _t) { @@ -893,13 +893,13 @@ struct FieldVariantParser { using OutputVarType = typename W::OutputVarType; /// Expresses the variables as type T. - static ResultType read(const R& _r, InputVarType* _var) noexcept { + static ResultType read(const R& _r, const InputVarType& _var) noexcept { static_assert( internal::no_duplicate_field_names>(), "Externally tagged variants cannot have duplicate field " "names."); - const auto to_map = [&](auto _obj) { return _r.to_map(&_obj); }; + const auto to_map = [&](auto _obj) { return _r.to_map(_obj); }; const auto to_result = [&](auto _map) -> ResultType { if (_map.size() != 1) { @@ -910,8 +910,8 @@ struct FieldVariantParser { } const auto it = _map.begin(); const auto& disc_value = it->first; - auto& var = it->second; - return find_matching_alternative(_r, disc_value, &var); + const auto& var = it->second; + return find_matching_alternative(_r, disc_value, var); }; return _r.to_object(_var).transform(to_map).and_then(to_result); @@ -937,9 +937,9 @@ struct FieldVariantParser { private: template - static ResultType find_matching_alternative(const R& _r, - const std::string& _disc_value, - InputVarType* _var) noexcept { + static ResultType find_matching_alternative( + const R& _r, const std::string& _disc_value, + const InputVarType& _var) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { return Error( "Could not parse std::variant, could not match field named " @@ -985,7 +985,7 @@ struct Parser> { /// Expresses the variables as type T. template static Result> read( - const R& _r, InputVarType* _var, + const R& _r, const InputVarType& _var, const std::string _errors = "") noexcept { if constexpr (_i == 0 && internal::all_fields>()) { @@ -999,7 +999,8 @@ struct Parser> { const auto try_next = [&_r, _var, &_errors](const auto& _err) { auto errors = _errors; - errors += std::string("\n -") + _err.what(); + errors += std::string("\n " + std::to_string(_i + 1) + ")") + + _err.what(); return read<_i + 1>(_r, _var, errors); }; @@ -1045,26 +1046,26 @@ struct VectorParser { using T = typename VecType::value_type; - static Result read(const R& _r, InputVarType* _var) noexcept { + static Result read(const R& _r, + const InputVarType& _var) noexcept { using namespace std::ranges::views; const auto get_elem = [&](auto& _v) { - return Parser>::read(_r, &_v).value(); + return Parser>::read(_r, _v).value(); }; const auto get_pair = [&](auto& _v) { if constexpr (is_map_like()) { using K = std::decay_t; using V = std::decay_t; - return Parser>>::read(_r, - &_v) + return Parser>>::read(_r, _v) .value(); } }; const auto to_container = [&](InputArrayType&& _arr) -> Result { - auto input_vars = _r.to_vec(&_arr); + auto input_vars = _r.to_vec(_arr); VecType vec; if constexpr (is_forward_list()) { for (auto it = input_vars.rbegin(); it != input_vars.rend(); From b081cd0a30fe56377200e68fc7de05115ec4ad28 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sun, 22 Oct 2023 17:44:07 +0200 Subject: [PATCH 36/48] Removed "no dependencies" claim --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 146d2aec..2bd502d7 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Design principles for reflect-cpp include: - Close integration with containers from the C++ standard library - Close adherence to C++ idioms -- Out-of-the-box support for JSON, no dependencies +- Out-of-the-box support for JSON - Simple installation: If no JSON support is required, reflect-cpp is header-only. For JSON support, only a single source file needs to be compiled. - Simple extendability to other serialization formats - Simple extendability to custom classes From 32bc4fd0758600c56fa590cd16019d4b99b7a8e4 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sun, 22 Oct 2023 18:29:37 +0200 Subject: [PATCH 37/48] Added default constructors for Ref and Box --- include/rfl/Box.hpp | 2 ++ include/rfl/Ref.hpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index dd107edd..998be07b 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -18,6 +18,8 @@ class Box { return Box(std::make_unique(std::forward(_args)...)); } + Box() : ptr_(std::make_unique()) {} + Box(const Box& _other) = delete; Box(Box&& _other) = default; diff --git a/include/rfl/Ref.hpp b/include/rfl/Ref.hpp index 866791ea..90f2ba50 100644 --- a/include/rfl/Ref.hpp +++ b/include/rfl/Ref.hpp @@ -18,6 +18,8 @@ class Ref { return Ref(std::make_shared(std::forward(_args)...)); } + Ref() : ptr_(std::make_shared()) {} + Ref(const Ref& _other) = default; Ref(Ref&& _other) = default; From 548fefe38b665e1ed26a3fb99e64ad5afccfdda7 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sun, 22 Oct 2023 19:06:43 +0200 Subject: [PATCH 38/48] Create supporting_your_own_format.md --- docs/supporting_your_own_format.md | 99 ++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 docs/supporting_your_own_format.md diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md new file mode 100644 index 00000000..7efd131f --- /dev/null +++ b/docs/supporting_your_own_format.md @@ -0,0 +1,99 @@ +# Supporting your own format + +In order to support your own serialization format, you need to implement a reader and a writer for your concept. + +The reader and writer constitute a thin layer between the serialization library of your choice and reflect-cpp. + +The requirements are laid down in the concepts [IsReader](https://github.com/getml/reflect-cpp/blob/main/include/rfl/parsing/IsReader.hpp) and +[IsWriter](https://github.com/getml/reflect-cpp/blob/main/include/rfl/parsing/IsWriter.hpp) and also documented below. + +Using the reader and the writer you can define your parser like this: + +```cpp +template +using YourParser = rfl::parsing::Parser; +``` + +This can then be used to implement a `read` function and a `write` function: + +```cpp +using InputVarType = typename YourReader::InputVarType; +using OutputVarType = typename YourWriter::OutputVarType; + +template +rfl::Result read(const std::string& _str) { + // This should be supported by whatever library you are + // using for your format. + const InputVarType root = str_to_input_var(_str); + + // You can pass variables to the constructor, if necessary + const auto r = Reader(...); + + return YourParser::read(r, root); +} + +template +std::string write(const T& _obj) { + // You can pass variables to the constructor, if necessary + auto w = Writer(...); + + OutputVarType var = Parser::write(w, _obj); + + // This should be supported by whatever library you are + // using for your format. + return output_var_to_str(var); +} +``` + +In the following two sections, we will provide templates for your `Reader` and `Writer`. +You should probably just Copy + Paste this into your own code and fill in the blanks. + +## Implementing your own writer + +Because writers are somewhat simpler, we will start with them. + +Any Writer needs to define the following types: + +1) An `OutputArrayType`, which must be an array-like data structure. +2) An `OutputObjectType`, which must contain key-value pairs. +3) An `OutputVarType`, which must be able to represent either + OutputArrayType, OutputObjectType or a basic type (bool, integral, + floating point, std::string). We hesitate to call these "primitive types", + because primitive types in C++ are defined as a slightly different group + of types. + +It also needs to support the following methods: + +```cpp +struct Writer { + using OutputArrayType = ...; + using OutputObjectType = ...; + using OutputVarType = ...; + + /// Appends `_var` to the end of `_arr`, thus mutating it. + void add(const OutputVarType _var, OutputArrayType* _arr) const noexcept {...} + + /// Returns an empty OutputVarType, the NULL type of the format. + OutputVarType empty_var() const noexcept {...} + + /// Generates an OutputVarType from a basic type + /// (std::string, bool, floating point or integral). + template + OutputVarType from_basic_type(const T& _var) const noexcept {...} + + /// Generates a new, empty array. + OutputArrayType new_array() const noexcept {...} + + /// Generates a new, empty object. + OutputObjectType new_object() const noexcept {...} + + /// Determines whether the var is empty (whether it is the NULL type). + bool is_empty(const OutputVarType& _var) const noexcept {...} + + /// Adds a new field to obj, thus mutating it. + void set_field(const std::string& _name, const OutputVarType& _var, + OutputObjectType* _obj) const noexcept {...} +}; +``` + +## Implementing your own reader From 882abbc7896a187a8fb21d797d292b88ea435df3 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sun, 22 Oct 2023 19:42:39 +0200 Subject: [PATCH 39/48] Added documentation for the custom reader --- docs/supporting_your_own_format.md | 120 ++++++++++++++++++++++++++++- 1 file changed, 119 insertions(+), 1 deletion(-) diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md index 7efd131f..983dad33 100644 --- a/docs/supporting_your_own_format.md +++ b/docs/supporting_your_own_format.md @@ -1,6 +1,7 @@ # Supporting your own format -In order to support your own serialization format, you need to implement a reader and a writer for your concept. +In order to support your own serialization format, you need to implement a reader and a writer on top of whatever serialization libary +you have chosen. The reader and writer constitute a thin layer between the serialization library of your choice and reflect-cpp. @@ -97,3 +98,120 @@ struct Writer { ``` ## Implementing your own reader + +Any Reader needs to define the following: + +1) An `InputArrayType`, which must be an array-like data structure. +2) An `InputObjectType`, which must contain key-value pairs. +3) An `InputVarType`, which must be able to represent either + `InputArrayType`, `InputObjectType` or a basic type (bool, integral, + floating point, std::string). +4) A `static constexpr bool has_custom_constructor`, that determines + whether the class in question as a custom constructor, which might + be called something like `from_json_obj(...)`. If you do not want to + support this functionality, just set it to false. + +It also needs to support the following methods: + +```cpp +struct Reader { + using InputArrayType = ...; + using InputObjectType = ...; + using InputVarType = ...; + + /// If you do not want to support custom constructors, + /// just set this to false. + template + static constexpr bool has_custom_constructor = false; + + /// Retrieves a particular field from an object. + /// Returns an rfl::Error if the field cannot be found. + rfl::Result get_field( + const std::string& _name, const InputObjectType& _obj) const noexcept {...} + + /// Determines whether a variable is empty (the NULL type). + bool is_empty(const InputVarType& _var) const noexcept {...} + + /// Cast _var as a basic type (bool, integral, + /// floating point, std::string). + /// Returns an rfl::Error if it cannot be cast + /// as that type + template + rfl::Result to_basic_type(const InputVarType& _var) const noexcept {...} + + /// Casts _var as an InputArrayType. + /// Returns an rfl::Error if `_var` cannot be cast as an array. + rfl::Result to_array(const InputVarType& _var) const noexcept {...} + + /// fct is a function that turns the field name into the field index of the + /// struct. It returns -1, if the fields does not exist on the struct. This + /// returns an std::array that can be used to build up the struct. + /// See below for a more comprehensive explanation. + template + std::array to_fields_array( + const FunctionType _fct, const InputObjectType& _obj) const noexcept {...} + + /// Iterates through an object and writes the contained key-value pairs into + /// a vector. + std::vector> to_map( + const InputObjectType& _obj) const noexcept {...} + + /// Casts _var as an InputObjectType. + /// Returns an rfl::Error if `_var` cannot be cast as an object. + rfl::Result to_object( + const InputVarType& _var) const noexcept {...} + + /// Iterates through an array and writes the contained values into + /// a std::vector. + std::vector to_vec(const InputArrayType& _arr) const noexcept {...} + + /// Constructs T using its custom constructor. This will only be triggered if + /// T was determined to have a custom constructor by + /// static constexpr bool has_custom_constructor, as defined above. + /// Returns an rfl::Error, if the custom constructor throws an exception. + template + rfl::Result use_custom_constructor( + const InputVarType& _var) const noexcept { + // If you do not want to support this functionality, + // just return this. + return rfl::Error("Not supported."); + } +}; +``` + +Of these methods, `to_fields_array` probably requires futher explanation. + +Consider the following struct: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + rfl::Field<"children", std::vector> children; +}; +``` + +This struct contains four fields. `rfl::parsing::Parser` expects `to_fields_array` +to return an `std::array` containing the field "firstName" in the +first position, "lastName" in the second position, "birthday" in the third position +and "children" in the fourth position. + +`rfl::parsing::Parser` will pass the following two elements: + +1. A function `_fct` of type `FunctionType`. +2. An object `_obj` of type `InputObjectType`. + +`_fct` takes a field name of type `std::string_view` as an input and +returns an index. This index signifies the position in the `std::array` +it wants this field to have. If the field is not contained in the struct, +the index will be -1. + +Your job is to implement the following: + +1. Iterate through `_obj`. +2. Identify the required index of the field name using `_fct`. +3. Set the corresponding field in `std::array` to the field value associated with the field name. +4. Any field that could not be set in steps 1-3 must be set to the NULL value, + such that `Reader.is_empty(...)` would return `true`. + From 96599faaf2420975682237199d8b5b1779d496b1 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sun, 22 Oct 2023 19:44:21 +0200 Subject: [PATCH 40/48] Update README.md --- docs/README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/README.md b/docs/README.md index bb1f70ec..2d6e57ee 100644 --- a/docs/README.md +++ b/docs/README.md @@ -40,3 +40,7 @@ 4.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md) +## 5) Advanced topics + +5.1) [Supporting your own format](https://github.com/getml/reflect-cpp/blob/main/docs/supporting_your_own_format.md) - For supporting your own serialization and deserialization formats. + From 6bf12bedb4db69f09e81e59d092702f8b227cda3 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sun, 22 Oct 2023 19:45:21 +0200 Subject: [PATCH 41/48] Update supporting_your_own_format.md --- docs/supporting_your_own_format.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md index 983dad33..cecaeb9e 100644 --- a/docs/supporting_your_own_format.md +++ b/docs/supporting_your_own_format.md @@ -47,7 +47,7 @@ std::string write(const T& _obj) { ``` In the following two sections, we will provide templates for your `Reader` and `Writer`. -You should probably just Copy + Paste this into your own code and fill in the blanks. +You should probably just copy + paste this into your own code and fill in the blanks. ## Implementing your own writer From 99358eea8239314c3cf78319ce8d516ec2c415ea Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Sun, 22 Oct 2023 19:49:00 +0200 Subject: [PATCH 42/48] Update supporting_your_own_format.md --- docs/supporting_your_own_format.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md index cecaeb9e..ad1230b2 100644 --- a/docs/supporting_your_own_format.md +++ b/docs/supporting_your_own_format.md @@ -58,7 +58,7 @@ Any Writer needs to define the following types: 1) An `OutputArrayType`, which must be an array-like data structure. 2) An `OutputObjectType`, which must contain key-value pairs. 3) An `OutputVarType`, which must be able to represent either - OutputArrayType, OutputObjectType or a basic type (bool, integral, + `OutputArrayType`, `OutputObjectType` or a basic type (bool, integral, floating point, std::string). We hesitate to call these "primitive types", because primitive types in C++ are defined as a slightly different group of types. From 6e38653a20a16463baac5a828bc9bd3009c2d472 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Mon, 23 Oct 2023 18:48:59 +0200 Subject: [PATCH 43/48] Added a reference to the JSON implementation --- docs/supporting_your_own_format.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md index ad1230b2..1b7d7537 100644 --- a/docs/supporting_your_own_format.md +++ b/docs/supporting_your_own_format.md @@ -49,6 +49,8 @@ std::string write(const T& _obj) { In the following two sections, we will provide templates for your `Reader` and `Writer`. You should probably just copy + paste this into your own code and fill in the blanks. +As a reference, you can take a look at how this is done for JSON: https://github.com/getml/reflect-cpp/tree/main/include/rfl/json + ## Implementing your own writer Because writers are somewhat simpler, we will start with them. From f48e0ff4253af39cbbe8737cbc4c5f6284232911 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Tue, 24 Oct 2023 21:30:24 +0200 Subject: [PATCH 44/48] Greatly simplified constructible_with_n_fields --- include/rfl/internal/has_n_fields.hpp | 1020 +------------------------ 1 file changed, 12 insertions(+), 1008 deletions(-) diff --git a/include/rfl/internal/has_n_fields.hpp b/include/rfl/internal/has_n_fields.hpp index e1dcbf9b..625fbeef 100644 --- a/include/rfl/internal/has_n_fields.hpp +++ b/include/rfl/internal/has_n_fields.hpp @@ -7,1022 +7,26 @@ namespace rfl { namespace internal { -template -concept aggregate = std::is_aggregate_v; - -template -concept constructable = aggregate && requires { - T{std::declval()...}; -}; - struct any { template constexpr operator T() const noexcept; }; -template -struct constructable_with_n_fields; +template +struct constructible_with_n_fields_impl : std::false_type {}; -/*The following boilerplate code was generated using a Python script: +template +struct constructible_with_n_fields_impl< + T, std::index_sequence, + std::void_t> : std::true_type {}; -def has_field_template(num: int) -> str: - anys = "".join([", any"] * num) - return """ - template - struct constructable_with_n_fields { - static constexpr bool value = constructable; - }; - """.replace( - "{num}", str(num) - ).replace( - "{anys}", anys - ) +template +using constructible_with_n_fields = + constructible_with_n_fields_impl>; - -code = "".join((has_field_template(i) for i in range(102))) -with open("generated_code.cpp", "w", encoding="utf-8") as codefile: - codefile.write(code) - -*/ - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = - constructable; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any>; -}; - -template -struct constructable_with_n_fields { - static constexpr bool value = constructable< - T, any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any, any, any, any, any, any, any, any, any, any, any, any, - any, any, any>; -}; - -// --------------------------------- -// End of generated boilerplate code -// --------------------------------- - -template -constexpr bool has_n_fields = constructable_with_n_fields::value && - !constructable_with_n_fields::value; +template +constexpr bool has_n_fields = constructible_with_n_fields::value && + !constructible_with_n_fields::value; } // namespace internal } // namespace rfl From 4d967ccde26ccce4184a510b1f28d20371d4aea7 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Wed, 25 Oct 2023 20:23:16 +0200 Subject: [PATCH 45/48] Added support custom constructors with results --- include/rfl/json/Reader.hpp | 6 ++++ include/rfl/json/read.hpp | 11 +++++-- tests/test_custom_constructor.hpp | 52 +++++++++++++++++++++++++++++++ tests/tests.cpp | 3 ++ 4 files changed, 69 insertions(+), 3 deletions(-) create mode 100644 tests/test_custom_constructor.hpp diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index e5ddf40e..bb091643 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -51,6 +51,12 @@ struct Reader { typename Reader::InputVarType>::value>> : std::true_type {}; + template + struct has_from_json_obj, decltype(T::from_json_obj), + typename Reader::InputVarType>::value>> + : std::true_type {}; + template static constexpr bool has_custom_constructor = has_from_json_obj::value; diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index 82a041e2..10f67666 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -14,15 +14,20 @@ namespace json { using InputObjectType = typename Reader::InputObjectType; using InputVarType = typename Reader::InputVarType; +/// Parses an object from a JSON var. +template +Result read(const InputVarType& _obj) { + const auto r = Reader(); + return Parser::read(r, _obj); +} + /// Parses an object from JSON using reflection. template Result read(const std::string& _json_str) { using PtrType = std::unique_ptr; yyjson_doc* doc = yyjson_read(_json_str.c_str(), _json_str.size(), 0); const auto ptr = PtrType(doc, yyjson_doc_free); - const auto root = InputVarType(yyjson_doc_get_root(doc)); - const auto r = Reader(); - return Parser::read(r, root); + return read(InputVarType(yyjson_doc_get_root(doc))); } } // namespace json diff --git a/tests/test_custom_constructor.hpp b/tests/test_custom_constructor.hpp new file mode 100644 index 00000000..4ca9c657 --- /dev/null +++ b/tests/test_custom_constructor.hpp @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +// Makes sure that the example in the README works as expected. +// It would be embarrassing if it didn't... +void test_custom_constructor() { + std::cout << "test_custom_constructor" << std::endl; + + struct Person { + static rfl::Result from_json_obj( + typename rfl::json::Reader::InputVarType _obj) { + /// This only exists for the purpose of the test. + const auto change_first_name = [](auto&& _person) { + return rfl::replace( + std::move(_person), + rfl::Field<"firstName", std::string>("Bart")); + }; + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::json::read>(_obj) + .transform(from_nt) + .transform(change_first_name); + } + + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + }; + + const auto res = rfl::json::read( + R"({"firstName":"Homer","lastName":"Simpson","birthday":"1987-04-19"})"); + + if (!res) { + std::cout << "Test failed on read. Error: " + << res.error().value().what() << std::endl; + return; + } + + if (res.value().first_name() != "Bart") { + std::cout << "Expected 'Bart', got '" << res.value().first_name() << "'" + << std::endl + << std::endl; + } else { + std::cout << "OK" << std::endl << std::endl; + } +} diff --git a/tests/tests.cpp b/tests/tests.cpp index 871285c4..ebb3de95 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -6,6 +6,7 @@ #include "test_custom_class2.hpp" #include "test_custom_class3.hpp" #include "test_custom_class4.hpp" +#include "test_custom_constructor.hpp" #include "test_default_values.hpp" #include "test_deque.hpp" #include "test_error_messages.hpp" @@ -77,5 +78,7 @@ int main() { test_as(); test_as_flatten(); + test_custom_constructor(); + return 0; } From 4fca517f8f37b9028f12602bb067f0e562935e74 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 25 Oct 2023 20:31:40 +0200 Subject: [PATCH 46/48] Added documentation on custom constructors --- docs/json.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/docs/json.md b/docs/json.md index db5c91e1..cc24e5f0 100644 --- a/docs/json.md +++ b/docs/json.md @@ -2,6 +2,8 @@ For JSON support, you must also include the header ``. +## Reading and writing + Suppose you have a struct like this: ```cpp @@ -26,6 +28,8 @@ const auto person = Person{...}; const std::string json_string = rfl::json::write(person); ``` +## Loading and saving + You can also load and save to disc using a very similar syntax: ```cpp @@ -35,5 +39,43 @@ const auto person = Person{...}; rfl::json::save("/path/to/file.json", person); ``` +## Custom constructors +One of the great things about C++ is that it gives you control over +when and how you code is compiled. + +For large and complex systems of structs, it is often a good idea to split up +your code into smaller compilation units. You can do so using custom constructors. + +For the JSON format, these must be a static function on your struct or class called +`from_json_obj` that take a `rfl::json::Reader::InputVarType` as input and return +the class or the class wrapped in `rfl::Result`. + +In your header file you can write something like this: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + + using JSONVar = typename rfl::json::Reader::InputVarType; + static rfl::Result from_json_obj(const JSONVar& _obj); +}; +``` + +And in your source file, you implement `from_json_obj` as follows: + +```cpp +rfl::Result Person::from_json_obj(const JSONVar& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::json::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the JSON parsing when the +source file is compiled. From 8f7c84954c7ce541ea75e1b820d74d29ac587f04 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Wed, 25 Oct 2023 22:05:12 +0200 Subject: [PATCH 47/48] Added more functionality to Box --- include/rfl/Box.hpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index 998be07b..6efd45c3 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -24,6 +24,11 @@ class Box { Box(Box&& _other) = default; + template , + bool>::type = true> + Box(Box&& _other) noexcept + : ptr_(std::make_unique(std::forward(*_other))) {} + ~Box() = default; /// Returns a pointer to the underlying object @@ -35,9 +40,23 @@ class Box { /// Move assignment operator Box& operator=(Box&& _other) noexcept = default; + /// Move assignment operator + template , + bool>::type = true> + Box& operator=(Box&& _other) noexcept { + ptr_ = std::make_unique(std::forward(*_other)); + return *this; + } + + /// Returns the underlying object. + T& operator*() { return *ptr_; } + /// Returns the underlying object. T& operator*() const { return *ptr_; } + /// Returns the underlying object. + T* operator->() { return ptr_.get(); } + /// Returns the underlying object. T* operator->() const { return ptr_.get(); } @@ -59,6 +78,18 @@ Box make_box(Args&&... _args) { return Box::make(std::forward(_args)...); } +template +inline auto operator<=>(const Box& _t1, const Box& _t2) { + return _t1.ptr() <=> _t2.ptr(); +} + +template +inline std::basic_ostream& operator<<( + std::basic_ostream& _os, const Box& _b) { + _os << _b.get(); + return _os; +} + } // namespace rfl #endif From b9a4542ea09ffce2a9119f267a5e93b73be0c552 Mon Sep 17 00:00:00 2001 From: Jeremy Perez Date: Fri, 27 Oct 2023 12:46:17 +0200 Subject: [PATCH 48/48] adapted test. --- include/rfl/Validator.hpp | 118 ++++++++++++++++++++++++++++++++++++++ tests/test_constr.hpp | 58 +++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 include/rfl/Validator.hpp create mode 100644 tests/test_constr.hpp diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp new file mode 100644 index 00000000..0a656b0e --- /dev/null +++ b/include/rfl/Validator.hpp @@ -0,0 +1,118 @@ +#ifndef RFL_VALIDATOR_HPP_ +#define RFL_VALIDATOR_HPP_ + +#include +#include +#include +#include +#include + +#include "internal/StringLiteral.hpp" +#include "rfl/Result.hpp" + +namespace rfl { + +template +concept HasValidation = requires(Class obj, Type value) { + { Class::validate(value) } -> std::same_as>; +}; + +template +concept HasDescription = requires(_Type obj) { + { obj.description } -> std::same_as>; +}; + + +template +requires HasValidation +struct Annotate { + public: + using ReflectionType = _Type; + ReflectionType value; + + template , bool> = true > + Annotate(const T& _value) : value(_value) { + std::optional validate_check = Class::validate(value); + if (validate_check.has_value()) { + throw std::runtime_error(validate_check.value().what()); + } + }; + + template , bool> = true > + Annotate(T&& _value) : value(std::forward(_value)) { + std::optional validate_check = Class::validate(value); + if (validate_check.has_value()) { + throw std::runtime_error(validate_check.value().what()); + } + } + + Annotate(ReflectionType _value) : value(_value) { + std::optional validate_check = Class::validate(value); + if (validate_check.has_value()) { + throw std::runtime_error(validate_check.value().what()); + } + } + +}; + +template +std::string to_string(const T& _value) { + std::ostringstream oss; + oss << _value; + return oss.str(); +} + +template +concept HasSize = requires(T obj) { + { obj.size() } -> std::same_as; +}; + +template +concept HasIntLength = HasSize || std::is_integral_v; + +template +struct Length { + static constexpr const auto min_length = _min_length; + static constexpr const auto max_length = _max_length; + + template + static std::optional validate(T _value) { + uint16_t size; + if constexpr (HasSize) { + size = _value.size(); + } else if (std::is_integral_v) { + size = _value; + } + if (size < _min_length) { + return rfl::Error("'" + to_string(_value) + + "' is less than the min length requirement of '" + + std::to_string(_min_length) + "'"); + } + if (size > _max_length) { + return rfl::Error("'" + to_string(_value) + + "' exceeds max length requirement of '" + + std::to_string(_max_length) + "'"); + } + return std::nullopt; + } +}; + +template +struct Pattern { + static constexpr const auto pattern = _pattern; + + static std::optional validate(std::string _value) { + std::regex regex_pattern(_pattern.str()); + if (!std::regex_match(_value, regex_pattern)) { + return rfl::Error("String '" + _value + "' did not match format '" + + _pattern.str() + "'"); + } + return std::nullopt; + } +}; + +} // namespace rfl +// +#endif diff --git a/tests/test_constr.hpp b/tests/test_constr.hpp new file mode 100644 index 00000000..0fd41da4 --- /dev/null +++ b/tests/test_constr.hpp @@ -0,0 +1,58 @@ +#include +#include + +#include "write_and_read.hpp" +void test_constr() { + std::cout << "test_constr" << std::endl; + + // Custom validation for string + // Masked credit cards + using MaskedCreditCardType = rfl::Annotate>; + //// Nick name between 5 and 10 characters long without regex use + using NickNameType = rfl::Annotate>; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + //rfl::Field<"id", rfl::UUIDv4> id; + //rfl::Field<"payload", rfl::Base64Encoded> payload; + rfl::Field<"maskedCreditCard", MaskedCreditCardType> masked_credit_card; + rfl::Field<"nickName", NickNameType> nick_name; + }; + + try { + const auto wrong_bart = Person{ + .first_name = "Bart", + //.id = "de76b905-5b32-4127-96d1-48e5321e11a6", + //.payload = "aGVsbG93b3JsZAo=", + .masked_credit_card = "XXXX-XXXX-XXXX-444A", + .nick_name = "Cosmo", + }; + } catch (const std::exception &e) { + std::cout << e.what() << std::endl; + //assert( + // e.what() == + // std::string( + // R"(String 'XXXX-XXXX-XXXX-444A' did not match format 'XXXX-XXXX-XXXX-\d{4}')")); + } + const auto correct_bart = Person{ + .first_name = "Bart", + //.id = "de76b905-5b32-4127-96d1-48e5321e11a6", + //.payload = "aGVsbG93b3JsZAo=", + .masked_credit_card = "XXXX-XXXX-XXXX-4440", + .nick_name = "Cosmo", + }; + + write_and_read(correct_bart, + "{\"firstName\":\"Bart\",\"lastName\":\"Simpson\"," + "\"id\":\"de76b905-5b32-4127-96d1-48e5321e11a6\"," + "\"payload\":\"aGVsbG93b3JsZAo=\"," + "\"maskedCreditCard\":\"XXXX-XXXX-XXXX-4440\"," + "\"nickName\":\"Cosmo\"}"); + + //struct Blub { + // rfl::Field<"firstName", + // rfl::Validate>; + //}; + // +}