Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/content/json_schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,31 @@ This will result in the following JSON schema:

You can insert this into the tools mentioned above and see the generated code.

## Variants and tagged unions

`rfl::TaggedUnion` becomes `oneOf`: every alternative has a different tag, so a value
matches exactly one of them.

`rfl::Variant` and `std::variant` become `anyOf`, because their alternatives can overlap:
`1` is both an `integer` and a `number`, and `{"width": 1, "height": 2}` matches both
`Square` and `Rectangle` from the example in [variants](../variants_and_tagged_unions).
`oneOf` would reject such values, even though reflect-cpp reads them without problems.

If you know that the alternatives of your variants never overlap, you can pass
`rfl::VariantsAsOneOf` to get `oneOf` for `rfl::Variant` and `std::variant` as well:

```cpp
const std::string json_schema =
rfl::json::to_schema<rfl::Variant<int, std::string>, rfl::VariantsAsOneOf>();
```

Warning: `oneOf` rejects values that match more than one alternative, so with this
processor the schema rejects `1` for `rfl::Variant<int, double>`. Structs can overlap
as well, for instance when additional properties are allowed (see `rfl::NoExtraFields`).

`std::optional` and `rfl::Generic` stay `anyOf` either way. `std::optional` is not
a variant, and the alternatives of `rfl::Generic` overlap (`1` is both an `integer` and a `number`).

## Adding descriptions

JSON schemata also often contain descriptions. reflect-cpp supports this as well.
Expand Down
14 changes: 14 additions & 0 deletions docs/content/processors.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ reflect-cpp currently supports the following processors:
- `rfl::NoFieldNames`
- `rfl::NoOptionals`
- `rfl::UnderlyingEnums`
- `rfl::VariantsAsOneOf`
- `rfl::SnakeCaseToCamelCase`
- `rfl::SnakeCaseToPascalCase`

