From d1a9bc6b617b8da03ce9174eb2606aa1dc603df3 Mon Sep 17 00:00:00 2001 From: Patrick Urbanke Date: Sun, 3 Mar 2024 07:09:28 +0100 Subject: [PATCH] Added the JSON schema; #25 --- include/rfl.hpp | 1 + include/rfl/AllOf.hpp | 11 + include/rfl/AnyOf.hpp | 9 + include/rfl/Description.hpp | 150 ++++++++++ include/rfl/Field.hpp | 6 +- include/rfl/Literal.hpp | 28 +- include/rfl/NamedTuple.hpp | 40 +-- include/rfl/OneOf.hpp | 9 + include/rfl/PatternValidator.hpp | 16 +- include/rfl/Rename.hpp | 3 +- include/rfl/Size.hpp | 10 + include/rfl/Validator.hpp | 25 +- include/rfl/comparisons.hpp | 63 +++++ .../rfl/internal/enums/StringConverter.hpp | 6 +- include/rfl/internal/get_field_names.hpp | 1 + include/rfl/internal/is_attribute.hpp | 9 +- include/rfl/internal/is_description.hpp | 30 ++ include/rfl/internal/is_field.hpp | 9 +- include/rfl/internal/is_flatten_field.hpp | 9 +- include/rfl/internal/is_literal.hpp | 28 ++ include/rfl/internal/is_named_tuple.hpp | 3 +- include/rfl/internal/is_pattern.hpp | 28 ++ include/rfl/internal/is_rename.hpp | 9 +- include/rfl/internal/is_validator.hpp | 28 ++ include/rfl/internal/is_variant.hpp | 26 ++ include/rfl/internal/num_fields.hpp | 10 + include/rfl/json.hpp | 1 + include/rfl/json/save.hpp | 2 + include/rfl/json/schema/JSONSchema.hpp | 25 ++ include/rfl/json/schema/Type.hpp | 147 ++++++++++ include/rfl/json/to_schema.hpp | 260 ++++++++++++++++++ include/rfl/parsing/FieldVariantParser.hpp | 9 + include/rfl/parsing/MapParser.hpp | 9 + include/rfl/parsing/NamedTupleParser.hpp | 19 ++ include/rfl/parsing/Parser.hpp | 1 + include/rfl/parsing/Parser_array.hpp | 12 + include/rfl/parsing/Parser_box.hpp | 7 + include/rfl/parsing/Parser_c_array.hpp | 8 + include/rfl/parsing/Parser_default.hpp | 128 +++++++++ include/rfl/parsing/Parser_optional.hpp | 10 + include/rfl/parsing/Parser_pair.hpp | 8 + include/rfl/parsing/Parser_ptr.hpp | 8 + include/rfl/parsing/Parser_ref.hpp | 7 + .../rfl/parsing/Parser_reference_wrapper.hpp | 7 + include/rfl/parsing/Parser_rename.hpp | 7 + include/rfl/parsing/Parser_result.hpp | 7 + include/rfl/parsing/Parser_rfl_array.hpp | 7 + include/rfl/parsing/Parser_rfl_variant.hpp | 7 + include/rfl/parsing/Parser_shared_ptr.hpp | 14 +- include/rfl/parsing/Parser_string_view.hpp | 47 ++++ include/rfl/parsing/Parser_tagged_union.hpp | 29 +- include/rfl/parsing/Parser_unique_ptr.hpp | 10 + include/rfl/parsing/Parser_variant.hpp | 22 ++ include/rfl/parsing/Parser_wstring.hpp | 9 +- include/rfl/parsing/TaggedUnionWrapper.hpp | 2 + include/rfl/parsing/TupleParser.hpp | 22 +- include/rfl/parsing/VectorParser.hpp | 10 + .../rfl/parsing/is_tagged_union_wrapper.hpp | 34 +++ include/rfl/parsing/schema/Definition.hpp | 21 ++ include/rfl/parsing/schema/Type.hpp | 98 +++++++ include/rfl/parsing/schema/ValidationType.hpp | 69 +++++ include/rfl/parsing/schema/make.hpp | 21 ++ .../rfl/parsing/schema/to_numeric_type.hpp | 43 +++ tests/json/test_json_schema.cpp | 81 ++++++ tests/json/test_json_schema.hpp | 4 + tests/json/tests.cpp | 2 + 66 files changed, 1715 insertions(+), 86 deletions(-) create mode 100644 include/rfl/Description.hpp create mode 100644 include/rfl/internal/is_description.hpp create mode 100644 include/rfl/internal/is_literal.hpp create mode 100644 include/rfl/internal/is_pattern.hpp create mode 100644 include/rfl/internal/is_validator.hpp create mode 100644 include/rfl/internal/is_variant.hpp create mode 100644 include/rfl/json/schema/JSONSchema.hpp create mode 100644 include/rfl/json/schema/Type.hpp create mode 100644 include/rfl/json/to_schema.hpp create mode 100644 include/rfl/parsing/Parser_string_view.hpp create mode 100644 include/rfl/parsing/is_tagged_union_wrapper.hpp create mode 100644 include/rfl/parsing/schema/Definition.hpp create mode 100644 include/rfl/parsing/schema/Type.hpp create mode 100644 include/rfl/parsing/schema/ValidationType.hpp create mode 100644 include/rfl/parsing/schema/make.hpp create mode 100644 include/rfl/parsing/schema/to_numeric_type.hpp create mode 100644 tests/json/test_json_schema.cpp create mode 100644 tests/json/test_json_schema.hpp diff --git a/include/rfl.hpp b/include/rfl.hpp index de895b87..183f2c70 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -11,6 +11,7 @@ #include "rfl/AnyOf.hpp" #include "rfl/Attribute.hpp" #include "rfl/Box.hpp" +#include "rfl/Description.hpp" #include "rfl/Field.hpp" #include "rfl/Flatten.hpp" #include "rfl/Literal.hpp" diff --git a/include/rfl/AllOf.hpp b/include/rfl/AllOf.hpp index c8ec2a30..9cd2ec03 100644 --- a/include/rfl/AllOf.hpp +++ b/include/rfl/AllOf.hpp @@ -1,7 +1,10 @@ #ifndef RFL_ALLOF_HPP_ #define RFL_ALLOF_HPP_ +#include + #include "Result.hpp" +#include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -13,6 +16,14 @@ struct AllOf { return validate_impl(_value); } + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto types = std::vector( + {C::template to_schema(), Cs::template to_schema()...}); + return ValidationType{ValidationType::AllOf{.types_ = types}}; + } + private: template static rfl::Result validate_impl(T _value) noexcept { diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index d0a344dd..1baa15a1 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -6,6 +6,7 @@ #include #include "Result.hpp" +#include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -17,6 +18,14 @@ struct AnyOf { return validate_impl(_value, {}); } + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto types = std::vector( + {C::template to_schema(), Cs::template to_schema()...}); + return ValidationType{ValidationType::AnyOf{.types_ = types}}; + } + private: static Error make_error_message(const std::vector& _errors) { std::string msg = diff --git a/include/rfl/Description.hpp b/include/rfl/Description.hpp new file mode 100644 index 00000000..64ad2c0d --- /dev/null +++ b/include/rfl/Description.hpp @@ -0,0 +1,150 @@ +#ifndef RFL_DESCRIPTION_HPP_ +#define RFL_DESCRIPTION_HPP_ + +#include +#include +#include +#include +#include + +#include "Literal.hpp" +#include "default.hpp" +#include "internal/StringLiteral.hpp" + +namespace rfl { + +/// Used to add a description to the field - this is only relevant for the JSON +/// schema and will be ignored by the normal serialization routines. +template +struct Description { + /// The underlying type. + using Type = T; + + /// The description of the field. + using Content = rfl::Literal<_description>; + + using ReflectionType = Type; + + Description() : value_(Type()) {} + + Description(const Type& _value) : value_(_value) {} + + Description(Type&& _value) noexcept : value_(std::move(_value)) {} + + Description(Description<_description, T>&& _field) noexcept = default; + + Description(const Description<_description, Type>& _field) = default; + + template + Description(const Description<_description, U>& _field) + : value_(_field.get()) {} + + template + Description(Description<_description, U>&& _field) : value_(_field.get()) {} + + template , + bool>::type = true> + Description(const U& _value) : value_(_value) {} + + template , + bool>::type = true> + Description(U&& _value) noexcept : value_(std::forward(_value)) {} + + template , + bool>::type = true> + Description(const Description<_description, U>& _field) + : value_(_field.value()) {} + + /// Assigns the underlying object to its default value. + template , + bool>::type = true> + Description(const Default& _default) : value_(Type()) {} + + ~Description() = default; + + /// The description of the field, for internal use. + constexpr static const internal::StringLiteral description_ = _description; + + /// 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. + Description<_description, T>& operator=( + const Description<_description, T>& _field) = default; + + /// Assigns the underlying object. + Description<_description, T>& operator=( + Description<_description, T>&& _field) = default; + + /// Assigns the underlying object. + template + auto& operator=(const Description<_description, U>& _field) { + value_ = _field.get(); + return *this; + } + + /// Assigns the underlying object. + template + auto& operator=(Description<_description, U>&& _field) { + value_ = std::forward(_field.value_); + return *this; + } + + /// Returns the underlying object - necessary for the reflection to work. + const Type& 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/Field.hpp b/include/rfl/Field.hpp index 720b6de2..cd971a06 100644 --- a/include/rfl/Field.hpp +++ b/include/rfl/Field.hpp @@ -62,12 +62,12 @@ struct Field { /// The name of the field, for internal use. constexpr static const internal::StringLiteral name_ = _name; - /// The name of the field. - constexpr static std::string_view name() { return name_.string_view(); } - /// Returns the underlying object. const Type& get() const { return value_; } + /// The name of the field. + constexpr static std::string_view name() { return name_.string_view(); } + /// Returns the underlying object. Type& operator()() { return value_; } diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 074c4598..e772a1b7 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -134,6 +134,9 @@ class Literal { /// The name defined by the Literal. std::string name() const { return find_name(); } + /// Returns all possible values of the literal as a std::vector. + static std::vector names() { return allowed_strings_vec(); } + /// Helper function to retrieve a name at compile time. template constexpr static auto name_of() { @@ -168,6 +171,9 @@ class Literal { /// Alias for .name(). std::string str() const { return name(); } + /// Alias for .names(). + static std::vector strings() { return allowed_strings_vec(); } + /// Returns the value actually contained in the Literal. ValueType value() const { return value_; } @@ -183,16 +189,28 @@ class Literal { /// Only the static methods are allowed to access this. Literal(const ValueType _value) : value_(_value) {} + /// Returns all of the allowed fields. + static std::string allowed_strings() { + const auto vec = allowed_strings_vec(); + std::string str; + for (size_t i = 0; i < vec.size(); ++i) { + const auto head = "'" + vec[i] + "'"; + str += i == 0 ? head : (", " + head); + } + return str; + } + /// Returns all of the allowed fields. template - static std::string allowed_strings(const std::string& _values = "") { + static std::vector allowed_strings_vec( + std::vector _values = {}) { using FieldType = typename std::tuple_element<_i, FieldsType>::type; - const auto head = "'" + FieldType::field_.str() + "'"; - const auto values = _values.size() == 0 ? head : _values + ", " + head; + const auto head = FieldType::field_.str(); + _values.push_back(head); if constexpr (_i + 1 < num_fields_) { - return allowed_strings<_i + 1>(values); + return allowed_strings_vec<_i + 1>(std::move(_values)); } else { - return values; + return _values; } } diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 0927827a..e5e77cc2 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -162,6 +162,26 @@ class NamedTuple { std::forward(_tail)...); } + /// Invokes a callable object once for each field in order. + template + void apply(F&& f) { + std::apply( + [&f](AFields&&... fields) { + ((f(std::forward(fields))), ...); + }, + fields()); + } + + /// Invokes a callable object once for each field in order. + template + void apply(F&& f) const { + std::apply( + [&f](AFields&&... fields) { + ((f(std::forward(fields))), ...); + }, + fields()); + } + /// Returns a tuple containing the fields. Fields fields() { return make_fields(); } @@ -210,26 +230,6 @@ class NamedTuple { return rfl::make_field<_field_name>(rfl::get<_field_name>(*this)); } - /// Invokes a callable object once for each field in order. - template - void apply(F&& f) { - std::apply( - [&f](AFields&&... fields) { - ((f(std::forward(fields))), ...); - }, - fields()); - } - - /// Invokes a callable object once for each field in order. - template - void apply(F&& f) const { - std::apply( - [&f](AFields&&... fields) { - ((f(std::forward(fields))), ...); - }, - fields()); - } - /// Copy assignment operator. NamedTuple& operator=( const NamedTuple& _other) = default; diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index 8e30922f..8f7aafd5 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -6,6 +6,7 @@ #include #include "Result.hpp" +#include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -17,6 +18,14 @@ struct OneOf { return validate_impl(_value, {}); } + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto types = std::vector( + {C::template to_schema(), Cs::template to_schema()...}); + return ValidationType{ValidationType::OneOf{.types_ = types}}; + } + private: static Error make_error_message(const std::vector& _errors) { std::string msg = "Expected exactly 1 out of " + diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index 892e08eb..18af3b53 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -4,19 +4,31 @@ #include #include "../ctre.hpp" +#include "Literal.hpp" #include "Result.hpp" #include "internal/StringLiteral.hpp" +#include "parsing/schema/ValidationType.hpp" namespace rfl { template struct PatternValidator { + using Name = Literal<_name>; + using Regex = Literal<_regex>; + static Result validate(const std::string& _str) noexcept { - if (ctre::match<_regex.arr_>(_str)) + if (ctre::match<_regex.arr_>(_str)) { return _str; - else + } else { return rfl::Error("String '" + _str + "' did not match format '" + _name.str() + "': '" + _regex.str() + "'."); + } + } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + return ValidationType{ValidationType::Regex{.pattern_ = Regex().str()}}; } }; diff --git a/include/rfl/Rename.hpp b/include/rfl/Rename.hpp index 66d69e8b..b02c95db 100644 --- a/include/rfl/Rename.hpp +++ b/include/rfl/Rename.hpp @@ -13,7 +13,8 @@ namespace rfl { -/// Used to define a field in the NamedTuple. +/// Used to assign a new name to a field, which is different from the name +/// inside the struct. template struct Rename { /// The underlying type. diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index dd0d3328..4070e70c 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -1,7 +1,12 @@ #ifndef RFL_SIZE_HPP_ #define RFL_SIZE_HPP_ +#include + +#include "Ref.hpp" #include "Result.hpp" +#include "parsing/Parser.hpp" +#include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -15,6 +20,11 @@ struct Size { }; return V::validate(_t.size()).transform(to_t).or_else(embellish_error); } + + template + static parsing::schema::ValidationType to_schema() { + return V::template to_schema(); + } }; } // namespace rfl diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 34cd4687..80c2d823 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -19,11 +19,10 @@ namespace rfl { template requires internal::HasValidation, T> struct Validator { - private: - using AllOfVs = std::conditional_t>; - public: using ReflectionType = T; + using ValidationType = + std::conditional_t>; /// Exception-free validation. static Result> from_value(const T& _value) noexcept { @@ -34,36 +33,38 @@ struct Validator { } } - Validator() : value_(AllOfVs::validate(T()).value()) {} + Validator() : value_(ValidationType::validate(T()).value()) {} Validator(Validator&& _other) noexcept = default; Validator(const Validator& _other) = default; - Validator(T&& _value) : value_(AllOfVs::validate(_value).value()) {} + Validator(T&& _value) : value_(ValidationType::validate(_value).value()) {} - Validator(const T& _value) : value_(AllOfVs::validate(_value).value()) {} + Validator(const T& _value) + : value_(ValidationType::validate(_value).value()) {} template , bool>::type = true> Validator(U&& _value) - : value_(AllOfVs::validate(T(std::forward(_value))).value()) {} + : value_(ValidationType::validate(T(std::forward(_value))).value()) {} template , bool>::type = true> - Validator(const U& _value) : value_(AllOfVs::validate(T(_value)).value()) {} + Validator(const U& _value) + : value_(ValidationType::validate(T(_value)).value()) {} ~Validator() = default; /// Assigns the underlying object. auto& operator=(const T& _value) { - value_ = AllOfVs::validate(_value).value(); + value_ = ValidationType::validate(_value).value(); return *this; } /// Assigns the underlying object. auto& operator=(T&& _value) { - value_ = AllOfVs::validate(std::forward(_value)).value(); + value_ = ValidationType::validate(std::forward(_value)).value(); return *this; } @@ -79,7 +80,7 @@ struct Validator { template , bool>::type = true> auto& operator=(U&& _value) noexcept { - value_ = AllOfVs::validate(T(std::forward(_value))).value(); + value_ = ValidationType::validate(T(std::forward(_value))).value(); return *this; } @@ -87,7 +88,7 @@ struct Validator { template , bool>::type = true> auto& operator=(const U& _value) { - value_ = AllOfVs::validate(T(_value)).value(); + value_ = ValidationType::validate(T(_value)).value(); return *this; } diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 38e3a524..7f7367fc 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -1,7 +1,10 @@ #ifndef RFL_COMPARISONS_HPP_ #define RFL_COMPARISONS_HPP_ +#include + #include "Result.hpp" +#include "parsing/schema/ValidationType.hpp" namespace rfl { @@ -17,6 +20,16 @@ struct EqualTo { } return _value; } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto value = + std::is_floating_point_v + ? std::variant(static_cast(_threshold)) + : std::variant(static_cast(_threshold)); + return ValidationType{ValidationType::EqualTo{.value_ = value}}; + } }; template @@ -31,6 +44,16 @@ struct Minimum { } return _value; } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto value = + std::is_floating_point_v + ? std::variant(static_cast(_threshold)) + : std::variant(static_cast(_threshold)); + return ValidationType{ValidationType::Minimum{.value_ = value}}; + } }; template @@ -45,6 +68,16 @@ struct ExclusiveMinimum { } return _value; } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto value = + std::is_floating_point_v + ? std::variant(static_cast(_threshold)) + : std::variant(static_cast(_threshold)); + return ValidationType{ValidationType::ExclusiveMinimum{.value_ = value}}; + } }; template @@ -59,6 +92,16 @@ struct Maximum { } return _value; } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto value = + std::is_floating_point_v + ? std::variant(static_cast(_threshold)) + : std::variant(static_cast(_threshold)); + return ValidationType{ValidationType::Maximum{.value_ = value}}; + } }; template @@ -73,6 +116,16 @@ struct ExclusiveMaximum { } return _value; } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto value = + std::is_floating_point_v + ? std::variant(static_cast(_threshold)) + : std::variant(static_cast(_threshold)); + return ValidationType{ValidationType::ExclusiveMaximum{.value_ = value}}; + } }; template @@ -87,6 +140,16 @@ struct NotEqualTo { } return _value; } + + template + static parsing::schema::ValidationType to_schema() { + using ValidationType = parsing::schema::ValidationType; + const auto value = + std::is_floating_point_v + ? std::variant(static_cast(_threshold)) + : std::variant(static_cast(_threshold)); + return ValidationType{ValidationType::NotEqualTo{.value_ = value}}; + } }; } // namespace rfl diff --git a/include/rfl/internal/enums/StringConverter.hpp b/include/rfl/internal/enums/StringConverter.hpp index b3d76dee..c7b36fe5 100644 --- a/include/rfl/internal/enums/StringConverter.hpp +++ b/include/rfl/internal/enums/StringConverter.hpp @@ -8,11 +8,11 @@ #include #include "../../Result.hpp" -#include "get_enum_names.hpp" -#include "is_flag_enum.hpp" #include "../../internal/strings/join.hpp" #include "../../internal/strings/split.hpp" #include "../../type_name_t.hpp" +#include "get_enum_names.hpp" +#include "is_flag_enum.hpp" namespace rfl { namespace internal { @@ -20,7 +20,7 @@ namespace enums { template class StringConverter { - private: + public: static constexpr bool is_flag_enum_ = is_flag_enum; static constexpr auto names_ = get_enum_names(); diff --git a/include/rfl/internal/get_field_names.hpp b/include/rfl/internal/get_field_names.hpp index 8260803a..347e2865 100644 --- a/include/rfl/internal/get_field_names.hpp +++ b/include/rfl/internal/get_field_names.hpp @@ -113,6 +113,7 @@ auto concat_literals(const Head& _head, const Tail&... _tail) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wundefined-var-template" +#pragma clang diagnostic ignored "-Wundefined-inline" #endif template diff --git a/include/rfl/internal/is_attribute.hpp b/include/rfl/internal/is_attribute.hpp index 97d44416..724c0881 100644 --- a/include/rfl/internal/is_attribute.hpp +++ b/include/rfl/internal/is_attribute.hpp @@ -21,14 +21,9 @@ 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; +constexpr bool is_attribute_v = + is_attribute>>::value; } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/is_description.hpp b/include/rfl/internal/is_description.hpp new file mode 100644 index 00000000..e7234f6c --- /dev/null +++ b/include/rfl/internal/is_description.hpp @@ -0,0 +1,30 @@ +#ifndef RFL_INTERNAL_ISDESCRIPTION_HPP_ +#define RFL_INTERNAL_ISDESCRIPTION_HPP_ + +#include +#include +#include + +#include "../Description.hpp" +#include "StringLiteral.hpp" + +namespace rfl { +namespace internal { + +template +class is_description; + +template +class is_description : public std::false_type {}; + +template +class is_description> : public std::true_type {}; + +template +constexpr bool is_description_v = + is_description>>::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/is_field.hpp b/include/rfl/internal/is_field.hpp index 795c3f9e..f0a81df4 100644 --- a/include/rfl/internal/is_field.hpp +++ b/include/rfl/internal/is_field.hpp @@ -20,14 +20,9 @@ class is_field : public std::false_type {}; template class is_field> : public std::true_type {}; -template -class is_field*> : public std::true_type {}; - -template -class is_field*> : public std::true_type {}; - template -constexpr bool is_field_v = is_field::value; +constexpr bool is_field_v = + is_field>>::value; } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/is_flatten_field.hpp b/include/rfl/internal/is_flatten_field.hpp index b8967ff5..d247f52b 100644 --- a/include/rfl/internal/is_flatten_field.hpp +++ b/include/rfl/internal/is_flatten_field.hpp @@ -20,13 +20,8 @@ template class is_flatten_field> : public std::true_type {}; template -class is_flatten_field*> : public std::true_type {}; - -template -class is_flatten_field*> : public std::true_type {}; - -template -constexpr bool is_flatten_field_v = is_flatten_field::value; +constexpr bool is_flatten_field_v = + is_flatten_field>>::value; } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/is_literal.hpp b/include/rfl/internal/is_literal.hpp new file mode 100644 index 00000000..0eb29eeb --- /dev/null +++ b/include/rfl/internal/is_literal.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_ISLITERAL_HPP_ +#define RFL_INTERNAL_ISLITERAL_HPP_ + +#include + +#include "../Literal.hpp" +#include "StringLiteral.hpp" + +namespace rfl { +namespace internal { + +template +class is_literal; + +template +class is_literal : public std::false_type {}; + +template +class is_literal> : public std::true_type {}; + +template +constexpr bool is_literal_v = + is_literal>>::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/is_named_tuple.hpp b/include/rfl/internal/is_named_tuple.hpp index ca5d6c22..5ac01c8d 100644 --- a/include/rfl/internal/is_named_tuple.hpp +++ b/include/rfl/internal/is_named_tuple.hpp @@ -18,7 +18,8 @@ template class is_named_tuple> : public std::true_type {}; template -constexpr bool is_named_tuple_v = is_named_tuple::value; +constexpr bool is_named_tuple_v = + is_named_tuple>>::value; } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/is_pattern.hpp b/include/rfl/internal/is_pattern.hpp new file mode 100644 index 00000000..676d0291 --- /dev/null +++ b/include/rfl/internal/is_pattern.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_ISPATTERN_HPP_ +#define RFL_INTERNAL_ISPATTERN_HPP_ + +#include + +#include "../Pattern.hpp" +#include "StringLiteral.hpp" + +namespace rfl { +namespace internal { + +template +class is_pattern; + +template +class is_pattern : public std::false_type {}; + +template +class is_pattern> : public std::true_type {}; + +template +constexpr bool is_pattern_v = + is_pattern>>::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/is_rename.hpp b/include/rfl/internal/is_rename.hpp index 16beeeb9..c518161b 100644 --- a/include/rfl/internal/is_rename.hpp +++ b/include/rfl/internal/is_rename.hpp @@ -20,14 +20,9 @@ class is_rename : public std::false_type {}; template class is_rename> : public std::true_type {}; -template -class is_rename*> : public std::true_type {}; - -template -class is_rename*> : public std::true_type {}; - template -constexpr bool is_rename_v = is_rename::value; +constexpr bool is_rename_v = + is_rename>>::value; } // namespace internal } // namespace rfl diff --git a/include/rfl/internal/is_validator.hpp b/include/rfl/internal/is_validator.hpp new file mode 100644 index 00000000..e8374f0a --- /dev/null +++ b/include/rfl/internal/is_validator.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_INTERNAL_ISVALIDATOR_HPP_ +#define RFL_INTERNAL_ISVALIDATOR_HPP_ + +#include + +#include "../Validator.hpp" +#include "StringLiteral.hpp" + +namespace rfl { +namespace internal { + +template +class is_validator; + +template +class is_validator : public std::false_type {}; + +template +class is_validator> : public std::true_type {}; + +template +constexpr bool is_validator_v = + is_validator>>::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/is_variant.hpp b/include/rfl/internal/is_variant.hpp new file mode 100644 index 00000000..f79f1d79 --- /dev/null +++ b/include/rfl/internal/is_variant.hpp @@ -0,0 +1,26 @@ +#ifndef RFL_INTERNAL_ISVARIANT_HPP_ +#define RFL_INTERNAL_ISVARIANT_HPP_ + +#include +#include + +namespace rfl { +namespace internal { + +template +class is_variant; + +template +class is_variant : public std::false_type {}; + +template +class is_variant> : public std::true_type {}; + +template +constexpr bool is_variant_v = + is_variant>>::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/internal/num_fields.hpp b/include/rfl/internal/num_fields.hpp index f7198d34..fb88454a 100644 --- a/include/rfl/internal/num_fields.hpp +++ b/include/rfl/internal/num_fields.hpp @@ -39,6 +39,12 @@ This is the purpose of get_nested_array_size(). #endif #endif +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundefined-var-template" +#pragma clang diagnostic ignored "-Wundefined-inline" +#endif + namespace rfl { namespace internal { @@ -114,4 +120,8 @@ constexpr std::size_t num_fields = CountFieldsHelper::count_fields(); } // namespace internal } // namespace rfl +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + #endif diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index 89e5a9fe..34faaa20 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -7,6 +7,7 @@ #include "json/load.hpp" #include "json/read.hpp" #include "json/save.hpp" +#include "json/to_schema.hpp" #include "json/write.hpp" #endif diff --git a/include/rfl/json/save.hpp b/include/rfl/json/save.hpp index 6491bb35..c2ac2eb9 100644 --- a/include/rfl/json/save.hpp +++ b/include/rfl/json/save.hpp @@ -1,6 +1,8 @@ #ifndef RFL_JSON_SAVE_HPP_ #define RFL_JSON_SAVE_HPP_ +#include + #include #include #include diff --git a/include/rfl/json/schema/JSONSchema.hpp b/include/rfl/json/schema/JSONSchema.hpp new file mode 100644 index 00000000..7aedfb7b --- /dev/null +++ b/include/rfl/json/schema/JSONSchema.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_JSON_SCHEMA_JSONSCHEMA_HPP_ +#define RFL_JSON_SCHEMA_JSONSCHEMA_HPP_ + +#include +#include +#include + +#include "../../Flatten.hpp" +#include "../../Literal.hpp" +#include "../../Rename.hpp" +#include "Type.hpp" + +namespace rfl::json::schema { + +template +struct JSONSchema { + Rename<"$schema", Literal<"https://json-schema.org/draft/2020-12/schema">> + schema; + Flatten root; + std::map definitions; +}; + +} // namespace rfl::json::schema + +#endif diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp new file mode 100644 index 00000000..7352cad0 --- /dev/null +++ b/include/rfl/json/schema/Type.hpp @@ -0,0 +1,147 @@ +#ifndef RFL_JSON_SCHEMA_TYPE_HPP_ +#define RFL_JSON_SCHEMA_TYPE_HPP_ + +#include +#include +#include +#include +#include + +#include "../../Literal.hpp" +#include "../../Rename.hpp" + +namespace rfl::json::schema { + +/// The JSON representation of internal::schema::Type. +struct Type { + struct Boolean { + std::optional description; + Literal<"boolean"> type; + }; + + struct Integer { + Literal<"integer"> type; + std::optional description; + }; + + struct Number { + Literal<"number"> type; + std::optional description; + }; + + struct String { + Literal<"string"> type; + std::optional description; + }; + + using NumericType = std::variant; + + struct AllOf { + std::optional description; + std::vector allOf; + }; + + struct AnyOf { + std::optional description; + std::vector anyOf; + }; + + struct ExclusiveMaximum { + std::optional description; + std::variant exclusiveMaximum; + std::string type; + }; + + struct ExclusiveMinimum { + std::optional description; + std::variant exclusiveMinimum; + std::string type; + }; + + struct FixedSizeTypedArray { + Literal<"array"> type; + std::optional description; + rfl::Ref items; + size_t minContains; + size_t maxContains; + }; + + struct Maximum { + std::optional description; + std::variant maximum; + std::string type; + }; + + struct Minimum { + std::optional description; + std::variant minimum; + std::string type; + }; + + struct Null { + Literal<"null"> type; + std::optional description; + }; + + struct Object { + Literal<"object"> type; + std::optional description; + std::map properties; + std::vector required; + }; + + struct OneOf { + std::optional description; + std::vector oneOf; + }; + + struct Reference { + Rename<"$ref", std::optional> ref; + std::optional description; + }; + + struct Regex { + Literal<"string"> type; + std::optional description; + std::string pattern; + }; + + struct StringEnum { + Literal<"string"> type; + std::optional description; + rfl::Rename<"enum", std::vector> values; + }; + + struct StringMap { + Literal<"object"> type; + std::optional description; + rfl::Ref additionalProperties; + }; + + struct Tuple { + Literal<"array"> type; + std::optional description; + std::vector prefixItems; + bool items = false; + }; + + struct TypedArray { + Literal<"array"> type; + std::optional description; + rfl::Ref items; + }; + + using ReflectionType = + std::variant; + + const auto& reflection() const { return value; } + + ReflectionType value; +}; + +} // namespace rfl::json::schema + +#endif diff --git a/include/rfl/json/to_schema.hpp b/include/rfl/json/to_schema.hpp new file mode 100644 index 00000000..b9dc4286 --- /dev/null +++ b/include/rfl/json/to_schema.hpp @@ -0,0 +1,260 @@ +#ifndef RFL_JSON_TOSCHEMA_HPP_ +#define RFL_JSON_TOSCHEMA_HPP_ + +#include + +#include +#include +#include +#include + +#include "../Literal.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/ValidationType.hpp" +#include "../parsing/schema/make.hpp" +#include "Reader.hpp" +#include "Writer.hpp" +#include "schema/JSONSchema.hpp" +#include "schema/Type.hpp" +#include "write.hpp" + +namespace rfl::json { + +inline schema::Type type_to_json_schema_type( + const parsing::schema::Type& _type); + +inline bool is_optional(const parsing::schema::Type& _t) { + const auto handle = [](const auto& _v) -> bool { + using T = std::remove_cvref_t; + return std::is_same(); + }; + return std::visit(handle, _t.variant_); +} + +inline std::string numeric_type_to_string(const parsing::schema::Type& _type) { + const auto handle_variant = [](const auto& _t) -> std::string { + using T = std::remove_cvref_t; + using Type = parsing::schema::Type; + if constexpr (std::is_same() || + std::is_same() || + std::is_same() || + std::is_same() || + std::is_same()) { + return schema::Type::Integer{}.type.str(); + } else { + return schema::Type::Number{}.type.str(); + } + }; + return std::visit(handle_variant, _type.variant_); +} + +inline schema::Type handle_validation_type( + const parsing::schema::Type& _type, + const parsing::schema::ValidationType& _validation_type) { + const auto handle_variant = [&](const auto& _v) -> schema::Type { + using T = std::remove_cvref_t; + using ValidationType = parsing::schema::ValidationType; + if constexpr (std::is_same()) { + auto all_of = std::vector(); + for (const auto& t : _v.types_) { + all_of.emplace_back(handle_validation_type(_type, t)); + } + return schema::Type{.value = schema::Type::AllOf{.allOf = all_of}}; + + } else if constexpr (std::is_same()) { + auto any_of = std::vector(); + for (const auto& t : _v.types_) { + any_of.emplace_back(handle_validation_type(_type, t)); + } + return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}}; + + } else if constexpr (std::is_same()) { + auto one_of = std::vector(); + for (const auto& t : _v.types_) { + one_of.emplace_back(handle_validation_type(_type, t)); + } + return schema::Type{.value = schema::Type::OneOf{.oneOf = one_of}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Regex{.pattern = _v.pattern_}}; + + } else if constexpr (std::is_same()) { + return type_to_json_schema_type(_type); + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::ExclusiveMaximum{ + .exclusiveMaximum = _v.value_, + .type = numeric_type_to_string(_type)}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::ExclusiveMinimum{ + .exclusiveMinimum = _v.value_, + .type = numeric_type_to_string(_type)}}; + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Maximum{ + .maximum = _v.value_, .type = numeric_type_to_string(_type)}}; + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Minimum{ + .minimum = _v.value_, .type = numeric_type_to_string(_type)}}; + + } else if constexpr (std::is_same()) { + const auto maximum = schema::Type{ + .value = schema::Type::Maximum{ + .maximum = _v.value_, .type = numeric_type_to_string(_type)}}; + const auto minimum = schema::Type{ + .value = schema::Type::Minimum{ + .minimum = _v.value_, .type = numeric_type_to_string(_type)}}; + return schema::Type{.value = + schema::Type::AllOf{.allOf = {maximum, minimum}}}; + + } else if constexpr (std::is_same()) { + const auto excl_maximum = + schema::Type{.value = schema::Type::ExclusiveMaximum{ + .exclusiveMaximum = _v.value_, + .type = numeric_type_to_string(_type)}}; + const auto excl_minimum = + schema::Type{.value = schema::Type::ExclusiveMinimum{ + .exclusiveMinimum = _v.value_, + .type = numeric_type_to_string(_type)}}; + return schema::Type{ + .value = schema::Type::AnyOf{.anyOf = {excl_maximum, excl_minimum}}}; + + } else { + static_assert(rfl::always_false_v, "Not all cases were covered."); + } + }; + + return std::visit(handle_variant, _validation_type.variant_); +} + +inline schema::Type type_to_json_schema_type( + const parsing::schema::Type& _type) { + const auto handle_variant = [](const auto& _t) -> schema::Type { + using T = std::remove_cvref_t; + using Type = parsing::schema::Type; + if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Boolean{}}; + + } else if constexpr (std::is_same() || + std::is_same() || + std::is_same() || + std::is_same() || + std::is_same()) { + return schema::Type{.value = schema::Type::Integer{}}; + + } else if constexpr (std::is_same() || + std::is_same()) { + return schema::Type{.value = schema::Type::Number{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::String{}}; + + } else if constexpr (std::is_same()) { + auto any_of = std::vector(); + for (const auto& t : _t.types_) { + any_of.emplace_back(type_to_json_schema_type(t)); + } + return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}}; + + } else if constexpr (std::is_same()) { + auto res = type_to_json_schema_type(*_t.type_); + const auto update_prediction = [&](auto _v) -> schema::Type { + _v.description = _t.description_; + return schema::Type{_v}; + }; + return std::visit(update_prediction, res.value); + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::FixedSizeTypedArray{ + .items = Ref::make( + type_to_json_schema_type(*_t.type_)), + .minContains = _t.size_, + .maxContains = _t.size_}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = + schema::Type::StringEnum{.values = _t.values_}}; + + } else if constexpr (std::is_same()) { + auto properties = std::map(); + auto required = std::vector(); + for (const auto& [k, v] : _t.types_) { + properties[k] = type_to_json_schema_type(v); + if (!is_optional(v)) { + required.push_back(k); + } + } + return schema::Type{.value = schema::Type::Object{ + .properties = properties, .required = required}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::AnyOf{ + .anyOf = {type_to_json_schema_type(*_t.type_), + schema::Type{schema::Type::Null{}}}}}; + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Reference{.ref = "#/definitions/" + _t.name_}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::StringMap{ + .additionalProperties = Ref::make( + type_to_json_schema_type(*_t.value_type_))}}; + + } else if constexpr (std::is_same()) { + auto items = std::vector(); + for (const auto& t : _t.types_) { + items.emplace_back(type_to_json_schema_type(t)); + } + return schema::Type{.value = schema::Type::Tuple{.prefixItems = items}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::TypedArray{ + .items = Ref::make( + type_to_json_schema_type(*_t.type_))}}; + + } else if constexpr (std::is_same()) { + return handle_validation_type(*_t.type_, _t.validation_); + + } else { + static_assert(rfl::always_false_v, "Not all cases were covered."); + } + }; + + return std::visit(handle_variant, _type.variant_); +} + +template +struct TypeHelper {}; + +template +struct TypeHelper > { + using JSONSchemaType = std::variant...>; +}; + +/// Returns the JSON schema for a class. +template +std::string to_schema(const yyjson_write_flag _flag = 0) { + const auto internal_schema = parsing::schema::make(); + auto definitions = std::map(); + for (const auto& [k, v] : internal_schema.definitions_) { + definitions[k] = type_to_json_schema_type(v); + } + using JSONSchemaType = + typename TypeHelper::JSONSchemaType; + const auto to_schema = [&](auto&& _root) -> JSONSchemaType { + using U = std::decay_t; + return schema::JSONSchema{.root = std::move(_root), + .definitions = definitions}; + }; + auto root = type_to_json_schema_type(internal_schema.root_); + const auto json_schema = std::visit(to_schema, std::move(root.value)); + return write(json_schema, _flag); +} +} // namespace rfl::json + +#endif diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index fa8b2dc2..056da129 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_FIELD_VARIANT_PARSER_HPP_ #define RFL_PARSING_FIELD_VARIANT_PARSER_HPP_ +#include #include #include #include @@ -9,6 +10,7 @@ #include "../Result.hpp" #include "../always_false.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -68,6 +70,13 @@ struct FieldVariantParser { std::visit(handle, _v); } + static schema::Type to_schema( + std::map* _definitions, + std::vector _types = {}) { + using VariantType = std::variant...>; + return Parser::to_schema(_definitions); + } + private: template static ResultType find_matching_alternative( diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp index 6361fd47..2cd3b2be 100644 --- a/include/rfl/parsing/MapParser.hpp +++ b/include/rfl/parsing/MapParser.hpp @@ -1,14 +1,17 @@ #ifndef RFL_PARSING_MAPPARSER_HPP_ #define RFL_PARSING_MAPPARSER_HPP_ +#include #include #include #include +#include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -67,6 +70,12 @@ struct MapParser { _w.end_object(&obj); } + static schema::Type to_schema( + std::map* _definitions) { + return schema::Type{schema::Type::StringMap{Ref::make( + Parser::to_schema(_definitions))}}; + } + private: template static Result key_to_numeric(auto& _pair) noexcept { diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 7caa5888..7b06c0c3 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_NAMEDTUPLEPARSER_HPP_ #define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ +#include #include #include #include @@ -17,6 +18,7 @@ #include "Parser_base.hpp" #include "is_empty.hpp" #include "is_required.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -58,6 +60,23 @@ struct NamedTupleParser { _w.end_object(&obj); } + template + static schema::Type to_schema( + std::map* _definitions, + std::map _values = {}) { + using Type = schema::Type; + using T = NamedTuple; + constexpr size_t size = T::size(); + if constexpr (_i == size) { + return Type{Type::Object{_values}}; + } else { + using F = std::tuple_element_t<_i, typename T::Fields>; + _values[std::string(F::name())] = + Parser::to_schema(_definitions); + return to_schema<_i + 1>(_definitions, _values); + } + }; + private: /// Builds the named tuple field by field. template diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 7bb7cde2..889c1202 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -18,6 +18,7 @@ #include "Parser_rfl_array.hpp" #include "Parser_rfl_variant.hpp" #include "Parser_shared_ptr.hpp" +#include "Parser_string_view.hpp" #include "Parser_tagged_union.hpp" #include "Parser_tuple.hpp" #include "Parser_unique_ptr.hpp" diff --git a/include/rfl/parsing/Parser_array.hpp b/include/rfl/parsing/Parser_array.hpp index 751ed803..536f5fa8 100644 --- a/include/rfl/parsing/Parser_array.hpp +++ b/include/rfl/parsing/Parser_array.hpp @@ -2,13 +2,16 @@ #define RFL_PARSING_PARSER_ARRAY_HPP_ #include +#include #include #include +#include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -57,6 +60,15 @@ struct Parser> { _w.end_array(&arr); } + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + return schema::Type{schema::Type::FixedSizeTypedArray{ + .size_ = _size, + .type_ = + Ref::make(Parser::to_schema(_definitions))}}; + } + private: /// Extracts values from the array, field by field. template diff --git a/include/rfl/parsing/Parser_box.hpp b/include/rfl/parsing/Parser_box.hpp index 7c7ba208..af209309 100644 --- a/include/rfl/parsing/Parser_box.hpp +++ b/include/rfl/parsing/Parser_box.hpp @@ -1,11 +1,13 @@ #ifndef RFL_PARSING_PARSER_BOX_HPP_ #define RFL_PARSING_PARSER_BOX_HPP_ +#include #include #include "../Box.hpp" #include "../Result.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -27,6 +29,11 @@ struct Parser> { const P& _parent) noexcept { Parser>::write(_w, *_box, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_c_array.hpp b/include/rfl/parsing/Parser_c_array.hpp index fe34fb97..eaeee92a 100644 --- a/include/rfl/parsing/Parser_c_array.hpp +++ b/include/rfl/parsing/Parser_c_array.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_C_ARRAY_HPP_ #define RFL_PARSING_PARSER_C_ARRAY_HPP_ +#include #include #include "../Result.hpp" @@ -10,6 +11,7 @@ #include "Parent.hpp" #include "Parser_array.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -43,6 +45,12 @@ struct Parser { } _w.end_array(&arr); } + + static schema::Type to_schema( + std::map* _definitions) { + using StdArray = internal::to_std_array_t; + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index ec34fff0..81928fe9 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_DEFAULT_HPP_ #define RFL_PARSING_PARSER_DEFAULT_HPP_ +#include #include #include @@ -11,10 +12,16 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/is_basic_type.hpp" +#include "../internal/is_description.hpp" +#include "../internal/is_literal.hpp" +#include "../internal/is_validator.hpp" #include "../internal/to_ptr_named_tuple.hpp" +#include "../type_name_t.hpp" #include "AreReaderAndWriter.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "is_tagged_union_wrapper.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -96,6 +103,127 @@ struct Parser { "support for your own classes."); } } + + /// Generates a schema for the underlying type. + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + using Type = schema::Type; + if constexpr (std::is_same()) { + return Type{Type::Boolean{}}; + + } else if constexpr (std::is_same()) { + return Type{Type::Int32{}}; + + } else if constexpr (std::is_same()) { + return Type{Type::Int64{}}; + + } else if constexpr (std::is_same()) { + return Type{Type::UInt32{}}; + + } else if constexpr (std::is_same()) { + return Type{Type::UInt64{}}; + + } else if constexpr (std::is_integral()) { + return Type{Type::Integer{}}; + + } else if constexpr (std::is_same()) { + return Type{Type::Float{}}; + + } else if constexpr (std::is_floating_point_v) { + return Type{Type::Double{}}; + + } else if constexpr (std::is_same()) { + return Type{Type::String{}}; + + } else if constexpr (rfl::internal::is_description_v) { + return make_description(_definitions); + + } else if constexpr (std::is_enum_v) { + return make_enum(_definitions); + + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + return make_reference(_definitions); + + } else if constexpr (internal::is_literal_v) { + return Type{Type::Literal{.values_ = U::strings()}}; + + } else if constexpr (internal::is_validator_v) { + return make_validated(_definitions); + + } else if constexpr (internal::has_reflection_type_v) { + return Parser::to_schema(_definitions); + + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + } + + template + static schema::Type make_description( + std::map* _definitions) { + using Type = schema::Type; + return Type{Type::Description{ + .description_ = typename U::Content().str(), + .type_ = Ref::make( + Parser>::to_schema( + _definitions))}}; + } + + template + static schema::Type make_enum( + std::map* _definitions) { + using Type = schema::Type; + using S = internal::enums::StringConverter; + if constexpr (S::is_flag_enum_) { + return Type{Type::String{}}; + } else { + return Parser::to_schema(_definitions); + } + } + + template + static schema::Type make_reference( + std::map* _definitions) { + using Type = schema::Type; + const auto name = make_type_name(); + if (_definitions->find(name) == _definitions->end()) { + (*_definitions)[name] = + Type{Type::Integer{}}; // Placeholder to avoid infinite loop. + (*_definitions)[name] = + Parser>::to_schema(_definitions); + } + return Type{Type::Reference{name}}; + } + + template + static schema::Type make_validated( + std::map* _definitions) { + using Type = schema::Type; + using ReflectionType = std::remove_cvref_t; + using ValidationType = std::remove_cvref_t; + return Type{Type::Validated{ + .type_ = Ref::make( + Parser::to_schema(_definitions)), + .validation_ = ValidationType::template to_schema()}}; + } + + template + static std::string make_type_name() { + if constexpr (is_tagged_union_wrapper_v) { + return replace_non_alphanumeric(type_name_t().str() + + "__tagged"); + } else { + return replace_non_alphanumeric(type_name_t().str()); + } + } + + static std::string replace_non_alphanumeric(std::string _str) { + for (auto& ch : _str) { + ch = std::isalnum(ch) ? ch : '_'; + } + return _str; + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_optional.hpp b/include/rfl/parsing/Parser_optional.hpp index 8e1c7144..16643bbd 100644 --- a/include/rfl/parsing/Parser_optional.hpp +++ b/include/rfl/parsing/Parser_optional.hpp @@ -1,13 +1,16 @@ #ifndef RFL_PARSING_PARSER_OPTIONAL_HPP_ #define RFL_PARSING_PARSER_OPTIONAL_HPP_ +#include #include #include +#include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -39,6 +42,13 @@ struct Parser> { } Parser>::write(_w, *_o, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + return schema::Type{schema::Type::Optional{ + Ref::make(Parser::to_schema(_definitions))}}; + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_pair.hpp b/include/rfl/parsing/Parser_pair.hpp index 64a53d70..d33c3934 100644 --- a/include/rfl/parsing/Parser_pair.hpp +++ b/include/rfl/parsing/Parser_pair.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_PAIR_HPP_ #define RFL_PARSING_PARSER_PAIR_HPP_ +#include #include #include @@ -8,6 +9,7 @@ #include "../Result.hpp" #include "../always_false.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -36,6 +38,12 @@ struct Parser> { Parser>::write( _w, tup, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema( + _definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_ptr.hpp b/include/rfl/parsing/Parser_ptr.hpp index 20ed3f1d..738d0cca 100644 --- a/include/rfl/parsing/Parser_ptr.hpp +++ b/include/rfl/parsing/Parser_ptr.hpp @@ -1,12 +1,15 @@ #ifndef RFL_PARSING_PARSER_PTR_HPP_ #define RFL_PARSING_PARSER_PTR_HPP_ +#include #include +#include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -38,6 +41,11 @@ struct Parser { } Parser>::write(_w, *_ptr, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_ref.hpp b/include/rfl/parsing/Parser_ref.hpp index 72189840..441b7412 100644 --- a/include/rfl/parsing/Parser_ref.hpp +++ b/include/rfl/parsing/Parser_ref.hpp @@ -1,12 +1,14 @@ #ifndef RFL_PARSING_PARSER_REF_HPP_ #define RFL_PARSING_PARSER_REF_HPP_ +#include #include #include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -28,6 +30,11 @@ struct Parser> { const P& _parent) noexcept { Parser>::write(_w, *_ref, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_reference_wrapper.hpp b/include/rfl/parsing/Parser_reference_wrapper.hpp index bb5d0009..023fe13a 100644 --- a/include/rfl/parsing/Parser_reference_wrapper.hpp +++ b/include/rfl/parsing/Parser_reference_wrapper.hpp @@ -2,11 +2,13 @@ #define RFL_PARSING_PARSER_REFERENCE_WRAPPER_HPP_ #include +#include #include #include "../Result.hpp" #include "../always_false.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -33,6 +35,11 @@ struct Parser> { const P& _p) noexcept { Parser>::write(_w, _ref.get(), _p); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_rename.hpp b/include/rfl/parsing/Parser_rename.hpp index 89857a66..2cc94ab0 100644 --- a/include/rfl/parsing/Parser_rename.hpp +++ b/include/rfl/parsing/Parser_rename.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_RENAME_HPP_ #define RFL_PARSING_PARSER_RENAME_HPP_ +#include #include #include "../Rename.hpp" @@ -8,6 +9,7 @@ #include "../always_false.hpp" #include "../internal/StringLiteral.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -32,6 +34,11 @@ struct Parser> { const P& _parent) noexcept { Parser>::write(_w, _rename.value(), _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_result.hpp b/include/rfl/parsing/Parser_result.hpp index 303cf3b4..a7e0dd60 100644 --- a/include/rfl/parsing/Parser_result.hpp +++ b/include/rfl/parsing/Parser_result.hpp @@ -1,12 +1,14 @@ #ifndef RFL_PARSING_PARSER_RESULT_HPP_ #define RFL_PARSING_PARSER_RESULT_HPP_ +#include #include #include "../Result.hpp" #include "../always_false.hpp" #include "../internal/StringLiteral.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -55,6 +57,11 @@ struct Parser> { _r.transform(write_t).or_else(write_err); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_rfl_array.hpp b/include/rfl/parsing/Parser_rfl_array.hpp index cfce4de0..e3e837f9 100644 --- a/include/rfl/parsing/Parser_rfl_array.hpp +++ b/include/rfl/parsing/Parser_rfl_array.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_RFL_ARRAY_HPP_ #define RFL_PARSING_PARSER_RFL_ARRAY_HPP_ +#include #include #include "../Result.hpp" @@ -9,6 +10,7 @@ #include "../internal/to_std_array.hpp" #include "Parser_array.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -35,6 +37,11 @@ struct Parser> { const P& _parent) noexcept { Parser::write(_w, _arr.arr_, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_rfl_variant.hpp b/include/rfl/parsing/Parser_rfl_variant.hpp index d765a41a..5b85bc02 100644 --- a/include/rfl/parsing/Parser_rfl_variant.hpp +++ b/include/rfl/parsing/Parser_rfl_variant.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_RFL_VARIANT_HPP_ #define RFL_PARSING_PARSER_RFL_VARIANT_HPP_ +#include #include #include @@ -9,6 +10,7 @@ #include "../always_false.hpp" #include "FieldVariantParser.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -36,6 +38,11 @@ struct Parser> { Parser>::write(_w, _variant.variant(), _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser>::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_shared_ptr.hpp b/include/rfl/parsing/Parser_shared_ptr.hpp index d03ab412..60bb2e3a 100644 --- a/include/rfl/parsing/Parser_shared_ptr.hpp +++ b/include/rfl/parsing/Parser_shared_ptr.hpp @@ -1,13 +1,16 @@ #ifndef RFL_PARSING_PARSER_SHARED_PTR_HPP_ #define RFL_PARSING_PARSER_SHARED_PTR_HPP_ +#include #include #include +#include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -33,14 +36,21 @@ struct Parser> { } template - static OutputVarType write(const W& _w, const std::shared_ptr& _s, - const P& _parent) noexcept { + static void write(const W& _w, const std::shared_ptr& _s, + const P& _parent) noexcept { if (!_s) { ParentType::add_null(_w, _parent); return; } Parser>::write(_w, *_s, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + return schema::Type{schema::Type::Optional{ + Ref::make(Parser::to_schema(_definitions))}}; + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_string_view.hpp b/include/rfl/parsing/Parser_string_view.hpp new file mode 100644 index 00000000..62cb26fb --- /dev/null +++ b/include/rfl/parsing/Parser_string_view.hpp @@ -0,0 +1,47 @@ +#ifndef RFL_PARSING_PARSER_STRING_VIEW_HPP_ +#define RFL_PARSING_PARSER_STRING_VIEW_HPP_ + +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../always_false.hpp" +#include "Parser_base.hpp" +#include "schema/Type.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::string_view is dangerous and " + "therefore unsupported. " + "Please consider using std::string instead."); + return Error("Unsupported."); + } + + template + static void write(const W& _w, const std::string_view& _str, + const P& _p) noexcept { + Parser::write(_w, std::string(_str), _p); + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/Parser_tagged_union.hpp b/include/rfl/parsing/Parser_tagged_union.hpp index 950d2e39..fbc490aa 100644 --- a/include/rfl/parsing/Parser_tagged_union.hpp +++ b/include/rfl/parsing/Parser_tagged_union.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_TAGGED_UNION_HPP_ #define RFL_PARSING_PARSER_TAGGED_UNION_HPP_ +#include #include #include "../Result.hpp" @@ -8,14 +9,15 @@ #include "../always_false.hpp" #include "Parser_base.hpp" #include "TaggedUnionWrapper.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { template - requires AreReaderAndWriter> +requires AreReaderAndWriter> struct Parser> { using ResultType = Result>; @@ -49,6 +51,14 @@ struct Parser> { std::visit(handle, _tagged_union.variant_); } + static schema::Type to_schema( + std::map* _definitions) { + using VariantType = + std::variant), + AlternativeTypes>...>; + return Parser::to_schema(_definitions); + } + private: template static ResultType find_matching_alternative( @@ -114,18 +124,25 @@ struct Parser> { template static void write_wrapped(const W& _w, const T& _val, const P& _parent) noexcept { + const auto wrapped = wrap(_val); + Parser>::write(_w, wrapped, + _parent); + } + + /// Generates a wrapped version of the original object, which contains the + /// tag. + template + static auto wrap(const T& _val) noexcept { const auto tag = internal::make_tag(); using TagType = std::remove_cvref_t; if constexpr (internal::has_fields>()) { using WrapperType = TaggedUnionWrapperWithFields; - const auto wrapper = WrapperType{.tag = tag, .fields = &_val}; - Parser::write(_w, wrapper, _parent); + return WrapperType{.tag = tag, .fields = &_val}; } else { using WrapperType = TaggedUnionWrapperNoFields; - const auto wrapper = WrapperType{.tag = tag, .fields = &_val}; - Parser::write(_w, wrapper, _parent); + return WrapperType{.tag = tag, .fields = &_val}; } } }; diff --git a/include/rfl/parsing/Parser_unique_ptr.hpp b/include/rfl/parsing/Parser_unique_ptr.hpp index a8b269fb..9201e0e6 100644 --- a/include/rfl/parsing/Parser_unique_ptr.hpp +++ b/include/rfl/parsing/Parser_unique_ptr.hpp @@ -1,13 +1,16 @@ #ifndef RFL_PARSING_PARSER_UNIQUE_PTR_HPP_ #define RFL_PARSING_PARSER_UNIQUE_PTR_HPP_ +#include #include #include +#include "../Ref.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -41,6 +44,13 @@ struct Parser> { } Parser>::write(_w, *_s, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + using U = std::remove_cvref_t; + return schema::Type{schema::Type::Optional{ + Ref::make(Parser::to_schema(_definitions))}}; + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_variant.hpp b/include/rfl/parsing/Parser_variant.hpp index e46628b6..683e6da0 100644 --- a/include/rfl/parsing/Parser_variant.hpp +++ b/include/rfl/parsing/Parser_variant.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_VARIANT_HPP_ #define RFL_PARSING_PARSER_VARIANT_HPP_ +#include #include #include @@ -9,6 +10,7 @@ #include "../always_false.hpp" #include "FieldVariantParser.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -62,6 +64,26 @@ struct Parser> { return std::visit(handle, _variant); } } + + template + static schema::Type to_schema( + std::map* _definitions, + std::vector _types = {}) { + if constexpr (internal::all_fields>()) { + return FieldVariantParser::to_schema(_definitions); + } else { + using Type = schema::Type; + constexpr size_t size = sizeof...(FieldTypes); + if constexpr (_i == size) { + return Type{Type::AnyOf{.types_ = _types}}; + } else { + using U = std::remove_cvref_t< + std::variant_alternative_t<_i, std::variant>>; + _types.push_back(Parser::to_schema(_definitions)); + return to_schema<_i + 1>(_definitions, std::move(_types)); + } + } + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_wstring.hpp b/include/rfl/parsing/Parser_wstring.hpp index d9d290c7..9f3cc457 100644 --- a/include/rfl/parsing/Parser_wstring.hpp +++ b/include/rfl/parsing/Parser_wstring.hpp @@ -1,18 +1,20 @@ #ifndef RFL_PARSING_PARSER_WSTRING_HPP_ #define RFL_PARSING_PARSER_WSTRING_HPP_ +#include #include #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" #include "Parser_base.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { template - requires AreReaderAndWriter +requires AreReaderAndWriter struct Parser { public: using InputVarType = typename R::InputVarType; @@ -66,6 +68,11 @@ struct Parser { ParentType::add_value(_w, outStr, _parent); } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } }; } // namespace parsing diff --git a/include/rfl/parsing/TaggedUnionWrapper.hpp b/include/rfl/parsing/TaggedUnionWrapper.hpp index b3fe40b4..f4262611 100644 --- a/include/rfl/parsing/TaggedUnionWrapper.hpp +++ b/include/rfl/parsing/TaggedUnionWrapper.hpp @@ -12,12 +12,14 @@ namespace parsing { template struct TaggedUnionWrapperNoFields { + using Type = T; rfl::Rename<_discriminator, TagType> tag; rfl::Flatten fields; }; template struct TaggedUnionWrapperWithFields { + using Type = T; rfl::Field<_discriminator, TagType> tag; rfl::Flatten fields; }; diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index 31f07c3f..e3bf0c7d 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -1,12 +1,14 @@ #ifndef RFL_PARSING_TUPLEPARSER_HPP_ #define RFL_PARSING_TUPLEPARSER_HPP_ +#include #include #include #include "../Result.hpp" #include "../always_false.hpp" #include "Parent.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -55,6 +57,22 @@ struct TupleParser { _w.end_array(&arr); } + template + static schema::Type to_schema( + std::map* _definitions, + std::vector _types = {}) { + using Type = schema::Type; + constexpr size_t size = sizeof...(Ts); + if constexpr (_i == size) { + return Type{Type::Tuple{.types_ = _types}}; + } else { + using U = + std::remove_cvref_t>>; + _types.push_back(Parser::to_schema(_definitions)); + return to_schema<_i + 1>(_definitions, std::move(_types)); + } + } + private: template static Result> extract_field_by_field( @@ -77,8 +95,8 @@ struct TupleParser { template static auto extract_single_field( const R& _r, const std::vector& _vec) noexcept { - using NewFieldType = std::remove_cvref_t< - typename std::tuple_element<_i, std::tuple>::type>; + using NewFieldType = + std::remove_cvref_t>>; using ResultType = Result; diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp index db2bc8f8..53afe5ad 100644 --- a/include/rfl/parsing/VectorParser.hpp +++ b/include/rfl/parsing/VectorParser.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_VECTORPARSER_HPP_ #include +#include #include #include #include @@ -15,6 +16,7 @@ #include "is_map_like.hpp" #include "is_map_like_not_multimap.hpp" #include "is_set_like.hpp" +#include "schema/Type.hpp" namespace rfl { namespace parsing { @@ -64,6 +66,14 @@ struct VectorParser { } } + /// Generates a schema for the underlying type. + static schema::Type to_schema( + std::map* _definitions) { + using Type = schema::Type; + return Type{Type::TypedArray{ + .type_ = Ref::make(Parser::to_schema(_definitions))}}; + } + private: static auto get_elem(const R& _r, auto& _v) { return Parser>::read(_r, _v).value(); diff --git a/include/rfl/parsing/is_tagged_union_wrapper.hpp b/include/rfl/parsing/is_tagged_union_wrapper.hpp new file mode 100644 index 00000000..34021230 --- /dev/null +++ b/include/rfl/parsing/is_tagged_union_wrapper.hpp @@ -0,0 +1,34 @@ +#ifndef RFL_PARSING_ISTAGGEDUNIONWRAPPER_HPP_ +#define RFL_PARSING_ISTAGGEDUNIONWRAPPER_HPP_ + +#include + +#include "../internal/StringLiteral.hpp" +#include "TaggedUnionWrapper.hpp" + +namespace rfl { +namespace parsing { + +template +class is_tagged_union_wrapper; + +template +class is_tagged_union_wrapper : public std::false_type {}; + +template +class is_tagged_union_wrapper< + TaggedUnionWrapperNoFields> + : public std::true_type {}; + +template +class is_tagged_union_wrapper< + TaggedUnionWrapperWithFields> + : public std::true_type {}; + +template +constexpr bool is_tagged_union_wrapper_v = is_tagged_union_wrapper::value; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/schema/Definition.hpp b/include/rfl/parsing/schema/Definition.hpp new file mode 100644 index 00000000..80e42d05 --- /dev/null +++ b/include/rfl/parsing/schema/Definition.hpp @@ -0,0 +1,21 @@ +#ifndef RFL_PARSING_SCHEMA_DEFINITION_HPP_ +#define RFL_PARSING_SCHEMA_DEFINITION_HPP_ + +#include +#include + +#include "Type.hpp" + +namespace rfl::parsing::schema { + +struct Definition { + /// Contains the root element of the schema definition. + Type root_; + + /// Contains the definitions to be referenced by Type::Reference. + std::map definitions_; +}; + +} // namespace rfl::parsing::schema + +#endif diff --git a/include/rfl/parsing/schema/Type.hpp b/include/rfl/parsing/schema/Type.hpp new file mode 100644 index 00000000..0b8bb850 --- /dev/null +++ b/include/rfl/parsing/schema/Type.hpp @@ -0,0 +1,98 @@ +#ifndef RFL_PARSING_SCHEMA_TYPE_HPP_ +#define RFL_PARSING_SCHEMA_TYPE_HPP_ + +#include +#include +#include +#include +#include + +#include "../../Ref.hpp" +#include "ValidationType.hpp" + +namespace rfl::parsing::schema { + +struct Type { + struct Boolean {}; + + struct Int32 {}; + + struct Int64 {}; + + struct UInt32 {}; + + struct UInt64 {}; + + struct Integer {}; + + struct Float {}; + + struct Double {}; + + struct String {}; + + struct AnyOf { + std::vector types_; + }; + + struct Description { + std::string description_; + Ref type_; + }; + + struct FixedSizeTypedArray { + size_t size_; + Ref type_; + }; + + struct Literal { + std::vector values_; + }; + + struct Object { + std::map types_; + }; + + /// All values are assumed to be required unless explicitly stated otherwise + /// using this wrapper. + struct Optional { + Ref type_; + }; + + /// The is necessary to resolve circular definitions. Refers to something in + /// Definitions. + struct Reference { + std::string name_; + }; + + // A map with key type string. + struct StringMap { + Ref value_type_; + }; + + struct Tuple { + std::vector types_; + }; + + struct TypedArray { + Ref type_; + }; + + struct Validated { + Ref type_; + ValidationType validation_; + }; + + using VariantType = + std::variant; + + /// A type can be determined to be any of the above. + VariantType variant_; +}; + +} // namespace rfl::parsing::schema + +#endif diff --git a/include/rfl/parsing/schema/ValidationType.hpp b/include/rfl/parsing/schema/ValidationType.hpp new file mode 100644 index 00000000..fec2540c --- /dev/null +++ b/include/rfl/parsing/schema/ValidationType.hpp @@ -0,0 +1,69 @@ +#ifndef RFL_PARSING_SCHEMA_VALIDATIONTYPE_HPP_ +#define RFL_PARSING_SCHEMA_VALIDATIONTYPE_HPP_ + +#include +#include +#include +#include +#include + +#include "../../Ref.hpp" + +namespace rfl::parsing::schema { + +struct ValidationType { + struct AllOf { + std::vector types_; + }; + + struct AnyOf { + std::vector types_; + }; + + struct EqualTo { + std::variant value_; + }; + + struct ExclusiveMaximum { + std::variant value_; + }; + + struct ExclusiveMinimum { + std::variant value_; + }; + + struct Maximum { + std::variant value_; + }; + + struct Minimum { + std::variant value_; + }; + + struct NotEqualTo { + std::variant value_; + }; + + struct OneOf { + std::vector types_; + }; + + struct Regex { + std::string pattern_; + }; + + struct Size { + Ref size_limit_; + }; + + using VariantType = + std::variant; + + /// A type can be determined to be any of the above. + VariantType variant_; +}; + +} // namespace rfl::parsing::schema + +#endif diff --git a/include/rfl/parsing/schema/make.hpp b/include/rfl/parsing/schema/make.hpp new file mode 100644 index 00000000..a6a6886e --- /dev/null +++ b/include/rfl/parsing/schema/make.hpp @@ -0,0 +1,21 @@ +#ifndef RFL_PARSING_SCHEMA_MAKE_HPP_ +#define RFL_PARSING_SCHEMA_MAKE_HPP_ + +#include + +#include "../Parser.hpp" +#include "Definition.hpp" +#include "Type.hpp" + +namespace rfl::parsing::schema { + +template +Definition make() { + std::map definitions; + auto root = Parser::to_schema(&definitions); + return Definition{.root_ = root, .definitions_ = definitions}; +} + +} // namespace rfl::parsing::schema + +#endif diff --git a/include/rfl/parsing/schema/to_numeric_type.hpp b/include/rfl/parsing/schema/to_numeric_type.hpp new file mode 100644 index 00000000..cb9e4d47 --- /dev/null +++ b/include/rfl/parsing/schema/to_numeric_type.hpp @@ -0,0 +1,43 @@ +#ifndef RFL_PARSING_SCHEMA_TONUMERICTYPE_HPP_ +#define RFL_PARSING_SCHEMA_TONUMERICTYPE_HPP_ + +#include + +#include "../../always_false.hpp" +#include "Type.hpp" + +namespace rfl::parsing::schema { + +template +inline schema::Type::NumericType to_numeric_type() { + using U = std::remove_cvref_t; + + if constexpr (std::is_same()) { + return Type::NumericType(Type::Int32{}); + + } else if constexpr (std::is_same()) { + return Type::NumericType(Type::Int64{}); + + } else if constexpr (std::is_same()) { + return Type::NumericType(Type::UInt32{}); + + } else if constexpr (std::is_same()) { + return Type::NumericType(Type::UInt64{}); + + } else if constexpr (std::is_integral()) { + return Type::NumericType(Type::Integer{}); + + } else if constexpr (std::is_same()) { + return Type::NumericType(Type::Float{}); + + } else if constexpr (std::is_floating_point_v) { + return Type::NumericType(Type::Double{}); + + } else { + static_assert(always_false_v, "Not a numeric value."); + } +} + +} // namespace rfl::parsing::schema + +#endif diff --git a/tests/json/test_json_schema.cpp b/tests/json/test_json_schema.cpp new file mode 100644 index 00000000..f51b48b3 --- /dev/null +++ b/tests/json/test_json_schema.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "test_readme_example.hpp" +#include "write_and_read.hpp" + +namespace test_json_schema { + +enum class Color { red, green, blue }; + +struct Rectangle { + double width; + double height; +}; + +struct Square { + double width; +}; + +struct Circle { + double radius; +}; + +using Age = rfl::Validator, rfl::Maximum<130>>; + +using FieldVariant = + rfl::Variant, + rfl::Field<"square", Square>, rfl::Field<"circle", Circle>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + rfl::Description<"Must be a proper email in the form xxx@xxx.xxx.", + rfl::Email> + email; + std::string town = "Springfield"; + Color color; + Age age; + float salary; + rfl::Description< + "The person's children. Pass an empty array for no children.", + std::vector> + children; + std::variant, int> variant; + std::tuple, int> tuple; + rfl::Rename<"taggedUnion", + rfl::TaggedUnion<"shape", Rectangle, Square, Circle>> + tagged_union; + rfl::Rename<"fieldVariant", FieldVariant> field_variant; +}; + +void test() { + std::cout << std::source_location::current().function_name() << std::endl; + + const auto json_schema = rfl::json::to_schema< + rfl::Description<"JSON schema that describes the required " + "attributes for the person class.", + Person>>(); + + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"radius":{"type":"number"},"shape":{"type":"string","enum":["Circle"]}},"required":["radius","shape"]},"test_json_schema__Person":{"type":"object","properties":{"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"color":{"type":"string","enum":["red","green","blue"]},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema__Circle"}},"required":["circle"]}]},"firstName":{"type":"string"},"lastName":{"type":"string"},"salary":{"type":"number"},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"town":{"type":"string"},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]}},"required":["age","children","color","email","fieldVariant","firstName","lastName","salary","taggedUnion","town","tuple","variant"]},"test_json_schema__Rectangle":{"type":"object","properties":{"height":{"type":"number"},"width":{"type":"number"}},"required":["height","width"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"height":{"type":"number"},"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"}},"required":["height","shape","width"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; + + if (json_schema != expected) { + std::cout << "Test failed. Expected:" << std::endl + << expected << std::endl + << "Got: " << std::endl + << json_schema << std::endl + << std::endl; + + return; + } + + std::cout << "OK" << std::endl << std::endl; +} +} // namespace test_json_schema diff --git a/tests/json/test_json_schema.hpp b/tests/json/test_json_schema.hpp new file mode 100644 index 00000000..ec30a8ba --- /dev/null +++ b/tests/json/test_json_schema.hpp @@ -0,0 +1,4 @@ +namespace test_json_schema { +void test(); +} + diff --git a/tests/json/tests.cpp b/tests/json/tests.cpp index e9af7282..aef770dd 100644 --- a/tests/json/tests.cpp +++ b/tests/json/tests.cpp @@ -30,6 +30,7 @@ #include "test_flatten_anonymous.hpp" #include "test_forward_list.hpp" #include "test_inside_function.hpp" +#include "test_json_schema.hpp" #include "test_list.hpp" #include "test_literal.hpp" #include "test_literal_map.hpp" @@ -152,6 +153,7 @@ int main() { test_meta_fields::test(); test_wstring::test(); + test_json_schema::test(); return 0; }