diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..2e22cf9c7 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -44,6 +44,7 @@ #include "rfl/Processors.hpp" #include "rfl/Ref.hpp" #include "rfl/Rename.hpp" +#include "rfl/SchemaExt.hpp" #include "rfl/Settings.hpp" #include "rfl/Short.hpp" #include "rfl/Size.hpp" diff --git a/include/rfl/SchemaExt.hpp b/include/rfl/SchemaExt.hpp new file mode 100644 index 000000000..2589679b1 --- /dev/null +++ b/include/rfl/SchemaExt.hpp @@ -0,0 +1,196 @@ +#ifndef RFL_SCHEMAEXT_HPP_ +#define RFL_SCHEMAEXT_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +#include "Generic.hpp" +#include "Object.hpp" +#include "Processors.hpp" + +namespace rfl { + +/// Optional Draft 2020-12 JSON Schema annotations (`title`, `examples`, and +/// arbitrary `x-*` extension properties) attachable via `rfl::SchemaExtension`. +struct SchemaAnnotations { + std::optional title = std::nullopt; + std::optional> examples = std::nullopt; + Object extensions = {}; + + bool empty() const noexcept { + return (!title.has_value() || title->empty()) && + (!examples.has_value() || examples->empty()) && + extensions.empty(); + } +}; + +/// Specialize `rfl::SchemaName` to override the `$defs` identifier emitted +/// for type `T` (instead of the default mangled C++ type name). +/// +/// Supported members: +/// - `static constexpr std::string_view value = "ExportConfig";` OR +/// - `static std::string_view value();` (or returning `std::string`). +template +struct SchemaName {}; + +/// Specialize `rfl::SchemaExtension` on a custom wrapper type (such as +/// `ConfigOption`) or struct to attach `title`, `examples`, and arbitrary +/// `x-*` extension keywords to its generated JSON Schema node. +/// +/// Supported members: +/// - `static rfl::SchemaAnnotations annotations();` AND/OR +/// - `static rfl::Object extensions();` +/// - `static constexpr bool inline_schema = true;` (optional, for reflection +/// wrappers that should emit their schema inline rather than via `$defs`). +template +struct SchemaExtension {}; + +/// Opt-in JSON Schema processor: emit `minimum` and `maximum` bounds matching +/// C++ integer widths (`int8_t`..`int64_t`, `uint8_t`..`uint64_t`). +struct IntegerBounds { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +/// Opt-in JSON Schema processor: emit `minItems` and `maxItems` equal to +/// `prefixItems.size()` on fixed-arity tuple schemas. +struct TupleBounds { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +/// Opt-in JSON Schema processor: omit `"required": []` on object schemas that +/// have no required properties. +struct OmitEmptyRequired { + template + static auto process(auto&& _named_tuple) { + return std::forward(_named_tuple); + } +}; + +namespace internal { + +template +struct has_schema_processor : std::false_type {}; + +template +struct has_schema_processor : std::true_type {}; + +template +struct has_schema_processor> + : std::bool_constant<(has_schema_processor::value || ...)> {}; + +template +inline constexpr bool integer_bounds_v = + has_schema_processor>::value; + +template +inline constexpr bool tuple_bounds_v = + has_schema_processor>::value; + +template +inline constexpr bool omit_empty_required_v = + has_schema_processor>::value; + +// --- SchemaName detection --- + +template +concept HasSchemaNameTraitVar = requires { + { SchemaName::value } -> std::convertible_to; +}; + +template +concept HasSchemaNameTraitFn = requires { + { SchemaName::value() } -> std::convertible_to; +}; + +template +inline constexpr bool has_schema_name_v = + HasSchemaNameTraitVar> || + HasSchemaNameTraitFn>; + +template +inline std::string get_schema_name() { + using U = std::remove_cvref_t; + if constexpr (HasSchemaNameTraitFn) { + return std::string(std::string_view(SchemaName::value())); + } else if constexpr (HasSchemaNameTraitVar) { + return std::string(std::string_view(SchemaName::value)); + } else { + return {}; + } +} + +// --- SchemaExtension annotations --- + +template +concept HasSchemaExtensionAnnotationsFn = requires { + { SchemaExtension::annotations() } -> std::convertible_to; +}; + +template +concept HasSchemaExtensionExtensionsFn = requires { + { SchemaExtension::extensions() } -> std::convertible_to>; +}; + +template +concept HasSchemaExtensionInlineFlag = requires { + { SchemaExtension::inline_schema } -> std::convertible_to; +}; + +template +consteval bool schema_extension_inline() { + using U = std::remove_cvref_t; + if constexpr (HasSchemaExtensionInlineFlag) { + return static_cast(SchemaExtension::inline_schema); + } else { + return false; + } +} + +template +inline constexpr bool schema_extension_inline_v = schema_extension_inline(); + +template +inline constexpr bool has_schema_annotations_v = + HasSchemaExtensionAnnotationsFn> || + HasSchemaExtensionExtensionsFn>; + +template +inline SchemaAnnotations get_schema_annotations() { + using U = std::remove_cvref_t; + SchemaAnnotations out; + if constexpr (HasSchemaExtensionAnnotationsFn) { + auto ext = SchemaExtension::annotations(); + if (ext.title && !ext.title->empty()) out.title = std::move(ext.title); + if (ext.examples && !ext.examples->empty()) { + out.examples = std::move(ext.examples); + } + for (const auto& [k, v] : ext.extensions) { + out.extensions[k] = v; + } + } + if constexpr (HasSchemaExtensionExtensionsFn) { + for (const auto& [k, v] : SchemaExtension::extensions()) { + out.extensions[k] = v; + } + } + return out; +} + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/capnproto/is_named_type.hpp b/include/rfl/capnproto/is_named_type.hpp index cad64d631..4f27ae99a 100644 --- a/include/rfl/capnproto/is_named_type.hpp +++ b/include/rfl/capnproto/is_named_type.hpp @@ -8,10 +8,14 @@ namespace rfl::capnproto { inline bool is_named_type(const parsing::schema::Type& _type) { return _type.variant_.visit([&](const auto& _v) -> bool { using T = std::remove_cvref_t; - return std::is_same() || - std::is_same() || - std::is_same() || - std::is_same(); + if constexpr (std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same() || + std::is_same() || + std::is_same(); + } }); } diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp index b032c83b2..87289457b 100644 --- a/include/rfl/json/schema/Type.hpp +++ b/include/rfl/json/schema/Type.hpp @@ -1,10 +1,13 @@ #ifndef RFL_JSON_SCHEMA_TYPE_HPP_ #define RFL_JSON_SCHEMA_TYPE_HPP_ +#include #include #include #include +#include +#include "../../ExtraFields.hpp" #include "../../Flatten.hpp" #include "../../Generic.hpp" #include "../../Literal.hpp" @@ -19,20 +22,25 @@ namespace rfl::json::schema { struct Type { /// Common annotation fields shared by all schema subtypes. struct Annotations { + std::optional title{}; std::optional description{}; std::optional deprecated{}; std::optional deprecationMessage{}; rfl::Rename<"default", std::optional> defaultValue{}; + std::optional> examples{}; + rfl::ExtraFields extensions{}; }; struct Boolean { - rfl::Flatten annotations{}; Literal<"boolean"> type{}; + rfl::Flatten annotations{}; }; struct Integer { Literal<"integer"> type{}; rfl::Flatten annotations{}; + std::optional minimum{}; + std::optional> maximum{}; }; struct Number { @@ -101,7 +109,7 @@ struct Type { Literal<"object"> type{}; rfl::Flatten annotations{}; rfl::Object properties{}; - std::vector required{}; + std::optional> required{}; std::optional, bool>> additionalProperties{}; }; @@ -144,6 +152,8 @@ struct Type { rfl::Flatten annotations{}; std::vector prefixItems{}; bool items = false; + std::optional minItems{}; + std::optional maxItems{}; }; struct TypedArray { diff --git a/include/rfl/json/to_schema.hpp b/include/rfl/json/to_schema.hpp index 00cbcca9f..9aa0443fb 100644 --- a/include/rfl/json/to_schema.hpp +++ b/include/rfl/json/to_schema.hpp @@ -10,6 +10,7 @@ #include #include "../Processors.hpp" +#include "../SchemaExt.hpp" #include "../Variant.hpp" #include "../common.hpp" #include "../internal/default_if_missing_v.hpp" @@ -28,6 +29,16 @@ struct TypeHelper> { using JSONSchemaType = rfl::Variant...>; }; +struct SchemaRenderOptions { + bool no_required = false; + bool omit_empty_required = false; + bool tuple_bounds = false; +}; + +RFL_API std::string to_schema_internal_schema( + const parsing::schema::Definition& internal_schema, const yyjson_write_flag, + const SchemaRenderOptions& _options, const std::string& comment = ""); + RFL_API std::string to_schema_internal_schema( const parsing::schema::Definition& internal_schema, const yyjson_write_flag, const bool _no_required, const std::string& comment = ""); @@ -38,8 +49,12 @@ std::string to_schema(const yyjson_write_flag _flag = 0, const std::string& comment = "") { using P = Processors; const auto internal_schema = parsing::schema::make(); - return to_schema_internal_schema(internal_schema, _flag, - internal::default_if_missing_v