Expand Down Expand Up @@ -492,6 +493,19 @@ The resulting JSON string looks like this:
{"radius":2.0,"color":1}
```

### `rfl::VariantsAsOneOf`

By default, the JSON schema describes `rfl::Variant` and `std::variant` as `anyOf`.
By passing the processor `rfl::VariantsAsOneOf` to `rfl::json::to_schema`, they
become `oneOf`:

```cpp
rfl::json::to_schema<rfl::Variant<int, std::string>, rfl::VariantsAsOneOf>();
```

It only changes the schema, not reading or writing. Please refer to
the [JSON schema documentation](../json_schema) for details.

### `rfl::SnakeCaseToCamelCase`

Please refer to the example above.
Expand Down
1 change: 1 addition & 0 deletions include/rfl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
#include "rfl/UnderlyingEnums.hpp"
#include "rfl/Validator.hpp"
#include "rfl/Variant.hpp"
#include "rfl/VariantsAsOneOf.hpp"
#include "rfl/Vectorstring.hpp"
#include "rfl/always_false.hpp"
#include "rfl/apply.hpp"
Expand Down
31 changes: 31 additions & 0 deletions include/rfl/VariantsAsOneOf.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#ifndef RFL_VARIANTSASONEOF_HPP_
#define RFL_VARIANTSASONEOF_HPP_

namespace rfl {

/// A processor that makes the JSON schema describe rfl::Variant and
/// std::variant as oneOf instead of anyOf.
/// This is a marker type (doesn't modify data) that changes the generated
/// schema. It has no effect on reading or writing.
/// By default, untagged variants are described as anyOf, because their
/// alternatives can overlap: 1 matches both alternatives of
/// rfl::Variant<int, double>, and oneOf would reject it. rfl::TaggedUnion is
/// always described as oneOf, and std::optional and rfl::Generic always as
/// anyOf.
/// Usage: rfl::json::to_schema<MyStruct, VariantsAsOneOf>()
struct VariantsAsOneOf {
public:
/// Identity process function - returns the named tuple unchanged.
/// The actual change happens in the schema generation, not here.
/// @tparam StructType The struct type being processed
/// @param _named_tuple The named tuple representation of the struct
/// @return The same named tuple (unchanged)
template <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};

} // namespace rfl

#endif
32 changes: 32 additions & 0 deletions include/rfl/internal/variants_as_one_of_v.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#ifndef RFL_INTERNAL_VARIANTSASONEOF_HPP_
#define RFL_INTERNAL_VARIANTSASONEOF_HPP_

#include <type_traits>

#include "../Processors.hpp"
#include "../VariantsAsOneOf.hpp"

namespace rfl::internal {

template <class T>
class variants_as_one_of;

template <class T>
class variants_as_one_of : public std::false_type {};

template <>
class variants_as_one_of<VariantsAsOneOf> : public std::true_type {};

template <class Head, class... Tail>
struct variants_as_one_of<Processors<Head, Tail...>> {
static constexpr bool value = (variants_as_one_of<Head>::value || ... ||
variants_as_one_of<Tail>::value);
};

template <class T>
constexpr bool variants_as_one_of_v =
variants_as_one_of<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;

} // namespace rfl::internal

#endif
4 changes: 3 additions & 1 deletion include/rfl/parsing/FieldVariantParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "../Variant.hpp"
#include "../internal/no_duplicate_field_names.hpp"
#include "../internal/to_ptr_field.hpp"
#include "../internal/variants_as_one_of_v.hpp"
#include "../make_named_tuple.hpp"
#include "FieldVariantReader.hpp"
#include "Parser_base.hpp"
Expand Down Expand Up @@ -97,7 +98,8 @@ struct FieldVariantParser {
std::map<std::string, schema::Type>* _definitions) {
return schema::Type{schema::Type::AnyOf{
.types_ = std::vector<schema::Type>(
{one_field_to_type<FieldTypes>(_definitions)...})}};
{one_field_to_type<FieldTypes>(_definitions)...}),
.mutually_exclusive_ = internal::variants_as_one_of_v<ProcessorsType>}};
}

private:
Expand Down
5 changes: 4 additions & 1 deletion include/rfl/parsing/ParserRflVariant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "../internal/add_tags_to_variants_v.hpp"
#include "../internal/all_fields.hpp"
#include "../internal/nth_element_t.hpp"
#include "../internal/variants_as_one_of_v.hpp"
#include "../visit.hpp"
#include "FieldVariantParser.hpp"
#include "Parent.hpp"
Expand Down Expand Up @@ -202,7 +203,9 @@ class ParserRflVariant<R, W, rfl::Variant<AlternativeTypes...>,
} else {
return schema::Type{schema::Type::AnyOf{
.types_ = std::vector<schema::Type>(
{one_field_to_type<AlternativeTypes>(_definitions)...})}};
{one_field_to_type<AlternativeTypes>(_definitions)...}),
.mutually_exclusive_ =
internal::variants_as_one_of_v<ProcessorsType>}};
}
}

Expand Down
13 changes: 12 additions & 1 deletion include/rfl/parsing/ParserTaggedUnion.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "../Result.hpp"
#include "../TaggedUnion.hpp"
#include "../always_false.hpp"
#include "../internal/add_tags_to_variants_v.hpp"
#include "../internal/no_field_names_v.hpp"
#include "../internal/strings/strings.hpp"
#include "../named_tuple_t.hpp"
Expand Down Expand Up @@ -132,7 +133,17 @@ struct ParserTaggedUnion<R, W, TaggedUnion<_discriminator, AlternativeTypes...>,
using VariantType = std::variant<decltype(
wrap_if_necessary<AlternativeTypes>(std::declval<AlternativeTypes>()))
...>;
return Parser<R, W, VariantType, ProcessorsType>::to_schema(_definitions);
auto type =
Parser<R, W, VariantType, ProcessorsType>::to_schema(_definitions);
if constexpr (!internal::add_tags_to_variants_v<ProcessorsType> &&
!internal::add_namespaced_tags_to_variants_v<
ProcessorsType>) {
// The tags are unique, so a value can match at most one alternative.
if (auto* any_of = rfl::get_if<schema::Type::AnyOf>(&type.variant_)) {
any_of->mutually_exclusive_ = true;
}
}
return type;
}
}

Expand Down
10 changes: 9 additions & 1 deletion include/rfl/parsing/ParserVariant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
#include <type_traits>
#include <variant>

#include "../Generic.hpp"
#include "../NamedTuple.hpp"
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../internal/add_tags_to_variants_v.hpp"
#include "../internal/all_fields.hpp"
#include "../internal/to_ptr_field.hpp"
#include "../internal/variants_as_one_of_v.hpp"
#include "../visit.hpp"
#include "FieldVariantParser.hpp"
#include "Parent.hpp"
Expand Down Expand Up @@ -233,9 +235,15 @@ class ParserVariant<R, W, std::variant<AlternativeTypes...>, ProcessorsType> {
_definitions);

} else {
// rfl::Generic stays anyOf: 1 is both an integer and a number.
constexpr bool as_one_of =
internal::variants_as_one_of_v<ProcessorsType> &&
!std::is_same_v<std::variant<AlternativeTypes...>,
Generic::ReflectionType::value_type>;
return schema::Type{schema::Type::AnyOf{
.types_ = std::vector<schema::Type>(
{one_field_to_type<AlternativeTypes>(_definitions)...})}};
{one_field_to_type<AlternativeTypes>(_definitions)...}),
.mutually_exclusive_ = as_one_of}};
}
}

Expand Down
5 changes: 5 additions & 0 deletions include/rfl/parsing/schema/Type.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ struct RFL_API Type {

struct AnyOf {
std::vector<Type> types_;
/// True if a value may match only one of the types: always for a tagged
/// union, whose alternatives differ in their tag, and for other variants
/// when the VariantsAsOneOf processor is passed. JSON schema emits these
/// as oneOf instead of anyOf.
bool mutually_exclusive_ = false;
};

struct Deprecated {
Expand Down
3 changes: 3 additions & 0 deletions src/rfl/json/to_schema.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type,
for (const auto& t : _t.types_) {
any_of.emplace_back(type_to_json_schema_type(t, _no_required));
}
if (_t.mutually_exclusive_) {
return schema::Type{.value = schema::Type::OneOf{.oneOf = any_of}};
}
return schema::Type{.value = schema::Type::AnyOf{.anyOf = any_of}};

} else if constexpr (std::is_same<T, Type::DefaultVal>()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ TEST(json, test_default_val_tagged_union_schema) {
EXPECT_EQ(
(rfl::json::to_schema<
rfl::TaggedUnion<"type", DefaultAlternative, OtherAlternative>>()),
R"({"$schema":"https://json-schema.org/draft/2020-12/schema","anyOf":[{"$ref":"#/$defs/test_default_val_without_default_construction__DefaultAlternative__tagged"},{"$ref":"#/$defs/test_default_val_without_default_construction__OtherAlternative__tagged"}],"$defs":{"test_default_val_without_default_construction__DefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["DefaultAlternative"]},"output":{"type":"string","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]},"test_default_val_without_default_construction__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]}}})");
R"({"$schema":"https://json-schema.org/draft/2020-12/schema","oneOf":[{"$ref":"#/$defs/test_default_val_without_default_construction__DefaultAlternative__tagged"},{"$ref":"#/$defs/test_default_val_without_default_construction__OtherAlternative__tagged"}],"$defs":{"test_default_val_without_default_construction__DefaultAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["DefaultAlternative"]},"output":{"type":"string","default":"out.csv"},"k":{"type":"integer"}},"required":["type","k"]},"test_default_val_without_default_construction__OtherAlternative__tagged":{"type":"object","properties":{"type":{"type":"string","enum":["OtherAlternative"]},"q":{"type":"string"}},"required":["type","q"]}}})");
}

} // namespace test_default_val_without_default_construction
2 changes: 1 addition & 1 deletion tests/json/test_json_schema.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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":[{"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":{"oneOf":[{"$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);
}
Expand Down
Loading
Loading