diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index f0bc9328..bbdc0c31 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -18,10 +18,11 @@ jobs: - name: Run test run: | g++ --version - cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON -DCMAKE_BUILD_TYPE=Release + cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_XML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build -j 4 ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests ./build/tests/json/reflect-cpp-json-tests + ./build/tests/xml/reflect-cpp-xml-tests linux-clang: runs-on: ubuntu-latest @@ -45,10 +46,11 @@ jobs: CXX: clang++ run: | clang --version - cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON -DCMAKE_BUILD_TYPE=Release + cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_XML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build -j 4 ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests ./build/tests/json/reflect-cpp-json-tests + ./build/tests/xml/reflect-cpp-xml-tests # The latest MSVC version on GitHub Actions has a bug, and it's difficult to switch to another version. @@ -67,4 +69,4 @@ jobs: # cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON # cmake --build build -j 4 # .\build\tests\flexbuffers\Release\reflect-cpp-flexbuffers-tests.exe -# .\build\tests\json\Release\reflect-cpp-json-tests.exe \ No newline at end of file +# .\build\tests\json\Release\reflect-cpp-json-tests.exe diff --git a/.gitignore b/.gitignore index c75e7162..9fb66da0 100644 --- a/.gitignore +++ b/.gitignore @@ -43,4 +43,6 @@ # Output files *.json *.fb -!vcpkg.json \ No newline at end of file +*.xml + +!vcpkg.json diff --git a/CMakeLists.txt b/CMakeLists.txt index 455205c0..ffb2bf6e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,13 +2,13 @@ cmake_minimum_required(VERSION 3.15) option(REFLECTCPP_BUILD_SHARED "Build shared library" OFF) option(REFLECTCPP_FLEXBUFFERS "Enable flexbuffers support" OFF) +option(REFLECTCPP_XML "Enable XML support" OFF) option(REFLECTCPP_BUILD_TESTS "Build tests" OFF) - # enable vcpkg if require features other than JSON -if (REFLECTCPP_FLEXBUFFERS) -set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file") +if (REFLECTCPP_FLEXBUFFERS OR REFLECTCPP_XML) + set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file") endif () project(reflectcpp) @@ -20,16 +20,21 @@ if (REFLECTCPP_BUILD_SHARED) else () add_library(reflectcpp STATIC src/yyjson.c) endif () -target_include_directories(reflectcpp PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) +target_include_directories(reflectcpp PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) if (REFLECTCPP_FLEXBUFFERS) find_package(flatbuffers CONFIG REQUIRED) target_link_libraries(reflectcpp INTERFACE flatbuffers::flatbuffers) endif () +if (REFLECTCPP_XML) + find_package(pugixml CONFIG REQUIRED) + target_link_libraries(reflectcpp INTERFACE pugixml::pugixml) +endif () + target_compile_options(reflectcpp PRIVATE -Wall) if (REFLECTCPP_BUILD_TESTS) add_subdirectory(tests) -endif () \ No newline at end of file +endif () diff --git a/README.md b/README.md index e9209772..d8f36d12 100644 --- a/README.md +++ b/README.md @@ -341,12 +341,17 @@ Finally, it is very easy to extend full support to your own classes, refer to th ## Serialization formats -reflect-cpp currently supports the following serialization formats: +reflect-cpp is deliberately designed in a very modular way, using [concepts](https://en.cppreference.com/w/cpp/language/constraints), to make it as easy as possible to interface C or C++ libraries for various serialization formats. Refer to the [documentation](https://github.com/getml/reflect-cpp/tree/main/docs) for details. PRs related to serialization formats are welcome. -- **JSON**: Out-of-the-box support, no additional dependencies required. -- **flexbuffers**: Requires [flatbuffers](https://github.com/google/flatbuffers). +The following table lists the serialization formats currently supported by reflect-cpp and the underlying libraries used: -reflect-cpp is deliberately designed in a very modular format, using [concepts](https://en.cppreference.com/w/cpp/language/constraints), to make it as easy as possible to support additional serialization formats. Refer to the [documentation](https://github.com/getml/reflect-cpp/tree/main/docs) for details. PRs related to serialization formats are welcome. +| Format | Library | Version | License | Remarks | +|--------------|------------------------------------------------------|--------------|------------| -----------------------------------------------------| +| JSON | [YYJSON](https://github.com/ibireme/yyjson) | >= 0.8.0 | MIT | out-of-the-box support, included in this repository | +| flexbuffers | [flatbuffers](https://github.com/google/flatbuffers) | >= 23.5.26#1 | Apache 2.0 | | +| XML | [pugixml](https://github.com/zeux/pugixml) | >= 1.14 | MIT | | + +Please also refer to the *vcpkg.json* in this repository. ## Documentation @@ -367,7 +372,7 @@ If you **do not** need JSON support or you want to link YYJSON yourself, then re Simply copy the contents of the folder `include` into your source repository or add it to your include path and also add `src/yyjson.c` to your source files for compilation. -If you need support for other serialization formats like flexbuffers, you should also include and link the respective libraries, as listed in the previous section. +If you need support for other serialization formats like flexbuffers or XML, you should also include and link the respective libraries, as listed in the section on serialization formats. ### Option 3: Compilation using cmake @@ -399,6 +404,7 @@ To use reflect-cpp in your project: add_subdirectory(reflect-cpp) # Add this project as a subdirectory set(REFLECTCPP_FLEXBUFFERS ON) # Optional +set(REFLECTCPP_XML ON) # Optional target_link_libraries(your_project PRIVATE reflectcpp) # Link against the library ``` @@ -413,7 +419,9 @@ vcpkg is a great, but very ambitious and complex project (just like C++ is a gre 3. On some occasions you might be asked to specify a compiler. You can do so by simply adding it to the cmake command as follows: `cmake -S . -B build ... -DCMAKE_C_COMPILER=gcc -DCMAKE_C_COMPILER=g++` or `cmake -S . -B build ... -DCMAKE_C_COMPILER=clang-17 -DCMAKE_C_COMPILER=clang++-17` (or whatever supported compiler you would like to use). -## Compiling the tests +## Compiling and running the tests + +### JSON only To compile the tests, do the following: @@ -421,9 +429,16 @@ To compile the tests, do the following: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC +``` + +To run the tests, do the following: + +``` ./build/tests/json/reflect-cpp-json-tests ``` +### All serialization formats + To compile the tests with serialization formats other than JSON, do the following: ```bash @@ -433,11 +448,17 @@ git submodule update --init ./vcpkg/bootstrap-vcpkg.bat # Windows # You may be prompted to install additional dependencies. -cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON -DCMAKE_BUILD_TYPE=Release +cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_XML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC +``` + +To run the tests, do the following: + +``` ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests ./build/tests/json/reflect-cpp-json-tests +./build/tests/xml/reflect-cpp-xml-tests ``` ## Related projects @@ -453,7 +474,3 @@ reflect-cpp has been developed by [scaleML](https://www.scaleml.de), a company s reflect-cpp is released under the MIT License. Refer to the LICENSE file for details. reflect-cpp includes [YYJSON](https://github.com/ibireme/yyjson), the fastest JSON library currently in existence. YYJSON is written by YaoYuan and also released under the MIT License. - - - - diff --git a/docs/xml.md b/docs/xml.md new file mode 100644 index 00000000..827c0f62 --- /dev/null +++ b/docs/xml.md @@ -0,0 +1,245 @@ +# XML + +For XML support, you must also include the header `` and include the pugixml library (https://github.com/zeux/pugixml) in your project. + +## Simple example + +Consider the following example: + +```cpp +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector child; +}; + +const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + +const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + +const auto homer = Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + +rfl::xml::write(homer); +``` + +This will result in the following XML string: + +```xml + + + Homer + Simpson + Springfield + 1987-04-19 + 45 + homer@simpson.com + + Bart + Simpson + Springfield + 1987-04-19 + 10 + bart@simpson.com + + + Lisa + Simpson + Springfield + 1987-04-19 + 8 + lisa@simpson.com + + + Maggie + Simpson + Springfield + 1987-04-19 + 0 + maggie@simpson.com + + +``` + +Unlike most other formats, XML distinguishes between attributes and nodes. +If you want something to be displayed as an attribute, you must mark it as such: + +```cpp +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", rfl::Attribute> first_name; + rfl::Rename<"lastName", rfl::Attribute> last_name = "Simpson"; + rfl::Attribute town = "Springfield"; + rfl::Attribute> birthday; + rfl::Attribute age; + rfl::Attribute email; + std::vector child; +}; + +const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + +const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + +const auto homer = Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + +rfl::xml::write(homer); +``` + +This will result in the following XML string: + +```xml + + + + + + +``` + +Note that only boolean values, string values, integral values or floating point values can be represented as attributes. + +There also is a special field name called `xml_content` to be used when you want a value directly inserted into the content. +Again, only boolean values, string values, integral values or floating point values can be represented this way: + +```cpp +struct Person { + std::string xml_content; + rfl::Attribute town = "Springfield"; + rfl::Attribute> birthday; + rfl::Attribute email; + std::vector child; +}; + +const auto bart = Person{.xml_content = "Bart Simpson", + .birthday = "1987-04-19", + .email = "bart@simpson.com"}; + +const auto lisa = Person{.xml_content = "Lisa Simpson", + .birthday = "1987-04-19", + .email = "lisa@simpson.com"}; + +const auto maggie = Person{.xml_content = "Maggie Simpson", + .birthday = "1987-04-19", + .email = "maggie@simpson.com"}; + +const auto homer = Person{.xml_content = "Homer Simpson", + .birthday = "1987-04-19", + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + +rfl::xml::write(homer); +``` + +This will result in the following XML string: + +```xml + +Homer SimpsonBart Simpson + Lisa Simpson + Maggie Simpson + +``` + +## Limitations of the XML format + +### There must be exactly one root node + +The XML format requires that there must be exactly one root node. +Other formats, like JSON, allow you to have an array as the root element. XML disallows that. + +### The root node must have a name + +As you may have noticed, reflect-cpp uses the names of fields as the names of the XML nodes or attributes. +However, the root node does not have a field name associated with it. So reflect-cpp will use the name +of the struct as the name of the root node. This is a problem when the root node is a template parameter, +because the name of the root node cannot contain "<" or ">". + +In this case, you can explicitly set a root node name like this: + +```cpp +rfl::xml::write<"NameOfTheRootNode">(homer); +``` + +### No nested arrays + +Unlike JSON, XML doesn't have an explicit concept of arrays. Array-like structures are represented by simply +writing the same field over and over again (i.e. Homer's children in the examples above). + +This also implies that something like this cannot be properly represented in XML: + +```cpp +struct Person { + std::string name; + std::vector> child; +}; +``` + +There is no way to represent a vector of vectors in XML. It's a limitation of the format. + +### Integers cannot be tags + +In JSON, it is possible to represent a map with integers as keys like this: + +```cpp +std::map homer; +homer[1] = "Homer"; +homer[2] = "Simpson"; + +rfl::json::write(homer); +``` + +This will be represented as follows: + +```json +{"1":"Homer","2":"Simpson"} +``` + +In XML, this is impossible. The XML standard requires that the tag must not start with an integer. + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::xml::load("/path/to/file.xml"); + +const auto person = Person{...}; +rfl::xml::save("/path/to/file.xml", person); +``` + diff --git a/include/rfl.hpp b/include/rfl.hpp index 6b800dd4..191b1da3 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -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" diff --git a/include/rfl/Attribute.hpp b/include/rfl/Attribute.hpp new file mode 100644 index 00000000..72d5f657 --- /dev/null +++ b/include/rfl/Attribute.hpp @@ -0,0 +1,136 @@ +#ifndef RFL_ATTRIBUTE_HPP_ +#define RFL_ATTRIBUTE_HPP_ + +#include +#include +#include +#include +#include + +#include "rfl/Literal.hpp" +#include "rfl/default.hpp" + +namespace rfl { + +template +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&& _attr) noexcept = default; + + Attribute(const Attribute& _attr) = default; + + template + Attribute(const Attribute& _attr) : value_(_attr.get()) {} + + template + Attribute(Attribute&& _attr) : value_(_attr.get()) {} + + template , + bool>::type = true> + Attribute(const U& _value) : value_(_value) {} + + template , + bool>::type = true> + Attribute(U&& _value) noexcept : value_(std::forward(_value)) {} + + template , + bool>::type = true> + Attribute(const Attribute& _attr) : value_(_attr.value()) {} + + /// Assigns the underlying object to its default value. + template , + 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 , + bool>::type = true> + auto& operator=(const U& _value) { + value_ = _value; + return *this; + } + + /// Assigns the underlying object to its default value. + template , + bool>::type = true> + auto& operator=(const Default& _default) { + value_ = Type(); + return *this; + } + + /// Assigns the underlying object. + Attribute& operator=(const Attribute& _attr) = default; + + /// Assigns the underlying object. + Attribute& operator=(Attribute&& _attr) = default; + + /// Assigns the underlying object. + template + auto& operator=(const Attribute& _attr) { + value_ = _attr.get(); + return *this; + } + + /// Assigns the underlying object. + template + auto& operator=(Attribute&& _attr) { + value_ = std::forward(_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 diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index 696c8016..4c7dad5a 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -309,13 +309,13 @@ class Result { } /// Returns the value or a default. - T value_or(const T& _default) noexcept { - const auto handle_variant = - [&](const TOrError& _t_or_err) -> T { - if constexpr (!std::is_same()) { + T value_or(T&& _default) noexcept { + const auto handle_variant = [&](TOrError&& _t_or_err) -> T { + using Type = std::decay_t; + if constexpr (!std::is_same()) { return std::forward(_t_or_err); } else { - return _default; + return std::forward(_default); } }; return std::visit(handle_variant, t_or_err_); diff --git a/include/rfl/internal/is_attribute.hpp b/include/rfl/internal/is_attribute.hpp new file mode 100644 index 00000000..043aaa5d --- /dev/null +++ b/include/rfl/internal/is_attribute.hpp @@ -0,0 +1,34 @@ +#ifndef RFL_INTERNAL_ISATTRIBUTE_HPP_ +#define RFL_INTERNAL_ISATTRIBUTE_HPP_ + +#include +#include +#include + +#include "rfl/Field.hpp" + +namespace rfl { +namespace internal { + +template +class is_attribute; + +template +class is_attribute : public std::false_type {}; + +template +class is_attribute> : public std::true_type {}; + +template +class is_attribute*> : public std::true_type {}; + +template +class is_attribute*> : public std::true_type {}; + +template +constexpr bool is_attribute_v = is_attribute::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/strings/replace_all.hpp b/include/rfl/internal/strings/replace_all.hpp new file mode 100644 index 00000000..bd77338c --- /dev/null +++ b/include/rfl/internal/strings/replace_all.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_ +#define RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_ + +#include +#include + +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 diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp new file mode 100644 index 00000000..a3becfbe --- /dev/null +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -0,0 +1,110 @@ +#ifndef RFL_PARSING_FIELD_VARIANT_PARSER_HPP_ +#define RFL_PARSING_FIELD_VARIANT_PARSER_HPP_ + +#include +#include +#include +#include + +#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 +requires AreReaderAndWriter> +struct FieldVariantParser { + using ResultType = Result>; + + 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>(), + "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& _v) noexcept { + static_assert( + internal::no_duplicate_field_names>(), + "Externally tagged variants cannot have duplicate field " + "names."); + + const auto handle = [&](const auto& _field) { + const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); + using NamedTupleType = std::decay_t; + return Parser::write(_w, named_tuple); + }; + + return std::visit(handle, _v); + } + + private: + template + static ResultType find_matching_alternative( + const R& _r, const std::string& _disc_value, + const InputVarType& _var) noexcept { + if constexpr (_i == sizeof...(FieldTypes)) { + return Error( + "Could not parse std::variant, could not match field named " + "'" + + _disc_value + "'."); + } else { + using FieldType = std::decay_t< + typename std::tuple_element<_i, std::tuple>::type>; + + using ValueType = std::decay_t; + + const auto key = FieldType::name_.str(); + + if (key == _disc_value) { + const auto to_variant = [](ValueType&& _val) { + return std::variant(FieldType(std::move(_val))); + }; + + const auto embellish_error = [&](const Error& _e) { + return Error("Could not parse std::variant with field '" + + _disc_value + "': " + _e.what()); + }; + + return Parser::read(_r, _var) + .transform(to_variant) + .or_else(embellish_error); + } else { + return find_matching_alternative<_i + 1>(_r, _disc_value, _var); + } + } + } +}; +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp new file mode 100644 index 00000000..6ef5504f --- /dev/null +++ b/include/rfl/parsing/MapParser.hpp @@ -0,0 +1,125 @@ +#ifndef RFL_PARSING_MAPPARSER_HPP_ +#define RFL_PARSING_MAPPARSER_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter +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; + using ValueType = std::decay_t; + + static Result 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>::write(_w, v); + if constexpr (internal::has_reflection_type_v) { + using ReflT = typename KeyType::ReflectionType; + + if constexpr (std::is_integral_v || + std::is_floating_point_v) { + _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 || + std::is_floating_point_v) { + _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 + static Result key_to_numeric(auto& _pair) noexcept { + try { + if constexpr (std::is_integral_v) { + return static_cast(std::stoi(_pair.first)); + } else if constexpr (std::is_floating_point_v) { + return static_cast(std::stod(_pair.first)); + } else { + static_assert(always_false_v, "Unsupported type"); + } + } catch (std::exception& e) { + return Error(e.what()); + } + } + + static Result> 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 || + std::is_floating_point_v) { + return key_to_numeric(_pair).transform(to_pair); + + } else if constexpr (internal::has_reflection_type_v) { + using ReflT = typename KeyType::ReflectionType; + + if constexpr (std::is_integral_v || + std::is_floating_point_v) { + return key_to_numeric(_pair).transform(to_pair); + } else { + return to_pair(_pair.first); + } + + } else { + return std::move(_pair); + } + } + + static std::pair 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>::read(_r, _pair.second) + .and_then(to_pair) + .value(); + } + + static Result 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 diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp new file mode 100644 index 00000000..ca0f4c4b --- /dev/null +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -0,0 +1,222 @@ +#ifndef RFL_PARSING_NAMEDTUPLEPARSER_HPP_ +#define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ + +#include +#include +#include + +#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 +requires AreReaderAndWriter> +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> read( + const R& _r, const InputVarType& _var) noexcept { + const auto& indices = field_indices(); + const auto fct = [&](const std::string_view& _str) -> std::int16_t { + const auto it = indices.find(_str); + return it != indices.end() ? it->second : static_cast(-1); + }; + const auto to_fields_array = [&](auto _obj) { + return _r.template to_fields_array(fct, _obj); + }; + const auto build = [&](auto _fields_vec) { + return build_named_tuple_recursively(_r, _fields_vec); + }; + return _r.to_object(_var).transform(to_fields_array).and_then(build); + } + + /// Transforms a NamedTuple into a JSON object. + static OutputVarType write(const W& _w, + const NamedTuple& _tup) noexcept { + auto obj = _w.new_object(); + build_object_recursively(_w, _tup, &obj); + return OutputVarType(obj); + } + + private: + /// Builds the named tuple field by field. + template + static Result> build_named_tuple_recursively( + const R& _r, + const std::array, sizeof...(FieldTypes)>& + _fields_arr, + Args&&... _args) noexcept { + constexpr auto i = sizeof...(Args); + + if constexpr (i == sizeof...(FieldTypes)) { + return NamedTuple(std::move(_args)...); + } else { + using FieldType = typename std::tuple_element< + i, typename NamedTuple::Fields>::type; + + using ValueType = std::decay_t; + + const auto& f = std::get(_fields_arr); + + if (!f) { + if constexpr (is_required()) { + const auto key = FieldType::name_.str(); + return collect_errors( + _r, _fields_arr, + std::vector( + {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(_r, _fields_arr, + std::vector({std::move(_error)})); + }; + + return get_value(_r, *f).or_else(handle_error).and_then(build); + } + } + + /// If something went wrong, we want to collect all of the errors - it's + /// just good UX. + template + static Error collect_errors( + const R& _r, + const std::array, sizeof...(FieldTypes)>& + _fields_arr, + std::vector _errors) noexcept { + if constexpr (_i == sizeof...(FieldTypes)) { + if (_errors.size() == 1) { + return std::move(_errors[0]); + } else { + std::string msg = + "Found " + std::to_string(_errors.size()) + " errors:"; + for (size_t i = 0; i < _errors.size(); ++i) { + msg += "\n" + std::to_string(i + 1) + ") " + + internal::strings::replace_all(_errors.at(i).what(), "\n", + "\n "); + } + return Error(msg); + } + } else { + using FieldType = typename std::tuple_element< + _i, typename NamedTuple::Fields>::type; + + using ValueType = std::decay_t; + + const auto& f = std::get<_i>(_fields_arr); + + if (!f) { + if constexpr (is_required()) { + const auto key = FieldType::name_.str(); + _errors.emplace_back(Error("Field named '" + key + "' not found.")); + } + return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors)); + } + + const auto add_error_if_applicable = + [&](Error&& _error) -> Result { + _errors.emplace_back(std::move(_error)); + return _error; + }; + + get_value(_r, *f).or_else(add_error_if_applicable); + + return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors)); + } + } + + /// Builds the object field by field. + template + static void build_object_recursively(const W& _w, + const NamedTuple& _tup, + OutputObjectType* _ptr) noexcept { + if constexpr (_i >= sizeof...(FieldTypes)) { + return; + } else { + using FieldType = + typename std::tuple_element<_i, std::tuple>::type; + using ValueType = std::decay_t; + auto value = Parser::write(_w, rfl::get<_i>(_tup)); + const auto name = FieldType::name_.str(); + if constexpr (!is_required()) { + if (!_w.is_empty(value)) { + _w.set_field(name, value, _ptr); + } + } else { + _w.set_field(name, value, _ptr); + } + return build_object_recursively<_i + 1>(_w, _tup, _ptr); + } + } + + /// 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 + static auto get_value(const R& _r, const InputVarType _var) noexcept { + static_assert(FieldType::name_ != internal::StringLiteral("xml_content") || + internal::is_basic_type_v, + "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; + return Parser::read(_r, _var).or_else(embellish_error); + } + + /// Builds the object field by field. + template + static void set_field_indices( + std::unordered_map* + _field_indices) noexcept { + if constexpr (_i >= sizeof...(FieldTypes)) { + return; + } else { + using FieldType = + typename std::tuple_element<_i, std::tuple>::type; + const auto name = FieldType::name_.string_view(); + (*_field_indices)[name] = static_cast(_i); + set_field_indices<_i + 1>(_field_indices); + } + } + + private: + /// Maps each of the field names to an index signifying their order. + static inline internal::Memoization< + std::unordered_map> + field_indices_; +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index c453780f..b0a165e2 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -1,1390 +1,25 @@ #ifndef RFL_PARSING_PARSER_HPP_ #define RFL_PARSING_PARSER_HPP_ -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "rfl/Box.hpp" -#include "rfl/Literal.hpp" -#include "rfl/NamedTuple.hpp" -#include "rfl/Ref.hpp" -#include "rfl/Result.hpp" -#include "rfl/TaggedUnion.hpp" -#include "rfl/always_false.hpp" -#include "rfl/field_type.hpp" -#include "rfl/from_named_tuple.hpp" -#include "rfl/internal/Fields.hpp" -#include "rfl/internal/Memoization.hpp" -#include "rfl/internal/StringLiteral.hpp" -#include "rfl/internal/all_fields.hpp" -#include "rfl/internal/enums/StringConverter.hpp" -#include "rfl/internal/flattened_ptr_tuple_t.hpp" -#include "rfl/internal/flattened_tuple_t.hpp" -#include "rfl/internal/get_field_names.hpp" -#include "rfl/internal/get_type_name.hpp" -#include "rfl/internal/has_fields.hpp" -#include "rfl/internal/has_reflection_method_v.hpp" -#include "rfl/internal/has_reflection_type_v.hpp" -#include "rfl/internal/has_tag_v.hpp" -#include "rfl/internal/is_basic_type.hpp" -#include "rfl/internal/make_tag.hpp" -#include "rfl/internal/move_from_tuple.hpp" -#include "rfl/internal/no_duplicate_field_names.hpp" -#include "rfl/internal/tag_t.hpp" -#include "rfl/internal/to_flattened_ptr_tuple.hpp" -#include "rfl/internal/to_ptr_named_tuple.hpp" -#include "rfl/internal/tuple_t.hpp" -#include "rfl/named_tuple_t.hpp" -#include "rfl/parsing/AreReaderAndWriter.hpp" -#include "rfl/parsing/TaggedUnionWrapper.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_required.hpp" -#include "rfl/parsing/is_set_like.hpp" -#include "rfl/to_named_tuple.hpp" - -namespace rfl { -namespace parsing { - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter -struct Parser; - -// ---------------------------------------------------------------------------- - -/// Default case - anything that cannot be explicitly matched. -template -requires AreReaderAndWriter -struct Parser { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result read(const R& _r, const InputVarType& _var) noexcept { - if constexpr (R::template has_custom_constructor) { - return _r.template use_custom_constructor(_var); - } else { - if constexpr (internal::has_reflection_type_v) { - using ReflectionType = std::decay_t; - const auto wrap_in_t = [](auto _named_tuple) -> Result { - try { - return T(_named_tuple); - } catch (std::exception& e) { - return Error(e.what()); - } - }; - return Parser::read(_r, _var).and_then(wrap_in_t); - } else if constexpr (std::is_class_v && std::is_aggregate_v) { - using NamedTupleType = named_tuple_t; - const auto to_struct = [](NamedTupleType&& _n) -> Result { - try { - return from_named_tuple(std::move(_n)); - } catch (std::exception& e) { - return Error(e.what()); - } - }; - return Parser::read(_r, _var).and_then(to_struct); - } else if constexpr (std::is_enum_v) { - using StringConverter = internal::enums::StringConverter; - return _r.template to_basic_type(_var).and_then( - StringConverter::string_to_enum); - } else if constexpr (internal::is_basic_type_v) { - return _r.template to_basic_type>(_var); - } else { - static_assert( - always_false_v, - "Unsupported type. Please refer to the sections on custom " - "classes and custom parsers for information on how add " - "support for your own classes."); - } - } - } - - /// Converts the variable to a JSON type. - static auto write(const W& _w, const T& _var) noexcept { - if constexpr (internal::has_reflection_type_v) { - using ReflectionType = std::decay_t; - if constexpr (internal::has_reflection_method_v) { - return Parser::write(_w, _var.reflection()); - } else { - const auto& [r] = _var; - return Parser::write(_w, r); - } - } else if constexpr (std::is_class_v && std::is_aggregate_v) { - const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var); - using PtrNamedTupleType = std::decay_t; - return Parser::write(_w, ptr_named_tuple); - } else if constexpr (std::is_enum_v) { - using StringConverter = internal::enums::StringConverter; - const auto str = StringConverter::enum_to_string(_var); - return _w.from_basic_type(str); - } else if constexpr (internal::is_basic_type_v) { - return _w.from_basic_type(_var); - } else { - static_assert(always_false_v, - "Unsupported type. Please refer to the sections on custom " - "classes and custom parsers for information on how add " - "support for your own classes."); - } - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter -struct Parser { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result read(const R& _r, const InputVarType& _var) noexcept { - static_assert(always_false_v, - "Reading into raw pointers is dangerous and " - "therefore unsupported. " - "Please consider using std::unique_ptr, rfl::Box, " - "std::shared_ptr, " - "rfl::Ref or std::optional instead."); - return Error("Unsupported."); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const T* _ptr) noexcept { - if (!_ptr) { - return _w.empty_var(); - } - return Parser>::write(_w, *_ptr); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - static Result> read( - const R& _r, const InputVarType& _var) noexcept { - static_assert(always_false_v, - "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 _ref) noexcept { - return Parser>::write(_w, _ref.get()); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - public: - using InputArrayType = typename R::InputArrayType; - using InputVarType = typename R::InputVarType; - - using OutputArrayType = typename W::OutputArrayType; - using OutputVarType = typename W::OutputVarType; - - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - const auto to_vec = [&](const auto& _arr) { return _r.to_vec(_arr); }; - - const auto check_size = [](auto _vec) -> Result> { - if (_vec.size() != _size) { - return Error("Expected " + std::to_string(_size) + " fields, got " + - std::to_string(_vec.size()) + "."); - } - return std::move(_vec); - }; - - const auto extract = [&_r](auto _vec) { - return extract_field_by_field(_r, std::move(_vec)); - }; - - return _r.to_array(_var) - .transform(to_vec) - .and_then(check_size) - .and_then(extract); - } - - static OutputVarType write(const W& _w, - const std::array& _arr) noexcept { - auto arr = _w.new_array(); - for (auto it = _arr.begin(); it != _arr.end(); ++it) { - _w.add(Parser>::write(_w, *it), &arr); - } - return OutputVarType(arr); - } - - private: - /// Extracts values from the array, field by field. - template - static Result> extract_field_by_field( - const R& _r, std::vector _vec, - AlreadyExtracted&&... _already_extracted) noexcept { - constexpr size_t i = sizeof...(AlreadyExtracted); - if constexpr (i == _size) { - return std::array({std::move(_already_extracted)...}); - } else { - const auto extract_next = [&](auto&& new_entry) { - return extract_field_by_field(_r, std::move(_vec), - std::move(_already_extracted)..., - std::move(new_entry)); - }; - return extract_single_field(_r, _vec).and_then(extract_next); - } - } - - /// Extracts a single field from a JSON. - template - static auto extract_single_field( - const R& _r, const std::vector& _vec) noexcept { - return Parser::read(_r, _vec[_i]); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read(const R& _r, const InputVarType& _var) noexcept { - const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; - return Parser>::read(_r, _var).transform(to_box); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const Box& _box) noexcept { - return Parser>::write(_w, *_box); - } -}; - -// ---------------------------------------------------------------------------- - -/// Used for maps for which the key type is std::string. These are -/// represented as objects. -template -requires AreReaderAndWriter -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; - using ValueType = std::decay_t; - - static Result 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>::write(_w, v); - if constexpr (internal::has_reflection_type_v) { - using ReflT = typename KeyType::ReflectionType; - - if constexpr (std::is_integral_v || - std::is_floating_point_v) { - _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 || - std::is_floating_point_v) { - _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 - static Result key_to_numeric(auto& _pair) noexcept { - try { - if constexpr (std::is_integral_v) { - return static_cast(std::stoi(_pair.first)); - } else if constexpr (std::is_floating_point_v) { - return static_cast(std::stod(_pair.first)); - } else { - static_assert(always_false_v, "Unsupported type"); - } - } catch (std::exception& e) { - return Error(e.what()); - } - } - - static Result> 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 || - std::is_floating_point_v) { - return key_to_numeric(_pair).transform(to_pair); - - } else if constexpr (internal::has_reflection_type_v) { - using ReflT = typename KeyType::ReflectionType; - - if constexpr (std::is_integral_v || - std::is_floating_point_v) { - return key_to_numeric(_pair).transform(to_pair); - } else { - return to_pair(_pair.first); - } - - } else { - return std::move(_pair); - } - } - - static std::pair 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>::read(_r, _pair.second) - .and_then(to_pair) - .value(); - } - - static Result 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; - } -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public MapParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public MapParser> { -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - 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> read( - const R& _r, const InputVarType& _var) noexcept { - const auto& indices = field_indices(); - const auto fct = [&](const std::string_view& _str) -> std::int16_t { - const auto it = indices.find(_str); - return it != indices.end() ? it->second : static_cast(-1); - }; - const auto to_fields_array = [&](auto _obj) { - return _r.template to_fields_array(fct, _obj); - }; - const auto build = [&](auto _fields_vec) { - return build_named_tuple_recursively(_r, _fields_vec); - }; - return _r.to_object(_var).transform(to_fields_array).and_then(build); - } - - /// Transforms a NamedTuple into a JSON object. - static OutputVarType write(const W& _w, - const NamedTuple& _tup) noexcept { - auto obj = _w.new_object(); - build_object_recursively(_w, _tup, &obj); - return OutputVarType(obj); - } - - private: - /// Builds the named tuple field by field. - template - static Result> build_named_tuple_recursively( - const R& _r, - const std::array, sizeof...(FieldTypes)>& - _fields_arr, - Args&&... _args) noexcept { - constexpr auto i = sizeof...(Args); - - if constexpr (i == sizeof...(FieldTypes)) { - return NamedTuple(std::move(_args)...); - } else { - using FieldType = typename std::tuple_element< - i, typename NamedTuple::Fields>::type; - - using ValueType = std::decay_t; - - const auto& f = std::get(_fields_arr); - - if (!f) { - if constexpr (is_required()) { - const auto key = FieldType::name_.str(); - return collect_errors( - _r, _fields_arr, - std::vector( - {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(_r, _fields_arr, - std::vector({std::move(_error)})); - }; - - return get_value(_r, *f).or_else(handle_error).and_then(build); - } - } - - /// If something went wrong, we want to collect all of the errors - it's - /// just good UX. - template - static Error collect_errors( - const R& _r, - const std::array, sizeof...(FieldTypes)>& - _fields_arr, - std::vector _errors) noexcept { - if constexpr (_i == sizeof...(FieldTypes)) { - if (_errors.size() == 1) { - return std::move(_errors[0]); - } else { - std::string msg = - "Found " + std::to_string(_errors.size()) + " errors:"; - for (size_t i = 0; i < _errors.size(); ++i) { - msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what(); - } - return Error(msg); - } - } else { - using FieldType = typename std::tuple_element< - _i, typename NamedTuple::Fields>::type; - - using ValueType = std::decay_t; - - const auto& f = std::get<_i>(_fields_arr); - - if (!f) { - if constexpr (is_required()) { - const auto key = FieldType::name_.str(); - _errors.emplace_back(Error("Field named '" + key + "' not found.")); - } - return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors)); - } - - const auto add_error_if_applicable = - [&](Error&& _error) -> Result { - _errors.emplace_back(std::move(_error)); - return _error; - }; - - get_value(_r, *f).or_else(add_error_if_applicable); - - return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors)); - } - } - - /// Builds the object field by field. - template - static void build_object_recursively(const W& _w, - const NamedTuple& _tup, - OutputObjectType* _ptr) noexcept { - if constexpr (_i >= sizeof...(FieldTypes)) { - return; - } else { - using FieldType = - typename std::tuple_element<_i, std::tuple>::type; - using ValueType = std::decay_t; - auto value = Parser::write(_w, rfl::get<_i>(_tup)); - const auto name = FieldType::name_.str(); - if constexpr (!is_required()) { - if (!_w.is_empty(value)) { - _w.set_field(name, value, _ptr); - } - } else { - _w.set_field(name, value, _ptr); - } - return build_object_recursively<_i + 1>(_w, _tup, _ptr); - } - } - - /// 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 - static auto get_value(const R& _r, const InputVarType _var) noexcept { - const auto embellish_error = [&](const Error& _e) { - const auto key = FieldType::name_.str(); - return Error("Failed to parse field '" + key + "': " + _e.what()); - }; - using ValueType = std::decay_t; - return Parser::read(_r, _var).or_else(embellish_error); - } - - /// Builds the object field by field. - template - static void set_field_indices( - std::unordered_map* - _field_indices) noexcept { - if constexpr (_i >= sizeof...(FieldTypes)) { - return; - } else { - using FieldType = - typename std::tuple_element<_i, std::tuple>::type; - const auto name = FieldType::name_.string_view(); - (*_field_indices)[name] = static_cast(_i); - set_field_indices<_i + 1>(_field_indices); - } - } - - private: - /// Maps each of the field names to an index signifying their order. - static inline internal::Memoization< - std::unordered_map> - field_indices_; -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - if (_r.is_empty(_var)) { - return std::optional(); - } - const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; - return Parser>::read(_r, _var).transform(to_opt); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const std::optional& _o) noexcept { - if (!_o) { - return _w.empty_var(); - } - return Parser>::write(_w, *_o); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read(const R& _r, const InputVarType& _var) noexcept { - const auto to_ref = [&](auto&& _t) { return Ref::make(std::move(_t)); }; - return Parser>::read(_r, _var).transform(to_ref); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const Ref& _ref) noexcept { - return Parser>::write(_w, *_ref); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - const auto to_rename = [](auto&& _t) { - return Rename<_name, T>(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_rename); - } - - static OutputVarType write(const W& _w, - const Rename<_name, T>& _rename) noexcept { - return Parser>::write(_w, _rename.value()); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - using ErrorType = NamedTuple>; - using VariantType = std::variant, ErrorType>; - - /// Expresses the variables as type T. - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - const auto handle = [](auto&& _t) -> Result { - using Type = std::decay_t; - if constexpr (std::is_same()) { - return Error(_t.template get<"error">()); - } else { - return std::forward>(_t); - } - }; - - const auto to_res = [&](VariantType&& _v) -> Result { - return std::visit(handle, std::forward(_v)); - }; - - return Result>( - Parser::read(_r, _var).transform(to_res)); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, const Result& _r) noexcept { - const auto write_t = [&](const auto& _t) -> OutputVarType { - return Parser>::write(_w, _t); - }; - - const auto write_err = [&](const auto& _err) -> OutputVarType { - return Parser::write( - _w, ErrorType(make_field<"error">(_err.what()))); - }; - - return *_r.transform(write_t).or_else(write_err); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - if (_r.is_empty(*_var)) { - return std::shared_ptr(); - } - const auto to_ptr = [](auto&& _t) { - return std::make_shared(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_ptr); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, - const std::shared_ptr& _s) noexcept { - if (!_s) { - return _w.empty_var(); - } - return Parser>::write(_w, *_s); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read( - const R& _r, const InputVarType& _var) noexcept { - const auto to_pair = [&](auto&& _t) { - return std::make_pair(std::move(std::get<0>(_t)), - std::move(std::get<1>(_t))); - }; - return Parser>::read(_r, _var) - .transform(to_pair); - } - - /// Transform a std::pair into an array - static OutputVarType write( - const W& _w, const std::pair& _p) noexcept { - const auto tup = std::make_tuple(&_p.first, &_p.second); - return Parser>::write( - _w, tup); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using ResultType = Result>; - - public: - using InputObjectType = typename R::InputObjectType; - using InputVarType = typename R::InputVarType; - - using OutputObjectType = typename W::OutputObjectType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static ResultType read(const R& _r, const InputVarType& _var) noexcept { - const auto get_disc = [&_r](auto _obj) { - return get_discriminator(_r, _obj); - }; - - const auto to_result = [&_r, _var](const std::string& _disc_value) { - return find_matching_alternative(_r, _disc_value, _var); - }; - - return _r.to_object(_var).and_then(get_disc).and_then(to_result); - } - - /// Expresses the variables as a JSON type. - static OutputVarType write( - const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>& - _tagged_union) noexcept { - const auto handle = [&](const auto& _val) -> OutputVarType { - return write_wrapped(_w, _val); - }; - return std::visit(handle, _tagged_union.variant_); - } - - private: - template - static ResultType find_matching_alternative( - const R& _r, const std::string& _disc_value, - const InputVarType& _var) noexcept { - if constexpr (_i == sizeof...(AlternativeTypes)) { - return Error("Could not parse tagged union, could not match " + - _discriminator.str() + " '" + _disc_value + "'."); - } else { - using AlternativeType = std::decay_t< - std::variant_alternative_t<_i, std::variant>>; - - if (contains_disc_value(_disc_value)) { - const auto to_tagged_union = [](auto&& _val) { - return TaggedUnion<_discriminator, AlternativeTypes...>( - std::move(_val)); - }; - - const auto embellish_error = [&](Error&& _e) { - return Error( - "Could not parse tagged union with " - "discrimininator " + - _discriminator.str() + " '" + _disc_value + "': " + _e.what()); - }; - - return Parser::read(_r, _var) - .transform(to_tagged_union) - .or_else(embellish_error); - - } else { - return find_matching_alternative<_i + 1>(_r, _disc_value, _var); - } - } - } - - /// Retrieves the discriminator. - static Result get_discriminator( - const R& _r, const InputObjectType& _obj) noexcept { - const auto embellish_error = [](const auto& _err) { - return Error("Could not parse tagged union: Could not find field '" + - _discriminator.str() + - "' or type of field was not a string."); - }; - - const auto to_type = [&_r](auto _var) { - return _r.template to_basic_type(_var); - }; - - return _r.get_field(_discriminator.str(), _obj) - .and_then(to_type) - .or_else(embellish_error); - } - - /// Determines whether the discriminating literal contains the value - /// retrieved from the object. - template - static inline bool contains_disc_value( - const std::string& _disc_value) noexcept { - return internal::tag_t::contains(_disc_value); - } - - /// Writes a wrapped version of the original object, which contains the tag. - template - static OutputVarType write_wrapped(const W& _w, const T& _val) noexcept { - const auto tag = internal::make_tag(); - using TagType = std::decay_t; - if constexpr (internal::has_fields>()) { - using WrapperType = - TaggedUnionWrapperWithFields; - const auto wrapper = WrapperType{.tag = tag, .fields = &_val}; - return Parser::write(_w, wrapper); - } else { - using WrapperType = - TaggedUnionWrapperNoFields; - const auto wrapper = WrapperType{.tag = tag, .fields = &_val}; - return Parser::write(_w, wrapper); - } - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - public: - using InputArrayType = typename R::InputArrayType; - using InputVarType = typename R::InputVarType; - - using OutputArrayType = typename W::OutputArrayType; - using OutputVarType = typename W::OutputVarType; - - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - const auto to_vec = [&](auto _arr) { return _r.to_vec(_arr); }; - - const auto check_size = [](auto _vec) -> Result> { - if (_vec.size() > sizeof...(Ts)) { - return Error("Expected " + std::to_string(sizeof...(Ts)) + - " fields, got " + std::to_string(_vec.size()) + "."); - } - return std::move(_vec); - }; - - const auto extract = [&_r](auto _vec) { - return extract_field_by_field(_r, std::move(_vec)); - }; - - return _r.to_array(_var) - .transform(to_vec) - .and_then(check_size) - .and_then(extract); - } - - static OutputVarType write(const W& _w, - const std::tuple& _tup) noexcept { - auto arr = _w.new_array(); - to_array<0>(_w, _tup, &arr); - return arr; - } - - private: - /// Extracts values from the array, field by field. - template - static Result> extract_field_by_field( - const R& _r, std::vector _vec, - AlreadyExtracted&&... _already_extracted) noexcept { - constexpr size_t i = sizeof...(AlreadyExtracted); - if constexpr (i == sizeof...(Ts)) { - return std::tuple( - std::make_tuple(std::move(_already_extracted)...)); - } else { - const auto extract_next = [&](auto&& new_entry) { - return extract_field_by_field(_r, std::move(_vec), - std::move(_already_extracted)..., - std::move(new_entry)); - }; - return extract_single_field(_r, _vec).and_then(extract_next); - } - } - - /// Extracts a single field from a JSON. - template - static auto extract_single_field( - const R& _r, const std::vector& _vec) noexcept { - using NewFieldType = - std::decay_t>::type>; - - using ResultType = Result; - - if (_i >= _vec.size()) { - if constexpr (is_required()) { - 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::read(_r, _vec[_i]); - } - - /// Transforms a tuple to an array. - template - static void to_array(const W& _w, const std::tuple& _tup, - OutputArrayType* _ptr) noexcept { - if constexpr (_i < sizeof...(Ts)) { - using NewFieldType = std::decay_t< - typename std::tuple_element<_i, std::tuple>::type>; - - const auto val = - Parser::write(_w, std::get<_i>(_tup)); - _w.add(val, _ptr); - to_array<_i + 1>(_w, _tup, _ptr); - } - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read(const R& _r, - const InputVarType& _var) noexcept { - if (_r.is_empty(_var)) { - return std::unique_ptr(); - } - const auto to_ptr = [](auto&& _t) { - return std::make_unique(std::move(_t)); - }; - return Parser>::read(_r, _var).transform(to_ptr); - } - - /// Expresses the variable a a JSON. - static OutputVarType write(const W& _w, - const std::unique_ptr& _s) noexcept { - if (!_s) { - return _w.empty_var(); - } - return Parser>::write(_w, *_s); - } -}; - -// ---------------------------------------------------------------------------- - -/// To be used when all options of the variants are rfl::Field. Essentially, -/// this is an externally tagged union. -template -requires AreReaderAndWriter> -struct FieldVariantParser { - using ResultType = Result>; - - public: - using InputObjectType = typename R::InputObjectType; - using InputVarType = typename R::InputVarType; - - using OutputObjectType = typename W::OutputObjectType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static ResultType read(const R& _r, const InputVarType& _var) noexcept { - static_assert( - internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field " - "names."); - - 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); - } - - /// Expresses the variables as a JSON type. - static OutputVarType write(const W& _w, - const std::variant& _v) noexcept { - static_assert( - internal::no_duplicate_field_names>(), - "Externally tagged variants cannot have duplicate field " - "names."); - - const auto handle = [&](const auto& _field) { - const auto named_tuple = make_named_tuple(internal::to_ptr_field(_field)); - using NamedTupleType = std::decay_t; - return Parser::write(_w, named_tuple); - }; - - return std::visit(handle, _v); - } - - private: - template - static ResultType find_matching_alternative( - const R& _r, const std::string& _disc_value, - const InputVarType& _var) noexcept { - if constexpr (_i == sizeof...(FieldTypes)) { - return Error( - "Could not parse std::variant, could not match field named " - "'" + - _disc_value + "'."); - } else { - using FieldType = std::decay_t< - typename std::tuple_element<_i, std::tuple>::type>; - - using ValueType = std::decay_t; - - const auto key = FieldType::name_.str(); - - if (key == _disc_value) { - const auto to_variant = [](ValueType&& _val) { - return std::variant(FieldType(std::move(_val))); - }; - - const auto embellish_error = [&](const Error& _e) { - return Error("Could not parse std::variant with field '" + - _disc_value + "': " + _e.what()); - }; - - return Parser::read(_r, _var) - .transform(to_variant) - .or_else(embellish_error); - } else { - return find_matching_alternative<_i + 1>(_r, _disc_value, _var); - } - } - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - static Result> read( - const R& _r, const InputVarType& _var) noexcept { - const auto to_rfl_variant = [](auto&& _var) { - return rfl::Variant( - std::forward>(_var)); - }; - return Parser>::read(_r, _var).transform( - to_rfl_variant); - } - - static OutputVarType write( - const W& _w, const rfl::Variant& _variant) noexcept { - return Parser>::write(_w, - _variant.variant()); - } -}; - -// ---------------------------------------------------------------------------- - -template -requires AreReaderAndWriter> -struct Parser> { - using InputVarType = typename R::InputVarType; - using OutputVarType = typename W::OutputVarType; - - /// Expresses the variables as type T. - template - static Result> read( - const R& _r, const InputVarType& _var, - const std::string _errors = "") noexcept { - if constexpr (_i == 0 && - internal::all_fields>()) { - return FieldVariantParser::read(_r, _var); - } else if constexpr (_i == sizeof...(FieldTypes)) { - return Error("Could not parse variant: " + _errors); - } else { - const auto to_variant = [](auto&& _val) { - return std::variant(std::move(_val)); - }; - - const auto try_next = [&_r, _var, &_errors](const auto& _err) { - auto errors = _errors; - errors += - std::string("\n " + std::to_string(_i + 1) + ")") + _err.what(); - return read<_i + 1>(_r, _var, errors); - }; - - using AltType = std::decay_t< - std::variant_alternative_t<_i, std::variant>>; - - return Parser::read(_r, _var) - .transform(to_variant) - .or_else(try_next); - } - } - - /// Expresses the variables as a JSON type. - static OutputVarType write( - const W& _w, const std::variant& _variant) noexcept { - if constexpr (internal::all_fields>()) { - return FieldVariantParser::write(_w, _variant); - } else { - const auto handle = [&](const auto& _v) { - using Type = std::decay_t; - return Parser::write(_w, _v); - }; - return std::visit(handle, _variant); - } - } -}; - -// ---------------------------------------------------------------------------- - -/// 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 -requires AreReaderAndWriter -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 read(const R& _r, const InputVarType& _var) noexcept { - if constexpr (treat_as_map()) { - return MapParser::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::write(_w, _vec); - } else { - auto arr = _w.new_array(); - for (const auto& v : _vec) { - _w.add(Parser>::write(_w, v), &arr); - } - return OutputVarType(arr); - } - } - - private: - static auto get_elem(const R& _r, auto& _v) { - return Parser>::read(_r, _v).value(); - }; - - static auto get_pair(const R& _r, auto& _v) { - using K = std::decay_t; - using V = std::decay_t; - return Parser>>::read(_r, _v).value(); - } - - static Result to_container(const R& _r, InputArrayType&& _arr) { - auto input_vars = _r.to_vec(_arr); - VecType vec; - if constexpr (is_forward_list()) { - for (auto it = input_vars.rbegin(); it != input_vars.rend(); ++it) { - vec.emplace_front(get_elem(_r, *it)); - } - } else if constexpr (is_map_like()) { - for (auto& v : input_vars) { - vec.insert(get_pair(_r, v)); - } - } else if constexpr (is_set_like()) { - 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 to_result(const R& _r, InputArrayType&& _arr) { - try { - return to_container(_r, std::forward(_arr)); - } catch (std::exception& e) { - return Error(e.what()); - } - } - - static constexpr bool treat_as_map() { - if constexpr (is_map_like_not_multimap()) { - if constexpr (internal::has_reflection_type_v) { - using U = std::decay_t; - return std::is_same() || std::is_integral_v || - std::is_floating_point_v; - - // We do not need std::string here, it is already caught by the template - // specialization. - } else if constexpr (std::is_integral_v || - std::is_floating_point_v) { - return true; - } else { - return false; - } - } else { - return false; - } - } -}; - -template -requires AreReaderAndWriter> -struct Parser> : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -template -requires AreReaderAndWriter> -struct Parser> - : public VectorParser> { -}; - -} // namespace parsing -} // namespace rfl - -#endif // JSON_PARSER_HPP_ +#include "rfl/parsing/Parser_array.hpp" +#include "rfl/parsing/Parser_base.hpp" +#include "rfl/parsing/Parser_box.hpp" +#include "rfl/parsing/Parser_default.hpp" +#include "rfl/parsing/Parser_map_like.hpp" +#include "rfl/parsing/Parser_named_tuple.hpp" +#include "rfl/parsing/Parser_optional.hpp" +#include "rfl/parsing/Parser_pair.hpp" +#include "rfl/parsing/Parser_ptr.hpp" +#include "rfl/parsing/Parser_ref.hpp" +#include "rfl/parsing/Parser_reference_wrapper.hpp" +#include "rfl/parsing/Parser_rename.hpp" +#include "rfl/parsing/Parser_result.hpp" +#include "rfl/parsing/Parser_rfl_variant.hpp" +#include "rfl/parsing/Parser_shared_ptr.hpp" +#include "rfl/parsing/Parser_tagged_union.hpp" +#include "rfl/parsing/Parser_tuple.hpp" +#include "rfl/parsing/Parser_unique_ptr.hpp" +#include "rfl/parsing/Parser_variant.hpp" +#include "rfl/parsing/Parser_vector_like.hpp" + +#endif diff --git a/include/rfl/parsing/Parser_array.hpp b/include/rfl/parsing/Parser_array.hpp new file mode 100644 index 00000000..a7ea34ea --- /dev/null +++ b/include/rfl/parsing/Parser_array.hpp @@ -0,0 +1,85 @@ +#ifndef RFL_PARSING_PARSER_ARRAY_HPP_ +#define RFL_PARSING_PARSER_ARRAY_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { +template +requires AreReaderAndWriter> +struct Parser> { + public: + using InputArrayType = typename R::InputArrayType; + using InputVarType = typename R::InputVarType; + + using OutputArrayType = typename W::OutputArrayType; + using OutputVarType = typename W::OutputVarType; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + const auto to_vec = [&](const auto& _arr) { return _r.to_vec(_arr); }; + + const auto check_size = [](auto _vec) -> Result> { + if (_vec.size() != _size) { + return Error("Expected " + std::to_string(_size) + " fields, got " + + std::to_string(_vec.size()) + "."); + } + return std::move(_vec); + }; + + const auto extract = [&_r](auto _vec) { + return extract_field_by_field(_r, std::move(_vec)); + }; + + return _r.to_array(_var) + .transform(to_vec) + .and_then(check_size) + .and_then(extract); + } + + static OutputVarType write(const W& _w, + const std::array& _arr) noexcept { + auto arr = _w.new_array(); + for (auto it = _arr.begin(); it != _arr.end(); ++it) { + _w.add(Parser>::write(_w, *it), &arr); + } + return OutputVarType(arr); + } + + private: + /// Extracts values from the array, field by field. + template + static Result> extract_field_by_field( + const R& _r, std::vector _vec, + AlreadyExtracted&&... _already_extracted) noexcept { + constexpr size_t i = sizeof...(AlreadyExtracted); + if constexpr (i == _size) { + return std::array({std::move(_already_extracted)...}); + } else { + const auto extract_next = [&](auto&& new_entry) { + return extract_field_by_field(_r, std::move(_vec), + std::move(_already_extracted)..., + std::move(new_entry)); + }; + return extract_single_field(_r, _vec).and_then(extract_next); + } + } + + /// Extracts a single field from a JSON. + template + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { + return Parser::read(_r, _vec[_i]); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_base.hpp b/include/rfl/parsing/Parser_base.hpp new file mode 100644 index 00000000..3fbce8fd --- /dev/null +++ b/include/rfl/parsing/Parser_base.hpp @@ -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 +requires AreReaderAndWriter +struct Parser; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_box.hpp b/include/rfl/parsing/Parser_box.hpp new file mode 100644 index 00000000..245ba135 --- /dev/null +++ b/include/rfl/parsing/Parser_box.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_PARSING_PARSER_BOX_HPP_ +#define RFL_PARSING_PARSER_BOX_HPP_ + +#include + +#include "rfl/Box.hpp" +#include "rfl/Result.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; + return Parser>::read(_r, _var).transform(to_box); + } + + static OutputVarType write(const W& _w, const Box& _box) noexcept { + return Parser>::write(_w, *_box); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp new file mode 100644 index 00000000..341b581f --- /dev/null +++ b/include/rfl/parsing/Parser_default.hpp @@ -0,0 +1,101 @@ +#ifndef RFL_PARSING_PARSER_DEFAULT_HPP_ +#define RFL_PARSING_PARSER_DEFAULT_HPP_ + +#include +#include + +#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 +requires AreReaderAndWriter +struct Parser { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (R::template has_custom_constructor) { + return _r.template use_custom_constructor(_var); + } else { + if constexpr (internal::has_reflection_type_v) { + using ReflectionType = std::decay_t; + const auto wrap_in_t = [](auto _named_tuple) -> Result { + try { + return T(_named_tuple); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + return Parser::read(_r, _var).and_then(wrap_in_t); + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + using NamedTupleType = named_tuple_t; + const auto to_struct = [](NamedTupleType&& _n) -> Result { + try { + return from_named_tuple(std::move(_n)); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + return Parser::read(_r, _var).and_then(to_struct); + } else if constexpr (std::is_enum_v) { + using StringConverter = internal::enums::StringConverter; + return _r.template to_basic_type(_var).and_then( + StringConverter::string_to_enum); + } else if constexpr (internal::is_basic_type_v) { + return _r.template to_basic_type>(_var); + } else { + static_assert( + always_false_v, + "Unsupported type. Please refer to the sections on custom " + "classes and custom parsers for information on how add " + "support for your own classes."); + } + } + } + + /// Converts the variable to a JSON type. + static auto write(const W& _w, const T& _var) noexcept { + if constexpr (internal::has_reflection_type_v) { + using ReflectionType = std::decay_t; + if constexpr (internal::has_reflection_method_v) { + return Parser::write(_w, _var.reflection()); + } else { + const auto& [r] = _var; + return Parser::write(_w, r); + } + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var); + using PtrNamedTupleType = std::decay_t; + return Parser::write(_w, ptr_named_tuple); + } else if constexpr (std::is_enum_v) { + using StringConverter = internal::enums::StringConverter; + const auto str = StringConverter::enum_to_string(_var); + return _w.from_basic_type(str); + } else if constexpr (internal::is_basic_type_v) { + return _w.from_basic_type(_var); + } else { + static_assert(always_false_v, + "Unsupported type. Please refer to the sections on custom " + "classes and custom parsers for information on how add " + "support for your own classes."); + } + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_map_like.hpp b/include/rfl/parsing/Parser_map_like.hpp new file mode 100644 index 00000000..19433180 --- /dev/null +++ b/include/rfl/parsing/Parser_map_like.hpp @@ -0,0 +1,33 @@ +#ifndef RFL_PARSING_PARSER_MAP_LIKE_HPP_ +#define RFL_PARSING_PARSER_MAP_LIKE_HPP_ + +#include +#include +#include +#include +#include + +#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 +requires AreReaderAndWriter> +struct Parser> + : public MapParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public MapParser> { +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_named_tuple.hpp b/include/rfl/parsing/Parser_named_tuple.hpp new file mode 100644 index 00000000..a97e033a --- /dev/null +++ b/include/rfl/parsing/Parser_named_tuple.hpp @@ -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 +requires AreReaderAndWriter> +struct Parser> + : public NamedTupleParser { +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_optional.hpp b/include/rfl/parsing/Parser_optional.hpp new file mode 100644 index 00000000..aa8cdb0a --- /dev/null +++ b/include/rfl/parsing/Parser_optional.hpp @@ -0,0 +1,40 @@ +#ifndef RFL_PARSING_PARSER_OPTIONAL_HPP_ +#define RFL_PARSING_PARSER_OPTIONAL_HPP_ + +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if (_r.is_empty(_var)) { + return std::optional(); + } + const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; + return Parser>::read(_r, _var).transform(to_opt); + } + + static OutputVarType write(const W& _w, const std::optional& _o) noexcept { + if (!_o) { + return _w.empty_var(); + } + return Parser>::write(_w, *_o); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_pair.hpp b/include/rfl/parsing/Parser_pair.hpp new file mode 100644 index 00000000..e7e10d36 --- /dev/null +++ b/include/rfl/parsing/Parser_pair.hpp @@ -0,0 +1,44 @@ +#ifndef RFL_PARSING_PARSER_PAIR_HPP_ +#define RFL_PARSING_PARSER_PAIR_HPP_ + +#include +#include + +#include "rfl/Ref.hpp" +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto to_pair = [&](auto&& _t) { + return std::make_pair(std::move(std::get<0>(_t)), + std::move(std::get<1>(_t))); + }; + return Parser>::read(_r, _var) + .transform(to_pair); + } + + /// Transform a std::pair into an array + static OutputVarType write( + const W& _w, const std::pair& _p) noexcept { + const auto tup = std::make_tuple(&_p.first, &_p.second); + return Parser>::write( + _w, tup); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_ptr.hpp b/include/rfl/parsing/Parser_ptr.hpp new file mode 100644 index 00000000..7fba9299 --- /dev/null +++ b/include/rfl/parsing/Parser_ptr.hpp @@ -0,0 +1,42 @@ +#ifndef RFL_PARSING_PARSER_PTR_HPP_ +#define RFL_PARSING_PARSER_PTR_HPP_ + +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter +struct Parser { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result read(const R& _r, const InputVarType& _var) noexcept { + static_assert(always_false_v, + "Reading into raw pointers is dangerous and " + "therefore unsupported. " + "Please consider using std::unique_ptr, rfl::Box, " + "std::shared_ptr, " + "rfl::Ref or std::optional instead."); + return Error("Unsupported."); + } + + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const T* _ptr) noexcept { + if (!_ptr) { + return _w.empty_var(); + } + return Parser>::write(_w, *_ptr); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_ref.hpp b/include/rfl/parsing/Parser_ref.hpp new file mode 100644 index 00000000..83799e40 --- /dev/null +++ b/include/rfl/parsing/Parser_ref.hpp @@ -0,0 +1,35 @@ +#ifndef RFL_PARSING_PARSER_REF_HPP_ +#define RFL_PARSING_PARSER_REF_HPP_ + +#include + +#include "rfl/Ref.hpp" +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_ref = [&](auto&& _t) { return Ref::make(std::move(_t)); }; + return Parser>::read(_r, _var).transform(to_ref); + } + + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, const Ref& _ref) noexcept { + return Parser>::write(_w, *_ref); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_reference_wrapper.hpp b/include/rfl/parsing/Parser_reference_wrapper.hpp new file mode 100644 index 00000000..06e96e87 --- /dev/null +++ b/include/rfl/parsing/Parser_reference_wrapper.hpp @@ -0,0 +1,40 @@ +#ifndef RFL_PARSING_PARSER_REFERENCE_WRAPPER_HPP_ +#define RFL_PARSING_PARSER_REFERENCE_WRAPPER_HPP_ + +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + static_assert(always_false_v, + "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 _ref) noexcept { + return Parser>::write(_w, _ref.get()); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_rename.hpp b/include/rfl/parsing/Parser_rename.hpp new file mode 100644 index 00000000..79471992 --- /dev/null +++ b/include/rfl/parsing/Parser_rename.hpp @@ -0,0 +1,38 @@ +#ifndef RFL_PARSING_PARSER_RENAME_HPP_ +#define RFL_PARSING_PARSER_RENAME_HPP_ + +#include + +#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 +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + const auto to_rename = [](auto&& _t) { + return Rename<_name, T>(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_rename); + } + + static OutputVarType write(const W& _w, + const Rename<_name, T>& _rename) noexcept { + return Parser>::write(_w, _rename.value()); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_result.hpp b/include/rfl/parsing/Parser_result.hpp new file mode 100644 index 00000000..ee615822 --- /dev/null +++ b/include/rfl/parsing/Parser_result.hpp @@ -0,0 +1,59 @@ +#ifndef RFL_PARSING_PARSER_RESULT_HPP_ +#define RFL_PARSING_PARSER_RESULT_HPP_ + +#include + +#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 +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + using ErrorType = NamedTuple>; + using VariantType = std::variant, ErrorType>; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + const auto handle = [](auto&& _t) -> Result { + using Type = std::decay_t; + if constexpr (std::is_same()) { + return Error(_t.template get<"error">()); + } else { + return std::forward>(_t); + } + }; + + const auto to_res = [&](VariantType&& _v) -> Result { + return std::visit(handle, std::forward(_v)); + }; + + return Result>( + Parser::read(_r, _var).transform(to_res)); + } + + static OutputVarType write(const W& _w, const Result& _r) noexcept { + const auto write_t = [&](const auto& _t) -> OutputVarType { + return Parser>::write(_w, _t); + }; + + const auto write_err = [&](const auto& _err) -> OutputVarType { + return Parser::write( + _w, ErrorType(make_field<"error">(_err.what()))); + }; + + return *_r.transform(write_t).or_else(write_err); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_rfl_variant.hpp b/include/rfl/parsing/Parser_rfl_variant.hpp new file mode 100644 index 00000000..bea91959 --- /dev/null +++ b/include/rfl/parsing/Parser_rfl_variant.hpp @@ -0,0 +1,43 @@ +#ifndef RFL_PARSING_PARSER_RFL_VARIANT_HPP_ +#define RFL_PARSING_PARSER_RFL_VARIANT_HPP_ + +#include +#include + +#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 +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto to_rfl_variant = [](auto&& _var) { + return rfl::Variant( + std::forward>(_var)); + }; + return Parser>::read(_r, _var).transform( + to_rfl_variant); + } + + static OutputVarType write( + const W& _w, const rfl::Variant& _variant) noexcept { + return Parser>::write(_w, + _variant.variant()); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_shared_ptr.hpp b/include/rfl/parsing/Parser_shared_ptr.hpp new file mode 100644 index 00000000..d7828c31 --- /dev/null +++ b/include/rfl/parsing/Parser_shared_ptr.hpp @@ -0,0 +1,45 @@ +#ifndef RFL_PARSING_PARSER_SHARED_PTR_HPP_ +#define RFL_PARSING_PARSER_SHARED_PTR_HPP_ + +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if (_r.is_empty(*_var)) { + return std::shared_ptr(); + } + const auto to_ptr = [](auto&& _t) { + return std::make_shared(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_ptr); + } + + /// Expresses the variable a a JSON. + static OutputVarType write(const W& _w, + const std::shared_ptr& _s) noexcept { + if (!_s) { + return _w.empty_var(); + } + return Parser>::write(_w, *_s); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_tagged_union.hpp b/include/rfl/parsing/Parser_tagged_union.hpp new file mode 100644 index 00000000..093c4270 --- /dev/null +++ b/include/rfl/parsing/Parser_tagged_union.hpp @@ -0,0 +1,133 @@ +#ifndef RFL_PARSING_PARSER_TAGGED_UNION_HPP_ +#define RFL_PARSING_PARSER_TAGGED_UNION_HPP_ + +#include + +#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 +requires AreReaderAndWriter> +struct Parser> { + using ResultType = Result>; + + 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 + static ResultType find_matching_alternative( + const R& _r, const std::string& _disc_value, + const InputVarType& _var) noexcept { + if constexpr (_i == sizeof...(AlternativeTypes)) { + return Error("Could not parse tagged union, could not match " + + _discriminator.str() + " '" + _disc_value + "'."); + } else { + using AlternativeType = std::decay_t< + std::variant_alternative_t<_i, std::variant>>; + + if (contains_disc_value(_disc_value)) { + const auto to_tagged_union = [](auto&& _val) { + return TaggedUnion<_discriminator, AlternativeTypes...>( + std::move(_val)); + }; + + const auto embellish_error = [&](Error&& _e) { + return Error( + "Could not parse tagged union with " + "discrimininator " + + _discriminator.str() + " '" + _disc_value + "': " + _e.what()); + }; + + return Parser::read(_r, _var) + .transform(to_tagged_union) + .or_else(embellish_error); + + } else { + return find_matching_alternative<_i + 1>(_r, _disc_value, _var); + } + } + } + + /// Retrieves the discriminator. + static Result get_discriminator( + const R& _r, const InputObjectType& _obj) noexcept { + const auto embellish_error = [](const auto& _err) { + return Error("Could not parse tagged union: Could not find field '" + + _discriminator.str() + + "' or type of field was not a string."); + }; + + const auto to_type = [&_r](auto _var) { + return _r.template to_basic_type(_var); + }; + + return _r.get_field(_discriminator.str(), _obj) + .and_then(to_type) + .or_else(embellish_error); + } + + /// Determines whether the discriminating literal contains the value + /// retrieved from the object. + template + static inline bool contains_disc_value( + const std::string& _disc_value) noexcept { + return internal::tag_t::contains(_disc_value); + } + + /// Writes a wrapped version of the original object, which contains the tag. + template + static OutputVarType write_wrapped(const W& _w, const T& _val) noexcept { + const auto tag = internal::make_tag(); + using TagType = std::decay_t; + if constexpr (internal::has_fields>()) { + using WrapperType = + TaggedUnionWrapperWithFields; + const auto wrapper = WrapperType{.tag = tag, .fields = &_val}; + return Parser::write(_w, wrapper); + } else { + using WrapperType = + TaggedUnionWrapperNoFields; + const auto wrapper = WrapperType{.tag = tag, .fields = &_val}; + return Parser::write(_w, wrapper); + } + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_tuple.hpp b/include/rfl/parsing/Parser_tuple.hpp new file mode 100644 index 00000000..17293992 --- /dev/null +++ b/include/rfl/parsing/Parser_tuple.hpp @@ -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 +requires AreReaderAndWriter> +struct Parser> + : public TupleParser { +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_unique_ptr.hpp b/include/rfl/parsing/Parser_unique_ptr.hpp new file mode 100644 index 00000000..9e091528 --- /dev/null +++ b/include/rfl/parsing/Parser_unique_ptr.hpp @@ -0,0 +1,43 @@ +#ifndef RFL_PARSING_PARSER_UNIQUE_PTR_HPP_ +#define RFL_PARSING_PARSER_UNIQUE_PTR_HPP_ + +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" +#include "rfl/parsing/Parser_base.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + static Result> read(const R& _r, + const InputVarType& _var) noexcept { + if (_r.is_empty(_var)) { + return std::unique_ptr(); + } + const auto to_ptr = [](auto&& _t) { + return std::make_unique(std::move(_t)); + }; + return Parser>::read(_r, _var).transform(to_ptr); + } + + static OutputVarType write(const W& _w, + const std::unique_ptr& _s) noexcept { + if (!_s) { + return _w.empty_var(); + } + return Parser>::write(_w, *_s); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_variant.hpp b/include/rfl/parsing/Parser_variant.hpp new file mode 100644 index 00000000..8d3ee5bf --- /dev/null +++ b/include/rfl/parsing/Parser_variant.hpp @@ -0,0 +1,69 @@ +#ifndef RFL_PARSING_PARSER_VARIANT_HPP_ +#define RFL_PARSING_PARSER_VARIANT_HPP_ + +#include +#include + +#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 +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + template + static Result> read( + const R& _r, const InputVarType& _var, + const std::string _errors = "") noexcept { + if constexpr (_i == 0 && + internal::all_fields>()) { + return FieldVariantParser::read(_r, _var); + } else if constexpr (_i == sizeof...(FieldTypes)) { + return Error("Could not parse variant: " + _errors); + } else { + const auto to_variant = [](auto&& _val) { + return std::variant(std::move(_val)); + }; + + const auto try_next = [&_r, _var, &_errors](const auto& _err) { + auto errors = _errors; + errors += std::string("\n" + std::to_string(_i + 1) + ") ") + + 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>>; + + return Parser::read(_r, _var) + .transform(to_variant) + .or_else(try_next); + } + } + + static OutputVarType write( + const W& _w, const std::variant& _variant) noexcept { + if constexpr (internal::all_fields>()) { + return FieldVariantParser::write(_w, _variant); + } else { + const auto handle = [&](const auto& _v) { + using Type = std::decay_t; + return Parser::write(_w, _v); + }; + return std::visit(handle, _variant); + } + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_vector_like.hpp b/include/rfl/parsing/Parser_vector_like.hpp new file mode 100644 index 00000000..adf0cd47 --- /dev/null +++ b/include/rfl/parsing/Parser_vector_like.hpp @@ -0,0 +1,96 @@ +#ifndef RFL_PARSING_PARSER_VECTOR_LIKE_HPP_ +#define RFL_PARSING_PARSER_VECTOR_LIKE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +template +requires AreReaderAndWriter> +struct Parser> + : public VectorParser> { +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp new file mode 100644 index 00000000..76de0f34 --- /dev/null +++ b/include/rfl/parsing/TupleParser.hpp @@ -0,0 +1,110 @@ +#ifndef RFL_PARSING_TUPLEPARSER_HPP_ +#define RFL_PARSING_TUPLEPARSER_HPP_ + +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/always_false.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter> +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> read(const R& _r, + const InputVarType& _var) noexcept { + const auto to_vec = [&](auto _arr) { return _r.to_vec(_arr); }; + + const auto check_size = [](auto _vec) -> Result> { + if (_vec.size() > sizeof...(Ts)) { + return Error("Expected " + std::to_string(sizeof...(Ts)) + + " fields, got " + std::to_string(_vec.size()) + "."); + } + return std::move(_vec); + }; + + const auto 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& _tup) noexcept { + auto arr = _w.new_array(); + to_array<0>(_w, _tup, &arr); + return arr; + } + + private: + template + static Result> extract_field_by_field( + const R& _r, std::vector _vec, + AlreadyExtracted&&... _already_extracted) noexcept { + constexpr size_t i = sizeof...(AlreadyExtracted); + if constexpr (i == sizeof...(Ts)) { + return std::tuple( + std::make_tuple(std::move(_already_extracted)...)); + } else { + const auto extract_next = [&](auto&& new_entry) { + return extract_field_by_field(_r, std::move(_vec), + std::move(_already_extracted)..., + std::move(new_entry)); + }; + return extract_single_field(_r, _vec).and_then(extract_next); + } + } + + template + static auto extract_single_field( + const R& _r, const std::vector& _vec) noexcept { + using NewFieldType = + std::decay_t>::type>; + + using ResultType = Result; + + if (_i >= _vec.size()) { + if constexpr (is_required()) { + 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::read(_r, _vec[_i]); + } + + template + static void to_array(const W& _w, const std::tuple& _tup, + OutputArrayType* _ptr) noexcept { + if constexpr (_i < sizeof...(Ts)) { + using NewFieldType = std::decay_t< + typename std::tuple_element<_i, std::tuple>::type>; + + const auto val = + Parser::write(_w, std::get<_i>(_tup)); + _w.add(val, _ptr); + to_array<_i + 1>(_w, _tup, _ptr); + } + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp new file mode 100644 index 00000000..01c46624 --- /dev/null +++ b/include/rfl/parsing/VectorParser.hpp @@ -0,0 +1,125 @@ +#ifndef RFL_PARSING_VECTORPARSER_HPP_ +#define RFL_PARSING_VECTORPARSER_HPP_ + +#include +#include +#include + +#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 +requires AreReaderAndWriter +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 read(const R& _r, const InputVarType& _var) noexcept { + if constexpr (treat_as_map()) { + return MapParser::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::write(_w, _vec); + } else { + auto arr = _w.new_array(); + for (const auto& v : _vec) { + _w.add(Parser>::write(_w, v), &arr); + } + return OutputVarType(arr); + } + } + + private: + static auto get_elem(const R& _r, auto& _v) { + return Parser>::read(_r, _v).value(); + }; + + static auto get_pair(const R& _r, auto& _v) { + using K = std::decay_t; + using V = std::decay_t; + return Parser>>::read(_r, _v).value(); + } + + static Result to_container(const R& _r, InputArrayType&& _arr) { + auto input_vars = _r.to_vec(_arr); + VecType vec; + if constexpr (is_forward_list()) { + for (auto it = input_vars.rbegin(); it != input_vars.rend(); ++it) { + vec.emplace_front(get_elem(_r, *it)); + } + } else if constexpr (is_map_like()) { + for (auto& v : input_vars) { + vec.insert(get_pair(_r, v)); + } + } else if constexpr (is_set_like()) { + 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 to_result(const R& _r, InputArrayType&& _arr) { + try { + return to_container(_r, std::forward(_arr)); + } catch (std::exception& e) { + return Error(e.what()); + } + } + + static constexpr bool treat_as_map() { + if constexpr (is_map_like_not_multimap()) { + if constexpr (internal::has_reflection_type_v) { + using U = std::decay_t; + return std::is_same() || std::is_integral_v || + std::is_floating_point_v; + + // We do not need std::string here, it is already caught by the template + // specialization. + } else if constexpr (std::is_integral_v || + std::is_floating_point_v) { + return true; + } else { + return false; + } + } else { + return false; + } + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/is_map_like.hpp b/include/rfl/parsing/is_map_like.hpp index 34249982..caaa5719 100644 --- a/include/rfl/parsing/is_map_like.hpp +++ b/include/rfl/parsing/is_map_like.hpp @@ -26,6 +26,10 @@ class is_map_like> : public std::true_type {}; template class is_map_like> : public std::true_type {}; +template +constexpr bool is_map_like_v = + is_map_like>>::value; + } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/is_required.hpp b/include/rfl/parsing/is_required.hpp index 967cc06d..75832221 100644 --- a/include/rfl/parsing/is_required.hpp +++ b/include/rfl/parsing/is_required.hpp @@ -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 is_required; +class is_never_required; template -class is_required : public std::true_type {}; +class is_never_required : public std::false_type {}; template -class is_required : public std::false_type {}; +class is_never_required> : public std::true_type {}; template -class is_required> : public std::false_type {}; +class is_never_required> : public std::true_type {}; template -class is_required> : public std::false_type {}; +class is_never_required> : public std::true_type {}; template -class is_required> : public std::false_type {}; +constexpr bool is_never_required_v = is_never_required::value; -template -class is_required> : public is_required {}; +template +consteval bool is_required() { + using Type = std::decay_t>; + if constexpr (internal::has_reflection_type_v) { + return is_required(); + } else if constexpr (internal::is_rename_v) { + return is_required(); + } else { + return !(is_never_required_v || + (_ignore_empty_containers && + (is_vector_like_v || is_map_like_v))); + } +} } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/is_vector_like.hpp b/include/rfl/parsing/is_vector_like.hpp new file mode 100644 index 00000000..1eba273a --- /dev/null +++ b/include/rfl/parsing/is_vector_like.hpp @@ -0,0 +1,53 @@ +#ifndef RFL_PARSING_IS_VECTOR_LIKE_HPP_ +#define RFL_PARSING_IS_VECTOR_LIKE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rfl { +namespace parsing { + +template +class is_vector_like; + +template +class is_vector_like : public std::false_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +class is_vector_like> : public std::true_type {}; + +template +constexpr bool is_vector_like_v = + is_vector_like>>::value; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/xml.hpp b/include/rfl/xml.hpp new file mode 100644 index 00000000..aaa876e4 --- /dev/null +++ b/include/rfl/xml.hpp @@ -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 diff --git a/include/rfl/xml/OutputArray.hpp b/include/rfl/xml/OutputArray.hpp new file mode 100644 index 00000000..8ba8814c --- /dev/null +++ b/include/rfl/xml/OutputArray.hpp @@ -0,0 +1,41 @@ +#ifndef RFL_XML_OUTPUTARRAY_HPP_ +#define RFL_XML_OUTPUTARRAY_HPP_ + +#include +#include +#include + +#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& _var) { vars_.push_back(_var); } + + private: + /// The underlying variables. + std::vector> vars_; +}; + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/OutputNull.hpp b/include/rfl/xml/OutputNull.hpp new file mode 100644 index 00000000..5787b7b6 --- /dev/null +++ b/include/rfl/xml/OutputNull.hpp @@ -0,0 +1,32 @@ +#ifndef RFL_XML_OUTPUTNULL_HPP_ +#define RFL_XML_OUTPUTNULL_HPP_ + +#include +#include +#include + +#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 diff --git a/include/rfl/xml/OutputObject.hpp b/include/rfl/xml/OutputObject.hpp new file mode 100644 index 00000000..b1003f7d --- /dev/null +++ b/include/rfl/xml/OutputObject.hpp @@ -0,0 +1,44 @@ +#ifndef RFL_XML_OUTPUTOBJECT_HPP_ +#define RFL_XML_OUTPUTOBJECT_HPP_ + +#include +#include +#include + +#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& _var) { + vars_.push_back(std::make_pair(_name, _var)); + } + + private: + /// The underlying variables. + std::vector>> vars_; +}; + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/OutputValue.hpp b/include/rfl/xml/OutputValue.hpp new file mode 100644 index 00000000..9d023225 --- /dev/null +++ b/include/rfl/xml/OutputValue.hpp @@ -0,0 +1,67 @@ +#ifndef RFL_XML_OUTPUTVALUE_HPP_ +#define RFL_XML_OUTPUTVALUE_HPP_ + +#include +#include +#include + +#include "rfl/always_false.hpp" +#include "rfl/xml/OutputVar.hpp" + +namespace rfl { +namespace xml { + +template +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::string>()) { + return val_; + } else if constexpr (std::is_same, bool>()) { + return val_ ? "true" : "false"; + } else if constexpr (std::is_floating_point>() || + std::is_integral>()) { + return std::to_string(val_); + } else { + static_assert(always_false_v, "Unsupported type"); + } + } + + private: + /// Whether you want this encoded as an attribute. + bool is_attribute_; + + /// The underlying value. + T val_; +}; + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/OutputVar.hpp b/include/rfl/xml/OutputVar.hpp new file mode 100644 index 00000000..a20c151b --- /dev/null +++ b/include/rfl/xml/OutputVar.hpp @@ -0,0 +1,24 @@ +#ifndef RFL_XML_OUTPUTVAR_HPP_ +#define RFL_XML_OUTPUTVAR_HPP_ + +#include +#include + +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 diff --git a/include/rfl/xml/Parser.hpp b/include/rfl/xml/Parser.hpp new file mode 100644 index 00000000..54093fca --- /dev/null +++ b/include/rfl/xml/Parser.hpp @@ -0,0 +1,40 @@ +#ifndef RFL_XML_PARSER_HPP_ +#define RFL_XML_PARSER_HPP_ + +#include + +#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 +requires AreReaderAndWriter> +struct Parser> + : public NamedTupleParser { +}; + +} // namespace parsing +} // namespace rfl + +namespace rfl { +namespace xml { + +template +using Parser = parsing::Parser; + +} +} // namespace rfl + +#endif diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp new file mode 100644 index 00000000..c3f100de --- /dev/null +++ b/include/rfl/xml/Reader.hpp @@ -0,0 +1,193 @@ +#ifndef RFL_XML_READER_HPP_ +#define RFL_XML_READER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 node_or_attribute_; + }; + + using InputArrayType = XMLInputArray; + using InputObjectType = XMLInputObject; + using InputVarType = XMLInputVar; + + // TODO + template + static constexpr bool has_custom_constructor = false; + + /// XML-only helper function. This is needed because XML distinguishes between + /// nodes and attributes. + static rfl::Result cast_as_node( + const std::variant& + _node_or_attribute) { + const auto cast = [](const auto& _n) -> Result { + using Type = std::decay_t; + if constexpr (std::is_same()) { + return _n; + } else { + return Error("Field '" + std::string(_n.name()) + "' is an attribute."); + } + }; + return std::visit(cast, _node_or_attribute); + } + + rfl::Result 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 + rfl::Result to_basic_type(const InputVarType _var) const noexcept { + const auto get_value = [](const auto& _n) -> std::string { + using Type = std::decay_t; + if constexpr (std::is_same()) { + return std::string(_n.child_value()); + } else { + return std::string(_n.value()); + } + }; + + if constexpr (std::is_same, std::string>()) { + return std::visit(get_value, _var.node_or_attribute_); + } else if constexpr (std::is_same, bool>()) { + return std::visit(get_value, _var.node_or_attribute_) == "true"; + } else if constexpr (std::is_floating_point>()) { + const auto str = std::visit(get_value, _var.node_or_attribute_); + try { + return static_cast(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>()) { + const auto str = std::visit(get_value, _var.node_or_attribute_); + try { + return static_cast(std::stoi(str)); + } catch (std::exception& e) { + return Error("Could not cast '" + std::string(str) + "' to integer."); + } + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + } + + rfl::Result 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 + std::array, size> to_fields_array( + const FunctionType _fct, const InputObjectType _obj) const noexcept { + std::array, 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> to_map( + const InputObjectType _obj) const noexcept { + std::vector> 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 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 to_vec(const InputArrayType _arr) const noexcept { + const auto name = _arr.node_.name(); + std::vector vec; + for (auto node = _arr.node_; node; node = node.next_sibling(name)) { + vec.push_back(InputVarType(node)); + } + return vec; + } + + template + rfl::Result use_custom_constructor( + const InputVarType _var) const noexcept { + return rfl::Error("TODO"); + } +}; + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/Writer.hpp b/include/rfl/xml/Writer.hpp new file mode 100644 index 00000000..abc129b6 --- /dev/null +++ b/include/rfl/xml/Writer.hpp @@ -0,0 +1,65 @@ +#ifndef RFL_XML_WRITER_HPP_ +#define RFL_XML_WRITER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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; + using OutputObjectType = Ref; + using OutputVarType = Ref; + + Writer() {} + + ~Writer() = default; + + void add(const OutputVarType _var, OutputArrayType* _arr) const noexcept { + (*_arr)->push_back(_var); + } + + OutputVarType empty_var() const noexcept { return make_ref(); } + + template + OutputVarType from_basic_type( + const T& _var, const bool _is_attribute = false) const noexcept { + return make_ref>(_var, _is_attribute); + } + + OutputArrayType new_array() const noexcept { return make_ref(); } + + OutputObjectType new_object() const noexcept { + return make_ref(); + } + + 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_ diff --git a/include/rfl/xml/is_required_for_xml.hpp b/include/rfl/xml/is_required_for_xml.hpp new file mode 100644 index 00000000..136eab03 --- /dev/null +++ b/include/rfl/xml/is_required_for_xml.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_XML_IS_REQUIRED_FOR_XML_HPP_ +#define RFL_XML_IS_REQUIRED_FOR_XML_HPP_ + +#include + +#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 +consteval bool is_required_for_xml() { + using Type = std::decay_t>; + if constexpr (internal::has_reflection_type_v) { + return is_required_for_xml(); + } else { + return parsing::is_required() && !parsing::is_vector_like_v; + } +} + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/load.hpp b/include/rfl/xml/load.hpp new file mode 100644 index 00000000..20e5cee2 --- /dev/null +++ b/include/rfl/xml/load.hpp @@ -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 +Result load(const std::string& _fname) { + const auto read_string = [](const auto& _str) { return read(_str); }; + return rfl::io::load_string(_fname).and_then(read_string); +} + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/read.hpp b/include/rfl/xml/read.hpp new file mode 100644 index 00000000..62fff39a --- /dev/null +++ b/include/rfl/xml/read.hpp @@ -0,0 +1,49 @@ +#ifndef RFL_XML_READ_HPP_ +#define RFL_XML_READ_HPP_ + +#include +#include +#include + +#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 +Result read(const InputVarType& _var) { + const auto r = Reader(); + return Parser::read(r, _var); +} + +/// Parses an object from XML using reflection. +template +Result 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(var); +} + +/// Parses an object from a stringstream. +template +Result read(std::istream& _stream) { + const auto xml_str = std::string(std::istreambuf_iterator(_stream), + std::istreambuf_iterator()); + return read(xml_str); +} + +} // namespace xml +} // namespace rfl + +#endif diff --git a/include/rfl/xml/save.hpp b/include/rfl/xml/save.hpp new file mode 100644 index 00000000..282f9f86 --- /dev/null +++ b/include/rfl/xml/save.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_XML_SAVE_HPP_ +#define RFL_XML_SAVE_HPP_ + +#include +#include +#include + +#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 +Result 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 diff --git a/include/rfl/xml/write.hpp b/include/rfl/xml/write.hpp new file mode 100644 index 00000000..adb5681f --- /dev/null +++ b/include/rfl/xml/write.hpp @@ -0,0 +1,68 @@ +#ifndef RFL_XML_WRITE_HPP_ +#define RFL_XML_WRITE_HPP_ + +#include +#include +#include +#include +#include + +#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 +consteval auto get_root_name() { + if constexpr (_root != internal::StringLiteral("")) { + return _root; + } else { + return internal::remove_namespaces< + internal::get_type_name>()>(); + } +} + +/// Writes a XML into an ostream. +template +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::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 +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_ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5e1d99cc..7fe72a52 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -6,9 +6,12 @@ else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20 -Wall -Wno-sign-compare -Wno-missing-braces -Wno-psabi -pthread -fno-strict-aliasing -fwrapv -O2 -ftemplate-backtrace-limit=0 -fsanitize=undefined") endif() - add_subdirectory(json) if (REFLECTCPP_FLEXBUFFERS) add_subdirectory(flexbuffers) -endif() \ No newline at end of file +endif() + +if (REFLECTCPP_XML) + add_subdirectory(xml) +endif() diff --git a/tests/flexbuffers/CMakeLists.txt b/tests/flexbuffers/CMakeLists.txt index 63b3366c..19125e19 100644 --- a/tests/flexbuffers/CMakeLists.txt +++ b/tests/flexbuffers/CMakeLists.txt @@ -1,4 +1,4 @@ -project(reflect-cpp-json-tests) +project(reflect-cpp-flexbuffer-tests) file(GLOB_RECURSE SOURCES "*.cpp") diff --git a/tests/xml/CMakeLists.txt b/tests/xml/CMakeLists.txt new file mode 100644 index 00000000..c22bc116 --- /dev/null +++ b/tests/xml/CMakeLists.txt @@ -0,0 +1,8 @@ +project(reflect-cpp-xml-tests) + +file(GLOB_RECURSE SOURCES "*.cpp") + +add_executable(reflect-cpp-xml-tests ${SOURCES}) + +target_link_libraries(reflect-cpp-xml-tests PRIVATE reflectcpp) + diff --git a/tests/xml/get_pugixml.sh b/tests/xml/get_pugixml.sh new file mode 100755 index 00000000..3aa890cd --- /dev/null +++ b/tests/xml/get_pugixml.sh @@ -0,0 +1,3 @@ +#!/bin/bash +wget https://github.com/zeux/pugixml/releases/download/v1.14/pugixml-1.14.tar.gz +tar -xzvf pugixml-1.14.tar.gz diff --git a/tests/xml/test_array.cpp b/tests/xml/test_array.cpp new file mode 100644 index 00000000..7485cbfe --- /dev/null +++ b/tests/xml/test_array.cpp @@ -0,0 +1,37 @@ +#include "test_array.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_array { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children = nullptr; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto bart = Person{.first_name = "Bart"}; + + auto lisa = Person{.first_name = "Lisa"}; + + auto maggie = Person{.first_name = "Maggie"}; + + const auto homer = Person{ + .first_name = "Homer", + .children = std::make_unique>(std::array{ + std::move(bart), std::move(lisa), std::move(maggie)})}; + + write_and_read(homer); +} +} // namespace test_array diff --git a/tests/xml/test_array.hpp b/tests/xml/test_array.hpp new file mode 100644 index 00000000..502c3388 --- /dev/null +++ b/tests/xml/test_array.hpp @@ -0,0 +1,4 @@ +namespace test_array{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_attributes.cpp b/tests/xml/test_attributes.cpp new file mode 100644 index 00000000..9e5e5931 --- /dev/null +++ b/tests/xml/test_attributes.cpp @@ -0,0 +1,52 @@ +#include "test_attributes.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_attributes { + +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", rfl::Attribute> first_name; + rfl::Rename<"lastName", rfl::Attribute> last_name = "Simpson"; + rfl::Attribute town = "Springfield"; + rfl::Attribute> birthday; + rfl::Attribute age; + rfl::Attribute email; + std::vector child; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + + const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + + const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + + const auto homer = Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_attributes diff --git a/tests/xml/test_attributes.hpp b/tests/xml/test_attributes.hpp new file mode 100644 index 00000000..e77be6af --- /dev/null +++ b/tests/xml/test_attributes.hpp @@ -0,0 +1,4 @@ +namespace test_attributes { +void test(); +} + diff --git a/tests/xml/test_box.cpp b/tests/xml/test_box.cpp new file mode 100644 index 00000000..04d88641 --- /dev/null +++ b/tests/xml/test_box.cpp @@ -0,0 +1,50 @@ +#include "test_box.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_box { + +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Box lesser; + rfl::Box greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + + auto leaf2 = DecisionTree::Leaf{.value = 5.0}; + + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_box(DecisionTree{leaf1}), + .greater = rfl::make_box(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); + +} +} // namespace test_box diff --git a/tests/xml/test_box.hpp b/tests/xml/test_box.hpp new file mode 100644 index 00000000..a564b9e1 --- /dev/null +++ b/tests/xml/test_box.hpp @@ -0,0 +1,4 @@ +namespace test_box{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_custom_class1.cpp b/tests/xml/test_custom_class1.cpp new file mode 100644 index 00000000..35f4a1da --- /dev/null +++ b/tests/xml/test_custom_class1.cpp @@ -0,0 +1,42 @@ +#include "test_custom_class1.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_custom_class1 { + +struct Person { + struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::vector children; + }; + + using ReflectionType = PersonImpl; + + Person(const PersonImpl& _impl) : impl(_impl) {} + + Person(const std::string& _first_name) + : impl(PersonImpl{.first_name = _first_name}) {} + + const ReflectionType& reflection() const { return impl; }; + + private: + PersonImpl impl; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person("Bart"); + + write_and_read(bart); +} +} // namespace test_custom_class1 diff --git a/tests/xml/test_custom_class1.hpp b/tests/xml/test_custom_class1.hpp new file mode 100644 index 00000000..eafe6cd0 --- /dev/null +++ b/tests/xml/test_custom_class1.hpp @@ -0,0 +1,4 @@ +namespace test_custom_class1{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_custom_class3.cpp b/tests/xml/test_custom_class3.cpp new file mode 100644 index 00000000..2ea105e4 --- /dev/null +++ b/tests/xml/test_custom_class3.cpp @@ -0,0 +1,68 @@ +#include "test_custom_class3.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_custom_class3 { + +struct Person { + Person(const std::string& _first_name, const std::string& _last_name, + const int _age) + : first_name_(_first_name), last_name_(_last_name), age_(_age) {} + + const auto& first_name() const { return first_name_; } + + const auto& last_name() const { return last_name_; } + + auto age() const { return age_; } + + private: + std::string first_name_; + std::string last_name_; + int age_; +}; + +struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; + + static PersonImpl from_class(const Person& _p) noexcept { + return PersonImpl{.first_name = _p.first_name(), + .last_name = _p.last_name(), + .age = _p.age()}; + } + + Person to_class() const { return Person(first_name(), last_name(), age); } +}; +} // namespace test_custom_class3 + +namespace rfl { +namespace parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace parsing +} // namespace rfl + +namespace test_custom_class3 { + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person("Bart", "Simpson", 10); + + write_and_read(bart); +} + +} // namespace test_custom_class3 diff --git a/tests/xml/test_custom_class3.hpp b/tests/xml/test_custom_class3.hpp new file mode 100644 index 00000000..9a6fdab4 --- /dev/null +++ b/tests/xml/test_custom_class3.hpp @@ -0,0 +1,4 @@ +namespace test_custom_class3{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_custom_class4.cpp b/tests/xml/test_custom_class4.cpp new file mode 100644 index 00000000..e2d79a94 --- /dev/null +++ b/tests/xml/test_custom_class4.cpp @@ -0,0 +1,69 @@ +#include "test_custom_class4.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_custom_class4 { + +struct Person { + Person(const std::string& _first_name, + const rfl::Box& _last_name, int _age) + : first_name_(_first_name), + last_name_(rfl::make_box(*_last_name)), + age_(_age) {} + + const auto& first_name() const { return first_name_; } + + const auto& last_name() const { return last_name_; } + + auto age() const { return age_; } + + private: + std::string first_name_; + rfl::Box last_name_; + int age_; +}; + +struct PersonImpl { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", rfl::Box> last_name; + rfl::Field<"age", int> age; + + static PersonImpl from_class(const Person& _p) noexcept { + return PersonImpl{.first_name = _p.first_name(), + .last_name = rfl::make_box(*_p.last_name()), + .age = _p.age()}; + } +}; + +} // namespace test_custom_class4 + +namespace rfl { +namespace parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace parsing +} // namespace rfl + +namespace test_custom_class4 { + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = test_custom_class4::Person( + "Bart", rfl::make_box("Simpson"), 10); + + write_and_read(bart); +} +} // namespace test_custom_class4 diff --git a/tests/xml/test_custom_class4.hpp b/tests/xml/test_custom_class4.hpp new file mode 100644 index 00000000..2d3b151a --- /dev/null +++ b/tests/xml/test_custom_class4.hpp @@ -0,0 +1,4 @@ +namespace test_custom_class4{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_default_values.cpp b/tests/xml/test_default_values.cpp new file mode 100644 index 00000000..7613a6e3 --- /dev/null +++ b/tests/xml/test_default_values.cpp @@ -0,0 +1,33 @@ +#include "test_default_values.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_default_values { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::vector children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{.first_name = "Bart"}; + const auto lisa = Person{.first_name = "Lisa"}; + const auto maggie = Person{.first_name = "Maggie"}; + const auto homer = + Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_default_values diff --git a/tests/xml/test_default_values.hpp b/tests/xml/test_default_values.hpp new file mode 100644 index 00000000..c8f8360e --- /dev/null +++ b/tests/xml/test_default_values.hpp @@ -0,0 +1,4 @@ +namespace test_default_values{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_deque.cpp b/tests/xml/test_deque.cpp new file mode 100644 index 00000000..cdcceac0 --- /dev/null +++ b/tests/xml/test_deque.cpp @@ -0,0 +1,34 @@ +#include "test_deque.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_deque { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto children = std::make_unique>(); + children->emplace_back(Person{.first_name = "Bart"}); + children->emplace_back(Person{.first_name = "Lisa"}); + children->emplace_back(Person{.first_name = "Maggie"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); + +} +} // namespace test_deque diff --git a/tests/xml/test_deque.hpp b/tests/xml/test_deque.hpp new file mode 100644 index 00000000..6781e880 --- /dev/null +++ b/tests/xml/test_deque.hpp @@ -0,0 +1,4 @@ +namespace test_deque{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_enum.cpp b/tests/xml/test_enum.cpp new file mode 100644 index 00000000..0095ee19 --- /dev/null +++ b/tests/xml/test_enum.cpp @@ -0,0 +1,30 @@ +#include "test_enum.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_enum { + +enum class Color { red, green, blue, yellow }; + +struct Circle { + float radius; + Color color; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto circle = Circle{.radius = 2.0, .color = Color::green}; + + write_and_read(circle); +} + +} // namespace test_enum diff --git a/tests/xml/test_enum.hpp b/tests/xml/test_enum.hpp new file mode 100644 index 00000000..2e2e0b3d --- /dev/null +++ b/tests/xml/test_enum.hpp @@ -0,0 +1,4 @@ +namespace test_enum { +void test(); +} + diff --git a/tests/xml/test_field_variant.cpp b/tests/xml/test_field_variant.cpp new file mode 100644 index 00000000..114d000c --- /dev/null +++ b/tests/xml/test_field_variant.cpp @@ -0,0 +1,40 @@ +#include "test_field_variant.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_field_variant { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>>; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read<"shape">(r); +} +} // namespace test_field_variant diff --git a/tests/xml/test_field_variant.hpp b/tests/xml/test_field_variant.hpp new file mode 100644 index 00000000..ba93e732 --- /dev/null +++ b/tests/xml/test_field_variant.hpp @@ -0,0 +1,4 @@ +namespace test_field_variant{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_flag_enum.cpp b/tests/xml/test_flag_enum.cpp new file mode 100644 index 00000000..3846c1fd --- /dev/null +++ b/tests/xml/test_flag_enum.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "test_enum.hpp" +#include "write_and_read.hpp" + +namespace test_flag_enum { + +enum class Color { + red = 256, + green = 512, + blue = 1024, + yellow = 2048, + orange = (256 | 2048) // red + yellow = orange +}; + +inline Color operator|(Color c1, Color c2) { + return static_cast(static_cast(c1) | static_cast(c2)); +} + +struct Circle { + float radius; + Color color; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto circle = + Circle{.radius = 2.0, .color = Color::blue | Color::orange}; + + write_and_read(circle); +} + +} // namespace test_flag_enum diff --git a/tests/xml/test_flag_enum.hpp b/tests/xml/test_flag_enum.hpp new file mode 100644 index 00000000..2f4dc7a0 --- /dev/null +++ b/tests/xml/test_flag_enum.hpp @@ -0,0 +1,4 @@ +namespace test_flag_enum { +void test(); +} + diff --git a/tests/xml/test_flag_enum_with_int.cpp b/tests/xml/test_flag_enum_with_int.cpp new file mode 100644 index 00000000..4a0eb52d --- /dev/null +++ b/tests/xml/test_flag_enum_with_int.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "test_enum.hpp" +#include "write_and_read.hpp" + +namespace test_flag_enum_with_int { + +enum class Color { + red = 256, + green = 512, + blue = 1024, + yellow = 2048, + orange = (256 | 2048) // red + yellow = orange +}; + +inline Color operator|(Color c1, Color c2) { + return static_cast(static_cast(c1) | static_cast(c2)); +} + +struct Circle { + float radius; + Color color; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto circle = Circle{.radius = 2.0, .color = static_cast(10000)}; + + write_and_read(circle); +} + +} // namespace test_flag_enum_with_int diff --git a/tests/xml/test_flag_enum_with_int.hpp b/tests/xml/test_flag_enum_with_int.hpp new file mode 100644 index 00000000..a7512b60 --- /dev/null +++ b/tests/xml/test_flag_enum_with_int.hpp @@ -0,0 +1,4 @@ +namespace test_flag_enum_with_int { +void test(); +} + diff --git a/tests/xml/test_flatten.cpp b/tests/xml/test_flatten.cpp new file mode 100644 index 00000000..468add92 --- /dev/null +++ b/tests/xml/test_flatten.cpp @@ -0,0 +1,39 @@ +#include "test_flatten.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_flatten { + +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", rfl::Box> last_name; + rfl::Field<"age", int> age; +}; + +struct Employee { + rfl::Flatten person; + rfl::Field<"employer", rfl::Box> employer; + rfl::Field<"salary", float> salary; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = rfl::make_box("Simpson"), + .age = 45}, + .employer = rfl::make_box("Mr. Burns"), + .salary = 60000.0}; + + write_and_read(employee); +} +} // namespace test_flatten diff --git a/tests/xml/test_flatten.hpp b/tests/xml/test_flatten.hpp new file mode 100644 index 00000000..24d60e11 --- /dev/null +++ b/tests/xml/test_flatten.hpp @@ -0,0 +1,4 @@ +namespace test_flatten{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_flatten_anonymous.cpp b/tests/xml/test_flatten_anonymous.cpp new file mode 100644 index 00000000..c1bc0f07 --- /dev/null +++ b/tests/xml/test_flatten_anonymous.cpp @@ -0,0 +1,40 @@ +#include "test_flatten_anonymous.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_flatten_anonymous { + +struct Person { + std::string first_name; + rfl::Box last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + rfl::Box employer; + float salary; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = rfl::make_box("Simpson"), + .age = 45}, + .employer = rfl::make_box("Mr. Burns"), + .salary = 60000.0}; + + write_and_read(employee); +} + +} // namespace test_flatten_anonymous diff --git a/tests/xml/test_flatten_anonymous.hpp b/tests/xml/test_flatten_anonymous.hpp new file mode 100644 index 00000000..7ffa2785 --- /dev/null +++ b/tests/xml/test_flatten_anonymous.hpp @@ -0,0 +1,4 @@ +namespace test_flatten_anonymous{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_forward_list.cpp b/tests/xml/test_forward_list.cpp new file mode 100644 index 00000000..ed0d07b8 --- /dev/null +++ b/tests/xml/test_forward_list.cpp @@ -0,0 +1,34 @@ +#include "test_forward_list.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_forward_list { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto children = std::make_unique>(); + children->emplace_front(Person{.first_name = "Maggie"}); + children->emplace_front(Person{.first_name = "Lisa"}); + children->emplace_front(Person{.first_name = "Bart"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); + +} +} // namespace test_forward_list diff --git a/tests/xml/test_forward_list.hpp b/tests/xml/test_forward_list.hpp new file mode 100644 index 00000000..9784a0c4 --- /dev/null +++ b/tests/xml/test_forward_list.hpp @@ -0,0 +1,4 @@ +namespace test_forward_list{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_literal.cpp b/tests/xml/test_literal.cpp new file mode 100644 index 00000000..9b940423 --- /dev/null +++ b/tests/xml/test_literal.cpp @@ -0,0 +1,31 @@ +#include "test_literal.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_literal { + +using FirstName = rfl::Literal<"Homer", "Marge", "Bart", "Lisa", "Maggie">; +using LastName = rfl::Literal<"Simpson">; + +struct Person { + rfl::Rename<"firstName", FirstName> first_name; + rfl::Rename<"lastName", LastName> last_name; + std::vector children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{.first_name = FirstName::make<"Bart">()}; + + write_and_read(bart); +} +} // namespace test_literal diff --git a/tests/xml/test_literal.hpp b/tests/xml/test_literal.hpp new file mode 100644 index 00000000..ccd500ef --- /dev/null +++ b/tests/xml/test_literal.hpp @@ -0,0 +1,4 @@ +namespace test_literal{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_literal_map.cpp b/tests/xml/test_literal_map.cpp new file mode 100644 index 00000000..b9a03851 --- /dev/null +++ b/tests/xml/test_literal_map.cpp @@ -0,0 +1,29 @@ +#include "test_literal_map.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_literal_map { + +using FieldName = rfl::Literal<"firstName", "lastName">; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + std::map> homer; + homer.insert(std::make_pair(FieldName::make<"firstName">(), + std::make_unique("Homer"))); + homer.insert(std::make_pair(FieldName::make<"lastName">(), + std::make_unique("Simpson"))); + + write_and_read<"person">(homer); +} +} // namespace test_literal_map diff --git a/tests/xml/test_literal_map.hpp b/tests/xml/test_literal_map.hpp new file mode 100644 index 00000000..cc05d0c8 --- /dev/null +++ b/tests/xml/test_literal_map.hpp @@ -0,0 +1,4 @@ +namespace test_literal_map{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_map.cpp b/tests/xml/test_map.cpp new file mode 100644 index 00000000..3e897fe3 --- /dev/null +++ b/tests/xml/test_map.cpp @@ -0,0 +1,33 @@ +#include "test_map.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_map { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::map children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto children = std::map(); + children.insert(std::make_pair("child1", Person{.first_name = "Bart"})); + children.insert(std::make_pair("child2", Person{.first_name = "Lisa"})); + children.insert(std::make_pair("child3", Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_map diff --git a/tests/xml/test_map.hpp b/tests/xml/test_map.hpp new file mode 100644 index 00000000..9ae49728 --- /dev/null +++ b/tests/xml/test_map.hpp @@ -0,0 +1,4 @@ +namespace test_map{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_map_with_key_validation.cpp b/tests/xml/test_map_with_key_validation.cpp new file mode 100644 index 00000000..20f831af --- /dev/null +++ b/tests/xml/test_map_with_key_validation.cpp @@ -0,0 +1,34 @@ +#include "test_map_with_key_validation.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_map_with_key_validation { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto children = std::make_unique>(); + + children->insert(std::make_pair("Bart", Person{.first_name = "Bart"})); + children->insert(std::make_pair("Lisa", Person{.first_name = "Lisa"})); + children->insert(std::make_pair("Maggie", Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_map_with_key_validation diff --git a/tests/xml/test_map_with_key_validation.hpp b/tests/xml/test_map_with_key_validation.hpp new file mode 100644 index 00000000..1372f926 --- /dev/null +++ b/tests/xml/test_map_with_key_validation.hpp @@ -0,0 +1,4 @@ +namespace test_map_with_key_validation{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_monster_example.cpp b/tests/xml/test_monster_example.cpp new file mode 100644 index 00000000..e9a443ad --- /dev/null +++ b/tests/xml/test_monster_example.cpp @@ -0,0 +1,67 @@ +#include "test_monster_example.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_monster_example { + +using Color = rfl::Literal<"Red", "Green", "Blue">; + +struct Weapon { + std::string name; + short damage; +}; + +using Equipment = rfl::Variant>; + +struct Vec3 { + float x; + float y; + float z; +}; + +struct Monster { + Vec3 pos; + short mana = 150; + short hp = 100; + std::string name; + bool friendly = false; + std::vector inventory; + Color color = Color::make<"Blue">(); + std::vector weapons; + Equipment equipped; + std::vector path; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto sword = Weapon{.name = "Sword", .damage = 3}; + const auto axe = Weapon{.name = "Axe", .damage = 5}; + + const auto weapons = std::vector({sword, axe}); + + const auto position = Vec3{1.0f, 2.0f, 3.0f}; + + const auto inventory = + std::vector({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + + const auto orc = Monster{.pos = position, + .mana = 150, + .hp = 80, + .name = "MyMonster", + .inventory = inventory, + .color = Color::make<"Red">(), + .weapons = weapons, + .equipped = rfl::make_field<"weapon">(axe)}; + + write_and_read(orc); + +} +} // namespace test_monster_example diff --git a/tests/xml/test_monster_example.hpp b/tests/xml/test_monster_example.hpp new file mode 100644 index 00000000..f2d959fc --- /dev/null +++ b/tests/xml/test_monster_example.hpp @@ -0,0 +1,4 @@ +namespace test_monster_example{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_readme_example.cpp b/tests/xml/test_readme_example.cpp new file mode 100644 index 00000000..f75b51ce --- /dev/null +++ b/tests/xml/test_readme_example.cpp @@ -0,0 +1,52 @@ +#include "test_readme_example.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_readme_example { + +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector child; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{.first_name = "Bart", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com"}; + + const auto lisa = Person{.first_name = "Lisa", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + + const auto maggie = Person{.first_name = "Maggie", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + + const auto homer = Person{.first_name = "Homer", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_readme_example diff --git a/tests/xml/test_readme_example.hpp b/tests/xml/test_readme_example.hpp new file mode 100644 index 00000000..68c6cf81 --- /dev/null +++ b/tests/xml/test_readme_example.hpp @@ -0,0 +1,4 @@ +namespace test_readme_example{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_ref.cpp b/tests/xml/test_ref.cpp new file mode 100644 index 00000000..39a0c726 --- /dev/null +++ b/tests/xml/test_ref.cpp @@ -0,0 +1,50 @@ +#include "test_ref.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_ref { + +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Ref lesser; + rfl::Ref greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + + const auto leaf2 = DecisionTree::Leaf{.value = 5.0}; + + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_ref(DecisionTree{leaf1}), + .greater = rfl::make_ref(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); + +} +} // namespace test_ref diff --git a/tests/xml/test_ref.hpp b/tests/xml/test_ref.hpp new file mode 100644 index 00000000..d289ba09 --- /dev/null +++ b/tests/xml/test_ref.hpp @@ -0,0 +1,4 @@ +namespace test_ref{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_save_load.cpp b/tests/xml/test_save_load.cpp new file mode 100644 index 00000000..71adfcb3 --- /dev/null +++ b/tests/xml/test_save_load.cpp @@ -0,0 +1,70 @@ +#include "test_save_load.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace test_save_load { + +using Age = rfl::Validator, rfl::Maximum<130>>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com", + .children = std::vector()}; + + const auto lisa = Person{.first_name = "Lisa", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + + const auto maggie = Person{.first_name = "Maggie", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + + const auto homer1 = + Person{.first_name = "Homer", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .children = std::vector({bart, lisa, maggie})}; + + rfl::xml::save("homer.xml", homer1); + + const auto homer2 = rfl::xml::load("homer.xml").value(); + + const auto string1 = rfl::xml::write(homer1); + const auto string2 = rfl::xml::write(homer2); + + if (string1 != string2) { + std::cout << "Test failed. Content was not identical." << std::endl + << std::endl; + return; + } + + std::cout << "OK" << std::endl << std::endl; +} +} // namespace test_save_load diff --git a/tests/xml/test_save_load.hpp b/tests/xml/test_save_load.hpp new file mode 100644 index 00000000..7bf10359 --- /dev/null +++ b/tests/xml/test_save_load.hpp @@ -0,0 +1,4 @@ +namespace test_save_load { +void test(); +} + diff --git a/tests/xml/test_set.cpp b/tests/xml/test_set.cpp new file mode 100644 index 00000000..fa135b37 --- /dev/null +++ b/tests/xml/test_set.cpp @@ -0,0 +1,31 @@ +#include "test_set.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_set { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto children = std::make_unique>( + std::set({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_set diff --git a/tests/xml/test_set.hpp b/tests/xml/test_set.hpp new file mode 100644 index 00000000..142a663b --- /dev/null +++ b/tests/xml/test_set.hpp @@ -0,0 +1,4 @@ +namespace test_set{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_size.cpp b/tests/xml/test_size.cpp new file mode 100644 index 00000000..d3f5d6cf --- /dev/null +++ b/tests/xml/test_size.cpp @@ -0,0 +1,43 @@ +#include "test_size.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_size { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + rfl::Validator, + rfl::Size, rfl::EqualTo<3>>>> + children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{ + .first_name = "Bart", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto lisa = Person{ + .first_name = "Lisa", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto maggie = Person{ + .first_name = "Maggie", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto homer = + Person{.first_name = "Homer", + .last_name = "Simpson", + .birthday = "1987-04-19", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_size diff --git a/tests/xml/test_size.hpp b/tests/xml/test_size.hpp new file mode 100644 index 00000000..be330df0 --- /dev/null +++ b/tests/xml/test_size.hpp @@ -0,0 +1,4 @@ +namespace test_size{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_string_map.cpp b/tests/xml/test_string_map.cpp new file mode 100644 index 00000000..b4cd9e42 --- /dev/null +++ b/tests/xml/test_string_map.cpp @@ -0,0 +1,25 @@ +#include "test_string_map.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_string_map { +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + std::map> homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + write_and_read<"person">(homer); +} +} // namespace test_string_map diff --git a/tests/xml/test_string_map.hpp b/tests/xml/test_string_map.hpp new file mode 100644 index 00000000..94cb975a --- /dev/null +++ b/tests/xml/test_string_map.hpp @@ -0,0 +1,4 @@ +namespace test_string_map{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_tagged_union.cpp b/tests/xml/test_tagged_union.cpp new file mode 100644 index 00000000..21d0e20c --- /dev/null +++ b/tests/xml/test_tagged_union.cpp @@ -0,0 +1,37 @@ +#include "test_tagged_union.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_tagged_union { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read<"root">(r); +} +} // namespace test_tagged_union diff --git a/tests/xml/test_tagged_union.hpp b/tests/xml/test_tagged_union.hpp new file mode 100644 index 00000000..5d522ff9 --- /dev/null +++ b/tests/xml/test_tagged_union.hpp @@ -0,0 +1,4 @@ +namespace test_tagged_union{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_timestamp.cpp b/tests/xml/test_timestamp.cpp new file mode 100644 index 00000000..da643b1e --- /dev/null +++ b/tests/xml/test_timestamp.cpp @@ -0,0 +1,37 @@ +#include "test_timestamp.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_timestamp { + +using TS = rfl::Timestamp<"%Y-%m-%d">; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + TS birthday; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto result = TS::from_string("nonsense"); + + if (result) { + std::cout << "Failed: Expected an error, but got none." << std::endl; + return; + } + + const auto bart = Person{.first_name = "Bart", .birthday = "1987-04-19"}; + + write_and_read(bart); +} +} // namespace test_timestamp diff --git a/tests/xml/test_timestamp.hpp b/tests/xml/test_timestamp.hpp new file mode 100644 index 00000000..891d89b9 --- /dev/null +++ b/tests/xml/test_timestamp.hpp @@ -0,0 +1,4 @@ +namespace test_timestamp{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_unique_ptr.cpp b/tests/xml/test_unique_ptr.cpp new file mode 100644 index 00000000..52c676cb --- /dev/null +++ b/tests/xml/test_unique_ptr.cpp @@ -0,0 +1,34 @@ +#include "test_unique_ptr.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_unique_ptr { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto children = std::make_unique>(); + children->emplace_back(Person{.first_name = "Bart"}); + children->emplace_back(Person{.first_name = "Lisa"}); + children->emplace_back(Person{.first_name = "Maggie"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_unique_ptr diff --git a/tests/xml/test_unique_ptr.hpp b/tests/xml/test_unique_ptr.hpp new file mode 100644 index 00000000..428ea2a2 --- /dev/null +++ b/tests/xml/test_unique_ptr.hpp @@ -0,0 +1,4 @@ +namespace test_unique_ptr{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_unique_ptr2.cpp b/tests/xml/test_unique_ptr2.cpp new file mode 100644 index 00000000..cd91ccb8 --- /dev/null +++ b/tests/xml/test_unique_ptr2.cpp @@ -0,0 +1,49 @@ +#include "test_unique_ptr2.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_unique_ptr2 { + +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + std::unique_ptr lesser; + std::unique_ptr greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + + auto leaf2 = DecisionTree::Leaf{.value = 5.0}; + + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = std::make_unique(DecisionTree{leaf1}), + .greater = std::make_unique(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); +} +} // namespace test_unique_ptr2 diff --git a/tests/xml/test_unique_ptr2.hpp b/tests/xml/test_unique_ptr2.hpp new file mode 100644 index 00000000..74adc170 --- /dev/null +++ b/tests/xml/test_unique_ptr2.hpp @@ -0,0 +1,4 @@ +namespace test_unique_ptr2{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_variant.cpp b/tests/xml/test_variant.cpp new file mode 100644 index 00000000..49b9f041 --- /dev/null +++ b/tests/xml/test_variant.cpp @@ -0,0 +1,37 @@ +#include "test_variant.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_variant { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = std::variant>; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read<"root">(r); +} +} // namespace test_variant diff --git a/tests/xml/test_variant.hpp b/tests/xml/test_variant.hpp new file mode 100644 index 00000000..0e58ce71 --- /dev/null +++ b/tests/xml/test_variant.hpp @@ -0,0 +1,4 @@ +namespace test_variant{ + void test(); +} + \ No newline at end of file diff --git a/tests/xml/test_xml_content.cpp b/tests/xml/test_xml_content.cpp new file mode 100644 index 00000000..be011125 --- /dev/null +++ b/tests/xml/test_xml_content.cpp @@ -0,0 +1,44 @@ +#include "test_xml_content.hpp" + +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_xml_content { + +struct Person { + std::string xml_content; + rfl::Attribute town = "Springfield"; + rfl::Attribute> birthday; + rfl::Attribute email; + std::vector child; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto bart = Person{.xml_content = "Bart Simpson", + .birthday = "1987-04-19", + .email = "bart@simpson.com"}; + + const auto lisa = Person{.xml_content = "Lisa Simpson", + .birthday = "1987-04-19", + .email = "lisa@simpson.com"}; + + const auto maggie = Person{.xml_content = "Maggie Simpson", + .birthday = "1987-04-19", + .email = "maggie@simpson.com"}; + + const auto homer = Person{.xml_content = "Homer Simpson", + .birthday = "1987-04-19", + .email = "homer@simpson.com", + .child = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_xml_content diff --git a/tests/xml/test_xml_content.hpp b/tests/xml/test_xml_content.hpp new file mode 100644 index 00000000..58b774fb --- /dev/null +++ b/tests/xml/test_xml_content.hpp @@ -0,0 +1,4 @@ +namespace test_xml_content { +void test(); +} + diff --git a/tests/xml/tests.cpp b/tests/xml/tests.cpp new file mode 100644 index 00000000..e15a4023 --- /dev/null +++ b/tests/xml/tests.cpp @@ -0,0 +1,67 @@ +#include "test_array.hpp" +#include "test_attributes.hpp" +#include "test_box.hpp" +#include "test_custom_class1.hpp" +#include "test_custom_class3.hpp" +#include "test_custom_class4.hpp" +#include "test_default_values.hpp" +#include "test_deque.hpp" +#include "test_enum.hpp" +#include "test_field_variant.hpp" +#include "test_flag_enum.hpp" +#include "test_flag_enum_with_int.hpp" +#include "test_flatten.hpp" +#include "test_flatten_anonymous.hpp" +#include "test_forward_list.hpp" +#include "test_literal.hpp" +#include "test_literal_map.hpp" +#include "test_map.hpp" +#include "test_map_with_key_validation.hpp" +#include "test_monster_example.hpp" +#include "test_readme_example.hpp" +#include "test_ref.hpp" +#include "test_save_load.hpp" +#include "test_set.hpp" +#include "test_size.hpp" +#include "test_tagged_union.hpp" +#include "test_timestamp.hpp" +#include "test_unique_ptr.hpp" +#include "test_unique_ptr2.hpp" +#include "test_variant.hpp" +#include "test_xml_content.hpp" + +int main() { + test_readme_example::test(); + test_attributes::test(); + test_xml_content::test(); + test_flatten::test(); + test_flatten_anonymous::test(); + test_enum::test(); + test_flag_enum::test(); + test_flag_enum_with_int::test(); + test_map::test(); + test_map_with_key_validation::test(); + test_variant::test(); + test_field_variant::test(); + test_tagged_union::test(); + test_deque::test(); + test_forward_list::test(); + test_literal_map::test(); + test_literal::test(); + test_monster_example::test(); + test_ref::test(); + test_set::test(); + test_size::test(); + test_timestamp::test(); + test_unique_ptr::test(); + test_unique_ptr2::test(); + test_array::test(); + test_box::test(); + test_custom_class1::test(); + test_custom_class3::test(); + test_custom_class4::test(); + test_default_values::test(); + test_save_load::test(); + + return 0; +} diff --git a/tests/xml/write_and_read.hpp b/tests/xml/write_and_read.hpp new file mode 100644 index 00000000..ceb85c8a --- /dev/null +++ b/tests/xml/write_and_read.hpp @@ -0,0 +1,36 @@ +#ifndef WRITE_AND_READ_ +#define WRITE_AND_READ_ + +#include +#include +#include + +#include "rfl/internal/StringLiteral.hpp" + +template < + rfl::internal::StringLiteral _root_name = rfl::internal::StringLiteral(""), + class T> +void write_and_read(const T& _struct) { + const auto xml_string1 = rfl::xml::write<_root_name>(_struct); + const auto res = rfl::xml::read(xml_string1); + if (!res) { + std::cout << "Test failed on read. Error: " << res.error().value().what() + << std::endl + << "Original string: " << xml_string1 << std::endl + << std::endl; + return; + } + const auto xml_string2 = rfl::xml::write<_root_name>(res.value()); + if (xml_string2 != xml_string1) { + std::cout << "Test failed on read. Expected:" << std::endl + << xml_string1 << std::endl + << "Got: " << std::endl + << xml_string2 << std::endl + << std::endl; + return; + } + // std::cout << xml_string1 << std::endl; + std::cout << "OK" << std::endl << std::endl; +} + +#endif diff --git a/vcpkg.json b/vcpkg.json index c2810a64..85839dc5 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -1,15 +1,23 @@ { - "name" : "reflectcpp", - "version-string" : "1.0.0", - "builtin-baseline" : "50bffcc62d7f6571eb32bc1a0b1807e77af1166c", - "dependencies" : [ { - "name" : "vcpkg-cmake-config", - "version>=" : "2022-02-06#1" - }, { - "name" : "vcpkg-cmake", - "version>=" : "2023-05-04" - }, { - "name" : "flatbuffers", - "version>=" : "23.5.26#1" - } ] -} \ No newline at end of file + "name": "reflectcpp", + "version-string": "0.3.0", + "builtin-baseline": "50bffcc62d7f6571eb32bc1a0b1807e77af1166c", + "dependencies": [ + { + "name": "flatbuffers", + "version>=": "23.5.26#1" + }, + { + "name": "pugixml", + "version>=": "1.14" + }, + { + "name": "vcpkg-cmake", + "version>=": "2023-05-04" + }, + { + "name": "vcpkg-cmake-config", + "version>=": "2022-02-06#1" + } + ] +}