, comment); + const SchemaRenderOptions options{ + .no_required = internal::default_if_missing_v

, + .omit_empty_required = internal::omit_empty_required_v

, + .tuple_bounds = internal::tuple_bounds_v

, + }; + return to_schema_internal_schema(internal_schema, _flag, options, comment); } } // namespace rfl::json diff --git a/include/rfl/parsing/ParserBasicType.hpp b/include/rfl/parsing/ParserBasicType.hpp index f950ff017..5f71001dc 100644 --- a/include/rfl/parsing/ParserBasicType.hpp +++ b/include/rfl/parsing/ParserBasicType.hpp @@ -1,10 +1,13 @@ #ifndef RFL_PARSING_PARSER_BASIC_TYPE_HPP_ #define RFL_PARSING_PARSER_BASIC_TYPE_HPP_ +#include +#include #include #include #include "../Result.hpp" +#include "../SchemaExt.hpp" #include "../always_false.hpp" #include "../enums.hpp" #include "../from_named_tuple.hpp" @@ -78,6 +81,22 @@ struct ParserBasicType { if constexpr (std::is_same()) { return Type{Type::Boolean{}}; + } else if constexpr (std::is_integral_v && + internal::integer_bounds_v && + !schemaful::IsSchemafulReader && + !schemaful::IsSchemafulWriter) { + if constexpr (std::is_unsigned_v) { + return Type{Type::BoundedInteger{ + .minimum_ = 0, + .maximum_ = rfl::Variant( + static_cast(std::numeric_limits::max()))}}; + } else { + return Type{Type::BoundedInteger{ + .minimum_ = static_cast(std::numeric_limits::min()), + .maximum_ = rfl::Variant( + static_cast(std::numeric_limits::max()))}}; + } + } else if constexpr (std::is_same()) { return Type{Type::Int32{}}; diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..2b0e89a38 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -6,6 +6,7 @@ #include #include "../Result.hpp" +#include "../SchemaExt.hpp" #include "../always_false.hpp" #include "../internal/HasFromReflectionMethod.hpp" #include "../internal/always_inline.hpp" @@ -75,6 +76,18 @@ namespace rfl::parsing { +inline void apply_schema_annotations(schema::Type* _schema, + const SchemaAnnotations& _ann) { + if (_ann.empty()) { + return; + } + *_schema = schema::Type{schema::Type::Annotated{ + .title_ = _ann.title, + .examples_ = _ann.examples, + .extensions_ = _ann.extensions, + .type_ = Ref::make(std::move(*_schema))}}; +} + /// Default case - anything that cannot be explicitly matched. template requires AreReaderAndWriter @@ -600,14 +613,37 @@ struct Parser { } else if constexpr (rfl::internal::is_deprecated_v) { return make_deprecated(_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); + auto validated = make_validated(_definitions); + if constexpr (internal::has_schema_annotations_v) { + apply_schema_annotations(&validated, + internal::get_schema_annotations()); + } + return validated; + + } else if constexpr (internal::schema_extension_inline_v && + (internal::has_reflection_type_v || + internal::has_read_reflector || + internal::has_write_reflector)) { + schema::Type inner = [&]() { + if constexpr (internal::has_reflection_type_v) { + return Parser::to_schema(_definitions); + } else { + return Parser::ReflType, + ProcessorsType>::to_schema(_definitions); + } + }(); + if constexpr (internal::has_schema_annotations_v) { + apply_schema_annotations(&inner, internal::get_schema_annotations()); + } + return inner; + + } else if constexpr (std::is_class_v && std::is_aggregate_v) { + return make_reference(_definitions); } else if constexpr (internal::has_reflection_type_v || internal::has_read_reflector || @@ -687,6 +723,10 @@ struct Parser { _definitions); } } + if constexpr (internal::has_schema_annotations_v) { + apply_schema_annotations(&(*_definitions)[name], + internal::get_schema_annotations()); + } } return Type{Type::Reference{name}}; } diff --git a/include/rfl/parsing/make_type_name.hpp b/include/rfl/parsing/make_type_name.hpp index 35e9a554b..263d9f84e 100644 --- a/include/rfl/parsing/make_type_name.hpp +++ b/include/rfl/parsing/make_type_name.hpp @@ -1,6 +1,10 @@ #ifndef RFL_PARSING_MAKETYPENAME_HPP_ #define RFL_PARSING_MAKETYPENAME_HPP_ +#include +#include + +#include "../SchemaExt.hpp" #include "../type_name_t.hpp" #include "is_tagged_union_wrapper.hpp" @@ -14,7 +18,7 @@ namespace rfl::parsing { */ inline std::string replace_non_alphanumeric(std::string _str) { for (auto& ch : _str) { - ch = std::isalnum(ch) ? ch : '_'; + ch = std::isalnum(static_cast(ch)) ? ch : '_'; } return _str; } @@ -22,15 +26,29 @@ inline std::string replace_non_alphanumeric(std::string _str) { /** * @brief Generates a type name for the type U. * + * Respects `rfl::SchemaName` when specialized. + * * @tparam U The type to generate the name for. * @return The type name. */ template static std::string make_type_name() { if constexpr (is_tagged_union_wrapper_v) { - return replace_non_alphanumeric(type_name_t().str() + - "__tagged"); + using Inner = typename U::Type; + if constexpr (internal::has_schema_name_v) { + auto custom = internal::get_schema_name(); + if (!custom.empty()) { + return custom + "__tagged"; + } + } + return replace_non_alphanumeric(type_name_t().str() + "__tagged"); } else { + if constexpr (internal::has_schema_name_v) { + auto custom = internal::get_schema_name(); + if (!custom.empty()) { + return custom; + } + } return replace_non_alphanumeric(type_name_t().str()); } } diff --git a/include/rfl/parsing/schema/Type.hpp b/include/rfl/parsing/schema/Type.hpp index ea3bc17de..cc7c040b7 100644 --- a/include/rfl/parsing/schema/Type.hpp +++ b/include/rfl/parsing/schema/Type.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_SCHEMA_TYPE_HPP_ #include +#include #include #include #include @@ -33,6 +34,11 @@ struct RFL_API Type { struct Integer {}; + struct BoundedInteger { + int64_t minimum_; + rfl::Variant maximum_; + }; + struct Float {}; struct Double {}; @@ -114,12 +120,20 @@ struct RFL_API Type { ValidationType validation_; }; + struct Annotated { + std::optional title_; + std::optional> examples_; + rfl::Object extensions_; + Ref type_; + }; + using VariantType = rfl::Variant; + UInt64, Integer, BoundedInteger, Float, Double, String, + AnyOf, Annotated, DefaultVal, Deprecated, Description, + DescribedLiteral, FixedSizeTypedArray, Literal, Object, + Optional, Reference, StringMap, Tuple, TypedArray, + Validated>; /** * @brief Default constructor. diff --git a/src/rfl/avro/to_schema.cpp b/src/rfl/avro/to_schema.cpp index 5b8e25a3b..c1bc3e512 100644 --- a/src/rfl/avro/to_schema.cpp +++ b/src/rfl/avro/to_schema.cpp @@ -26,6 +26,9 @@ SOFTWARE. #include "rfl/avro/to_schema.hpp" +#include +#include + #include "rfl/avro/schema/Type.hpp" #include "rfl/json.hpp" #include "rfl/parsing/schemaful/tuple_to_object.hpp" @@ -35,8 +38,12 @@ namespace rfl::avro { inline bool is_named_type(const parsing::schema::Type& _type) { return _type.variant_.visit([&](const auto& _v) -> bool { using T = std::remove_cvref_t; - return std::is_same() || - std::is_same(); + if constexpr (std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same(); + } }); } @@ -63,6 +70,22 @@ schema::Type type_to_avro_schema_type( std::is_same()) { return schema::Type{.value = schema::Type::Long{}}; + } else if constexpr (std::is_same()) { + const bool fits_i32 = + _t.minimum_ >= std::numeric_limits::min() && + _t.maximum_.visit([](const auto _m) { + if constexpr (std::is_signed_v) { + return _m <= std::numeric_limits::max(); + } else { + return _m <= + static_cast(std::numeric_limits::max()); + } + }); + if (fits_i32) { + return schema::Type{.value = schema::Type::Int{}}; + } + return schema::Type{.value = schema::Type::Long{}}; + } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::Float{}}; @@ -80,7 +103,8 @@ schema::Type type_to_avro_schema_type( } return schema::Type{.value = any_of}; - } else if constexpr (std::is_same()) { + } else if constexpr (std::is_same() || + std::is_same()) { return type_to_avro_schema_type(*_t.type_, _definitions, _already_known, _num_unnamed); diff --git a/src/rfl/capnproto/to_schema.cpp b/src/rfl/capnproto/to_schema.cpp index 6d166e286..e4c0af618 100644 --- a/src/rfl/capnproto/to_schema.cpp +++ b/src/rfl/capnproto/to_schema.cpp @@ -26,6 +26,8 @@ SOFTWARE. #include "rfl/capnproto/to_schema.hpp" +#include +#include #include #include #include @@ -139,6 +141,17 @@ schema::Type reference_to_capnproto_schema_type( } } +bool is_literal_definition(const parsing::schema::Type& _type) { + return _type.variant_.visit([](const auto& _def) -> bool { + using D = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return is_literal_definition(*_def.type_); + } else { + return std::is_same_v; + } + }); +} + schema::Type string_map_to_capnproto_schema_type( const parsing::schema::Type::StringMap& _map, const std::map& _definitions, @@ -151,12 +164,7 @@ schema::Type string_map_to_capnproto_schema_type( if constexpr (std::is_same_v) { const auto it = _definitions.find(_value.type_name); return _cnp_types->enums_.contains(_value.type_name) || - (it != _definitions.end() && - it->second.variant_.visit([](const auto& _definition) { - return std::is_same_v< - std::remove_cvref_t, - parsing::schema::Type::Literal>; - })); + (it != _definitions.end() && is_literal_definition(it->second)); } else { return !std::is_same_v && !std::is_same_v && !std::is_same_v && !std::is_same_v && @@ -196,6 +204,33 @@ schema::Type type_to_capnproto_schema_type( std::is_same()) { return schema::Type{.value = schema::Type::Int32{}}; + } else if constexpr (std::is_same()) { + if (_t.minimum_ < 0) { + const bool fits_i32 = + _t.minimum_ >= std::numeric_limits::min() && + _t.maximum_.visit([](const auto _m) { + if constexpr (std::is_signed_v) { + return _m <= std::numeric_limits::max(); + } else { + return _m <= static_cast( + std::numeric_limits::max()); + } + }); + return fits_i32 ? schema::Type{.value = schema::Type::Int32{}} + : schema::Type{.value = schema::Type::Int64{}}; + } + const bool fits_u32 = _t.maximum_.visit([](const auto _m) { + if constexpr (std::is_signed_v) { + return _m >= 0 && + static_cast(_m) <= + std::numeric_limits::max(); + } else { + return _m <= std::numeric_limits::max(); + } + }); + return fits_u32 ? schema::Type{.value = schema::Type::UInt32{}} + : schema::Type{.value = schema::Type::UInt64{}}; + } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::Int64{}}; @@ -222,7 +257,8 @@ schema::Type type_to_capnproto_schema_type( return type_to_capnproto_schema_type(*_t.type_, _definitions, _parent, _cnp_types); - } else if constexpr (std::is_same()) { + } else if constexpr (std::is_same() || + std::is_same()) { return type_to_capnproto_schema_type(*_t.type_, _definitions, _parent, _cnp_types); diff --git a/src/rfl/json/to_schema.cpp b/src/rfl/json/to_schema.cpp index 3fda88bd2..ef58db762 100644 --- a/src/rfl/json/to_schema.cpp +++ b/src/rfl/json/to_schema.cpp @@ -32,7 +32,7 @@ SOFTWARE. namespace rfl::json { schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, - const bool _no_required); + const SchemaRenderOptions& _options); bool is_optional(const parsing::schema::Type& _t) { return _t.variant_.visit([&](const auto& _v) -> bool { @@ -44,6 +44,9 @@ bool is_optional(const parsing::schema::Type& _t) { parsing::schema::Type::Description>) { return is_optional(*_v.type_); + } else if constexpr (std::is_same_v) { + return is_optional(*_v.type_); + } else if constexpr (std::is_same_v) { return is_optional(*_v.type_); @@ -62,7 +65,8 @@ std::string numeric_type_to_string(const parsing::schema::Type& _type) { std::is_same() || 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(); @@ -74,28 +78,28 @@ std::string numeric_type_to_string(const parsing::schema::Type& _type) { schema::Type handle_validation_type( const parsing::schema::Type& _type, const parsing::schema::ValidationType& _validation_type, - const bool _no_required) { + const SchemaRenderOptions& _options) { 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, _no_required)); + all_of.emplace_back(handle_validation_type(_type, t, _options)); } 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, _no_required)); + any_of.emplace_back(handle_validation_type(_type, t, _options)); } 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, _no_required)); + one_of.emplace_back(handle_validation_type(_type, t, _options)); } return schema::Type{.value = schema::Type::OneOf{.oneOf = one_of}}; @@ -103,7 +107,7 @@ schema::Type handle_validation_type( return schema::Type{.value = schema::Type::Regex{.pattern = _v.pattern_}}; } else if constexpr (std::is_same()) { - auto t = type_to_json_schema_type(_type, _no_required); + auto t = type_to_json_schema_type(_type, _options); // Size validates decoded bytes, not the length of the Base64 text. if (const auto* str = rfl::get_if(&t.value); str && str->contentEncoding) { @@ -138,7 +142,7 @@ schema::Type handle_validation_type( .size_limit_ = rfl::Ref::make(limiter)}}); } return handle_validation_type(_type, ValidationType{.variant_ = v}, - _no_required); + _options); } } return t; @@ -197,13 +201,17 @@ schema::Type handle_validation_type( } schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, - const bool _no_required) { + const SchemaRenderOptions& _options) { 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()) { + return schema::Type{.value = schema::Type::Integer{ + .minimum = _t.minimum_, .maximum = _t.maximum_}}; + } else if constexpr (std::is_same() || std::is_same() || std::is_same() || @@ -226,12 +234,28 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, } 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, _no_required)); + any_of.emplace_back(type_to_json_schema_type(t, _options)); } 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_, _options); + const auto update_annotations = [&](auto _v) -> schema::Type { + if (_t.title_ && !_t.title_->empty()) { + _v.annotations.value_.title = *_t.title_; + } + if (_t.examples_ && !_t.examples_->empty()) { + _v.annotations.value_.examples = *_t.examples_; + } + for (const auto& [k, val] : _t.extensions_) { + _v.annotations.value_.extensions[k] = val; + } + return schema::Type{std::move(_v)}; + }; + return rfl::visit(update_annotations, std::move(res.value)); + } else if constexpr (std::is_same()) { - auto res = type_to_json_schema_type(*_t.type_, _no_required); + auto res = type_to_json_schema_type(*_t.type_, _options); if (!_t.default_value_.has_value()) { return res; } @@ -242,7 +266,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, return rfl::visit(update_prediction, res.value); } else if constexpr (std::is_same()) { - auto res = type_to_json_schema_type(*_t.type_, _no_required); + auto res = type_to_json_schema_type(*_t.type_, _options); const auto update_prediction = [&](auto _v) -> schema::Type { _v.annotations.value_.description = _t.description_; _v.annotations.value_.deprecated = true; @@ -252,7 +276,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, return rfl::visit(update_prediction, res.value); } else if constexpr (std::is_same()) { - auto res = type_to_json_schema_type(*_t.type_, _no_required); + auto res = type_to_json_schema_type(*_t.type_, _options); const auto update_prediction = [&](auto _v) -> schema::Type { _v.annotations.value_.description = _t.description_; return schema::Type{_v}; @@ -263,7 +287,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, return schema::Type{ .value = schema::Type::FixedSizeTypedArray{ .items = Ref::make( - type_to_json_schema_type(*_t.type_, _no_required)), + type_to_json_schema_type(*_t.type_, _options)), .minItems = _t.size_, .maxItems = _t.size_}}; @@ -291,8 +315,8 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, auto properties = rfl::Object(); auto required = std::vector(); for (const auto& [k, v] : _t.types_) { - properties[k] = type_to_json_schema_type(v, _no_required); - if (!is_optional(v) && !_no_required) { + properties[k] = type_to_json_schema_type(v, _options); + if (!is_optional(v) && !_options.no_required) { required.push_back(k); } } @@ -308,20 +332,44 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, return std::nullopt; } return std::make_shared( - type_to_json_schema_type(*_a, _no_required)); + type_to_json_schema_type(*_a, _options)); } }, _t.additional_properties_); + std::optional> req_field = + (_options.omit_empty_required && required.empty()) + ? std::nullopt + : std::optional>(std::move(required)); return schema::Type{.value = schema::Type::Object{ .properties = properties, - .required = required, + .required = std::move(req_field), .additionalProperties = additional_properties}}; } else if constexpr (std::is_same()) { + auto inner = type_to_json_schema_type(*_t.type_, _options); + if (auto* any_of = rfl::get_if(&inner.value); + any_of && !any_of->annotations.value_.title && + !any_of->annotations.value_.description && + !any_of->annotations.value_.deprecated && + !any_of->annotations.value_.deprecationMessage && + !any_of->annotations.value_.defaultValue.value().has_value() && + !any_of->annotations.value_.examples && + any_of->annotations.value_.extensions.empty()) { + bool has_null = false; + for (const auto& branch : any_of->anyOf) { + if (rfl::holds_alternative(branch.value)) { + has_null = true; + break; + } + } + if (!has_null) { + any_of->anyOf.emplace_back(schema::Type{schema::Type::Null{}}); + } + return inner; + } return schema::Type{ .value = schema::Type::AnyOf{ - .anyOf = {type_to_json_schema_type(*_t.type_, _no_required), - schema::Type{schema::Type::Null{}}}}}; + .anyOf = {std::move(inner), schema::Type{schema::Type::Null{}}}}}; } else if constexpr (std::is_same()) { return schema::Type{ @@ -331,23 +379,36 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, return schema::Type{ .value = schema::Type::StringMap{ .additionalProperties = Ref::make( - type_to_json_schema_type(*_t.value_type_, _no_required))}}; + type_to_json_schema_type(*_t.value_type_, _options))}}; } 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, _no_required)); + items.emplace_back(type_to_json_schema_type(t, _options)); + } + auto tuple_schema = schema::Type::Tuple{.prefixItems = items}; + if (_options.tuple_bounds) { + tuple_schema.minItems = items.size(); + tuple_schema.maxItems = items.size(); } - return schema::Type{.value = schema::Type::Tuple{.prefixItems = items}}; + return schema::Type{.value = std::move(tuple_schema)}; } else if constexpr (std::is_same()) { return schema::Type{ .value = schema::Type::TypedArray{ .items = Ref::make( - type_to_json_schema_type(*_t.type_, _no_required))}}; + type_to_json_schema_type(*_t.type_, _options))}}; } else if constexpr (std::is_same()) { - return handle_validation_type(*_t.type_, _t.validation_, _no_required); + auto validated = + handle_validation_type(*_t.type_, _t.validation_, _options); + if (rfl::holds_alternative(_t.type_->variant_)) { + auto bounded = type_to_json_schema_type(*_t.type_, _options); + return schema::Type{ + .value = schema::Type::AllOf{ + .allOf = {std::move(bounded), std::move(validated)}}}; + } + return validated; } else { static_assert(rfl::always_false_v, "Not all cases were covered."); @@ -359,11 +420,11 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, std::string to_schema_internal_schema( const parsing::schema::Definition& internal_schema, - const yyjson_write_flag _flag, const bool _no_required, + const yyjson_write_flag _flag, const SchemaRenderOptions& _options, const std::string& comment) { auto definitions = std::map(); for (const auto& [k, v] : internal_schema.definitions_) { - definitions[k] = type_to_json_schema_type(v, _no_required); + definitions[k] = type_to_json_schema_type(v, _options); } using JSONSchemaType = typename TypeHelper::JSONSchemaType; @@ -376,9 +437,18 @@ std::string to_schema_internal_schema( .definitions = definitions, }; }; - auto root = type_to_json_schema_type(internal_schema.root_, _no_required); + auto root = type_to_json_schema_type(internal_schema.root_, _options); const auto json_schema = rfl::visit(to_schema, std::move(root.value)); return write(json_schema, _flag); } +std::string to_schema_internal_schema( + const parsing::schema::Definition& internal_schema, + const yyjson_write_flag _flag, const bool _no_required, + const std::string& comment) { + return to_schema_internal_schema( + internal_schema, _flag, + SchemaRenderOptions{.no_required = _no_required}, comment); +} + } // namespace rfl::json diff --git a/tests/json/test_json_schema.cpp b/tests/json/test_json_schema.cpp index 80a029fe5..2e56e696a 100644 --- a/tests/json/test_json_schema.cpp +++ b/tests/json/test_json_schema.cpp @@ -67,7 +67,7 @@ TEST(json, test_json_schema) { Person>>(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"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,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema__Square__tagged"},{"$ref":"#/$defs/test_json_schema__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema__Circle"}},"required":["circle"]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema__WithExtraFields"}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant","generic","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"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"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","$defs":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}},{"type":"null"}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"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,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema__Square__tagged"},{"$ref":"#/$defs/test_json_schema__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema__Circle"}},"required":["circle"]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema__WithExtraFields"}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant","generic","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"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"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_json_schema4.cpp b/tests/json/test_json_schema4.cpp index 6ff498eca..ed296f047 100644 --- a/tests/json/test_json_schema4.cpp +++ b/tests/json/test_json_schema4.cpp @@ -65,7 +65,7 @@ TEST(json, test_json_schema4) { rfl::json::to_schema(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema4__Person","$defs":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema4__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":[]},"test_json_schema4__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":[]},"test_json_schema4__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"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,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema4__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema4__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema4__Square__tagged"},{"$ref":"#/$defs/test_json_schema4__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema4__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema4__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema4__Circle"}},"required":[]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema4__WithExtraFields"}},"required":[]},"test_json_schema4__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":[]},"test_json_schema4__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":[]},"test_json_schema4__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":[],"additionalProperties":{"type":"string"}}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_json_schema4__Person","$defs":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/$defs/rfl__Generic"}},{"type":"array","items":{"$ref":"#/$defs/rfl__Generic"}},{"type":"null"}]},"test_json_schema4__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":[]},"test_json_schema4__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":[]},"test_json_schema4__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"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,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/$defs/test_json_schema4__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/$defs/test_json_schema4__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/$defs/test_json_schema4__Rectangle__tagged"},{"$ref":"#/$defs/test_json_schema4__Square__tagged"},{"$ref":"#/$defs/test_json_schema4__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/$defs/test_json_schema4__Rectangle"}},"required":[]},{"type":"object","properties":{"square":{"$ref":"#/$defs/test_json_schema4__Square"}},"required":[]},{"type":"object","properties":{"circle":{"$ref":"#/$defs/test_json_schema4__Circle"}},"required":[]}]},"generic":{"$ref":"#/$defs/rfl__Generic"},"with_extra_fields":{"$ref":"#/$defs/test_json_schema4__WithExtraFields"}},"required":[]},"test_json_schema4__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":[]},"test_json_schema4__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":[]},"test_json_schema4__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":[]},"test_json_schema4__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":[],"additionalProperties":{"type":"string"}}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_optional_variant_schema.cpp b/tests/json/test_optional_variant_schema.cpp new file mode 100644 index 000000000..312c21da6 --- /dev/null +++ b/tests/json/test_optional_variant_schema.cpp @@ -0,0 +1,51 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_optional_variant_schema { + +struct WithOptionalVariants { + std::optional> std_var; + std::optional> rfl_var; + rfl::Description<"A described optional variant", + std::optional>> + described; + std::optional> nested_opt; +}; + +TEST(json, optional_std_variant_flattens_any_of) { + const auto schema = + rfl::json::to_schema>>(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}],"$defs":{}})"; + EXPECT_EQ(schema, expected); +} + +TEST(json, optional_rfl_variant_flattens_any_of) { + const auto schema = + rfl::json::to_schema>>(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}],"$defs":{}})"; + EXPECT_EQ(schema, expected); +} + +TEST(json, struct_with_optional_variants_and_description) { + const auto schema = rfl::json::to_schema(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/$defs/test_optional_variant_schema__WithOptionalVariants","$defs":{"test_optional_variant_schema__WithOptionalVariants":{"type":"object","properties":{"std_var":{"anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}]},"rfl_var":{"anyOf":[{"type":"integer"},{"type":"string"},{"type":"null"}]},"described":{"description":"A described optional variant","anyOf":[{"type":"boolean"},{"type":"number"},{"type":"null"}]},"nested_opt":{"anyOf":[{"type":"integer"},{"type":"null"}]}},"required":[]}}})"; + EXPECT_EQ(schema, expected); +} + +TEST(json, optional_preserves_inner_annotated_variant) { + const auto schema = rfl::json::to_schema< + std::optional>>>(); + const std::string expected = + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"description":"inner","anyOf":[{"type":"integer"},{"type":"string"}]},{"type":"null"}],"$defs":{}})"; + EXPECT_EQ(schema, expected); +} + +} // namespace test_optional_variant_schema diff --git a/tests/json/test_schema_ext_and_bounds.cpp b/tests/json/test_schema_ext_and_bounds.cpp new file mode 100644 index 000000000..89648c285 --- /dev/null +++ b/tests/json/test_schema_ext_and_bounds.cpp @@ -0,0 +1,243 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_schema_ext_and_bounds { + +struct CustomNamedConfig { + std::string host = "localhost"; + int port = 8080; +}; + +struct AnnotatedType { + std::string name; +}; + +struct InlineToken { + using ReflectionType = std::string; + std::string value; + const std::string& reflection() const { return value; } +}; + +struct InlineHost { + InlineToken token; +}; + +struct BoundedIntegers { + int8_t i8; + uint8_t u8; + int16_t i16; + uint16_t u16; + int32_t i32; + uint32_t u32; + int64_t i64; + uint64_t u64; + rfl::Validator> port; +}; + +struct TupleAndOptional { + std::optional opt; + std::tuple pair; +}; + +struct FnNamedConfig { + int v = 0; +}; + +using AnnotatedPort = rfl::Validator, rfl::Maximum<65535>>; + +struct WithAnnotatedValidator { + AnnotatedPort port = 80; +}; + +struct WithRequiredAndOptional { + std::string required_field; + std::optional opt; +}; + +struct BooleanDefaultOrder { + rfl::DefaultVal enabled = true; +}; + +} // namespace test_schema_ext_and_bounds + +namespace rfl { + +template <> +struct SchemaName { + static constexpr std::string_view value = "ExportedConfig"; +}; + +template <> +struct SchemaExtension { + static SchemaAnnotations annotations() { + SchemaAnnotations ann; + ann.title = "Annotated Title"; + ann.examples = std::vector{Generic("ex1")}; + ann.extensions["x-category"] = Generic("core"); + return ann; + } + static Object extensions() { + Object ext; + ext["x-stability"] = Generic("stable"); + return ext; + } +}; + +template <> +struct SchemaExtension { + static constexpr bool inline_schema = true; + static SchemaAnnotations annotations() { + SchemaAnnotations ann; + ann.title = "Inline Token"; + ann.extensions["x-sensitive"] = Generic(true); + return ann; + } +}; + +template <> +struct SchemaName { + static std::string value() { return "DynamicConfig"; } +}; + +template <> +struct SchemaExtension { + static constexpr bool inline_schema = true; + static SchemaAnnotations annotations() { + SchemaAnnotations ann; + ann.title = "TCP Port"; + return ann; + } +}; + +} // namespace rfl + +namespace test_schema_ext_and_bounds { + +TEST(json, test_schema_name_override) { + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("$ref":"#/$defs/ExportedConfig")"), + std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("ExportedConfig":{"type":"object")"), + std::string::npos) + << schema; + + using Tagged = rfl::TaggedUnion<"kind", CustomNamedConfig>; + const auto tagged_schema = rfl::json::to_schema(); + EXPECT_NE(tagged_schema.find(R"(ExportedConfig__tagged)"), std::string::npos) + << tagged_schema; + + const auto fn_schema = rfl::json::to_schema(); + EXPECT_NE(fn_schema.find(R"("$ref":"#/$defs/DynamicConfig")"), + std::string::npos) + << fn_schema; +} + +TEST(json, test_schema_extension_title_examples_extensions_and_inline) { + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find(R"("title":"Annotated Title")"), std::string::npos) + << schema; + EXPECT_NE(schema.find(R"("examples":["ex1"])"), std::string::npos) << schema; + EXPECT_NE(schema.find(R"("x-category":"core")"), std::string::npos) << schema; + EXPECT_NE(schema.find(R"("x-stability":"stable")"), std::string::npos) + << schema; + + const auto inline_schema = rfl::json::to_schema(); + EXPECT_EQ(inline_schema.find("InlineToken"), std::string::npos) + << inline_schema; + EXPECT_NE(inline_schema.find( + R"("token":{"type":"string","title":"Inline Token","x-sensitive":true})"), + std::string::npos) + << inline_schema; + + // SchemaExtension with inline_schema = true on a Validator must preserve + // validation constraints (and apply annotations). + const auto val_schema = rfl::json::to_schema(); + EXPECT_NE(val_schema.find(R"("title":"TCP Port")"), std::string::npos) + << val_schema; + EXPECT_NE(val_schema.find(R"("minimum":1)"), std::string::npos) << val_schema; + EXPECT_NE(val_schema.find(R"("maximum":65535)"), std::string::npos) + << val_schema; +} + +TEST(json, test_schema_integer_bounds_processor) { + // Without IntegerBounds, plain integers have no minimum/maximum. + const auto plain = rfl::json::to_schema(); + EXPECT_NE(plain.find(R"("u8":{"type":"integer"})"), std::string::npos) + << plain; + + const auto bounded = + rfl::json::to_schema(); + EXPECT_NE(bounded.find(R"("i8":{"type":"integer","minimum":-128,"maximum":127})"), + std::string::npos) + << bounded; + EXPECT_NE(bounded.find(R"("u8":{"type":"integer","minimum":0,"maximum":255})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find(R"("i16":{"type":"integer","minimum":-32768,"maximum":32767})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find(R"("u16":{"type":"integer","minimum":0,"maximum":65535})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("i32":{"type":"integer","minimum":-2147483648,"maximum":2147483647})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("u32":{"type":"integer","minimum":0,"maximum":4294967295})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("i64":{"type":"integer","minimum":-9223372036854775808,"maximum":9223372036854775807})"), + std::string::npos) + << bounded; + EXPECT_NE( + bounded.find( + R"("u64":{"type":"integer","minimum":0,"maximum":18446744073709551615})"), + std::string::npos) + << bounded; + // Validated integer combines width bounds and validator via allOf. + EXPECT_NE( + bounded.find( + R"("port":{"allOf":[{"type":"integer","minimum":0,"maximum":65535},{"minimum":1,"type":"integer"}]})"), + std::string::npos) + << bounded; +} + +TEST(json, test_schema_tuple_bounds_omit_empty_required_and_bool_order) { + const auto schema = + rfl::json::to_schema(); + EXPECT_EQ(schema.find(R"("required")"), std::string::npos) << schema; + EXPECT_NE(schema.find(R"("minItems":2,"maxItems":2)"), std::string::npos) + << schema; + + // OmitEmptyRequired keeps non-empty required arrays intact. + const auto non_empty = + rfl::json::to_schema(); + EXPECT_NE(non_empty.find(R"("required":["required_field"])"), + std::string::npos) + << non_empty; + + // Boolean schema emits "type":"boolean" before "default":true. + const auto bool_schema = rfl::json::to_schema(); + EXPECT_NE(bool_schema.find(R"("enabled":{"type":"boolean","default":true})"), + std::string::npos) + << bool_schema; +} + +} // namespace test_schema_ext_and_bounds