Added XML support; #21

This commit is contained in:
Patrick Urbanke
2023-12-20 21:07:36 +01:00
parent 2281849dde
commit c5347eee28
124 changed files with 4652 additions and 1437 deletions
+1
View File
@@ -9,6 +9,7 @@
#include "rfl/AllOf.hpp"
#include "rfl/AnyOf.hpp"
#include "rfl/Attribute.hpp"
#include "rfl/Box.hpp"
#include "rfl/Field.hpp"
#include "rfl/Flatten.hpp"
+136
View File
@@ -0,0 +1,136 @@
#ifndef RFL_ATTRIBUTE_HPP_
#define RFL_ATTRIBUTE_HPP_
#include <algorithm>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>
#include "rfl/Literal.hpp"
#include "rfl/default.hpp"
namespace rfl {
template <class T>
struct Attribute {
using Type = T;
using ReflectionType = T;
Attribute() : value_(Type()) {}
Attribute(const Type& _value) : value_(_value) {}
Attribute(Type&& _value) noexcept : value_(std::move(_value)) {}
Attribute(Attribute<T>&& _attr) noexcept = default;
Attribute(const Attribute<Type>& _attr) = default;
template <class U>
Attribute(const Attribute<U>& _attr) : value_(_attr.get()) {}
template <class U>
Attribute(Attribute<U>&& _attr) : value_(_attr.get()) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, Type>,
bool>::type = true>
Attribute(const U& _value) : value_(_value) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, Type>,
bool>::type = true>
Attribute(U&& _value) noexcept : value_(std::forward<U>(_value)) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, Type>,
bool>::type = true>
Attribute(const Attribute<U>& _attr) : value_(_attr.value()) {}
/// Assigns the underlying object to its default value.
template <class U = Type,
typename std::enable_if<std::is_default_constructible_v<U>,
bool>::type = true>
Attribute(const Default& _default) : value_(Type()) {}
~Attribute() = default;
/// Returns the underlying object.
const Type& get() const { return value_; }
/// Returns the underlying object.
Type& operator()() { return value_; }
/// Returns the underlying object.
const Type& operator()() const { return value_; }
/// Assigns the underlying object.
auto& operator=(const Type& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object.
auto& operator=(Type&& _value) noexcept {
value_ = std::move(_value);
return *this;
}
/// Assigns the underlying object.
template <class U, typename std::enable_if<std::is_convertible_v<U, Type>,
bool>::type = true>
auto& operator=(const U& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object to its default value.
template <class U = Type,
typename std::enable_if<std::is_default_constructible_v<U>,
bool>::type = true>
auto& operator=(const Default& _default) {
value_ = Type();
return *this;
}
/// Assigns the underlying object.
Attribute<T>& operator=(const Attribute<T>& _attr) = default;
/// Assigns the underlying object.
Attribute<T>& operator=(Attribute<T>&& _attr) = default;
/// Assigns the underlying object.
template <class U>
auto& operator=(const Attribute<U>& _attr) {
value_ = _attr.get();
return *this;
}
/// Assigns the underlying object.
template <class U>
auto& operator=(Attribute<U>&& _attr) {
value_ = std::forward<T>(_attr.value_);
return *this;
}
/// We want all parsers other than the XML parser to treat attributes like
/// normal fields, so we just implement the reflection interface.
const ReflectionType& reflection() const { return value_; }
/// Assigns the underlying object.
void set(const Type& _value) { value_ = _value; }
/// Assigns the underlying object.
void set(Type&& _value) { value_ = std::move(_value); }
/// Returns the underlying object.
Type& value() { return value_; }
/// Returns the underlying object.
const Type& value() const { return value_; }
/// The underlying value.
Type value_;
};
} // namespace rfl
#endif
+5 -5
View File
@@ -309,13 +309,13 @@ class Result {
}
/// Returns the value or a default.
T value_or(const T& _default) noexcept {
const auto handle_variant =
[&]<class TOrError>(const TOrError& _t_or_err) -> T {
if constexpr (!std::is_same<TOrError, Error>()) {
T value_or(T&& _default) noexcept {
const auto handle_variant = [&]<class TOrError>(TOrError&& _t_or_err) -> T {
using Type = std::decay_t<TOrError>;
if constexpr (!std::is_same<Type, Error>()) {
return std::forward<T>(_t_or_err);
} else {
return _default;
return std::forward<T>(_default);
}
};
return std::visit(handle_variant, t_or_err_);
+34
View File
@@ -0,0 +1,34 @@
#ifndef RFL_INTERNAL_ISATTRIBUTE_HPP_
#define RFL_INTERNAL_ISATTRIBUTE_HPP_
#include <tuple>
#include <type_traits>
#include <utility>
#include "rfl/Field.hpp"
namespace rfl {
namespace internal {
template <class T>
class is_attribute;
template <class T>
class is_attribute : public std::false_type {};
template <class Type>
class is_attribute<Attribute<Type>> : public std::true_type {};
template <class Type>
class is_attribute<Attribute<Type>*> : public std::true_type {};
template <class Type>
class is_attribute<const Attribute<Type>*> : public std::true_type {};
template <class T>
constexpr bool is_attribute_v = is_attribute<T>::value;
} // namespace internal
} // namespace rfl
#endif
@@ -0,0 +1,28 @@
#ifndef RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_
#define RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_
#include <string>
#include <vector>
namespace rfl {
namespace internal {
namespace strings {
inline std::string replace_all(const std::string& _str,
const std::string& _from,
const std::string& _to) {
auto str = _str;
size_t pos = 0;
while ((pos = str.find(_from, pos)) != std::string::npos) {
str.replace(pos, _from.length(), _to);
pos += _to.length();
}
return str;
}
} // namespace strings
} // namespace internal
} // namespace rfl
#endif
+110
View File
@@ -0,0 +1,110 @@
#ifndef RFL_PARSING_FIELD_VARIANT_PARSER_HPP_
#define RFL_PARSING_FIELD_VARIANT_PARSER_HPP_
#include <stdexcept>
#include <string>
#include <type_traits>
#include <variant>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
/// To be used when all options of the variants are rfl::Field. Essentially,
/// this is an externally tagged union.
template <class R, class W, class... FieldTypes>
requires AreReaderAndWriter<R, W, std::variant<FieldTypes...>>
struct FieldVariantParser {
using ResultType = Result<std::variant<FieldTypes...>>;
public:
using InputObjectType = typename R::InputObjectType;
using InputVarType = typename R::InputVarType;
using OutputObjectType = typename W::OutputObjectType;
using OutputVarType = typename W::OutputVarType;
static ResultType read(const R& _r, const InputVarType& _var) noexcept {
static_assert(
internal::no_duplicate_field_names<std::tuple<FieldTypes...>>(),
"Externally tagged variants cannot have duplicate field "
"names.");
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);
};
return _r.to_object(_var).transform(to_map).and_then(to_result);
}
static OutputVarType write(const W& _w,
const std::variant<FieldTypes...>& _v) noexcept {
static_assert(
internal::no_duplicate_field_names<std::tuple<FieldTypes...>>(),
"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<decltype(named_tuple)>;
return Parser<R, W, NamedTupleType>::write(_w, named_tuple);
};
return std::visit(handle, _v);
}
private:
template <int _i = 0>
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<FieldTypes...>>::type>;
using ValueType = std::decay_t<typename FieldType::Type>;
const auto key = FieldType::name_.str();
if (key == _disc_value) {
const auto to_variant = [](ValueType&& _val) {
return std::variant<FieldTypes...>(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<R, W, ValueType>::read(_r, _var)
.transform(to_variant)
.or_else(embellish_error);
} else {
return find_matching_alternative<_i + 1>(_r, _disc_value, _var);
}
}
}
};
} // namespace parsing
} // namespace rfl
#endif
+125
View File
@@ -0,0 +1,125 @@
#ifndef RFL_PARSING_MAPPARSER_HPP_
#define RFL_PARSING_MAPPARSER_HPP_
#include <stdexcept>
#include <string>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class MapType>
requires AreReaderAndWriter<R, W, MapType>
struct MapParser {
public:
using InputObjectType = typename R::InputObjectType;
using InputVarType = typename R::InputVarType;
using OutputObjectType = typename W::OutputObjectType;
using OutputVarType = typename W::OutputVarType;
using KeyType = std::decay_t<typename MapType::value_type::first_type>;
using ValueType = std::decay_t<typename MapType::value_type::second_type>;
static Result<MapType> read(const R& _r, const InputVarType& _var) noexcept {
const auto to_map = [&](const auto& _obj) { return make_map(_r, _obj); };
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) {
auto parsed_val = Parser<R, W, std::decay_t<ValueType>>::write(_w, v);
if constexpr (internal::has_reflection_type_v<KeyType>) {
using ReflT = typename KeyType::ReflectionType;
if constexpr (std::is_integral_v<ReflT> ||
std::is_floating_point_v<ReflT>) {
_w.set_field(std::to_string(k.reflection()), std::move(parsed_val),
&obj);
} else {
_w.set_field(k.reflection(), std::move(parsed_val), &obj);
}
} else if constexpr (std::is_integral_v<KeyType> ||
std::is_floating_point_v<KeyType>) {
_w.set_field(std::to_string(k), std::move(parsed_val), &obj);
} else {
_w.set_field(k, std::move(parsed_val), &obj);
}
}
return obj;
}
private:
template <class T>
static Result<T> key_to_numeric(auto& _pair) noexcept {
try {
if constexpr (std::is_integral_v<T>) {
return static_cast<T>(std::stoi(_pair.first));
} else if constexpr (std::is_floating_point_v<T>) {
return static_cast<T>(std::stod(_pair.first));
} else {
static_assert(always_false_v<T>, "Unsupported type");
}
} catch (std::exception& e) {
return Error(e.what());
}
}
static Result<std::pair<KeyType, ValueType>> make_key(auto& _pair) noexcept {
const auto to_pair = [&](auto _key) {
return std::make_pair(KeyType(std::move(_key)), std::move(_pair.second));
};
if constexpr (std::is_integral_v<KeyType> ||
std::is_floating_point_v<KeyType>) {
return key_to_numeric<KeyType>(_pair).transform(to_pair);
} else if constexpr (internal::has_reflection_type_v<KeyType>) {
using ReflT = typename KeyType::ReflectionType;
if constexpr (std::is_integral_v<ReflT> ||
std::is_floating_point_v<ReflT>) {
return key_to_numeric<ReflT>(_pair).transform(to_pair);
} else {
return to_pair(_pair.first);
}
} else {
return std::move(_pair);
}
}
static std::pair<KeyType, ValueType> get_pair(const R& _r, auto& _pair) {
const auto to_pair = [&](ValueType&& _val) {
auto pair = std::make_pair(std::move(_pair.first), std::move(_val));
return make_key(pair);
};
return Parser<R, W, std::decay_t<ValueType>>::read(_r, _pair.second)
.and_then(to_pair)
.value();
}
static Result<MapType> make_map(const R& _r, const auto& _obj) noexcept {
auto m = _r.to_map(_obj);
MapType res;
try {
for (auto& p : m) {
res.insert(get_pair(_r, p));
}
} catch (std::exception& e) {
return Error(e.what());
}
return res;
}
};
} // namespace parsing
} // namespace rfl
#endif
+222
View File
@@ -0,0 +1,222 @@
#ifndef RFL_PARSING_NAMEDTUPLEPARSER_HPP_
#define RFL_PARSING_NAMEDTUPLEPARSER_HPP_
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include "rfl/NamedTuple.hpp"
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/internal/is_basic_type.hpp"
#include "rfl/internal/strings/replace_all.hpp"
#include "rfl/parsing/is_required.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, bool _ignore_empty_containers, class... FieldTypes>
requires AreReaderAndWriter<R, W, NamedTuple<FieldTypes...>>
struct NamedTupleParser {
using InputObjectType = typename R::InputObjectType;
using InputVarType = typename R::InputVarType;
using OutputObjectType = typename W::OutputObjectType;
using OutputVarType = typename W::OutputVarType;
public:
/// Generates a NamedTuple from a JSON Object.
static Result<NamedTuple<FieldTypes...>> 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<std::uint16_t>(-1);
};
const auto to_fields_array = [&](auto _obj) {
return _r.template to_fields_array<sizeof...(FieldTypes)>(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<FieldTypes...>& _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 <class... Args>
static Result<NamedTuple<FieldTypes...>> build_named_tuple_recursively(
const R& _r,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_arr,
Args&&... _args) noexcept {
constexpr auto i = sizeof...(Args);
if constexpr (i == sizeof...(FieldTypes)) {
return NamedTuple<FieldTypes...>(std::move(_args)...);
} else {
using FieldType = typename std::tuple_element<
i, typename NamedTuple<FieldTypes...>::Fields>::type;
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = std::get<i>(_fields_arr);
if (!f) {
if constexpr (is_required<ValueType, _ignore_empty_containers>()) {
const auto key = FieldType::name_.str();
return collect_errors<i + 1>(
_r, _fields_arr,
std::vector<Error>(
{Error("Field named '" + key + "' not found!")}));
} else {
return build_named_tuple_recursively(
_r, _fields_arr, std::move(_args)..., FieldType(ValueType()));
}
}
const auto build = [&](auto&& _value) {
return build_named_tuple_recursively(
_r, _fields_arr, std::move(_args)..., FieldType(std::move(_value)));
};
const auto handle_error = [&](Error&& _error) {
return collect_errors<i + 1>(_r, _fields_arr,
std::vector<Error>({std::move(_error)}));
};
return get_value<FieldType>(_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 <int _i>
static Error collect_errors(
const R& _r,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_arr,
std::vector<Error> _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) + ") " +
internal::strings::replace_all(_errors.at(i).what(), "\n",
"\n ");
}
return Error(msg);
}
} else {
using FieldType = typename std::tuple_element<
_i, typename NamedTuple<FieldTypes...>::Fields>::type;
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = std::get<_i>(_fields_arr);
if (!f) {
if constexpr (is_required<ValueType, _ignore_empty_containers>()) {
const auto key = FieldType::name_.str();
_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<ValueType> {
_errors.emplace_back(std::move(_error));
return _error;
};
get_value<FieldType>(_r, *f).or_else(add_error_if_applicable);
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
}
}
/// Builds the object field by field.
template <int _i = 0>
static void build_object_recursively(const W& _w,
const NamedTuple<FieldTypes...>& _tup,
OutputObjectType* _ptr) noexcept {
if constexpr (_i >= sizeof...(FieldTypes)) {
return;
} else {
using FieldType =
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type;
using ValueType = std::decay_t<typename FieldType::Type>;
auto value = Parser<R, W, ValueType>::write(_w, rfl::get<_i>(_tup));
const auto name = FieldType::name_.str();
if constexpr (!is_required<ValueType, _ignore_empty_containers>()) {
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);
}
}
/// 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>);
}
/// Retrieves the value from the object. This is mainly needed to
/// generate a better error message.
template <class FieldType>
static auto get_value(const R& _r, const InputVarType _var) noexcept {
static_assert(FieldType::name_ != internal::StringLiteral("xml_content") ||
internal::is_basic_type_v<typename FieldType::Type>,
"xml_content must be a string, a boolean, a floating point "
"value or integral.");
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<typename FieldType::Type>;
return Parser<R, W, ValueType>::read(_r, _var).or_else(embellish_error);
}
/// Builds the object field by field.
template <size_t _i = 0>
static void set_field_indices(
std::unordered_map<std::string_view, std::int16_t>*
_field_indices) noexcept {
if constexpr (_i >= sizeof...(FieldTypes)) {
return;
} else {
using FieldType =
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type;
const auto name = FieldType::name_.string_view();
(*_field_indices)[name] = static_cast<std::int16_t>(_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<std::string_view, std::int16_t>>
field_indices_;
};
} // namespace parsing
} // namespace rfl
#endif
File diff suppressed because it is too large Load Diff
+85
View File
@@ -0,0 +1,85 @@
#ifndef RFL_PARSING_PARSER_ARRAY_HPP_
#define RFL_PARSING_PARSER_ARRAY_HPP_
#include <array>
#include <type_traits>
#include <vector>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T, size_t _size>
requires AreReaderAndWriter<R, W, std::array<T, _size>>
struct Parser<R, W, std::array<T, _size>> {
public:
using InputArrayType = typename R::InputArrayType;
using InputVarType = typename R::InputVarType;
using OutputArrayType = typename W::OutputArrayType;
using OutputVarType = typename W::OutputVarType;
static Result<std::array<T, _size>> 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<std::vector<InputVarType>> {
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));
};
return _r.to_array(_var)
.transform(to_vec)
.and_then(check_size)
.and_then(extract);
}
static OutputVarType write(const W& _w,
const std::array<T, _size>& _arr) noexcept {
auto arr = _w.new_array();
for (auto it = _arr.begin(); it != _arr.end(); ++it) {
_w.add(Parser<R, W, std::decay_t<T>>::write(_w, *it), &arr);
}
return OutputVarType(arr);
}
private:
/// Extracts values from the array, field by field.
template <class... AlreadyExtracted>
static Result<std::array<T, _size>> extract_field_by_field(
const R& _r, std::vector<InputVarType> _vec,
AlreadyExtracted&&... _already_extracted) noexcept {
constexpr size_t i = sizeof...(AlreadyExtracted);
if constexpr (i == _size) {
return std::array<T, _size>({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<i>(_r, _vec).and_then(extract_next);
}
}
/// Extracts a single field from a JSON.
template <int _i>
static auto extract_single_field(
const R& _r, const std::vector<InputVarType>& _vec) noexcept {
return Parser<R, W, T>::read(_r, _vec[_i]);
}
};
} // namespace parsing
} // namespace rfl
#endif
+16
View File
@@ -0,0 +1,16 @@
#ifndef RFL_PARSING_PARSER_BASE_HPP_
#define RFL_PARSING_PARSER_BASE_HPP_
#include "rfl/parsing/AreReaderAndWriter.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, T>
struct Parser;
} // namespace parsing
} // namespace rfl
#endif
+32
View File
@@ -0,0 +1,32 @@
#ifndef RFL_PARSING_PARSER_BOX_HPP_
#define RFL_PARSING_PARSER_BOX_HPP_
#include <type_traits>
#include "rfl/Box.hpp"
#include "rfl/Result.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, Box<T>>
struct Parser<R, W, Box<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
static Result<Box<T>> read(const R& _r, const InputVarType& _var) noexcept {
const auto to_box = [](auto&& _t) { return Box<T>::make(std::move(_t)); };
return Parser<R, W, std::decay_t<T>>::read(_r, _var).transform(to_box);
}
static OutputVarType write(const W& _w, const Box<T>& _box) noexcept {
return Parser<R, W, std::decay_t<T>>::write(_w, *_box);
}
};
} // namespace parsing
} // namespace rfl
#endif
+101
View File
@@ -0,0 +1,101 @@
#ifndef RFL_PARSING_PARSER_DEFAULT_HPP_
#define RFL_PARSING_PARSER_DEFAULT_HPP_
#include <stdexcept>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/from_named_tuple.hpp"
#include "rfl/internal/enums/StringConverter.hpp"
#include "rfl/internal/has_reflection_method_v.hpp"
#include "rfl/internal/has_reflection_type_v.hpp"
#include "rfl/internal/is_basic_type.hpp"
#include "rfl/internal/to_ptr_named_tuple.hpp"
#include "rfl/parsing/AreReaderAndWriter.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
/// Default case - anything that cannot be explicitly matched.
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, T>
struct Parser {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<T> read(const R& _r, const InputVarType& _var) noexcept {
if constexpr (R::template has_custom_constructor<T>) {
return _r.template use_custom_constructor<T>(_var);
} else {
if constexpr (internal::has_reflection_type_v<T>) {
using ReflectionType = std::decay_t<typename T::ReflectionType>;
const auto wrap_in_t = [](auto _named_tuple) -> Result<T> {
try {
return T(_named_tuple);
} catch (std::exception& e) {
return Error(e.what());
}
};
return Parser<R, W, ReflectionType>::read(_r, _var).and_then(wrap_in_t);
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
using NamedTupleType = named_tuple_t<T>;
const auto to_struct = [](NamedTupleType&& _n) -> Result<T> {
try {
return from_named_tuple<T>(std::move(_n));
} catch (std::exception& e) {
return Error(e.what());
}
};
return Parser<R, W, NamedTupleType>::read(_r, _var).and_then(to_struct);
} else if constexpr (std::is_enum_v<T>) {
using StringConverter = internal::enums::StringConverter<T>;
return _r.template to_basic_type<std::string>(_var).and_then(
StringConverter::string_to_enum);
} else if constexpr (internal::is_basic_type_v<T>) {
return _r.template to_basic_type<std::decay_t<T>>(_var);
} else {
static_assert(
always_false_v<T>,
"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<T>) {
using ReflectionType = std::decay_t<typename T::ReflectionType>;
if constexpr (internal::has_reflection_method_v<T>) {
return Parser<R, W, ReflectionType>::write(_w, _var.reflection());
} else {
const auto& [r] = _var;
return Parser<R, W, ReflectionType>::write(_w, r);
}
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var);
using PtrNamedTupleType = std::decay_t<decltype(ptr_named_tuple)>;
return Parser<R, W, PtrNamedTupleType>::write(_w, ptr_named_tuple);
} else if constexpr (std::is_enum_v<T>) {
using StringConverter = internal::enums::StringConverter<T>;
const auto str = StringConverter::enum_to_string(_var);
return _w.from_basic_type(str);
} else if constexpr (internal::is_basic_type_v<T>) {
return _w.from_basic_type(_var);
} else {
static_assert(always_false_v<T>,
"Unsupported type. Please refer to the sections on custom "
"classes and custom parsers for information on how add "
"support for your own classes.");
}
}
};
} // namespace parsing
} // namespace rfl
#endif
+33
View File
@@ -0,0 +1,33 @@
#ifndef RFL_PARSING_PARSER_MAP_LIKE_HPP_
#define RFL_PARSING_PARSER_MAP_LIKE_HPP_
#include <map>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/MapParser.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::map<std::string, T>>
struct Parser<R, W, std::map<std::string, T>>
: public MapParser<R, W, std::map<std::string, T>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::unordered_map<std::string, T>>
struct Parser<R, W, std::unordered_map<std::string, T>>
: public MapParser<R, W, std::unordered_map<std::string, T>> {
};
} // namespace parsing
} // namespace rfl
#endif
@@ -0,0 +1,20 @@
#ifndef RFL_PARSING_PARSER_NAMED_TUPLE_HPP_
#define RFL_PARSING_PARSER_NAMED_TUPLE_HPP_
#include "rfl/parsing/NamedTupleParser.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class... FieldTypes>
requires AreReaderAndWriter<R, W, NamedTuple<FieldTypes...>>
struct Parser<R, W, NamedTuple<FieldTypes...>>
: public NamedTupleParser<R, W, /*_ignore_empty_containers=*/false,
FieldTypes...> {
};
} // namespace parsing
} // namespace rfl
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef RFL_PARSING_PARSER_OPTIONAL_HPP_
#define RFL_PARSING_PARSER_OPTIONAL_HPP_
#include <optional>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::optional<T>>
struct Parser<R, W, std::optional<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
static Result<std::optional<T>> read(const R& _r,
const InputVarType& _var) noexcept {
if (_r.is_empty(_var)) {
return std::optional<T>();
}
const auto to_opt = [](auto&& _t) { return std::make_optional<T>(_t); };
return Parser<R, W, std::decay_t<T>>::read(_r, _var).transform(to_opt);
}
static OutputVarType write(const W& _w, const std::optional<T>& _o) noexcept {
if (!_o) {
return _w.empty_var();
}
return Parser<R, W, std::decay_t<T>>::write(_w, *_o);
}
};
} // namespace parsing
} // namespace rfl
#endif
+44
View File
@@ -0,0 +1,44 @@
#ifndef RFL_PARSING_PARSER_PAIR_HPP_
#define RFL_PARSING_PARSER_PAIR_HPP_
#include <type_traits>
#include <utility>
#include "rfl/Ref.hpp"
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class FirstType, class SecondType>
requires AreReaderAndWriter<R, W, std::pair<FirstType, SecondType>>
struct Parser<R, W, std::pair<FirstType, SecondType>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<std::pair<FirstType, SecondType>> 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<R, W, std::tuple<FirstType, SecondType>>::read(_r, _var)
.transform(to_pair);
}
/// Transform a std::pair into an array
static OutputVarType write(
const W& _w, const std::pair<FirstType, SecondType>& _p) noexcept {
const auto tup = std::make_tuple(&_p.first, &_p.second);
return Parser<R, W, std::tuple<const FirstType*, const SecondType*>>::write(
_w, tup);
}
};
} // namespace parsing
} // namespace rfl
#endif
+42
View File
@@ -0,0 +1,42 @@
#ifndef RFL_PARSING_PARSER_PTR_HPP_
#define RFL_PARSING_PARSER_PTR_HPP_
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, T*>
struct Parser<R, W, T*> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<T*> read(const R& _r, const InputVarType& _var) noexcept {
static_assert(always_false_v<T>,
"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<R, W, std::decay_t<T>>::write(_w, *_ptr);
}
};
} // namespace parsing
} // namespace rfl
#endif
+35
View File
@@ -0,0 +1,35 @@
#ifndef RFL_PARSING_PARSER_REF_HPP_
#define RFL_PARSING_PARSER_REF_HPP_
#include <type_traits>
#include "rfl/Ref.hpp"
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, Ref<T>>
struct Parser<R, W, Ref<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<Ref<T>> read(const R& _r, const InputVarType& _var) noexcept {
const auto to_ref = [&](auto&& _t) { return Ref<T>::make(std::move(_t)); };
return Parser<R, W, std::decay_t<T>>::read(_r, _var).transform(to_ref);
}
/// Expresses the variable a a JSON.
static OutputVarType write(const W& _w, const Ref<T>& _ref) noexcept {
return Parser<R, W, std::decay_t<T>>::write(_w, *_ref);
}
};
} // namespace parsing
} // namespace rfl
#endif
@@ -0,0 +1,40 @@
#ifndef RFL_PARSING_PARSER_REFERENCE_WRAPPER_HPP_
#define RFL_PARSING_PARSER_REFERENCE_WRAPPER_HPP_
#include <functional>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::reference_wrapper<T>>
struct Parser<R, W, std::reference_wrapper<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
static Result<std::reference_wrapper<T>> read(
const R& _r, const InputVarType& _var) noexcept {
static_assert(always_false_v<T>,
"Reading into std::reference_wrapper is dangerous and "
"therefore unsupported. "
"Please consider using std::unique_ptr, rfl::Box, "
"std::shared_ptr, or"
"rfl::Ref instead.");
return Error("Unsupported.");
}
static OutputVarType write(const W& _w,
const std::reference_wrapper<T> _ref) noexcept {
return Parser<R, W, std::decay_t<T>>::write(_w, _ref.get());
}
};
} // namespace parsing
} // namespace rfl
#endif
+38
View File
@@ -0,0 +1,38 @@
#ifndef RFL_PARSING_PARSER_RENAME_HPP_
#define RFL_PARSING_PARSER_RENAME_HPP_
#include <type_traits>
#include "rfl/Rename.hpp"
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T, internal::StringLiteral _name>
requires AreReaderAndWriter<R, W, Rename<_name, T>>
struct Parser<R, W, Rename<_name, T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
static Result<Rename<_name, T>> read(const R& _r,
const InputVarType& _var) noexcept {
const auto to_rename = [](auto&& _t) {
return Rename<_name, T>(std::move(_t));
};
return Parser<R, W, std::decay_t<T>>::read(_r, _var).transform(to_rename);
}
static OutputVarType write(const W& _w,
const Rename<_name, T>& _rename) noexcept {
return Parser<R, W, std::decay_t<T>>::write(_w, _rename.value());
}
};
} // namespace parsing
} // namespace rfl
#endif
+59
View File
@@ -0,0 +1,59 @@
#ifndef RFL_PARSING_PARSER_RESULT_HPP_
#define RFL_PARSING_PARSER_RESULT_HPP_
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, Result<T>>
struct Parser<R, W, Result<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
using ErrorType = NamedTuple<Field<"error", std::string>>;
using VariantType = std::variant<std::decay_t<T>, ErrorType>;
static Result<Result<T>> read(const R& _r,
const InputVarType& _var) noexcept {
const auto handle = [](auto&& _t) -> Result<T> {
using Type = std::decay_t<decltype(_t)>;
if constexpr (std::is_same<Type, ErrorType>()) {
return Error(_t.template get<"error">());
} else {
return std::forward<std::decay_t<T>>(_t);
}
};
const auto to_res = [&](VariantType&& _v) -> Result<T> {
return std::visit(handle, std::forward<VariantType>(_v));
};
return Result<Result<T>>(
Parser<R, W, VariantType>::read(_r, _var).transform(to_res));
}
static OutputVarType write(const W& _w, const Result<T>& _r) noexcept {
const auto write_t = [&](const auto& _t) -> OutputVarType {
return Parser<R, W, std::decay_t<T>>::write(_w, _t);
};
const auto write_err = [&](const auto& _err) -> OutputVarType {
return Parser<R, W, ErrorType>::write(
_w, ErrorType(make_field<"error">(_err.what())));
};
return *_r.transform(write_t).or_else(write_err);
}
};
} // namespace parsing
} // namespace rfl
#endif
@@ -0,0 +1,43 @@
#ifndef RFL_PARSING_PARSER_RFL_VARIANT_HPP_
#define RFL_PARSING_PARSER_RFL_VARIANT_HPP_
#include <type_traits>
#include <variant>
#include "rfl/Result.hpp"
#include "rfl/Variant.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/FieldVariantParser.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class... FieldTypes>
requires AreReaderAndWriter<R, W, rfl::Variant<FieldTypes...>>
struct Parser<R, W, rfl::Variant<FieldTypes...>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<rfl::Variant<FieldTypes...>> read(
const R& _r, const InputVarType& _var) noexcept {
const auto to_rfl_variant = [](auto&& _var) {
return rfl::Variant<FieldTypes...>(
std::forward<std::variant<FieldTypes...>>(_var));
};
return Parser<R, W, std::variant<FieldTypes...>>::read(_r, _var).transform(
to_rfl_variant);
}
static OutputVarType write(
const W& _w, const rfl::Variant<FieldTypes...>& _variant) noexcept {
return Parser<R, W, std::variant<FieldTypes...>>::write(_w,
_variant.variant());
}
};
} // namespace parsing
} // namespace rfl
#endif
+45
View File
@@ -0,0 +1,45 @@
#ifndef RFL_PARSING_PARSER_SHARED_PTR_HPP_
#define RFL_PARSING_PARSER_SHARED_PTR_HPP_
#include <memory>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::shared_ptr<T>>
struct Parser<R, W, std::shared_ptr<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<std::shared_ptr<T>> read(const R& _r,
const InputVarType& _var) noexcept {
if (_r.is_empty(*_var)) {
return std::shared_ptr<T>();
}
const auto to_ptr = [](auto&& _t) {
return std::make_shared<T>(std::move(_t));
};
return Parser<R, W, std::decay_t<T>>::read(_r, _var).transform(to_ptr);
}
/// Expresses the variable a a JSON.
static OutputVarType write(const W& _w,
const std::shared_ptr<T>& _s) noexcept {
if (!_s) {
return _w.empty_var();
}
return Parser<R, W, std::decay_t<T>>::write(_w, *_s);
}
};
} // namespace parsing
} // namespace rfl
#endif
+133
View File
@@ -0,0 +1,133 @@
#ifndef RFL_PARSING_PARSER_TAGGED_UNION_HPP_
#define RFL_PARSING_PARSER_TAGGED_UNION_HPP_
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/TaggedUnion.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
#include "rfl/parsing/TaggedUnionWrapper.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, internal::StringLiteral _discriminator,
class... AlternativeTypes>
requires AreReaderAndWriter<R, W,
TaggedUnion<_discriminator, AlternativeTypes...>>
struct Parser<R, W, TaggedUnion<_discriminator, AlternativeTypes...>> {
using ResultType = Result<TaggedUnion<_discriminator, AlternativeTypes...>>;
public:
using InputObjectType = typename R::InputObjectType;
using InputVarType = typename R::InputVarType;
using OutputObjectType = typename W::OutputObjectType;
using OutputVarType = typename W::OutputVarType;
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);
}
static OutputVarType write(
const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>&
_tagged_union) noexcept {
const auto handle = [&](const auto& _val) -> OutputVarType {
return write_wrapped(_w, _val);
};
return std::visit(handle, _tagged_union.variant_);
}
private:
template <int _i = 0>
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<AlternativeTypes...>>>;
if (contains_disc_value<AlternativeType>(_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<R, W, AlternativeType>::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<std::string> 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<std::string>(_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 <class T>
static inline bool contains_disc_value(
const std::string& _disc_value) noexcept {
return internal::tag_t<T>::contains(_disc_value);
}
/// Writes a wrapped version of the original object, which contains the tag.
template <class T>
static OutputVarType write_wrapped(const W& _w, const T& _val) noexcept {
const auto tag = internal::make_tag<T>();
using TagType = std::decay_t<decltype(tag)>;
if constexpr (internal::has_fields<std::decay_t<T>>()) {
using WrapperType =
TaggedUnionWrapperWithFields<T, TagType, _discriminator>;
const auto wrapper = WrapperType{.tag = tag, .fields = &_val};
return Parser<R, W, WrapperType>::write(_w, wrapper);
} else {
using WrapperType =
TaggedUnionWrapperNoFields<T, TagType, _discriminator>;
const auto wrapper = WrapperType{.tag = tag, .fields = &_val};
return Parser<R, W, WrapperType>::write(_w, wrapper);
}
}
};
} // namespace parsing
} // namespace rfl
#endif
+19
View File
@@ -0,0 +1,19 @@
#ifndef RFL_PARSING_PARSER_TUPLE_HPP_
#define RFL_PARSING_PARSER_TUPLE_HPP_
#include "rfl/parsing/Parser_base.hpp"
#include "rfl/parsing/TupleParser.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class... Ts>
requires AreReaderAndWriter<R, W, std::tuple<Ts...>>
struct Parser<R, W, std::tuple<Ts...>>
: public TupleParser<R, W, /*_ignore_empty_containers=*/false, Ts...> {
};
} // namespace parsing
} // namespace rfl
#endif
+43
View File
@@ -0,0 +1,43 @@
#ifndef RFL_PARSING_PARSER_UNIQUE_PTR_HPP_
#define RFL_PARSING_PARSER_UNIQUE_PTR_HPP_
#include <memory>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::unique_ptr<T>>
struct Parser<R, W, std::unique_ptr<T>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
static Result<std::unique_ptr<T>> read(const R& _r,
const InputVarType& _var) noexcept {
if (_r.is_empty(_var)) {
return std::unique_ptr<T>();
}
const auto to_ptr = [](auto&& _t) {
return std::make_unique<T>(std::move(_t));
};
return Parser<R, W, std::decay_t<T>>::read(_r, _var).transform(to_ptr);
}
static OutputVarType write(const W& _w,
const std::unique_ptr<T>& _s) noexcept {
if (!_s) {
return _w.empty_var();
}
return Parser<R, W, std::decay_t<T>>::write(_w, *_s);
}
};
} // namespace parsing
} // namespace rfl
#endif
+69
View File
@@ -0,0 +1,69 @@
#ifndef RFL_PARSING_PARSER_VARIANT_HPP_
#define RFL_PARSING_PARSER_VARIANT_HPP_
#include <type_traits>
#include <variant>
#include "rfl/Ref.hpp"
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/FieldVariantParser.hpp"
#include "rfl/parsing/Parser_base.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class... FieldTypes>
requires AreReaderAndWriter<R, W, std::variant<FieldTypes...>>
struct Parser<R, W, std::variant<FieldTypes...>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
template <int _i = 0>
static Result<std::variant<FieldTypes...>> read(
const R& _r, const InputVarType& _var,
const std::string _errors = "") noexcept {
if constexpr (_i == 0 &&
internal::all_fields<std::tuple<FieldTypes...>>()) {
return FieldVariantParser<R, W, FieldTypes...>::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<FieldTypes...>(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) + ") ") +
internal::strings::replace_all(_err.what(), "\n", "\n ");
return read<_i + 1>(_r, _var, errors);
};
using AltType = std::decay_t<
std::variant_alternative_t<_i, std::variant<FieldTypes...>>>;
return Parser<R, W, AltType>::read(_r, _var)
.transform(to_variant)
.or_else(try_next);
}
}
static OutputVarType write(
const W& _w, const std::variant<FieldTypes...>& _variant) noexcept {
if constexpr (internal::all_fields<std::tuple<FieldTypes...>>()) {
return FieldVariantParser<R, W, FieldTypes...>::write(_w, _variant);
} else {
const auto handle = [&](const auto& _v) {
using Type = std::decay_t<decltype(_v)>;
return Parser<R, W, Type>::write(_w, _v);
};
return std::visit(handle, _variant);
}
}
};
} // namespace parsing
} // namespace rfl
#endif
@@ -0,0 +1,96 @@
#ifndef RFL_PARSING_PARSER_VECTOR_LIKE_HPP_
#define RFL_PARSING_PARSER_VECTOR_LIKE_HPP_
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/Parser_base.hpp"
#include "rfl/parsing/VectorParser.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::deque<T>>
struct Parser<R, W, std::deque<T>> : public VectorParser<R, W, std::deque<T>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::forward_list<T>>
struct Parser<R, W, std::forward_list<T>>
: public VectorParser<R, W, std::forward_list<T>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::list<T>>
struct Parser<R, W, std::list<T>> : public VectorParser<R, W, std::list<T>> {
};
template <class R, class W, class K, class V>
requires AreReaderAndWriter<R, W, std::map<K, V>>
struct Parser<R, W, std::map<K, V>>
: public VectorParser<R, W, std::map<K, V>> {
};
template <class R, class W, class K, class V>
requires AreReaderAndWriter<R, W, std::multimap<K, V>>
struct Parser<R, W, std::multimap<K, V>>
: public VectorParser<R, W, std::multimap<K, V>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::multiset<T>>
struct Parser<R, W, std::multiset<T>>
: public VectorParser<R, W, std::multiset<T>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::set<T>>
struct Parser<R, W, std::set<T>> : public VectorParser<R, W, std::set<T>> {
};
template <class R, class W, class K, class V>
requires AreReaderAndWriter<R, W, std::unordered_map<K, V>>
struct Parser<R, W, std::unordered_map<K, V>>
: public VectorParser<R, W, std::unordered_map<K, V>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::unordered_multiset<T>>
struct Parser<R, W, std::unordered_multiset<T>>
: public VectorParser<R, W, std::unordered_multiset<T>> {
};
template <class R, class W, class K, class V>
requires AreReaderAndWriter<R, W, std::unordered_multimap<K, V>>
struct Parser<R, W, std::unordered_multimap<K, V>>
: public VectorParser<R, W, std::unordered_multimap<K, V>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::unordered_set<T>>
struct Parser<R, W, std::unordered_set<T>>
: public VectorParser<R, W, std::unordered_set<T>> {
};
template <class R, class W, class T>
requires AreReaderAndWriter<R, W, std::vector<T>>
struct Parser<R, W, std::vector<T>>
: public VectorParser<R, W, std::vector<T>> {
};
} // namespace parsing
} // namespace rfl
#endif
+110
View File
@@ -0,0 +1,110 @@
#ifndef RFL_PARSING_TUPLEPARSER_HPP_
#define RFL_PARSING_TUPLEPARSER_HPP_
#include <tuple>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, bool _ignore_empty_containers, class... Ts>
requires AreReaderAndWriter<R, W, std::tuple<Ts...>>
struct TupleParser {
public:
using InputArrayType = typename R::InputArrayType;
using InputVarType = typename R::InputVarType;
using OutputArrayType = typename W::OutputArrayType;
using OutputVarType = typename W::OutputVarType;
static Result<std::tuple<Ts...>> 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<std::vector<InputVarType>> {
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));
};
return _r.to_array(_var)
.transform(to_vec)
.and_then(check_size)
.and_then(extract);
}
static OutputVarType write(const W& _w,
const std::tuple<Ts...>& _tup) noexcept {
auto arr = _w.new_array();
to_array<0>(_w, _tup, &arr);
return arr;
}
private:
template <class... AlreadyExtracted>
static Result<std::tuple<Ts...>> extract_field_by_field(
const R& _r, std::vector<InputVarType> _vec,
AlreadyExtracted&&... _already_extracted) noexcept {
constexpr size_t i = sizeof...(AlreadyExtracted);
if constexpr (i == sizeof...(Ts)) {
return std::tuple<Ts...>(
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<i>(_r, _vec).and_then(extract_next);
}
}
template <int _i>
static auto extract_single_field(
const R& _r, const std::vector<InputVarType>& _vec) noexcept {
using NewFieldType =
std::decay_t<typename std::tuple_element<_i, std::tuple<Ts...>>::type>;
using ResultType = Result<NewFieldType>;
if (_i >= _vec.size()) {
if constexpr (is_required<NewFieldType, _ignore_empty_containers>()) {
return ResultType(Error("Array is of length " +
std::to_string(_vec.size()) + ", but field " +
std::to_string(_i + 1) + " is required."));
} else {
return ResultType(NewFieldType());
}
}
return Parser<R, W, NewFieldType>::read(_r, _vec[_i]);
}
template <int _i>
static void to_array(const W& _w, const std::tuple<Ts...>& _tup,
OutputArrayType* _ptr) noexcept {
if constexpr (_i < sizeof...(Ts)) {
using NewFieldType = std::decay_t<
typename std::tuple_element<_i, std::tuple<Ts...>>::type>;
const auto val =
Parser<R, W, NewFieldType>::write(_w, std::get<_i>(_tup));
_w.add(val, _ptr);
to_array<_i + 1>(_w, _tup, _ptr);
}
}
};
} // namespace parsing
} // namespace rfl
#endif
+125
View File
@@ -0,0 +1,125 @@
#ifndef RFL_PARSING_VECTORPARSER_HPP_
#define RFL_PARSING_VECTORPARSER_HPP_
#include <stdexcept>
#include <string>
#include <type_traits>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/parsing/MapParser.hpp"
#include "rfl/parsing/Parser_base.hpp"
#include "rfl/parsing/is_forward_list.hpp"
#include "rfl/parsing/is_map_like.hpp"
#include "rfl/parsing/is_map_like_not_multimap.hpp"
#include "rfl/parsing/is_set_like.hpp"
namespace rfl {
namespace parsing {
/// 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.
template <class R, class W, class VecType>
requires AreReaderAndWriter<R, W, VecType>
struct VectorParser {
public:
using InputArrayType = typename R::InputArrayType;
using InputVarType = typename R::InputVarType;
using OutputArrayType = typename W::OutputArrayType;
using OutputVarType = typename W::OutputVarType;
using T = typename VecType::value_type;
static Result<VecType> read(const R& _r, const InputVarType& _var) noexcept {
if constexpr (treat_as_map()) {
return MapParser<R, W, VecType>::read(_r, _var);
} else {
const auto to_res = [&](auto&& _v) {
return to_result(_r, std::move(_v));
};
return _r.to_array(_var).and_then(to_res);
}
}
static OutputVarType write(const W& _w, const VecType& _vec) noexcept {
if constexpr (treat_as_map()) {
return MapParser<R, W, VecType>::write(_w, _vec);
} else {
auto arr = _w.new_array();
for (const auto& v : _vec) {
_w.add(Parser<R, W, std::decay_t<T>>::write(_w, v), &arr);
}
return OutputVarType(arr);
}
}
private:
static auto get_elem(const R& _r, auto& _v) {
return Parser<R, W, std::decay_t<T>>::read(_r, _v).value();
};
static auto get_pair(const R& _r, auto& _v) {
using K = std::decay_t<typename T::first_type>;
using V = std::decay_t<typename T::second_type>;
return Parser<R, W, std::decay_t<std::pair<K, V>>>::read(_r, _v).value();
}
static Result<VecType> to_container(const R& _r, InputArrayType&& _arr) {
auto input_vars = _r.to_vec(_arr);
VecType vec;
if constexpr (is_forward_list<VecType>()) {
for (auto it = input_vars.rbegin(); it != input_vars.rend(); ++it) {
vec.emplace_front(get_elem(_r, *it));
}
} else if constexpr (is_map_like<VecType>()) {
for (auto& v : input_vars) {
vec.insert(get_pair(_r, v));
}
} else if constexpr (is_set_like<VecType>()) {
for (auto& v : input_vars) {
vec.insert(get_elem(_r, v));
}
} else {
for (auto& v : input_vars) {
vec.emplace_back(get_elem(_r, v));
}
}
return vec;
}
static Result<VecType> to_result(const R& _r, InputArrayType&& _arr) {
try {
return to_container(_r, std::forward<InputArrayType>(_arr));
} catch (std::exception& e) {
return Error(e.what());
}
}
static constexpr bool treat_as_map() {
if constexpr (is_map_like_not_multimap<VecType>()) {
if constexpr (internal::has_reflection_type_v<typename T::first_type>) {
using U = std::decay_t<typename T::first_type::ReflectionType>;
return std::is_same<U, std::string>() || std::is_integral_v<U> ||
std::is_floating_point_v<U>;
// We do not need std::string here, it is already caught by the template
// specialization.
} else if constexpr (std::is_integral_v<typename T::first_type> ||
std::is_floating_point_v<typename T::first_type>) {
return true;
} else {
return false;
}
} else {
return false;
}
}
};
} // namespace parsing
} // namespace rfl
#endif
+4
View File
@@ -26,6 +26,10 @@ class is_map_like<std::unordered_map<K, V>> : public std::true_type {};
template <class K, class V>
class is_map_like<std::unordered_multimap<K, V>> : public std::true_type {};
template <class T>
constexpr bool is_map_like_v =
is_map_like<std::decay_t<std::remove_pointer_t<T>>>::value;
} // namespace parsing
} // namespace rfl
+23 -8
View File
@@ -7,6 +7,9 @@
#include "rfl/Rename.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/internal/is_rename.hpp"
#include "rfl/parsing/is_map_like.hpp"
#include "rfl/parsing/is_vector_like.hpp"
namespace rfl {
namespace parsing {
@@ -14,25 +17,37 @@ namespace parsing {
/// Determines whether a field in a named tuple is required.
/// General case - most fields are required.
template <class T>
class is_required;
class is_never_required;
template <class T>
class is_required : public std::true_type {};
class is_never_required : public std::false_type {};
template <class T>
class is_required<T*> : public std::false_type {};
class is_never_required<std::optional<T>> : public std::true_type {};
template <class T>
class is_required<std::optional<T>> : public std::false_type {};
class is_never_required<std::shared_ptr<T>> : public std::true_type {};
template <class T>
class is_required<std::shared_ptr<T>> : public std::false_type {};
class is_never_required<std::unique_ptr<T>> : public std::true_type {};
template <class T>
class is_required<std::unique_ptr<T>> : public std::false_type {};
constexpr bool is_never_required_v = is_never_required<T>::value;
template <class T, internal::StringLiteral _name>
class is_required<Rename<_name, T>> : public is_required<T> {};
template <class T, bool _ignore_empty_containers>
consteval bool is_required() {
using Type = std::decay_t<std::remove_pointer_t<T>>;
if constexpr (internal::has_reflection_type_v<Type>) {
return is_required<typename Type::ReflectionType,
_ignore_empty_containers>();
} else if constexpr (internal::is_rename_v<Type>) {
return is_required<typename Type::Type, _ignore_empty_containers>();
} else {
return !(is_never_required_v<Type> ||
(_ignore_empty_containers &&
(is_vector_like_v<Type> || is_map_like_v<Type>)));
}
}
} // namespace parsing
} // namespace rfl
+53
View File
@@ -0,0 +1,53 @@
#ifndef RFL_PARSING_IS_VECTOR_LIKE_HPP_
#define RFL_PARSING_IS_VECTOR_LIKE_HPP_
#include <deque>
#include <forward_list>
#include <list>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace rfl {
namespace parsing {
template <class T>
class is_vector_like;
template <class T>
class is_vector_like : public std::false_type {};
template <class T>
class is_vector_like<std::deque<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::forward_list<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::list<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::multiset<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::set<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::unordered_multiset<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::unordered_set<T>> : public std::true_type {};
template <class T>
class is_vector_like<std::vector<T>> : public std::true_type {};
template <class T>
constexpr bool is_vector_like_v =
is_vector_like<std::decay_t<std::remove_pointer_t<T>>>::value;
} // namespace parsing
} // namespace rfl
#endif
+12
View File
@@ -0,0 +1,12 @@
#ifndef FLEXBUF_XML_HPP_
#define FLEXBUF_XML_HPP_
#include "rfl/xml/Parser.hpp"
#include "rfl/xml/Reader.hpp"
#include "rfl/xml/Writer.hpp"
#include "rfl/xml/load.hpp"
#include "rfl/xml/read.hpp"
#include "rfl/xml/save.hpp"
#include "rfl/xml/write.hpp"
#endif
+41
View File
@@ -0,0 +1,41 @@
#ifndef RFL_XML_OUTPUTARRAY_HPP_
#define RFL_XML_OUTPUTARRAY_HPP_
#include <pugixml.hpp>
#include <string>
#include <vector>
#include "rfl/Ref.hpp"
#include "rfl/xml/OutputVar.hpp"
namespace rfl {
namespace xml {
class OutputArray : public OutputVar {
public:
OutputArray() {}
~OutputArray() = default;
/// Inserts all elements into the builder.
void insert(const std::string& _key, pugi::xml_node* _parent) final {
for (auto& v : vars_) {
v->insert(_key, _parent);
}
};
/// Whether this is null.
bool is_null() const final { return false; }
/// Adds a new element to the vector.
void push_back(const Ref<OutputVar>& _var) { vars_.push_back(_var); }
private:
/// The underlying variables.
std::vector<Ref<OutputVar>> vars_;
};
} // namespace xml
} // namespace rfl
#endif
+32
View File
@@ -0,0 +1,32 @@
#ifndef RFL_XML_OUTPUTNULL_HPP_
#define RFL_XML_OUTPUTNULL_HPP_
#include <optional>
#include <pugixml.hpp>
#include <string>
#include "rfl/Ref.hpp"
#include "rfl/xml/OutputVar.hpp"
namespace rfl {
namespace xml {
class OutputNull : public OutputVar {
public:
OutputNull() {}
~OutputNull() = default;
/// Inserts all elements into the builder.
void insert(const std::string& _key, pugi::xml_node* _parent) final {
_parent->append_child(_key.c_str());
}
/// Whether this is null.
bool is_null() const final { return true; }
};
} // namespace xml
} // namespace rfl
#endif
+44
View File
@@ -0,0 +1,44 @@
#ifndef RFL_XML_OUTPUTOBJECT_HPP_
#define RFL_XML_OUTPUTOBJECT_HPP_
#include <pugixml.hpp>
#include <string>
#include <utility>
#include "rfl/Ref.hpp"
#include "rfl/xml/OutputVar.hpp"
namespace rfl {
namespace xml {
class OutputObject : public OutputVar {
public:
OutputObject() {}
~OutputObject() = default;
/// Inserts all elements into the builder.
void insert(const std::string& _key, pugi::xml_node* _parent) final {
auto node_child = _parent->append_child(_key.c_str());
for (auto& v : vars_) {
v.second->insert(v.first, &node_child);
}
};
/// Whether this is null.
bool is_null() const final { return false; }
/// Adds a new element to the vector.
void push_back(const std::string& _name, const Ref<OutputVar>& _var) {
vars_.push_back(std::make_pair(_name, _var));
}
private:
/// The underlying variables.
std::vector<std::pair<std::string, Ref<OutputVar>>> vars_;
};
} // namespace xml
} // namespace rfl
#endif
+67
View File
@@ -0,0 +1,67 @@
#ifndef RFL_XML_OUTPUTVALUE_HPP_
#define RFL_XML_OUTPUTVALUE_HPP_
#include <pugixml.hpp>
#include <string>
#include <utility>
#include "rfl/always_false.hpp"
#include "rfl/xml/OutputVar.hpp"
namespace rfl {
namespace xml {
template <class T>
class OutputValue : public OutputVar {
public:
static constexpr const char* XML_CONTENT = "xml_content";
public:
OutputValue(T _val, bool _is_attribute)
: is_attribute_(_is_attribute), val_(_val) {}
~OutputValue() = default;
/// Inserts all elements into the builder.
void insert(const std::string& _key, pugi::xml_node* _parent) final {
const auto str = to_string();
if (is_attribute_) {
_parent->append_attribute(_key.c_str()) = str.c_str();
} else if (_key == XML_CONTENT) {
_parent->append_child(pugi::node_pcdata).set_value(str.c_str());
} else {
auto node_child = _parent->append_child(_key.c_str());
node_child.append_child(pugi::node_pcdata).set_value(str.c_str());
}
};
/// Whether this is null.
bool is_null() const final { return false; }
private:
/// Transforms the underlying value into a string.
std::string to_string() {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
return val_;
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
return val_ ? "true" : "false";
} else if constexpr (std::is_floating_point<std::decay_t<T>>() ||
std::is_integral<std::decay_t<T>>()) {
return std::to_string(val_);
} else {
static_assert(always_false_v<T>, "Unsupported type");
}
}
private:
/// Whether you want this encoded as an attribute.
bool is_attribute_;
/// The underlying value.
T val_;
};
} // namespace xml
} // namespace rfl
#endif
+24
View File
@@ -0,0 +1,24 @@
#ifndef RFL_XML_OUTPUTVAR_HPP_
#define RFL_XML_OUTPUTVAR_HPP_
#include <pugixml.hpp>
#include <string>
namespace rfl {
namespace xml {
class OutputVar {
public:
virtual ~OutputVar() = default;
/// Inserts the value into the _parent.
virtual void insert(const std::string& _key, pugi::xml_node* _parent) = 0;
/// Whether this is null.
virtual bool is_null() const = 0;
};
} // namespace xml
} // namespace rfl
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef RFL_XML_PARSER_HPP_
#define RFL_XML_PARSER_HPP_
#include <type_traits>
#include "is_required_for_xml.hpp"
#include "rfl/internal/is_attribute.hpp"
#include "rfl/parsing/NamedTupleParser.hpp"
#include "rfl/parsing/Parser.hpp"
#include "rfl/xml/Reader.hpp"
#include "rfl/xml/Writer.hpp"
#include "rfl/xml/is_required_for_xml.hpp"
namespace rfl {
namespace parsing {
/// XML is very special. It doesn't have proper support for arrays, which means
/// that we just need to ignore empty containers. Therefore, we need to a
/// template specialization for the NamedTuple parser to accommodate for it.
template <class... FieldTypes>
requires AreReaderAndWriter<xml::Reader, xml::Writer, NamedTuple<FieldTypes...>>
struct Parser<xml::Reader, xml::Writer, NamedTuple<FieldTypes...>>
: public NamedTupleParser<xml::Reader, xml::Writer,
/*_ignore_empty_containers=*/true,
FieldTypes...> {
};
} // namespace parsing
} // namespace rfl
namespace rfl {
namespace xml {
template <class T>
using Parser = parsing::Parser<Reader, Writer, T>;
}
} // namespace rfl
#endif
+193
View File
@@ -0,0 +1,193 @@
#ifndef RFL_XML_READER_HPP_
#define RFL_XML_READER_HPP_
#include <array>
#include <exception>
#include <map>
#include <memory>
#include <pugixml.hpp>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <variant>
#include <vector>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
namespace rfl {
namespace xml {
struct Reader {
struct XMLInputArray {
XMLInputArray(pugi::xml_node _node) : node_(_node) {}
pugi::xml_node node_;
};
struct XMLInputObject {
XMLInputObject(pugi::xml_node _node) : node_(_node) {}
pugi::xml_node node_;
};
struct XMLInputVar {
XMLInputVar() : node_or_attribute_(pugi::xml_node()) {}
XMLInputVar(pugi::xml_attribute _attr) : node_or_attribute_(_attr) {}
XMLInputVar(pugi::xml_node _node) : node_or_attribute_(_node) {}
std::variant<pugi::xml_node, pugi::xml_attribute> node_or_attribute_;
};
using InputArrayType = XMLInputArray;
using InputObjectType = XMLInputObject;
using InputVarType = XMLInputVar;
// TODO
template <class T>
static constexpr bool has_custom_constructor = false;
/// XML-only helper function. This is needed because XML distinguishes between
/// nodes and attributes.
static rfl::Result<pugi::xml_node> cast_as_node(
const std::variant<pugi::xml_node, pugi::xml_attribute>&
_node_or_attribute) {
const auto cast = [](const auto& _n) -> Result<pugi::xml_node> {
using Type = std::decay_t<decltype(_n)>;
if constexpr (std::is_same<Type, pugi::xml_node>()) {
return _n;
} else {
return Error("Field '" + std::string(_n.name()) + "' is an attribute.");
}
};
return std::visit(cast, _node_or_attribute);
}
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType _obj) const noexcept {
const auto node = _obj.node_.child(_name.c_str());
if (!node) {
return rfl::Error("Object contains no field named '" + _name + "'.");
}
return InputVarType(node);
}
bool is_empty(const InputVarType _var) const noexcept {
const auto wrap = [](const auto& _node) { return !_node; };
return std::visit(cast_as_node, _var.node_or_attribute_)
.transform(wrap)
.value_or(false);
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType _var) const noexcept {
const auto get_value = [](const auto& _n) -> std::string {
using Type = std::decay_t<decltype(_n)>;
if constexpr (std::is_same<Type, pugi::xml_node>()) {
return std::string(_n.child_value());
} else {
return std::string(_n.value());
}
};
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
return std::visit(get_value, _var.node_or_attribute_);
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
return std::visit(get_value, _var.node_or_attribute_) == "true";
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
const auto str = std::visit(get_value, _var.node_or_attribute_);
try {
return static_cast<T>(std::stod(str));
} catch (std::exception& e) {
return Error("Could not cast '" + std::string(str) +
"' to floating point value.");
}
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
const auto str = std::visit(get_value, _var.node_or_attribute_);
try {
return static_cast<T>(std::stoi(str));
} catch (std::exception& e) {
return Error("Could not cast '" + std::string(str) + "' to integer.");
}
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
rfl::Result<InputArrayType> to_array(const InputVarType _var) const noexcept {
const auto wrap = [](const auto& _node) { return InputArrayType(_node); };
return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap);
}
template <size_t size, class FunctionType>
std::array<std::optional<InputVarType>, size> to_fields_array(
const FunctionType _fct, const InputObjectType _obj) const noexcept {
std::array<std::optional<InputVarType>, size> f_arr;
for (auto child = _obj.node_.first_child(); child;
child = child.next_sibling()) {
const auto name = child.name();
const auto ix = _fct(std::string_view(name));
// XML allows for duplicate node names, but we always want the first
// sibling.
if (ix != -1 && !f_arr[ix]) {
f_arr[ix] = InputVarType(child);
}
}
for (auto attr = _obj.node_.first_attribute(); attr;
attr = attr.next_attribute()) {
const auto name = attr.name();
const auto ix = _fct(std::string_view(name));
// XML allows for duplicate node names, but we always want the first
// sibling.
if (ix != -1 && !f_arr[ix]) {
f_arr[ix] = InputVarType(attr);
}
}
const auto ix = _fct(std::string_view("xml_content"));
if (ix != -1) {
f_arr[ix] = InputVarType(_obj.node_);
}
return f_arr;
}
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
for (auto child = _obj.node_.first_child(); child;
child = child.next_sibling()) {
auto p = std::make_pair(std::string(child.name()), InputVarType(child));
m.emplace_back(std::move(p));
}
return m;
}
rfl::Result<InputObjectType> to_object(
const InputVarType _var) const noexcept {
const auto wrap = [](const auto& _node) { return InputObjectType(_node); };
return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap);
}
std::vector<InputVarType> to_vec(const InputArrayType _arr) const noexcept {
const auto name = _arr.node_.name();
std::vector<InputVarType> vec;
for (auto node = _arr.node_; node; node = node.next_sibling(name)) {
vec.push_back(InputVarType(node));
}
return vec;
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
return rfl::Error("TODO");
}
};
} // namespace xml
} // namespace rfl
#endif
+65
View File
@@ -0,0 +1,65 @@
#ifndef RFL_XML_WRITER_HPP_
#define RFL_XML_WRITER_HPP_
#include <exception>
#include <map>
#include <pugixml.hpp>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "rfl/Ref.hpp"
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
#include "rfl/xml/OutputArray.hpp"
#include "rfl/xml/OutputNull.hpp"
#include "rfl/xml/OutputObject.hpp"
#include "rfl/xml/OutputValue.hpp"
namespace rfl {
namespace xml {
struct Writer {
using OutputArrayType = Ref<OutputArray>;
using OutputObjectType = Ref<OutputObject>;
using OutputVarType = Ref<OutputVar>;
Writer() {}
~Writer() = default;
void add(const OutputVarType _var, OutputArrayType* _arr) const noexcept {
(*_arr)->push_back(_var);
}
OutputVarType empty_var() const noexcept { return make_ref<OutputNull>(); }
template <class T>
OutputVarType from_basic_type(
const T& _var, const bool _is_attribute = false) const noexcept {
return make_ref<OutputValue<T>>(_var, _is_attribute);
}
OutputArrayType new_array() const noexcept { return make_ref<OutputArray>(); }
OutputObjectType new_object() const noexcept {
return make_ref<OutputObject>();
}
bool is_empty(const OutputVarType& _var) const noexcept {
return _var->is_null();
}
void set_field(const std::string& _name, const OutputVarType& _var,
OutputObjectType* _obj) const noexcept {
(*_obj)->push_back(_name, _var);
}
};
} // namespace xml
} // namespace rfl
#endif // XML_PARSER_HPP_
+28
View File
@@ -0,0 +1,28 @@
#ifndef RFL_XML_IS_REQUIRED_FOR_XML_HPP_
#define RFL_XML_IS_REQUIRED_FOR_XML_HPP_
#include <type_traits>
#include "rfl/internal/has_reflection_type_v.hpp"
#include "rfl/parsing/is_required.hpp"
#include "rfl/parsing/is_vector_like.hpp"
namespace rfl {
namespace xml {
// Empty vectors are simply not represented in XML. Therefore, XML requires more
// lax rules when things are required.
template <class T>
consteval bool is_required_for_xml() {
using Type = std::decay_t<std::remove_pointer_t<T>>;
if constexpr (internal::has_reflection_type_v<T>) {
return is_required_for_xml<typename T::ReflectionType>();
} else {
return parsing::is_required<Type>() && !parsing::is_vector_like_v<Type>;
}
}
} // namespace xml
} // namespace rfl
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef RFL_XML_LOAD_HPP_
#define RFL_XML_LOAD_HPP_
#include "rfl/Result.hpp"
#include "rfl/io/load_string.hpp"
#include "rfl/xml/read.hpp"
namespace rfl {
namespace xml {
template <class T>
Result<T> load(const std::string& _fname) {
const auto read_string = [](const auto& _str) { return read<T>(_str); };
return rfl::io::load_string(_fname).and_then(read_string);
}
} // namespace xml
} // namespace rfl
#endif
+49
View File
@@ -0,0 +1,49 @@
#ifndef RFL_XML_READ_HPP_
#define RFL_XML_READ_HPP_
#include <istream>
#include <pugixml.hpp>
#include <string>
#include "rfl/internal/get_type_name.hpp"
#include "rfl/internal/remove_namespaces.hpp"
#include "rfl/xml/Parser.hpp"
#include "rfl/xml/Reader.hpp"
namespace rfl {
namespace xml {
using InputVarType = typename Reader::InputVarType;
/// Parses an object from a XML var.
template <class T>
Result<T> read(const InputVarType& _var) {
const auto r = Reader();
return Parser<T>::read(r, _var);
}
/// Parses an object from XML using reflection.
template <class T>
Result<T> read(const std::string& _xml_str) {
pugi::xml_document doc;
const auto result = doc.load_string(_xml_str.c_str());
if (!result) {
return Error("XML string could not be parsed: " +
std::string(result.description()));
}
const auto var = InputVarType(doc.first_child());
return read<T>(var);
}
/// Parses an object from a stringstream.
template <class T>
Result<T> read(std::istream& _stream) {
const auto xml_str = std::string(std::istreambuf_iterator<char>(_stream),
std::istreambuf_iterator<char>());
return read<T>(xml_str);
}
} // namespace xml
} // namespace rfl
#endif
+27
View File
@@ -0,0 +1,27 @@
#ifndef RFL_XML_SAVE_HPP_
#define RFL_XML_SAVE_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/io/save_string.hpp"
#include "rfl/xml/write.hpp"
namespace rfl {
namespace xml {
template <internal::StringLiteral _root = internal::StringLiteral(""), class T>
Result<Nothing> save(const std::string& _fname, const T& _obj) {
const auto write_func = [](const auto& _obj, auto& _stream) -> auto& {
return write<_root>(_obj, _stream);
};
return rfl::io::save_string(_fname, _obj, write_func);
}
} // namespace xml
} // namespace rfl
#endif
+68
View File
@@ -0,0 +1,68 @@
#ifndef RFL_XML_WRITE_HPP_
#define RFL_XML_WRITE_HPP_
#include <ostream>
#include <pugixml.hpp>
#include <sstream>
#include <string>
#include <type_traits>
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/internal/get_type_name.hpp"
#include "rfl/internal/remove_namespaces.hpp"
#include "rfl/xml/Parser.hpp"
namespace rfl {
namespace xml {
template <internal::StringLiteral _root, class T>
consteval auto get_root_name() {
if constexpr (_root != internal::StringLiteral("")) {
return _root;
} else {
return internal::remove_namespaces<
internal::get_type_name<std::decay_t<T>>()>();
}
}
/// Writes a XML into an ostream.
template <internal::StringLiteral _root = internal::StringLiteral(""), class T>
std::ostream& write(const T& _obj, std::ostream& _stream,
const std::string& _indent = " ") {
constexpr auto root_name = get_root_name<_root, T>();
static_assert(root_name.string_view().find("<") == std::string_view::npos &&
root_name.string_view().find(">") == std::string_view::npos,
"The name of an XML root node cannot contain '<' or '>'. "
"Please assign an "
"explicit root name to rfl::xml::write(...) like this: "
"rfl::xml::write<\"root_name\">(...).");
auto w = Writer();
const auto xml_obj = Parser<T>::write(w, _obj);
pugi::xml_document doc;
auto declaration_node = doc.append_child(pugi::node_declaration);
declaration_node.append_attribute("version") = "1.0";
declaration_node.append_attribute("encoding") = "UTF-8";
xml_obj->insert(root_name.str(), &doc);
doc.save(_stream, _indent.c_str());
return _stream;
}
/// Returns a XML string.
template <internal::StringLiteral _root = internal::StringLiteral(""), class T>
std::string write(const T& _obj, const std::string& _indent = " ") {
std::stringstream stream;
write<_root, T>(_obj, stream);
return stream.str();
}
} // namespace xml
} // namespace rfl
#endif // XML_PARSER_HPP_