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
+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_