From f9a16641c9c255de7a5b257090ea06a4bc959b1f Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sun, 5 Nov 2023 11:38:33 +0100 Subject: [PATCH] Added support for parsing results --- include/rfl/Result.hpp | 546 +++++------ include/rfl/parsing/Parser.hpp | 1610 ++++++++++++++++---------------- tests/test_result.hpp | 32 + tests/tests.cpp | 2 + 4 files changed, 1118 insertions(+), 1072 deletions(-) create mode 100644 tests/test_result.hpp diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 2c84ffc4..696c8016 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -13,17 +13,17 @@ namespace rfl { /// To be returned class Error { - public: - Error(const std::string& _what) : what_(_what) {} + public: + Error(const std::string& _what) : what_(_what) {} - ~Error() = default; + ~Error() = default; - /// Returns the error message, equivalent to .what() in std::exception. - const std::string& what() const { return what_; } + /// Returns the error message, equivalent to .what() in std::exception. + const std::string& what() const { return what_; } - private: - /// Documents what went wrong - std::string what_; + private: + /// Documents what went wrong + std::string what_; }; /// Can be used when we are simply interested in whether an operation was @@ -33,310 +33,310 @@ struct Nothing {}; /// The Result class is used for monadic error handling. template class Result { - static_assert(!std::is_same(), - "The result type cannot be Error."); + static_assert(!std::is_same(), "The result type cannot be Error."); - public: - Result(const T& _val) : t_or_err_(_val) {} + public: + Result(const T& _val) : t_or_err_(_val) {} - Result(T&& _val) noexcept : t_or_err_(std::move(_val)) {} + Result(T&& _val) noexcept : t_or_err_(std::move(_val)) {} - Result(const Error& _err) : t_or_err_(_err) {} + Result(const Error& _err) : t_or_err_(_err) {} - Result(Error&& _err) noexcept : t_or_err_(std::move(_err)) {} + 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_) {} + Result(Result&& _other) noexcept = default; - template , - bool>::type = true> - Result(const Result& _other) - : t_or_err_( - _other.transform([](const U& _u) { return T(_u); }).t_or_err_) {} + Result(const Result& _other) = default; - ~Result() = default; + template , + bool>::type = true> + Result(Result&& _other) + : t_or_err_(std::forward>(_other) + .transform([](U&& _u) { return T(std::forward(_u)); }) + .t_or_err_) {} - /// Returns Result, if successful and error otherwise. - /// Inspired by .and(...) in the Rust std::result type. - template - Result and_other(const Result& _r) const noexcept { - const auto f = [&](const auto& _) { return _r; }; - return and_then(f); - } + template , + bool>::type = true> + Result(const Result& _other) + : t_or_err_( + _other.transform([](const U& _u) { return T(_u); }).t_or_err_) {} - /// Monadic operation - F must be a function of type T -> Result. - template - auto and_then(const F& _f) { - /// Result_U is expected to be of type Result. - using Result_U = typename std::invoke_result::type; + ~Result() = default; - const auto handle_variant = - [&](TOrError&& _t_or_err) -> Result_U { - if constexpr (!std::is_same, Error>()) { - return _f(std::forward(_t_or_err)); - } else { - return std::forward(_t_or_err); - } - }; + /// Returns Result, if successful and error otherwise. + /// Inspired by .and(...) in the Rust std::result type. + template + Result and_other(const Result& _r) const noexcept { + const auto f = [&](const auto& _) { return _r; }; + return and_then(f); + } - return std::visit(handle_variant, - std::forward>(t_or_err_)); - } + /// Monadic operation - F must be a function of type T -> Result. + template + auto and_then(const F& _f) { + /// Result_U is expected to be of type Result. + using Result_U = typename std::invoke_result::type; - /// Monadic operation - F must be a function of type T -> Result. - template - auto and_then(const F& _f) const { - /// Result_U is expected to be of type Result. - using Result_U = typename std::invoke_result::type; + const auto handle_variant = + [&](TOrError&& _t_or_err) -> Result_U { + if constexpr (!std::is_same, Error>()) { + return _f(std::forward(_t_or_err)); + } else { + return std::forward(_t_or_err); + } + }; - const auto handle_variant = - [&](const TOrError& _t_or_err) -> Result_U { - if constexpr (!std::is_same()) { - return _f(_t_or_err); - } else { - return _t_or_err; - } - }; + return std::visit(handle_variant, + std::forward>(t_or_err_)); + } - return std::visit(handle_variant, t_or_err_); - } + /// Monadic operation - F must be a function of type T -> Result. + template + auto and_then(const F& _f) const { + /// Result_U is expected to be of type Result. + using Result_U = typename std::invoke_result::type; - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - T* begin() noexcept { - const auto get_ptr = - [this](const TOrError& _t_or_err) -> T* { - if constexpr (!std::is_same()) { - return &_t_or_err; - } else { - return nullptr; - } - }; - return std::visit(get_ptr, t_or_err_); - } + const auto handle_variant = + [&](const TOrError& _t_or_err) -> Result_U { + if constexpr (!std::is_same()) { + return _f(_t_or_err); + } else { + return _t_or_err; + } + }; - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - const T* begin() const noexcept { - const auto get_ptr = - [this](const TOrError& _t_or_err) -> const T* { - if constexpr (!std::is_same()) { - return &_t_or_err; - } else { - return nullptr; - } - }; - return std::visit(get_ptr, t_or_err_); - } + return std::visit(handle_variant, t_or_err_); + } - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - T* end() noexcept { - const auto get_ptr = - [this](const TOrError& _t_or_err) -> T* { - if constexpr (!std::is_same()) { - return &_t_or_err + 1; - } else { - return nullptr; - } - }; - return std::visit(get_ptr, t_or_err_); - } + /// Results types can be iterated over, which even make it possible to use + /// them within a std::range. + T* begin() noexcept { + const auto get_ptr = + [this](const TOrError& _t_or_err) -> T* { + if constexpr (!std::is_same()) { + return &_t_or_err; + } else { + return nullptr; + } + }; + return std::visit(get_ptr, t_or_err_); + } - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - const T* end() const noexcept { - const auto get_ptr = - [](const TOrError& _t_or_err) -> const T* { - if constexpr (!std::is_same()) { - return &_t_or_err + 1; - } else { - return nullptr; - } - }; - return std::visit(get_ptr, t_or_err_); - } + /// Results types can be iterated over, which even make it possible to use + /// them within a std::range. + const T* begin() const noexcept { + const auto get_ptr = + [this](const TOrError& _t_or_err) -> const T* { + if constexpr (!std::is_same()) { + return &_t_or_err; + } else { + return nullptr; + } + }; + return std::visit(get_ptr, t_or_err_); + } - /// Returns an std::optional if this does in fact contain an error - /// or std::nullopt otherwise. - std::optional error() const noexcept { - const auto get_err = - []( - const TOrError& _t_or_err) -> std::optional { - if constexpr (!std::is_same()) { - return std::nullopt; - } else { - return _t_or_err; - } - }; - return std::visit(get_err, t_or_err_); - } + /// Results types can be iterated over, which even make it possible to use + /// them within a std::range. + T* end() noexcept { + const auto get_ptr = + [this](const TOrError& _t_or_err) -> T* { + if constexpr (!std::is_same()) { + return &_t_or_err + 1; + } else { + return nullptr; + } + }; + return std::visit(get_ptr, t_or_err_); + } - /// Returns true if the result contains a value, false otherwise. - operator bool() const noexcept { - return !std::holds_alternative(t_or_err_); - } + /// Results types can be iterated over, which even make it possible to use + /// them within a std::range. + const T* end() const noexcept { + const auto get_ptr = + [](const TOrError& _t_or_err) -> const T* { + if constexpr (!std::is_same()) { + return &_t_or_err + 1; + } else { + return nullptr; + } + }; + return std::visit(get_ptr, t_or_err_); + } - /// Allows access to the underlying value. Careful: Will result in undefined - /// behavior, if the result contains an error. - T& operator*() { return *std::get_if(&t_or_err_); } + /// Returns an std::optional if this does in fact contain an error + /// or std::nullopt otherwise. + std::optional error() const noexcept { + const auto get_err = + [](const TOrError& _t_or_err) -> std::optional { + if constexpr (!std::is_same()) { + return std::nullopt; + } else { + return _t_or_err; + } + }; + return std::visit(get_err, t_or_err_); + } - /// Allows read access to the underlying value. Careful: Will result in - /// undefined behavior, if the result contains an error. - const T& operator*() const { return *std::get_if(&t_or_err_); } + /// Returns true if the result contains a value, false otherwise. + operator bool() const noexcept { + return !std::holds_alternative(t_or_err_); + } - /// Assigns the underlying object. - Result& operator=(const Result& _other) = default; + /// Allows access to the underlying value. Careful: Will result in undefined + /// behavior, if the result contains an error. + T& operator*() { return *std::get_if(&t_or_err_); } - /// Assigns the underlying object. - Result& operator=(Result&& _other) = default; + /// Allows read access to the underlying value. Careful: Will result in + /// undefined behavior, if the result contains an error. + const T& operator*() const { return *std::get_if(&t_or_err_); } - /// Assigns the underlying object. - template , - bool>::type = true> - 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; - } + /// Assigns the underlying object. + Result& operator=(const Result& _other) = default; - /// Expects a function that takes of type Error -> Result and returns - /// Result. - template - Result or_else(const F& _f) { - const auto handle_variant = - [&](TOrError&& _t_or_err) -> Result { - if constexpr (std::is_same, Error>()) { - return _f(std::forward(_t_or_err)); - } else { - return std::forward(_t_or_err); - } - }; - return std::visit(handle_variant, - std::forward>(t_or_err_)); - } + /// Assigns the underlying object. + Result& operator=(Result&& _other) = default; - /// Expects a function that takes of type Error -> Result and returns - /// Result. - template - Result or_else(const F& _f) const { - const auto handle_variant = - [&_f](const TOrError& _t_or_err) -> Result { - if constexpr (std::is_same()) { - return _f(_t_or_err); - } else { - return _t_or_err; - } - }; - return std::visit(handle_variant, t_or_err_); - } + /// Assigns the underlying object. + template , + bool>::type = true> + 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; + } - /// Returns the value contained if successful or the provided result r if - /// not. - Result or_other(const Result& _r) const noexcept { - const auto f = [&](const auto& _) { return _r; }; - return or_else(f); - } + /// Expects a function that takes of type Error -> Result and returns + /// Result. + template + Result or_else(const F& _f) { + const auto handle_variant = + [&](TOrError&& _t_or_err) -> Result { + if constexpr (std::is_same, Error>()) { + return _f(std::forward(_t_or_err)); + } else { + return std::forward(_t_or_err); + } + }; + return std::visit(handle_variant, + std::forward>(t_or_err_)); + } - /// Functor operation - F must be a function of type T -> U. - template - auto transform(const F& _f) { - /// Result_U is expected to be of type Result. - using U = typename std::invoke_result::type; + /// Expects a function that takes of type Error -> Result and returns + /// Result. + template + Result or_else(const F& _f) const { + const auto handle_variant = + [&_f](const TOrError& _t_or_err) -> Result { + if constexpr (std::is_same()) { + return _f(_t_or_err); + } else { + return _t_or_err; + } + }; + return std::visit(handle_variant, t_or_err_); + } - const auto handle_variant = - [&](TOrError&& _t_or_err) -> rfl::Result { - if constexpr (!std::is_same, Error>()) { - return _f(std::forward(_t_or_err)); - } else { - return std::forward(_t_or_err); - } - }; + /// Returns the value contained if successful or the provided result r if + /// not. + Result or_other(const Result& _r) const noexcept { + const auto f = [&](const auto& _) { return _r; }; + return or_else(f); + } - return std::visit(handle_variant, - std::forward>(t_or_err_)); - } + /// Functor operation - F must be a function of type T -> U. + template + auto transform(const F& _f) { + /// Result_U is expected to be of type Result. + using U = typename std::invoke_result::type; - /// Functor operation - F must be a function of type T -> U. - template - auto transform(const F& _f) const { - /// Result_U is expected to be of type Result. - using U = typename std::invoke_result::type; + const auto handle_variant = + [&](TOrError&& _t_or_err) -> rfl::Result { + if constexpr (!std::is_same, Error>()) { + return _f(std::forward(_t_or_err)); + } else { + return std::forward(_t_or_err); + } + }; - const auto handle_variant = - [&](const TOrError& _t_or_err) -> rfl::Result { - if constexpr (!std::is_same()) { - return _f(_t_or_err); - } else { - return _t_or_err; - } - }; + return std::visit(handle_variant, + std::forward>(t_or_err_)); + } - return std::visit(handle_variant, t_or_err_); - } + /// Functor operation - F must be a function of type T -> U. + template + auto transform(const F& _f) const { + /// Result_U is expected to be of type Result. + using U = typename std::invoke_result::type; - /// Returns the value if the result does not contain an error, throws an - /// exceptions if not. Similar to .unwrap() in Rust. - T value() { - const auto handle_variant = - [&](TOrError& _t_or_err) -> T { - if constexpr (!std::is_same()) { - return std::forward(_t_or_err); - } else { - throw std::runtime_error(_t_or_err.what()); - } - }; - return std::visit(handle_variant, t_or_err_); - } + const auto handle_variant = + [&](const TOrError& _t_or_err) -> rfl::Result { + if constexpr (!std::is_same()) { + return _f(_t_or_err); + } else { + return _t_or_err; + } + }; - /// Returns the value if the result does not contain an error, throws an - /// exceptions if not. Similar to .unwrap() in Rust. - const T& value() const { - const auto handle_variant = - [&](const TOrError& _t_or_err) -> const T& { - if constexpr (!std::is_same()) { - return _t_or_err; - } else { - throw std::runtime_error(_t_or_err.what()); - } - }; - return std::visit(handle_variant, t_or_err_); - } + 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 if the result does not contain an error, throws an + /// exceptions if not. Similar to .unwrap() in Rust. + T value() { + const auto handle_variant = [&](TOrError& _t_or_err) -> T { + if constexpr (!std::is_same()) { + return std::forward(_t_or_err); + } else { + throw std::runtime_error(_t_or_err.what()); + } + }; + 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 = - [&](const TOrError& _t_or_err) -> T { - if constexpr (!std::is_same()) { - return _t_or_err; - } else { - return _default; - } - }; - return std::visit(handle_variant, t_or_err_); - } + /// Returns the value if the result does not contain an error, throws an + /// exceptions if not. Similar to .unwrap() in Rust. + const T& value() const { + const auto handle_variant = + [&](const TOrError& _t_or_err) -> const T& { + if constexpr (!std::is_same()) { + return _t_or_err; + } else { + throw std::runtime_error(_t_or_err.what()); + } + }; + return std::visit(handle_variant, t_or_err_); + } - private: - /// The underlying variant, can either be T or Error. - std::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 = + [&](const TOrError& _t_or_err) -> T { + if constexpr (!std::is_same()) { + return _t_or_err; + } else { + return _default; + } + }; + return std::visit(handle_variant, t_or_err_); + } + + private: + /// The underlying variant, can either be T or Error. + std::variant t_or_err_; }; } // namespace rfl diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 8c8642cd..8b645429 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -59,100 +59,96 @@ struct Parser; template requires AreReaderAndWriter struct Parser { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - 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 { - if constexpr (internal::has_reflection_type_v) { - using ReflectionType = std::decay_t; - const auto wrap_in_t = [](auto _named_tuple) -> Result { - try { - return T(_named_tuple); - } catch (std::exception& e) { - return Error(e.what()); - } - }; - return Parser::read(_r, _var).and_then( - wrap_in_t); - } else if constexpr (std::is_class_v && std::is_aggregate_v) { - using NamedTupleType = named_tuple_t; - const auto to_struct = [](NamedTupleType&& _n) -> Result { - try { - return from_named_tuple(std::move(_n)); - } catch (std::exception& e) { - return Error(e.what()); - } - }; - return Parser::read(_r, _var).and_then( - to_struct); - } else if constexpr (internal::is_basic_type_v) { - return _r.template to_basic_type>(_var); - } else { - static_assert( - always_false_v, + /// Expresses the variables as type T. + 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 { + if constexpr (internal::has_reflection_type_v) { + using ReflectionType = std::decay_t; + const auto wrap_in_t = [](auto _named_tuple) -> Result { + try { + return T(_named_tuple); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + return Parser::read(_r, _var).and_then(wrap_in_t); + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + using NamedTupleType = named_tuple_t; + const auto to_struct = [](NamedTupleType&& _n) -> Result { + try { + return from_named_tuple(std::move(_n)); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + return Parser::read(_r, _var).and_then(to_struct); + } else if constexpr (internal::is_basic_type_v) { + return _r.template to_basic_type>(_var); + } else { + static_assert( + always_false_v, + "Unsupported type. Please refer to the sections on custom " + "classes and custom parsers for information on how add " + "support for your own classes."); + } + } + } + + /// Converts the variable to a JSON type. + 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()); + } else { + const auto& [r] = _var; + 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); + } else if constexpr (internal::is_basic_type_v) { + return _w.from_basic_type(_var); + } else { + static_assert(always_false_v, "Unsupported type. Please refer to the sections on custom " "classes and custom parsers for information on how add " "support for your own classes."); - } - } - } - - /// Converts the variable to a JSON type. - 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()); - } else { - const auto& [r] = _var; - 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); - } else if constexpr (internal::is_basic_type_v) { - return _w.from_basic_type(_var); - } else { - static_assert( - always_false_v, - "Unsupported type. Please refer to the sections on custom " - "classes and custom parsers for information on how add " - "support for your own classes."); - } } + } }; template requires AreReaderAndWriter struct Parser { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result read(const R& _r, const InputVarType& _var) noexcept { - static_assert(always_false_v, - "Reading into raw pointers is dangerous and " - "therefore unsupported. " - "Please consider using std::unique_ptr, rfl::Box, " - "std::shared_ptr, " - "rfl::Ref or std::optional instead."); - return Error("Unsupported."); - } + /// Expresses the variables as type T. + static Result read(const R& _r, const InputVarType& _var) noexcept { + static_assert(always_false_v, + "Reading into raw pointers is dangerous and " + "therefore unsupported. " + "Please consider using std::unique_ptr, rfl::Box, " + "std::shared_ptr, " + "rfl::Ref or std::optional instead."); + return Error("Unsupported."); + } - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const T* _ptr) noexcept { - if (!_ptr) { - return _w.empty_var(); - } - return Parser>::write(_w, *_ptr); + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const T* _ptr) noexcept { + if (!_ptr) { + return _w.empty_var(); } + return Parser>::write(_w, *_ptr); + } }; // ---------------------------------------------------------------------------- @@ -160,71 +156,69 @@ struct Parser { template requires AreReaderAndWriter> struct Parser> { - public: - using InputArrayType = typename R::InputArrayType; - using InputVarType = typename R::InputVarType; + public: + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename W::OutputArrayType; - using OutputVarType = typename W::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - static Result> read( - const R& _r, const InputVarType& _var) noexcept { - const auto to_vec = [&](const 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> { - if (_vec.size() != _size) { - return Error("Expected " + std::to_string(_size) + - " fields, got " + std::to_string(_vec.size()) + - "."); - } - return std::move(_vec); - }; + const auto check_size = [](auto _vec) -> Result> { + if (_vec.size() != _size) { + return Error("Expected " + std::to_string(_size) + " fields, got " + + std::to_string(_vec.size()) + "."); + } + return std::move(_vec); + }; - const auto extract = [&_r](auto _vec) { - return extract_field_by_field(_r, std::move(_vec)); - }; + const auto extract = [&_r](auto _vec) { + return extract_field_by_field(_r, std::move(_vec)); + }; - return _r.to_array(_var) - .transform(to_vec) - .and_then(check_size) - .and_then(extract); + return _r.to_array(_var) + .transform(to_vec) + .and_then(check_size) + .and_then(extract); + } + + 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); } + return OutputVarType(arr); + } - 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); - } - return OutputVarType(arr); + private: + /// Extracts values from the array, field by field. + template + static Result> extract_field_by_field( + const R& _r, std::vector _vec, + AlreadyExtracted&&... _already_extracted) noexcept { + constexpr size_t i = sizeof...(AlreadyExtracted); + if constexpr (i == _size) { + return std::array({std::move(_already_extracted)...}); + } else { + const auto extract_next = [&](auto&& new_entry) { + return extract_field_by_field(_r, std::move(_vec), + std::move(_already_extracted)..., + std::move(new_entry)); + }; + return extract_single_field(_r, _vec).and_then(extract_next); } + } - private: - /// Extracts values from the array, field by field. - template - static Result> extract_field_by_field( - const R& _r, std::vector _vec, - AlreadyExtracted&&... _already_extracted) noexcept { - constexpr size_t i = sizeof...(AlreadyExtracted); - if constexpr (i == _size) { - return std::array({std::move(_already_extracted)...}); - } else { - const auto extract_next = [&](auto&& new_entry) { - return extract_field_by_field(_r, std::move(_vec), - std::move(_already_extracted)..., - std::move(new_entry)); - }; - 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, const std::vector& _vec) noexcept { - return Parser::read(_r, _vec[_i]); - } + /// Extracts a single field from a JSON. + template + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { + return Parser::read(_r, _vec[_i]); + } }; // ---------------------------------------------------------------------------- @@ -232,21 +226,19 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read(const R& _r, const InputVarType& _var) noexcept { - const auto to_box = [](auto&& _t) { - return Box::make(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_box); - } + /// Expresses the variables as type T. + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; + return Parser>::read(_r, _var).transform(to_box); + } - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const Box& _box) noexcept { - return Parser>::write(_w, *_box); - } + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const Box& _box) noexcept { + return Parser>::write(_w, *_box); + } }; // ---------------------------------------------------------------------------- @@ -256,51 +248,49 @@ struct Parser> { template requires AreReaderAndWriter struct MapParser { - public: - using InputObjectType = typename R::InputObjectType; - using InputVarType = typename R::InputVarType; + public: + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename W::OutputObjectType; - using OutputVarType = typename W::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; - using ValueType = std::decay_t; + using ValueType = std::decay_t; - 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) - .transform(to_pair) - .value(); - }; + 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) + .transform(to_pair) + .value(); + }; - const auto to_map = [&_r, - get_pair](const auto& _obj) -> Result { - auto m = _r.to_map(_obj); - MapType res; - try { - for (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); - } - - 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); + const auto to_map = [&_r, get_pair](const auto& _obj) -> Result { + auto m = _r.to_map(_obj); + MapType res; + try { + for (auto& p : m) { + res.insert(get_pair(p)); } - return obj; + } catch (std::exception& e) { + return Error(e.what()); + } + return res; + }; + + return _r.to_object(_var).and_then(to_map); + } + + 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); } + return obj; + } }; template @@ -320,206 +310,195 @@ struct Parser> template requires AreReaderAndWriter> struct Parser> { - using InputObjectType = typename R::InputObjectType; - using InputVarType = typename R::InputVarType; + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename W::OutputObjectType; - using OutputVarType = typename W::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; - public: - /// Generates a NamedTuple from a JSON Object. - 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); - return it != indices.end() ? it->second - : static_cast(-1); - }; - const auto to_fields_array = [&](auto _obj) { - return _r.template to_fields_array(fct, - _obj); - }; - const auto build = [&](auto _fields_vec) { - return build_named_tuple_recursively(_r, _fields_vec); - }; - return _r.to_object(_var).transform(to_fields_array).and_then(build); - } + public: + /// Generates a NamedTuple from a JSON Object. + 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); + return it != indices.end() ? it->second : static_cast(-1); + }; + const auto to_fields_array = [&](auto _obj) { + return _r.template to_fields_array(fct, _obj); + }; + const auto build = [&](auto _fields_vec) { + return build_named_tuple_recursively(_r, _fields_vec); + }; + return _r.to_object(_var).transform(to_fields_array).and_then(build); + } - /// Transforms a NamedTuple into a JSON object. - static OutputVarType write(const W& _w, - const NamedTuple& _tup) noexcept { - auto obj = _w.new_object(); - build_object_recursively(_w, _tup, &obj); - return OutputVarType(obj); - } + /// Transforms a NamedTuple into a JSON object. + static OutputVarType write(const W& _w, + const NamedTuple& _tup) noexcept { + auto obj = _w.new_object(); + build_object_recursively(_w, _tup, &obj); + return OutputVarType(obj); + } - private: - /// Builds the named tuple field by field. - template - static Result> build_named_tuple_recursively( - const R& _r, - const std::array& _fields_vec, - Args&&... _args) noexcept { - constexpr auto i = sizeof...(Args); + private: + /// Builds the named tuple field by field. + template + static Result> build_named_tuple_recursively( + const R& _r, + const std::array& _fields_vec, + Args&&... _args) noexcept { + constexpr auto i = sizeof...(Args); - if constexpr (i == sizeof...(FieldTypes)) { - return NamedTuple(std::move(_args)...); + if constexpr (i == sizeof...(FieldTypes)) { + return NamedTuple(std::move(_args)...); + } else { + using FieldType = typename std::tuple_element< + i, typename NamedTuple::Fields>::type; + + using ValueType = std::decay_t; + + const auto& f = std::get(_fields_vec); + + if (_r.is_empty(f)) { + if constexpr (is_required()) { + const auto key = FieldType::name_.str(); + return collect_errors( + _r, _fields_vec, + std::vector( + {Error("Field named '" + key + "' not found!")})); } else { - using FieldType = typename std::tuple_element< - i, typename NamedTuple::Fields>::type; - - using ValueType = std::decay_t; - - const auto& f = std::get(_fields_vec); - - if (_r.is_empty(f)) { - if constexpr (is_required()) { - const auto key = FieldType::name_.str(); - 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)..., - FieldType(ValueType())); - } - } - - const auto build = [&](auto&& _value) { - return build_named_tuple_recursively( - _r, _fields_vec, std::move(_args)..., - FieldType(std::move(_value))); - }; - - 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); + return build_named_tuple_recursively( + _r, _fields_vec, std::move(_args)..., FieldType(ValueType())); } + } + + const auto build = [&](auto&& _value) { + return build_named_tuple_recursively( + _r, _fields_vec, std::move(_args)..., FieldType(std::move(_value))); + }; + + 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 R& _r, - const std::array& _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 (_r.is_empty(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)); + /// If something went wrong, we want to collect all of the errors - it's + /// just good UX. + template + static Error collect_errors( + const R& _r, + const std::array& _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; - /// Builds the object field by field. - template - static void build_object_recursively(const W& _w, - const NamedTuple& _tup, - OutputObjectType* _ptr) noexcept { - if constexpr (_i >= sizeof...(FieldTypes)) { - return; - } else { - using FieldType = - typename std::tuple_element<_i, - std::tuple>::type; - using ValueType = std::decay_t; - auto value = Parser::write(_w, rfl::get<_i>(_tup)); - const auto name = FieldType::name_.str(); - if constexpr (!is_required()) { - if (!_w.is_empty(value)) { - _w.set_field(name, value, _ptr); - } - } else { - _w.set_field(name, value, _ptr); - } - return build_object_recursively<_i + 1>(_w, _tup, _ptr); + using ValueType = std::decay_t; + + const auto& f = std::get<_i>(_fields_vec); + + if (_r.is_empty(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)); + } - /// 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(); + 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)); + } + } + + /// Builds the object field by field. + template + static void build_object_recursively(const W& _w, + const NamedTuple& _tup, + OutputObjectType* _ptr) noexcept { + if constexpr (_i >= sizeof...(FieldTypes)) { + return; + } else { + using FieldType = + typename std::tuple_element<_i, std::tuple>::type; + using ValueType = std::decay_t; + auto value = Parser::write(_w, rfl::get<_i>(_tup)); + const auto name = FieldType::name_.str(); + if constexpr (!is_required()) { + if (!_w.is_empty(value)) { + _w.set_field(name, value, _ptr); } - return Parser>::field_indices_; + } else { + _w.set_field(name, value, _ptr); + } + return build_object_recursively<_i + 1>(_w, _tup, _ptr); } + } - /// Retrieves the value from the object. This is mainly needed to - /// generate a better error message. - template - 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); + /// 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_; + } - /// 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_.string_view(); - Parser>::field_indices_[name] = - static_cast(_i); - set_field_indices<_i + 1>(); - } + /// Retrieves the value from the object. This is mainly needed to + /// generate a better error message. + template + 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); + } + + /// 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_.string_view(); + 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_; + private: + /// Maps each of the field names to an index signifying their order. + static inline std::unordered_map + field_indices_; }; // ---------------------------------------------------------------------------- @@ -527,27 +506,72 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read(const R& _r, - const 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); + /// Expresses the variables as type T. + static Result> read(const R& _r, + const 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); + } - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, - const std::optional& _o) noexcept { - if (!_o) { - return _w.empty_var(); - } - return Parser>::write(_w, *_o); + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const std::optional& _o) noexcept { + if (!_o) { + return _w.empty_var(); } + return Parser>::write(_w, *_o); + } +}; + +// ---------------------------------------------------------------------------- + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + using ErrorType = NamedTuple>; + using VariantType = std::variant, ErrorType>; + + /// Expresses the variables as type T. + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + const auto handle = [](auto&& _t) -> Result { + using Type = std::decay_t; + if constexpr (std::is_same()) { + return Error(_t.template get<"error">()); + } else { + return std::forward>(_t); + } + }; + + const auto to_res = [&](VariantType&& _v) -> Result { + return std::visit(handle, std::forward(_v)); + }; + + return Result>( + Parser::read(_r, _var).transform(to_res)); + } + + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const Result& _r) noexcept { + const auto write_t = [&](const auto& _t) -> OutputVarType { + return Parser>::write(_w, _t); + }; + + const auto write_err = [&](const auto& _err) -> OutputVarType { + return Parser::write( + _w, ErrorType(make_field<"error">(_err.what()))); + }; + + return _r.transform(write_t).or_else(write_err).value(); + } }; // ---------------------------------------------------------------------------- @@ -555,21 +579,19 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read(const R& _r, const InputVarType& _var) noexcept { - const auto to_ref = [&](auto&& _t) { - return Ref::make(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_ref); - } + /// Expresses the variables as type T. + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_ref = [&](auto&& _t) { return Ref::make(std::move(_t)); }; + return Parser>::read(_r, _var).transform(to_ref); + } - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const Ref& _ref) noexcept { - return Parser>::write(_w, *_ref); - } + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const Ref& _ref) noexcept { + return Parser>::write(_w, *_ref); + } }; // ---------------------------------------------------------------------------- @@ -577,29 +599,29 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - if (_r.is_empty(*_var)) { - return std::shared_ptr(); - } - const auto to_ptr = [](auto&& _t) { - return std::make_shared(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_ptr); + /// Expresses the variables as type T. + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if (_r.is_empty(*_var)) { + return std::shared_ptr(); } + const auto to_ptr = [](auto&& _t) { + return std::make_shared(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_ptr); + } - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, - const std::shared_ptr& _s) noexcept { - if (!_s) { - return _w.empty_var(); - } - return Parser>::write(_w, *_s); + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, + const std::shared_ptr& _s) noexcept { + if (!_s) { + return _w.empty_var(); } + return Parser>::write(_w, *_s); + } }; // ---------------------------------------------------------------------------- @@ -607,28 +629,27 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read( - 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))); - }; - return Parser>::read(_r, _var) - .transform(to_pair); - } + /// Expresses the variables as type T. + static Result> read( + 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))); + }; + return Parser>::read(_r, _var) + .transform(to_pair); + } - /// Transform a std::pair into an array - static OutputVarType write( - const W& _w, const std::pair& _p) noexcept { - const auto tup = std::make_tuple(&_p.first, &_p.second); - return Parser< - R, W, std::tuple>::write(_w, - tup); - } + /// Transform a std::pair into an array + static OutputVarType write( + const W& _w, const std::pair& _p) noexcept { + const auto tup = std::make_tuple(&_p.first, &_p.second); + return Parser>::write( + _w, tup); + } }; // ---------------------------------------------------------------------------- @@ -638,106 +659,104 @@ template > struct Parser> { - using ResultType = Result>; + using ResultType = Result>; - public: - using InputObjectType = typename R::InputObjectType; - using InputVarType = typename R::InputVarType; + public: + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename W::OutputObjectType; - using OutputVarType = typename W::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static ResultType read(const R& _r, const InputVarType& _var) noexcept { - const auto get_disc = [&_r](auto _obj) { - return get_discriminator(_r, _obj); + /// Expresses the variables as type T. + static ResultType read(const R& _r, const InputVarType& _var) noexcept { + const auto get_disc = [&_r](auto _obj) { + return get_discriminator(_r, _obj); + }; + + const auto to_result = [&_r, _var](const std::string& _disc_value) { + return find_matching_alternative(_r, _disc_value, _var); + }; + + return _r.to_object(_var).and_then(get_disc).and_then(to_result); + } + + /// Expresses the variables as a JSON type. + static OutputVarType write( + const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>& + _tagged_union) noexcept { + using VariantType = + typename TaggedUnion<_discriminator, AlternativeTypes...>::VariantType; + return Parser::write(_w, _tagged_union.variant_); + } + + private: + template + 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 + "'."); + } else { + using AlternativeType = std::decay_t< + std::variant_alternative_t<_i, std::variant>>; + + if (contains_disc_value(_disc_value)) { + const auto to_tagged_union = [](auto&& _val) { + return TaggedUnion<_discriminator, AlternativeTypes...>( + std::move(_val)); }; - const auto to_result = [&_r, _var](const std::string& _disc_value) { - return find_matching_alternative(_r, _disc_value, _var); + const auto embellish_error = [&](Error&& _e) { + return Error( + "Could not parse tagged union with " + "discrimininator " + + _discriminator.str() + " '" + _disc_value + "': " + _e.what()); }; - return _r.to_object(_var).and_then(get_disc).and_then(to_result); - } - - /// Expresses the variables as a JSON type. - static OutputVarType write( - const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>& - _tagged_union) noexcept { - using VariantType = - typename TaggedUnion<_discriminator, - AlternativeTypes...>::VariantType; - return Parser::write(_w, _tagged_union.variant_); - } - - private: - template - 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 + "'."); - } else { - using AlternativeType = std::decay_t>>; - - if (contains_disc_value(_disc_value)) { - const auto to_tagged_union = [](auto&& _val) { - return TaggedUnion<_discriminator, AlternativeTypes...>( - std::move(_val)); - }; - - const auto embellish_error = [&](Error&& _e) { - return Error( - "Could not parse tagged union with " - "discrimininator " + - _discriminator.str() + " '" + _disc_value + - "': " + _e.what()); - }; - - return Parser::read(_r, _var) - .transform(to_tagged_union) - .or_else(embellish_error); - - } else { - return find_matching_alternative<_i + 1>(_r, _disc_value, _var); - } - } - } - - /// Retrieves the discriminator. - static Result get_discriminator( - 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 '" + - _discriminator.str() + "' or type of field was not a string."); - }; - - const auto to_type = [&_r](auto _var) { - return _r.template to_basic_type(_var); - }; - - return _r.get_field(_discriminator.str(), _obj) - .and_then(to_type) + return Parser::read(_r, _var) + .transform(to_tagged_union) .or_else(embellish_error); - } - /// Determines whether the discriminating literal contains the value - /// retrieved from the object. - template - static inline bool contains_disc_value( - const std::string& _disc_value) noexcept { - if constexpr (!internal::has_reflection_type_v) { - using LiteralType = field_type_t<_discriminator, T>; - return LiteralType::contains(_disc_value); - } else { - using LiteralType = - field_type_t<_discriminator, typename T::ReflectionType>; - return LiteralType::contains(_disc_value); - } + } else { + return find_matching_alternative<_i + 1>(_r, _disc_value, _var); + } } + } + + /// Retrieves the discriminator. + static Result get_discriminator( + 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 '" + + _discriminator.str() + + "' or type of field was not a string."); + }; + + const auto to_type = [&_r](auto _var) { + return _r.template to_basic_type(_var); + }; + + return _r.get_field(_discriminator.str(), _obj) + .and_then(to_type) + .or_else(embellish_error); + } + + /// Determines whether the discriminating literal contains the value + /// retrieved from the object. + template + static inline bool contains_disc_value( + const std::string& _disc_value) noexcept { + if constexpr (!internal::has_reflection_type_v) { + using LiteralType = field_type_t<_discriminator, T>; + return LiteralType::contains(_disc_value); + } else { + using LiteralType = + field_type_t<_discriminator, typename T::ReflectionType>; + return LiteralType::contains(_disc_value); + } + } }; // ---------------------------------------------------------------------------- @@ -745,87 +764,85 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - public: - using InputArrayType = typename R::InputArrayType; - using InputVarType = typename R::InputVarType; + public: + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename W::OutputArrayType; - using OutputVarType = typename W::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - static Result> read(const R& _r, - const 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 = [&](auto _arr) { return _r.to_vec(_arr); }; - const auto check_size = - [](auto _vec) -> Result> { - if (_vec.size() != sizeof...(Ts)) { - return Error("Expected " + std::to_string(sizeof...(Ts)) + - " fields, got " + std::to_string(_vec.size()) + - "."); - } - return std::move(_vec); - }; + const auto check_size = [](auto _vec) -> Result> { + if (_vec.size() != sizeof...(Ts)) { + return Error("Expected " + std::to_string(sizeof...(Ts)) + + " fields, got " + std::to_string(_vec.size()) + "."); + } + return std::move(_vec); + }; - const auto extract = [&_r](auto _vec) { - return extract_field_by_field(_r, std::move(_vec)); - }; + const auto extract = [&_r](auto _vec) { + return extract_field_by_field(_r, std::move(_vec)); + }; - return _r.to_array(_var) - .transform(to_vec) - .and_then(check_size) - .and_then(extract); + return _r.to_array(_var) + .transform(to_vec) + .and_then(check_size) + .and_then(extract); + } + + static OutputVarType write(const W& _w, + const std::tuple& _tup) noexcept { + auto arr = _w.new_array(); + to_array<0>(_w, _tup, &arr); + return arr; + } + + private: + /// Extracts values from the array, field by field. + template + static Result> extract_field_by_field( + const R& _r, std::vector _vec, + AlreadyExtracted&&... _already_extracted) noexcept { + constexpr size_t i = sizeof...(AlreadyExtracted); + if constexpr (i == sizeof...(Ts)) { + 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), + std::move(_already_extracted)..., + std::move(new_entry)); + }; + return extract_single_field(_r, _vec).and_then(extract_next); } + } - static OutputVarType write(const W& _w, - const std::tuple& _tup) noexcept { - auto arr = _w.new_array(); - to_array<0>(_w, _tup, &arr); - return arr; - } + /// Extracts a single field from a JSON. + template + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { + using NewFieldType = + std::decay_t>::type>; + return Parser::read(_r, _vec[_i]); + } - private: - /// Extracts values from the array, field by field. - template - static Result> extract_field_by_field( - const R& _r, std::vector _vec, - AlreadyExtracted&&... _already_extracted) noexcept { - constexpr size_t i = sizeof...(AlreadyExtracted); - if constexpr (i == sizeof...(Ts)) { - 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), - std::move(_already_extracted)..., - std::move(new_entry)); - }; - return extract_single_field(_r, _vec).and_then(extract_next); - } - } + /// Transforms a tuple to an array. + template + 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>; - /// Extracts a single field from a JSON. - template - 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]); - } - - /// Transforms a tuple to an array. - template - 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)); - _w.add(val, _ptr); - to_array<_i + 1>(_w, _tup, _ptr); - } + const auto val = + Parser::write(_w, std::get<_i>(_tup)); + _w.add(val, _ptr); + to_array<_i + 1>(_w, _tup, _ptr); } + } }; // ---------------------------------------------------------------------------- @@ -833,29 +850,29 @@ struct Parser> { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - if (_r.is_empty(_var)) { - return std::unique_ptr(); - } - const auto to_ptr = [](auto&& _t) { - return std::make_unique(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_ptr); + /// Expresses the variables as type T. + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if (_r.is_empty(_var)) { + return std::unique_ptr(); } + const auto to_ptr = [](auto&& _t) { + return std::make_unique(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_ptr); + } - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, - const std::unique_ptr& _s) noexcept { - if (!_s) { - return _w.empty_var(); - } - return Parser>::write(_w, *_s); + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, + const std::unique_ptr& _s) noexcept { + if (!_s) { + return _w.empty_var(); } + return Parser>::write(_w, *_s); + } }; // ---------------------------------------------------------------------------- @@ -865,95 +882,93 @@ struct Parser> { template requires AreReaderAndWriter> struct FieldVariantParser { - using ResultType = Result>; + using ResultType = Result>; - public: - using InputObjectType = typename R::InputObjectType; - using InputVarType = typename R::InputVarType; + public: + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; - using OutputObjectType = typename W::OutputObjectType; - using OutputVarType = typename W::OutputVarType; + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - 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."); + /// Expresses the variables as type T. + 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) { - return Error( - "Could not parse Field: Expected the object to have " - "exactly one field, but found " + - std::to_string(_map.size()) + " fields."); - } - const auto it = _map.begin(); - const auto& disc_value = it->first; - const auto& var = it->second; - return find_matching_alternative(_r, disc_value, var); + const auto to_result = [&](auto _map) -> ResultType { + if (_map.size() != 1) { + return Error( + "Could not parse Field: Expected the object to have " + "exactly one field, but found " + + std::to_string(_map.size()) + " fields."); + } + const auto it = _map.begin(); + const auto& disc_value = it->first; + 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); + } + + /// Expresses the variables as a JSON type. + static OutputVarType write(const W& _w, + const std::variant& _v) noexcept { + static_assert( + internal::no_duplicate_field_names>(), + "Externally tagged variants cannot have duplicate field " + "names."); + + const auto handle = [&](const auto& _field) { + const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); + using NamedTupleType = std::decay_t; + return Parser::write(_w, named_tuple); + }; + + return std::visit(handle, _v); + } + + private: + template + 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 " + "'" + + _disc_value + "'."); + } else { + using FieldType = std::decay_t< + typename std::tuple_element<_i, std::tuple>::type>; + + using ValueType = std::decay_t; + + const auto key = FieldType::name_.str(); + + if (key == _disc_value) { + const auto to_variant = [](ValueType&& _val) { + return std::variant(FieldType(std::move(_val))); }; - return _r.to_object(_var).transform(to_map).and_then(to_result); - } - - /// Expresses the variables as a JSON type. - static OutputVarType write(const W& _w, - const std::variant& _v) noexcept { - static_assert( - internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field " - "names."); - - const auto handle = [&](const auto& _field) { - const auto named_tuple = - make_named_tuple(internal::to_ptr_field(_field)); - using NamedTupleType = std::decay_t; - return Parser::write(_w, named_tuple); + const auto embellish_error = [&](const Error& _e) { + return Error("Could not parse std::variant with field '" + + _disc_value + "': " + _e.what()); }; - return std::visit(handle, _v); - } - - private: - template - 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 " - "'" + - _disc_value + "'."); - } else { - using FieldType = std::decay_t>::type>; - - using ValueType = std::decay_t; - - const auto key = FieldType::name_.str(); - - if (key == _disc_value) { - const auto to_variant = [](ValueType&& _val) { - return std::variant( - FieldType(std::move(_val))); - }; - - const auto embellish_error = [&](const Error& _e) { - return Error("Could not parse std::variant with field '" + - _disc_value + "': " + _e.what()); - }; - - return Parser::read(_r, _var) - .transform(to_variant) - .or_else(embellish_error); - } else { - return find_matching_alternative<_i + 1>(_r, _disc_value, _var); - } - } + return Parser::read(_r, _var) + .transform(to_variant) + .or_else(embellish_error); + } else { + return find_matching_alternative<_i + 1>(_r, _disc_value, _var); + } } + } }; // ---------------------------------------------------------------------------- @@ -961,53 +976,53 @@ struct FieldVariantParser { template requires AreReaderAndWriter> struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; - /// Expresses the variables as type T. - template - static Result> read( - const R& _r, const InputVarType& _var, - const std::string _errors = "") noexcept { - if constexpr (_i == 0 && - internal::all_fields>()) { - return FieldVariantParser::read(_r, _var); - } else if constexpr (_i == sizeof...(FieldTypes)) { - return Error("Could not parse variant: " + _errors); - } else { - const auto to_variant = [](auto&& _val) { - return std::variant(std::move(_val)); - }; + /// Expresses the variables as type T. + template + static Result> read( + const R& _r, const InputVarType& _var, + const std::string _errors = "") noexcept { + if constexpr (_i == 0 && + internal::all_fields>()) { + return FieldVariantParser::read(_r, _var); + } else if constexpr (_i == sizeof...(FieldTypes)) { + return Error("Could not parse variant: " + _errors); + } else { + const auto to_variant = [](auto&& _val) { + return std::variant(std::move(_val)); + }; - const auto try_next = [&_r, _var, &_errors](const auto& _err) { - auto errors = _errors; - errors += std::string("\n " + std::to_string(_i + 1) + ")") + - _err.what(); - return read<_i + 1>(_r, _var, errors); - }; + const auto try_next = [&_r, _var, &_errors](const auto& _err) { + auto errors = _errors; + errors += + std::string("\n " + std::to_string(_i + 1) + ")") + _err.what(); + return read<_i + 1>(_r, _var, errors); + }; - using AltType = std::decay_t< - std::variant_alternative_t<_i, std::variant>>; + using AltType = std::decay_t< + std::variant_alternative_t<_i, std::variant>>; - return Parser::read(_r, _var) - .transform(to_variant) - .or_else(try_next); - } + return Parser::read(_r, _var) + .transform(to_variant) + .or_else(try_next); } + } - /// Expresses the variables as a JSON type. - static OutputVarType write( - const W& _w, const std::variant& _variant) noexcept { - if constexpr (internal::all_fields>()) { - return FieldVariantParser::write(_w, _variant); - } else { - const auto handle = [&](const auto& _v) { - using Type = std::decay_t; - return Parser::write(_w, _v); - }; - return std::visit(handle, _variant); - } + /// Expresses the variables as a JSON type. + static OutputVarType write( + const W& _w, const std::variant& _variant) noexcept { + if constexpr (internal::all_fields>()) { + return FieldVariantParser::write(_w, _variant); + } else { + const auto handle = [&](const auto& _v) { + using Type = std::decay_t; + return Parser::write(_w, _v); + }; + return std::visit(handle, _variant); } + } }; // ---------------------------------------------------------------------------- @@ -1019,76 +1034,73 @@ struct Parser> { template requires AreReaderAndWriter struct VectorParser { - public: - using InputArrayType = typename R::InputArrayType; - using InputVarType = typename R::InputVarType; + public: + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; - using OutputArrayType = typename W::OutputArrayType; - using OutputVarType = typename W::OutputVarType; + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; - using T = typename VecType::value_type; + using T = typename VecType::value_type; - static Result read(const R& _r, - const InputVarType& _var) noexcept { - using namespace std::ranges::views; + 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(); - }; + const auto get_elem = [&](auto& _v) { + 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) - .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; - 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& 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& v : input_vars) { - vec.emplace_back(get_elem(v)); - } - } - return vec; - }; - - const auto to_result = [&](InputArrayType&& _arr) -> Result { - try { - return Result( - to_container(std::forward(_arr))); - } catch (std::exception& e) { - return Error(e.what()); - } - }; - - return _r.to_array(_var).and_then(to_result); - } - - 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); + const auto to_container = [&](InputArrayType&& _arr) -> Result { + auto input_vars = _r.to_vec(_arr); + VecType vec; + if constexpr (is_forward_list()) { + for (auto it = input_vars.rbegin(); it != input_vars.rend(); ++it) { + vec.emplace_front(get_elem(*it)); } - return OutputVarType(arr); + } else if constexpr (is_map_like()) { + 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& v : input_vars) { + vec.emplace_back(get_elem(v)); + } + } + return vec; + }; + + const auto to_result = [&](InputArrayType&& _arr) -> Result { + try { + return Result( + to_container(std::forward(_arr))); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + + return _r.to_array(_var).and_then(to_result); + } + + 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); } + return OutputVarType(arr); + } }; template diff --git a/tests/test_result.hpp b/tests/test_result.hpp new file mode 100644 index 00000000..6aaf6db2 --- /dev/null +++ b/tests/test_result.hpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_result() { + std::cout << "test_result" << std::endl; + + struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::vector>> children = + rfl::default_value; + }; + + const rfl::Result bart = Person{.first_name = "Bart"}; + + const rfl::Result lisa = Person{.first_name = "Lisa"}; + + const rfl::Result maggie = rfl::Error("Some error occurred."); + + const auto homer = Person{ + .first_name = "Homer", + .children = std::vector>({bart, lisa, maggie})}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson","children":[]},{"firstName":"Lisa","lastName":"Simpson","children":[]},{"error":"Some error occurred."}]})"); +} diff --git a/tests/tests.cpp b/tests/tests.cpp index f11c094c..e8d55e4b 100644 --- a/tests/tests.cpp +++ b/tests/tests.cpp @@ -28,6 +28,7 @@ #include "test_replace.hpp" #include "test_replace_flatten.hpp" #include "test_replace_with_other_struct.hpp" +#include "test_result.hpp" #include "test_set.hpp" #include "test_size.hpp" #include "test_string_map.hpp" @@ -71,6 +72,7 @@ int main() { test_string_map(); test_string_unordered_map(); test_error_messages(); + test_result(); test_custom_class1(); test_custom_class2();