Merge branch 'main' of github.com:getml/reflect-cpp

This commit is contained in:
Patrick Urbanke
2023-11-08 21:32:44 +01:00
15 changed files with 1583 additions and 33 deletions
+100 -4
View File
@@ -25,6 +25,8 @@ Design principles for reflect-cpp include:
- Simple extendability to custom classes
- No macros
## Example
```cpp
#include <iostream>
#include <rfl/json.hpp>
@@ -32,7 +34,7 @@ Design principles for reflect-cpp include:
// Age must be a plausible number, between 0 and 130. This will
// be validated automatically.
using Age = rfl::Validator<unsigned int,
using Age = rfl::Validator<int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
// "firstName", "lastName" and "children" are the field names
@@ -107,6 +109,8 @@ std::cout << "Hello, my name is " << homer2.first_name() << " "
<< homer2.last_name() << "." << std::endl;
```
## Error messages
reflect-cpp returns clear and comprehensive error messages:
```cpp
@@ -126,6 +130,96 @@ Found 5 errors:
5) Field named 'children' not found.
```
## Anonymous fields
`rfl::Field` is only necessary if you want to serialize field names. If you don't (possibly because you are using a binary format), you do not need to annotate your fields:
```cpp
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
std::string first_name;
std::string last_name;
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
std::vector<Person> children;
};
const auto bart = Person{.first_name = "Bart",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"};
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 homer =
Person{.first_name = "Homer",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com",
.children = std::vector<Person>({bart, lisa, maggie})};
```
This results in the following JSON string:
```json
["Homer","Simpson","1987-04-19",45,"homer@simpson.com",[["Bart","Simpson","1987-04-19",10,"bart@simpson.com",[]],["Lisa","Simpson","1987-04-19",8,"lisa@simpson.com",[]],["Maggie","Simpson","1987-04-19",0,"maggie@simpson.com",[]]]]
```
## Algebraic data types
reflect-cpp supports Pydantic-style tagged unions, which allow you to form algebraic data types:
```cpp
// All alternatives must contain a field named "shape". The type
// of the field must be an rfl::Literal.
struct Circle {
rfl::Field<"shape", rfl::Literal<"Circle">> shape = rfl::default_value;
rfl::Field<"radius", double> radius;
};
struct Rectangle {
rfl::Field<"shape", rfl::Literal<"Rectangle">> shape =
rfl::default_value;
rfl::Field<"height", double> height;
rfl::Field<"width", double> width;
};
struct Square {
rfl::Field<"shape", rfl::Literal<"Square">> shape = rfl::default_value;
rfl::Field<"width", double> width;
};
// Now you tell rfl::TaggedUnion that you want it to look for the field "shape".
using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>;
const Shapes r = Rectangle{.height = 10, .width = 5};
const auto json_string = rfl::json::write(r);
```
This results in the following JSON string:
```json
{"shape":"Rectangle","height":10.0,"width":5.0}
```
Other forms of tagging are supported as well. Refer to the [documentation](https://github.com/getml/reflect-cpp/tree/main/docs) for details.
## Support for containers
### C++ standard library
@@ -155,13 +249,15 @@ reflect-cpp supports the following containers from the C++ standard library:
### Additional containers
In addition, it includes the following custom containers:
In addition, it supports the following custom containers:
- `rfl::Box`: Similar to `std::unique_ptr`, but guaranteed to never be null.
- `rfl::Box`: Similar to `std::unique_ptr`, but (almost) guaranteed to never be null.
- `rfl::Literal`: An explicitly enumerated string.
- `rfl::NamedTuple`: Similar to `std::tuple`, but with named fields that can be retrieved via their name at compile time.
- `rfl::Ref`: Similar to `std::shared_ptr`, but guaranteed to never be null.
- `rfl::Ref`: Similar to `std::shared_ptr`, but (almost) guaranteed to never be null.
- `rfl::Result`: Allows for exception-free programming.
- `rfl::TaggedUnion`: Similar to `std::variant`, but with explicit tags that make parsing more efficient.
- `rfl::Validator`: Allows for automatic input validation.
### Custom classes
+8 -6
View File
@@ -10,17 +10,19 @@
1.3) [Struct flattening](https://github.com/getml/reflect-cpp/blob/main/docs/flatten_structs.md) - For making struct A "inherit" the fields of struct B.
1.4) [String literals](https://github.com/getml/reflect-cpp/blob/main/docs/literals.md) - For representing strings that can only assume a limited number of enumerated values.
1.4) [Anonymous fields](https://github.com/getml/reflect-cpp/blob/f/anonymous_structs/docs/anonymous_fields.md) - For structs without field names or `rfl::Field`.
1.5) [std::variant and rfl::TaggedUnion](https://github.com/getml/reflect-cpp/blob/main/docs/variants_and_tagged_unions.md) - For structs that can be one of several formats. This is the equivalent of an OR statement or a sum type in type theory.
1.5) [String literals](https://github.com/getml/reflect-cpp/blob/main/docs/literals.md) - For representing strings that can only assume a limited number of enumerated values.
1.6) [rfl::Box and rfl::Ref](https://github.com/getml/reflect-cpp/blob/main/docs/rfl_ref.md) - For defining recursive structures.
1.6) [std::variant and rfl::TaggedUnion](https://github.com/getml/reflect-cpp/blob/main/docs/variants_and_tagged_unions.md) - For structs that can be one of several formats. This is the equivalent of an OR statement or a sum type in type theory.
1.7) [rfl::Timestamp](https://github.com/getml/reflect-cpp/blob/main/docs/timestamps.md) - For serializing and deserializing timestamps.
1.7) [rfl::Box and rfl::Ref](https://github.com/getml/reflect-cpp/blob/main/docs/rfl_ref.md) - For defining recursive structures.
1.8) [rfl::Result](https://github.com/getml/reflect-cpp/blob/main/docs/result.md) - For error handling without exceptions.
1.8) [rfl::Timestamp](https://github.com/getml/reflect-cpp/blob/main/docs/timestamps.md) - For serializing and deserializing timestamps.
1.9) [Standard containers](https://github.com/getml/reflect-cpp/blob/main/docs/standard_containers.md) - Describes how reflect-cpp treats containers in the standard library.
1.9) [rfl::Result](https://github.com/getml/reflect-cpp/blob/main/docs/result.md) - For error handling without exceptions.
1.10) [Standard containers](https://github.com/getml/reflect-cpp/blob/main/docs/standard_containers.md) - Describes how reflect-cpp treats containers in the standard library.
## 2) Validation
+20
View File
@@ -0,0 +1,20 @@
# Anonymous fields
If you do not want to serialize field names, you do not have to use `rfl::Field`. You can just write your struct like this:
```cpp
struct Person {
std::string first_name;
std::string last_name;
std::vector<Person> children;
};
```
This is referred to as anonymous fields. It is particularly relevant if you are using a binary format.
This can be fully serialized and deserialized using `rfl::json::read` and `rfl::json::write`. No further annotations are needed.
However, there are a two things you have to keep in mind:
1) If you annotate *some* of the fields using either `rfl::Field` or `rfl::Flatten`, then you must annotate *all* of them using one of these two.
2) If you are combining structs using `rfl::Flatten`, then all fields in all structs must be annotated using either using either `rfl::Field` or `rfl::Flatten`.
+26 -2
View File
@@ -6,6 +6,7 @@
#include <regex>
#include <string>
#include <type_traits>
#include <utility>
#include "internal/HasValidation.hpp"
#include "internal/StringLiteral.hpp"
@@ -30,8 +31,19 @@ struct Validator {
Validator() : value_(V::validate(T()).value()) {}
Validator(Validator<T, V>&& _other) noexcept = default;
Validator(const Validator<T, V>& _other) = default;
Validator(T&& _value) : value_(V::validate(_value).value()) {}
Validator(const T& _value) : value_(V::validate(_value).value()) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Validator(U&& _value)
: value_(V::validate(T(std::forward<U>(_value))).value()) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
Validator(const U& _value) : value_(V::validate(T(_value)).value()) {}
@@ -44,11 +56,23 @@ struct Validator {
return *this;
}
/// Assigns the underlying object.
auto& operator=(T&& _value) {
value_ = V::validate(std::forward<T>(_value)).value();
return *this;
}
/// Assigns the underlying object.
Validator<T, V>& operator=(const Validator<T, V>& _other) = default;
/// Assigns the underlying object.
Validator<T, V>& operator=(Validator<T, V>&& _other) noexcept = default;
/// Assigns the underlying object.
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
auto& operator=(U&& _value) {
value_ = V::validate(T(std::forward<T>(_value))).value();
auto& operator=(U&& _value) noexcept {
value_ = V::validate(T(std::forward<U>(_value))).value();
return *this;
}
+65
View File
@@ -0,0 +1,65 @@
#ifndef RFL_INTERNAL_HASFIELDS_HPP_
#define RFL_INTERNAL_HASFIELDS_HPP_
#include <tuple>
#include <type_traits>
#include <utility>
#include "rfl/internal/is_field.hpp"
#include "rfl/internal/is_flatten_field.hpp"
#include "rfl/internal/ptr_tuple_t.hpp"
namespace rfl {
namespace internal {
template <class TupleType, int _i = 0>
constexpr bool all_fields_or_flatten() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return true;
} else {
using T = std::decay_t<std::tuple_element_t<_i, TupleType>>;
if constexpr (is_flatten_field_v<T>) {
return all_fields_or_flatten<
ptr_tuple_t<typename std::remove_pointer_t<T>::Type>>() &&
all_fields_or_flatten<TupleType, _i + 1>();
} else {
return is_field_v<T> && all_fields_or_flatten<TupleType, _i + 1>();
}
}
}
template <class TupleType, int _i = 0>
constexpr bool has_some_fields_or_flatten() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return false;
} else {
using T = std::decay_t<std::tuple_element_t<_i, TupleType>>;
return is_field_v<T> || is_flatten_field_v<T> ||
has_some_fields_or_flatten<TupleType, _i + 1>();
}
}
template <class T>
constexpr bool has_fields() {
if constexpr (is_named_tuple_v<T>) {
return true;
} else {
using TupleType = ptr_tuple_t<T>;
if constexpr (has_some_fields_or_flatten<TupleType>()) {
static_assert(
all_fields_or_flatten<TupleType>(),
"If some of your fields are annotated using rfl::Field<...> or "
"rfl::Flatten, then you must annotate all of your fields. "
"Also, you cannot combine annotated and "
"unannotated fields using rfl::Flatten<...>.");
return true;
} else {
return false;
}
}
}
} // namespace internal
} // namespace rfl
#endif
+6 -7
View File
@@ -12,13 +12,12 @@ namespace internal {
template <class TupleType, int _i = 0>
constexpr bool has_flatten_fields() {
if constexpr (_i == std::tuple_size_v<TupleType>) {
return false;
} else {
using T = std::decay_t<std::tuple_element_t<_i, TupleType>>;
return is_flatten_field<T>::value ||
has_flatten_fields<TupleType, _i + 1>();
}
if constexpr (_i == std::tuple_size_v<TupleType>) {
return false;
} else {
using T = std::decay_t<std::tuple_element_t<_i, TupleType>>;
return is_flatten_field_v<T> || has_flatten_fields<TupleType, _i + 1>();
}
}
} // namespace internal
+6
View File
@@ -20,6 +20,12 @@ class is_field : public std::false_type {};
template <StringLiteral _name, class Type>
class is_field<Field<_name, Type>> : public std::true_type {};
template <StringLiteral _name, class Type>
class is_field<Field<_name, Type>*> : public std::true_type {};
template <StringLiteral _name, class Type>
class is_field<const Field<_name, Type>*> : public std::true_type {};
template <class T>
constexpr bool is_field_v = is_field<T>::value;
@@ -19,6 +19,12 @@ class is_flatten_field : public std::false_type {};
template <class T>
class is_flatten_field<Flatten<T>> : public std::true_type {};
template <class T>
class is_flatten_field<Flatten<T>*> : public std::true_type {};
template <class T>
class is_flatten_field<const Flatten<T>*> : public std::true_type {};
template <class T>
constexpr bool is_flatten_field_v = is_flatten_field<T>::value;
+87
View File
@@ -0,0 +1,87 @@
#ifndef RFL_MOVE_FROM_TUPLE_HPP_
#define RFL_MOVE_FROM_TUPLE_HPP_
#include <functional>
#include <type_traits>
#include "rfl/internal/is_field.hpp"
#include "rfl/internal/is_named_tuple.hpp"
#include "rfl/internal/nt_to_ptr_named_tuple.hpp"
#include "rfl/internal/ptr_tuple_t.hpp"
#include "rfl/named_tuple_t.hpp"
namespace rfl {
namespace internal {
template <class PtrTupleType, class FlattenedPtrTupleType, class... Args>
auto unflatten_pointers(FlattenedPtrTupleType& _n, Args... _args) {
constexpr auto i = sizeof...(Args);
constexpr auto size = std::tuple_size_v<std::decay_t<PtrTupleType>>;
if constexpr (i == size) {
return std::make_tuple(_args...);
} else {
using Field = std::decay_t<std::tuple_element_t<i, PtrTupleType>>;
using T = std::decay_t<std::remove_pointer_t<typename Field::Type>>;
if constexpr (is_flatten_field<Field>::value) {
using SubPtrTupleType = std::decay_t<ptr_tuple_t<T>>;
return unflatten_pointers<PtrTupleType>(
_n, _args..., unflatten_pointers<SubPtrTupleType>(_n));
} else {
return unflatten_pointers<PtrTupleType>(
_n, _args..., _n.template get_field<Field::name_>());
}
}
}
template <class T, int _j, class Pointers, class... Args>
auto move_from_flattened_pointers(Pointers& _ptrs, Args&&... _args) {
constexpr auto i = sizeof...(Args);
if constexpr (i == std::tuple_size_v<std::decay_t<Pointers>>) {
return T{std::move(_args)...};
} else {
if constexpr (!is_flatten_field_v<FieldType>) {
return move_from_flattened_pointers<T, _j + 1>(
_ptrs, std::move(_args)..., std::move(*std::get<_j>(_ptrs)));
} else {
// TODO
/*using PtrTupleType = std::decay_t<unflattened_ptr_tuple_t<T>>;
using U = std::decay_t<
std::remove_pointer_t<std::tuple_element_t<i, PtrTupleType>>>;
return move_from_pointers<T>(_ptrs, std::move(_args)...,
move_from_pointers<U>(std::get<i>(_ptrs)));*/
}
}
}
/// Creates a struct of type T from a named tuple by moving the underlying
/// fields.
template <class T, class TupleType>
T move_from_tuple(TupleType&& _n) {
using RequiredType = std::decay_t<tuple_t<T>>;
if constexpr (is_named_tuple_v<std::decay_t<T>>) {
return std::move(_n);
} else {
auto flattened_ptr_tuple = tuple_to_ptr_tuple(_n);
using PtrTupleType = std::decay_t<unflattened_ptr_tuple_t<T>>;
auto pointers = make_pointers<PtrTupleType>(flattened_ptr_tuple);
return move_from_flattened_pointers<T, 0>(pointers);
}
}
} // namespace internal
} // namespace rfl
#endif
+19
View File
@@ -0,0 +1,19 @@
#ifndef RFL_INTERNAL_PTR_TUPLE_T_HPP_
#define RFL_INTERNAL_PTR_TUPLE_T_HPP_
#include <functional>
#include <type_traits>
#include "rfl/internal/to_ptr_tuple.hpp"
namespace rfl {
namespace internal {
template <class T>
using ptr_tuple_t =
typename std::invoke_result<decltype(to_ptr_tuple<T>), T>::type;
} // namespace internal
} // namespace rfl
#endif
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
#ifndef RFL_INTERNAL_TUPLE_T_HPP_
#define RFL_INTERNAL_TUPLE_T_HPP_
#include <functional>
#include <tuple>
#include <type_traits>
#include "rfl/internal/ptr_tuple_t.hpp"
#include "rfl/to_named_tuple.hpp"
namespace rfl {
namespace internal {
template <class T>
struct remove_ptrs_tup;
template <class... Ts>
struct remove_ptrs_tup<std::tuple<Ts...>> {
using TupleType = std::tuple<std::remove_pointer_t<Ts>...>;
};
template <class T>
using tuple_t = typename remove_ptrs_tup<ptr_tuple_t<T>>::TupleType;
} // namespace internal
} // namespace rfl
#endif
+34 -14
View File
@@ -32,11 +32,14 @@
#include "rfl/internal/Memoization.hpp"
#include "rfl/internal/StringLiteral.hpp"
#include "rfl/internal/all_fields.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/is_basic_type.hpp"
#include "rfl/internal/no_duplicate_field_names.hpp"
#include "rfl/internal/to_ptr_named_tuple.hpp"
#include "rfl/internal/to_ptr_tuple.hpp"
#include "rfl/internal/tuple_t.hpp"
#include "rfl/named_tuple_t.hpp"
#include "rfl/parsing/AreReaderAndWriter.hpp"
#include "rfl/parsing/is_forward_list.hpp"
@@ -79,15 +82,27 @@ struct Parser {
};
return Parser<R, W, ReflectionType>::read(_r, _var).and_then(wrap_in_t);
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
using NamedTupleType = named_tuple_t<T>;
const auto to_struct = [](NamedTupleType&& _n) -> Result<T> {
try {
return from_named_tuple<T>(std::move(_n));
} catch (std::exception& e) {
return Error(e.what());
}
};
return Parser<R, W, NamedTupleType>::read(_r, _var).and_then(to_struct);
if constexpr (internal::has_fields<T>()) {
using NamedTupleType = named_tuple_t<T>;
const auto to_struct = [](NamedTupleType&& _n) -> Result<T> {
try {
return from_named_tuple<T>(std::move(_n));
} catch (std::exception& e) {
return Error(e.what());
}
};
return Parser<R, W, NamedTupleType>::read(_r, _var).and_then(
to_struct);
} else {
using TupleType = internal::tuple_t<T>;
const auto make_t = [](auto&&... _f) -> T {
return T{std::move(_f)...};
};
const auto to_struct = [&](TupleType&& _tup) -> T {
return std::apply(make_t, std::move(_tup));
};
return Parser<R, W, TupleType>::read(_r, _var).transform(to_struct);
}
} else if constexpr (internal::is_basic_type_v<T>) {
return _r.template to_basic_type<std::decay_t<T>>(_var);
} else {
@@ -110,11 +125,16 @@ struct Parser {
const auto& [r] = _var;
return Parser<R, W, ReflectionType>::write(_w, r);
}
} else if constexpr (std::is_class_v<T> &&
!std::is_same<T, std::string>()) {
const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var);
using PtrNamedTupleType = std::decay_t<decltype(ptr_named_tuple)>;
return Parser<R, W, PtrNamedTupleType>::write(_w, ptr_named_tuple);
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
if constexpr (internal::has_fields<T>()) {
const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var);
using PtrNamedTupleType = std::decay_t<decltype(ptr_named_tuple)>;
return Parser<R, W, PtrNamedTupleType>::write(_w, ptr_named_tuple);
} else {
const auto ptr_tuple = internal::to_ptr_tuple(_var);
using PtrTupleType = std::decay_t<decltype(ptr_tuple)>;
return Parser<R, W, PtrTupleType>::write(_w, ptr_tuple);
}
} else if constexpr (internal::is_basic_type_v<T>) {
return _w.from_basic_type(_var);
} else {
+53
View File
@@ -0,0 +1,53 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_anonymous_fields() {
std::cout << "test_anonymous_fields" << std::endl;
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
std::string first_name;
std::string last_name;
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
std::vector<Person> children;
};
const auto bart = Person{.first_name = "Bart",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"};
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 homer =
Person{.first_name = "Homer",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com",
.children = std::vector<Person>({bart, lisa, maggie})};
write_and_read(
homer,
R"(["Homer","Simpson","1987-04-19",45,"homer@simpson.com",[["Bart","Simpson","1987-04-19",10,"bart@simpson.com",[]],["Lisa","Simpson","1987-04-19",8,"lisa@simpson.com",[]],["Maggie","Simpson","1987-04-19",0,"maggie@simpson.com",[]]]])");
}
+2
View File
@@ -1,4 +1,5 @@
#include "test_all_of.hpp"
#include "test_anonymous_fields.hpp"
#include "test_any_of.hpp"
#include "test_array.hpp"
#include "test_as.hpp"
@@ -73,6 +74,7 @@ int main() {
test_string_unordered_map();
test_error_messages();
test_result();
test_anonymous_fields();
test_custom_class1();
test_custom_class2();