diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 4d99f7ce..4e70bbb2 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -62,6 +62,235 @@ struct Parser; // ---------------------------------------------------------------------------- +/// Used for any structs that are aggregates. +template +struct StructParser { + using InputObjectType = typename R::InputObjectType; + using InputVarType = typename R::InputVarType; + + using OutputObjectType = typename W::OutputObjectType; + using OutputVarType = typename W::OutputVarType; + + using PtrTupleType = internal::ptr_tuple_t; + using TupleType = internal::flattened_tuple_t; + + static constexpr auto tuple_size = std::tuple_size_v; + + 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_tuple = [&](auto _fields_vec) -> TupleType { + return build_tuple_recursively(_r, _fields_vec); + }; + + const auto to_struct = [](TupleType&& _t) -> T { + return internal::move_from_tuple(std::move(_t)); + }; + + return _r.to_object(_var) + .transform(to_fields_array) + .and_then(build_tuple) + .transform(to_struct); + } + + /// Transforms a NamedTuple into a JSON object. + static OutputVarType write(const W& _w, const T& _var) noexcept { + const auto ptr_tuple = internal::to_flattened_ptr_tuple(_var); + + auto obj = _w.new_object(); + + build_object_recursively(_w, ptr_tuple, &obj); + + return OutputVarType(obj); + } + + private: + /// Builds the tuple field by field containing the values for the structs + /// recursively. + template + static Result build_tuple_recursively( + const R& _r, + const std::array, tuple_size>& _fields_arr, + Args&&... _args) noexcept { + constexpr auto i = sizeof...(Args); + + if constexpr (i == std::tuple_size_v) { + return std::make_tuple(std::move(_args)...); + } else { + using ValueType = + std::decay_t::type>; + + const auto& f = std::get(_fields_arr); + + const auto key = std::get(field_names()); + + if (!f) { + if constexpr (is_required()) { + return collect_errors( + _r, _fields_arr, + std::vector( + {Error("Field named '" + key + "' not found!")})); + } else { + return build_tuple_recursively(_r, _fields_arr, std::move(_args)..., + ValueType()); + } + } + + const auto handle_error = [&](Error&& _error) { + return collect_errors(_r, _fields_arr, + std::vector({std::move(_error)})); + }; + + const auto build_tuple = [&](auto&& _value) { + return build_tuple_recursively(_r, _fields_arr, std::move(_args)..., + std::move(_value)); + }; + + return get_value(_r, *f, key) + .or_else(handle_error) + .and_then(build_tuple); + } + } + + /// 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, tuple_size>& _fields_arr, + std::vector _errors) noexcept { + if constexpr (_i == tuple_size) { + 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 ValueType = + std::decay_t::type>; + + const auto& f = std::get<_i>(_fields_arr); + + const auto key = std::get<_i>(field_names()); + + if (!f) { + if constexpr (is_required()) { + _errors.emplace_back(Error("Field named '" + key + "' not found.")); + } + return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors)); + } + + const auto add_error_if_applicable = + [&](Error&& _error) -> Result { + _errors.emplace_back(std::move(_error)); + return _error; + }; + + get_value(_r, *f, key).or_else(add_error_if_applicable); + + return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors)); + } + } + + /// Builds the object field by field. + template + static void build_object_recursively(const W& _w, const PtrTupleType& _tup, + OutputObjectType* _ptr) noexcept { + if constexpr (_i >= tuple_size) { + return; + } else { + using ValueType = + std::decay_t::type>; + + auto value = Parser::write(_w, rfl::get<_i>(_tup)); + + const auto& key = std::get<_i>(field_names()); + + if constexpr (!is_required()) { + if (!_w.is_empty(value)) { + _w.set_field(key, value, _ptr); + } + } else { + _w.set_field(key, value, _ptr); + } + + return build_object_recursively<_i + 1>(_w, _tup, _ptr); + } + } + + /// 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 { + // return field_indices_.value(set_field_indices<0>); + return field_indices_; + } + + /// Uses a memoization pattern to retrieve the field names. + /// There are some objects that we are likely to parse many times, + /// so we only calculate these indices once. + static const auto& field_names() noexcept { + // return field_indices_.value(set_field_indices<0>); + return field_names_; + } + + /// 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, + const std::string& _key) noexcept { + const auto embellish_error = [&](const Error& _e) { + return Error("Failed to parse field '" + _key + "': " + _e.what()); + }; + return Parser::read(_r, _var).or_else(embellish_error); + } + + /// Builds the object field by field. + /*template + static void set_field_indices( + std::unordered_map* + _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(); + (*_field_indices)[name] = static_cast(_i); + set_field_indices<_i + 1>(_field_indices); + } + }*/ + + private: + /// Maps each of the field names to an index signifying their order. + /*static inline internal::Memoization< + std::unordered_map> + field_indices_;*/ + + static inline std::array field_names_; + + static inline std::unordered_map + field_indices_; +}; + +// ---------------------------------------------------------------------------- + /// Default case - anything that cannot be explicitly matched. template requires AreReaderAndWriter