diff --git a/include/rfl.hpp b/include/rfl.hpp index 432fff2f6..e340b957f 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -31,6 +31,7 @@ #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" #include "rfl/Literal.hpp" +#include "rfl/Metadata.hpp" #include "rfl/NamedTuple.hpp" #include "rfl/NoExtraFields.hpp" #include "rfl/NoFieldNames.hpp" diff --git a/include/rfl/Metadata.hpp b/include/rfl/Metadata.hpp new file mode 100644 index 000000000..bb9602b2d --- /dev/null +++ b/include/rfl/Metadata.hpp @@ -0,0 +1,157 @@ +#ifndef RFL_METADATA_HPP_ +#define RFL_METADATA_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +namespace rfl { + +/// Out-of-band per-field metadata (description and optional deprecation) that +/// attaches schema/documentation prose to a reflected struct WITHOUT embedding +/// long `StringLiteral` non-type template parameters into C++ field types. +struct FieldMeta { + /// Processed wire field name, or pre-processor field name (C++ member name, + /// or explicit `rfl::Rename` name when renamed). Exact wire-name matches + /// take precedence over pre-processor names. + std::string_view name; + + /// Optional human-readable description emitted in generated schemas. + std::string_view description = {}; + + /// Optional deprecation message. When non-empty, marks the field deprecated + /// in generated schemas (with `description`, matching `rfl::Deprecated`). + std::string_view deprecation_message = {}; +}; + +/// Specialize `rfl::Metadata` to attach zero-bloat out-of-band metadata to +/// struct `T` without wrapping its fields in `rfl::Description` / +/// `rfl::Deprecated`. +/// +/// Supported members on a specialization `rfl::Metadata`: +/// - `static constexpr std::array fields = ...;` +/// (or any contiguous range / `std::span`), OR +/// - `static std::span fields();` (or returning a +/// `const` lvalue reference to a contiguous range; may be defined out-of-line +/// in a `.cpp` file for complete compile-time isolation). +/// - Optional struct-level description: +/// `static constexpr std::string_view description = "...";` (or a non-null +/// `const char*`) or `static std::string_view description();` +/// +/// Notes: +/// - `rfl::Metadata` attaches to `Inner`'s own schema definition +/// (`$defs/Inner`); fields flattened via `rfl::Flatten` are looked up +/// on the enclosing struct's `rfl::Metadata`. +/// - For `rfl::TaggedUnion` alternatives wrapped in an internal tagged-union +/// wrapper, `rfl::Metadata` is consulted automatically. +/// - For custom types with `ReflectionType` or `rfl::Reflector`, +/// struct-level `Metadata::description` is honored; `Metadata::fields` +/// applies to reflected aggregate structs. +template +struct Metadata {}; + +namespace internal { + +template +concept HasFieldMetaVar = requires { + { Metadata::fields } -> std::ranges::contiguous_range; + { Metadata::fields } -> std::ranges::sized_range; + requires !std::is_member_object_pointer_v::fields)>; + requires std::same_as::fields)>>, + FieldMeta>; +}; + +template +concept HasAnyFieldMetaFn = requires { + { Metadata::fields() } -> std::ranges::contiguous_range; + { Metadata::fields() } -> std::ranges::sized_range; + requires std::same_as::fields())>>, + FieldMeta>; +}; + +template +concept HasFieldMetaFn = + HasAnyFieldMetaFn && + std::ranges::borrowed_range::fields())>; + +template +constexpr bool has_field_metadata_v = + HasFieldMetaVar> || + HasAnyFieldMetaFn>; + +template +std::span get_field_metadata() { + using U = std::remove_cvref_t; + static_assert( + !HasAnyFieldMetaFn || HasFieldMetaFn, + "rfl::Metadata::fields() must return a borrowed contiguous range " + "(for example, std::span or const auto&) so the " + "returned view does not dangle."); + if constexpr (HasFieldMetaFn) { + auto&& r = Metadata::fields(); + return std::span(std::ranges::data(r), + std::ranges::size(r)); + } else if constexpr (HasFieldMetaVar) { + return std::span(std::ranges::data(Metadata::fields), + std::ranges::size(Metadata::fields)); + } else { + return {}; + } +} + +template +concept HasStructDescriptionVar = requires { + { Metadata::description } -> std::convertible_to; + requires !std::is_member_object_pointer_v::description)>; +}; + +template +concept HasStructDescriptionFn = requires { + { Metadata::description() } -> std::convertible_to; +}; + +template +constexpr bool has_struct_description_v = + HasStructDescriptionVar> || + HasStructDescriptionFn>; + +template +std::string get_struct_description() { + using U = std::remove_cvref_t; + if constexpr (HasStructDescriptionFn) { + return std::string(std::string_view(Metadata::description())); + } else if constexpr (HasStructDescriptionVar) { + return std::string(std::string_view(Metadata::description)); + } else { + return {}; + } +} + +inline std::optional find_field_metadata( + const std::span _meta, const std::string_view _wire_name, + const std::string_view _raw_name = {}) noexcept { + for (const auto& entry : _meta) { + if (entry.name == _wire_name) { + return entry; + } + } + if (!_raw_name.empty() && _raw_name != _wire_name) { + for (const auto& entry : _meta) { + if (entry.name == _raw_name) { + return entry; + } + } + } + return std::nullopt; +} + +} // 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..a45a4986d 100644 --- a/include/rfl/capnproto/is_named_type.hpp +++ b/include/rfl/capnproto/is_named_type.hpp @@ -1,6 +1,8 @@ #ifndef RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ #define RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ +#include + #include "../parsing/schema/Type.hpp" namespace rfl::capnproto { @@ -8,10 +10,15 @@ 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 || + 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/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index edeaa3f4e..1e5a0e2d1 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -15,6 +16,7 @@ #include #include "../Generic.hpp" +#include "../Metadata.hpp" #include "../NamedTuple.hpp" #include "../Result.hpp" #include "../internal/always_inline.hpp" @@ -148,6 +150,22 @@ inline void set_schema_default_value(Generic _default, schema::Type* _schema) { }); } +/// Applies out-of-band `rfl::FieldMeta` (description / deprecation) to a field +/// schema node without embedding long StringLiteral NTTPs in field types. +inline void apply_field_metadata(schema::Type* _schema, + const FieldMeta& _meta) { + if (!_meta.deprecation_message.empty()) { + *_schema = schema::Type{schema::Type::Deprecated{ + .deprecation_message_ = std::string(_meta.deprecation_message), + .description_ = std::string(_meta.description), + .type_ = Ref::make(std::move(*_schema))}}; + } else if (!_meta.description.empty()) { + *_schema = schema::Type{schema::Type::Description{ + .description_ = std::string(_meta.description), + .type_ = Ref::make(std::move(*_schema))}}; + } +} + /// Free per-field serialization helper parameterized only by ValueType (never /// the enclosing NamedTuple's FieldTypes... pack). template void build_named_tuple_field_schema( std::map* _definitions, SchemaType* _schema, - const std::string_view _name, const FieldValPtrT _field_val) noexcept { + const std::string_view _wire_name, const std::string_view _raw_name, + const FieldValPtrT _field_val, + const std::span _field_meta) noexcept { using PtrT = std::remove_cvref_t; if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { auto s = Parser::to_schema(_definitions); @@ -230,10 +250,17 @@ void build_named_tuple_field_schema( &s); } } + if (!_field_meta.empty()) { + if (const auto meta = + internal::find_field_metadata(_field_meta, _wire_name, _raw_name); + meta.has_value()) { + detail::apply_field_metadata(&s, *meta); + } + } if constexpr (_no_field_names) { _schema->types_.emplace_back(std::move(s)); } else { - _schema->types_[std::string(_name)] = std::move(s); + _schema->types_[std::string(_wire_name)] = std::move(s); } } } @@ -489,14 +516,19 @@ struct NamedTupleParser { * @brief Generates the schema for the named tuple. * * @param _definitions The map of definitions to add to. + * @param _view Optional view into a default-constructed instance. + * @param _field_meta Optional out-of-band field metadata (`rfl::Metadata`). + * @param _raw_names Optional pre-processor field names for metadata lookup. * @return The schema type. */ template static schema::Type to_schema( std::map* _definitions, - View* _view = nullptr) noexcept { + View* _view = nullptr, + const std::span _field_meta = {}, + const std::span _raw_names = {}) noexcept { SchemaType schema; - build_schema(_definitions, &schema, _view, + build_schema(_definitions, &schema, _view, _field_meta, _raw_names, std::make_integer_sequence()); return schema::Type{schema}; } @@ -517,6 +549,8 @@ struct NamedTupleParser { template static void build_schema(std::map* _definitions, SchemaType* _schema, View* _view, + const std::span _field_meta, + const std::span _raw_names, std::integer_sequence) noexcept { if constexpr (!std::is_same_v) { (detail::build_named_tuple_field_schema< @@ -525,8 +559,12 @@ struct NamedTupleParser { typename internal::nth_element_t<_is, FieldTypes...>::Type>>( _definitions, _schema, internal::nth_element_t<_is, FieldTypes...>::name(), + static_cast(_is) < _raw_names.size() + ? _raw_names[static_cast(_is)] + : std::string_view{}, _view ? detail::extract_schema_field_ptr(rfl::get<_is>(*_view)) - : nullptr), + : nullptr, + _field_meta), ...); } else { (detail::build_named_tuple_field_schema< @@ -534,7 +572,11 @@ struct NamedTupleParser { std::remove_cvref_t< typename internal::nth_element_t<_is, FieldTypes...>::Type>>( _definitions, _schema, - internal::nth_element_t<_is, FieldTypes...>::name(), nullptr), + internal::nth_element_t<_is, FieldTypes...>::name(), + static_cast(_is) < _raw_names.size() + ? _raw_names[static_cast(_is)] + : std::string_view{}, + nullptr, _field_meta), ...); } diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..2974d8499 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -1,11 +1,18 @@ #ifndef RFL_PARSING_PARSER_DEFAULT_HPP_ #define RFL_PARSING_PARSER_DEFAULT_HPP_ +#include +#include #include +#include #include +#include #include +#include +#include "../Metadata.hpp" #include "../Result.hpp" +#include "../Tuple.hpp" #include "../always_false.hpp" #include "../internal/HasFromReflectionMethod.hpp" #include "../internal/always_inline.hpp" @@ -23,6 +30,7 @@ #include "../internal/processed_t.hpp" #include "../internal/ptr_cast.hpp" #include "../internal/to_ptr_named_tuple.hpp" +#include "../named_tuple_t.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" #include "MapParser.hpp" @@ -653,6 +661,8 @@ struct Parser { (*_definitions)[name] = Type{Type::Integer{}}; // Placeholder to avoid infinite loop. + using MetaType = unwrap_tagged_union_wrapper_t; + if constexpr (internal::has_reflection_type_v) { (*_definitions)[name] = Parser::to_schema( @@ -670,7 +680,46 @@ struct Parser { // alternative through a pointer that U{} leaves null, so we construct // the wrapper that holds the alternative by value instead. using DefaultsType = tagged_union_wrapper_no_ptr_t; - if constexpr (internal::has_default_val_v) { + + if constexpr (internal::has_field_metadata_v) { + const auto field_meta = internal::get_field_metadata(); + std::span raw_names_span; + using RawNT = named_tuple_t; + if constexpr (RawNT::size() > 0 && + NamedTupleType::size() >= RawNT::size()) { + // Processors such as rfl::AddStructName prepend synthetic fields + // before U's real members. Shift raw_names by the prefix length so + // index i aligns with NamedTupleType's field i. + static constexpr auto raw_names = + [](std::index_sequence<_is...>) { + constexpr size_t prefix = + NamedTupleType::size() - RawNT::size(); + std::array arr{}; + ((arr[prefix + _is] = + tuple_element_t<_is, typename RawNT::Fields>::name()), + ...); + return arr; + }(std::make_index_sequence()); + raw_names_span = raw_names; + } + if constexpr (internal::has_default_val_v) { + static_assert(requires { DefaultsType{}; }, + "A struct with rfl::DefaultVal fields must be " + "default-constructible, because the default values " + "come from a default-constructed instance."); + auto defaults = DefaultsType{}; + auto view = ProcessorsType::template process( + to_view(defaults)); + (*_definitions)[name] = + Parser::to_schema( + _definitions, &view, field_meta, raw_names_span); + } else { + (*_definitions)[name] = + Parser::to_schema( + _definitions, static_cast(nullptr), field_meta, + raw_names_span); + } + } else if constexpr (internal::has_default_val_v) { static_assert(requires { DefaultsType{}; }, "A struct with rfl::DefaultVal fields must be " "default-constructible, because the default values " @@ -687,6 +736,15 @@ struct Parser { _definitions); } } + + if constexpr (internal::has_struct_description_v) { + auto desc = internal::get_struct_description(); + if (!desc.empty()) { + (*_definitions)[name] = Type{Type::Description{ + .description_ = std::move(desc), + .type_ = Ref::make(std::move((*_definitions)[name]))}}; + } + } } return Type{Type::Reference{name}}; } diff --git a/include/rfl/parsing/tagged_union_wrapper_no_ptr.hpp b/include/rfl/parsing/tagged_union_wrapper_no_ptr.hpp index 46389155b..da496c50a 100644 --- a/include/rfl/parsing/tagged_union_wrapper_no_ptr.hpp +++ b/include/rfl/parsing/tagged_union_wrapper_no_ptr.hpp @@ -35,6 +35,29 @@ template using tagged_union_wrapper_no_ptr_t = typename tagged_union_wrapper_no_ptr>::Type; +template +struct unwrap_tagged_union_wrapper { + using Type = std::remove_cvref_t; +}; + +template +struct unwrap_tagged_union_wrapper< + TaggedUnionWrapperNoFields> { + using Type = std::remove_cvref_t; +}; + +template +struct unwrap_tagged_union_wrapper> { + using Type = std::remove_cvref_t; +}; + +template +using unwrap_tagged_union_wrapper_t = + typename unwrap_tagged_union_wrapper>::Type; + } // namespace parsing } // namespace rfl diff --git a/src/rfl/avro/to_schema.cpp b/src/rfl/avro/to_schema.cpp index 5b8e25a3b..6d4184ec0 100644 --- a/src/rfl/avro/to_schema.cpp +++ b/src/rfl/avro/to_schema.cpp @@ -35,8 +35,13 @@ 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 || + std::is_same_v) { + return is_named_type(*_v.type_); + } else { + return std::is_same() || + std::is_same(); + } }); } diff --git a/src/rfl/capnproto/to_schema.cpp b/src/rfl/capnproto/to_schema.cpp index 6d166e286..c97669e8b 100644 --- a/src/rfl/capnproto/to_schema.cpp +++ b/src/rfl/capnproto/to_schema.cpp @@ -139,6 +139,18 @@ schema::Type reference_to_capnproto_schema_type( } } +inline bool is_literal_type(const parsing::schema::Type& _type) { + return _type.variant_.visit([](const auto& _v) -> bool { + using T = std::remove_cvref_t; + if constexpr (std::is_same_v || + std::is_same_v) { + return is_literal_type(*_v.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 +163,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_type(it->second)); } else { return !std::is_same_v && !std::is_same_v && !std::is_same_v && !std::is_same_v && diff --git a/src/rfl/json/to_schema.cpp b/src/rfl/json/to_schema.cpp index 3fda88bd2..9a0eae38d 100644 --- a/src/rfl/json/to_schema.cpp +++ b/src/rfl/json/to_schema.cpp @@ -244,7 +244,9 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type, } else if constexpr (std::is_same()) { auto res = type_to_json_schema_type(*_t.type_, _no_required); const auto update_prediction = [&](auto _v) -> schema::Type { - _v.annotations.value_.description = _t.description_; + if (!_t.description_.empty()) { + _v.annotations.value_.description = _t.description_; + } _v.annotations.value_.deprecated = true; _v.annotations.value_.deprecationMessage = _t.deprecation_message_; return schema::Type{_v}; diff --git a/tests/json/test_metadata.cpp b/tests/json/test_metadata.cpp new file mode 100644 index 000000000..c02ee0f20 --- /dev/null +++ b/tests/json/test_metadata.cpp @@ -0,0 +1,513 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_metadata { + +struct InlineConfig { + rfl::Description<"Root cache directory", std::string> cache_dir = + "/var/cache/app"; + rfl::Description<"Max number of files", int> max_files = 100; + rfl::Description<"Enable compression", bool> compression = true; + rfl::Deprecated<"Use compression_codec instead", "Legacy compression flag", + bool> + legacy_gzip = false; +}; + +struct OutOfBandConfig { + std::string cache_dir = "/var/cache/app"; + int max_files = 100; + bool compression = true; + bool legacy_gzip = false; +}; + +struct OutOfBandDefaultValConfig { + rfl::DefaultVal cache_dir = "/var/cache/app"; + rfl::DefaultVal max_files = 100; + rfl::DefaultVal legacy_gzip = false; +}; + +struct RuntimeMetaConfig { + std::string host = "localhost"; + int port = 8080; +}; + +struct EmptyDescConfig { + int x = 1; +}; + +struct ProcessedConfig { + std::string cache_dir = "/tmp"; + rfl::Rename<"maxEntries", int> max_entries = 42; +}; + +struct InnerMeta { + int retries = 3; +}; + +struct OuterMeta { + std::string name = "app"; + InnerMeta inner = {}; +}; + +struct AddStructNameWithDefault { + rfl::DefaultVal count = 7; + std::string cache_dir = "/tmp"; +}; + +struct NamePriorityConfig { + int foo_bar = 1; +}; + +struct InlineDescPlusOobDeprecated { + rfl::Description<"Original inline description", int> value = 5; +}; + +struct CustomReflectedId { + using ReflectionType = std::string; + std::string value; + const std::string& reflection() const { return value; } +}; + +struct ContainerWithReflectedId { + CustomReflectedId id; +}; + +struct PlainDeprecatedOnly { + bool old_flag = false; +}; + +struct CircleAlt { + double radius_m = 1.0; +}; + +struct SquareAlt { + double side_m = 2.0; +}; + +struct FlattenedBase { + int base_id = 1; +}; + +struct FlattenedOuter { + rfl::Flatten base; + std::string label = "x"; +}; + +struct EmptyMetaStruct {}; + +struct VecRefMetaConfig { + int value = 0; +}; + +struct DanglingVecMeta {}; + +struct NonStaticMeta {}; + +} // namespace test_metadata + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"cache_dir", "Root cache directory"}, + {"max_files", "Max number of files"}, + {"compression", "Enable compression"}, + {"legacy_gzip", "Legacy compression flag", + "Use compression_codec instead"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"cache_dir", "Root cache directory"}, + {"max_files", "Max number of files"}, + {"legacy_gzip", "Legacy compression flag", + "Use compression_codec instead"}, + }}; +}; + +template <> +struct rfl::Metadata { + static std::span fields() { + static const std::array kFields = {{ + {"host", "Server hostname"}, + {"port", "Listening TCP port"}, + }}; + return kFields; + } + + static std::string_view description() { + return "Network endpoint configuration"; + } +}; + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = ""; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"cache_dir", "Directory on disk"}, + {"maxEntries", "Upper bound on entries"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"count", "Item count"}, + {"cache_dir", "Cache path under AddStructName + SnakeCaseToCamelCase"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = "Nested retry settings"; + static constexpr std::array fields = {{ + {"retries", "Number of retry attempts"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"name", "Application name"}, + {"inner", "Nested settings object"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + // Raw name listed BEFORE wire name; exact wire-name match must win: + {"foo_bar", "Raw fallback description"}, + {"fooBar", "Wire name wins"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"value", "", "Use replacement instead"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = "Opaque resource identifier"; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {.name = "old_flag", .deprecation_message = "Use new_flag"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = "A circle"; + static constexpr std::array fields = {{ + {"radius_m", "Radius in meters"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"base_id", "Flattened identifier"}, + {"label", "Outer label"}, + }}; +}; + +template <> +struct rfl::Metadata { + static constexpr std::string_view description = "Marker struct"; + static constexpr std::array fields = {}; +}; + +template <> +struct rfl::Metadata { + static const std::vector& fields() { + static const std::vector kFields = { + {"value", "Returned via const vector lvalue reference"}, + }; + return kFields; + } +}; + +template <> +struct rfl::Metadata { + static std::vector fields() { return {}; } +}; + +template <> +struct rfl::Metadata { + std::array fields = {{{"x", "bad"}}}; + std::string_view description = "bad"; +}; + +namespace test_metadata { + +namespace { + +rfl::Generic::Object sole_def_object(const std::string& _schema) { + const auto root = + rfl::json::read(_schema).value().to_object().value(); + const auto defs = root.get("$defs").value().to_object().value(); + EXPECT_EQ(defs.size(), 1u); + return defs.begin()->second.to_object().value(); +} + +} // namespace + +TEST(json, test_metadata_matches_inline_description_and_deprecated) { + const auto inline_schema = + rfl::json::to_schema(); + const auto oob_schema = + rfl::json::to_schema(); + + const auto inline_props = + sole_def_object(inline_schema).get("properties").value().to_object().value(); + const auto oob_props = + sole_def_object(oob_schema).get("properties").value().to_object().value(); + + EXPECT_EQ(rfl::json::write(inline_props), rfl::json::write(oob_props)); +} + +TEST(json, test_metadata_with_default_val_fields) { + const auto schema = rfl::json::to_schema(); + const auto def = sole_def_object(schema); + const auto props = def.get("properties").value().to_object().value(); + + const auto cache_dir = props.get("cache_dir").value().to_object().value(); + EXPECT_EQ(cache_dir.get("description").value().to_string().value(), + "Root cache directory"); + EXPECT_EQ(cache_dir.get("default").value().to_string().value(), + "/var/cache/app"); + + const auto max_files = props.get("max_files").value().to_object().value(); + EXPECT_EQ(max_files.get("description").value().to_string().value(), + "Max number of files"); + EXPECT_EQ(max_files.get("default").value().to_int().value(), 100); + + const auto legacy = props.get("legacy_gzip").value().to_object().value(); + EXPECT_EQ(legacy.get("description").value().to_string().value(), + "Legacy compression flag"); + EXPECT_EQ(legacy.get("deprecated").value().to_bool().value(), true); + EXPECT_EQ(legacy.get("deprecationMessage").value().to_string().value(), + "Use compression_codec instead"); + EXPECT_EQ(legacy.get("default").value().to_bool().value(), false); + + // DefaultVal fields remain optional even when wrapped in Description/Deprecated. + if (const auto req = def.get("required"); req.has_value()) { + EXPECT_TRUE(req.value().to_array().value().empty()); + } +} + +TEST(json, test_metadata_runtime_function_and_struct_description) { + const auto schema = + rfl::json::to_schema(); + const auto def = sole_def_object(schema); + EXPECT_EQ(def.get("description").value().to_string().value(), + "Network endpoint configuration"); + const auto props = def.get("properties").value().to_object().value(); + EXPECT_EQ(props.get("host").value().to_object().value() + .get("description").value().to_string().value(), + "Server hostname"); + EXPECT_EQ(props.get("port").value().to_object().value() + .get("description").value().to_string().value(), + "Listening TCP port"); + + // Empty struct description must not emit a bogus empty "description" key. + const auto empty_schema = rfl::json::to_schema(); + const auto empty_def = sole_def_object(empty_schema); + EXPECT_FALSE(empty_def.get("description").has_value()); +} + +TEST(json, test_metadata_with_processors_and_rename) { + const auto schema = + rfl::json::to_schema(); + const auto props = + sole_def_object(schema).get("properties").value().to_object().value(); + EXPECT_EQ(props.get("cacheDir").value().to_object().value() + .get("description").value().to_string().value(), + "Directory on disk"); + EXPECT_EQ(props.get("maxEntries").value().to_object().value() + .get("description").value().to_string().value(), + "Upper bound on entries"); +} + +TEST(json, test_metadata_with_add_struct_name_and_defaults) { + const auto schema_dv = + rfl::json::to_schema>(); + const auto props_dv = + sole_def_object(schema_dv).get("properties").value().to_object().value(); + EXPECT_EQ(rfl::json::write(props_dv.get("type").value()), + R"({"type":"string","enum":["AddStructNameWithDefault"]})"); + const auto count_obj = props_dv.get("count").value().to_object().value(); + EXPECT_EQ(count_obj.get("default").value().to_int().value(), 7); + EXPECT_EQ(count_obj.get("description").value().to_string().value(), + "Item count"); + + const auto schema_sc = + rfl::json::to_schema, + rfl::SnakeCaseToCamelCase, rfl::DefaultIfMissing>(); + const auto props_sc = + sole_def_object(schema_sc).get("properties").value().to_object().value(); + EXPECT_EQ(props_sc.get("cacheDir").value().to_object().value() + .get("description").value().to_string().value(), + "Cache path under AddStructName + SnakeCaseToCamelCase"); +} + +TEST(json, test_metadata_wire_name_precedence_and_inline_desc_preservation) { + const auto prio_schema = + rfl::json::to_schema(); + const auto prio_props = + sole_def_object(prio_schema).get("properties").value().to_object().value(); + EXPECT_EQ(prio_props.get("fooBar").value().to_object().value() + .get("description").value().to_string().value(), + "Wire name wins"); + EXPECT_EQ(prio_schema.find("Raw fallback description"), std::string::npos); + + const auto dep_schema = + rfl::json::to_schema(); + const auto dep_val = + sole_def_object(dep_schema).get("properties").value().to_object().value() + .get("value").value().to_object().value(); + EXPECT_EQ(dep_val.get("description").value().to_string().value(), + "Original inline description"); + EXPECT_EQ(dep_val.get("deprecated").value().to_bool().value(), true); + EXPECT_EQ(dep_val.get("deprecationMessage").value().to_string().value(), + "Use replacement instead"); +} + +TEST(json, test_metadata_nested_and_reflection_type_structs) { + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("\"description\":\"Application name\""), + std::string::npos); + EXPECT_NE(schema.find("\"description\":\"Nested settings object\""), + std::string::npos); + EXPECT_NE(schema.find("\"description\":\"Nested retry settings\""), + std::string::npos); + EXPECT_NE(schema.find("\"description\":\"Number of retry attempts\""), + std::string::npos); + + const auto refl_schema = rfl::json::to_schema(); + EXPECT_NE(refl_schema.find("\"description\":\"Opaque resource identifier\""), + std::string::npos); +} + +TEST(json, test_metadata_roundtrip_unchanged) { + const auto parsed = rfl::json::read( + R"({"max_files":250})") + .value(); + EXPECT_EQ(parsed.cache_dir, "/var/cache/app"); + EXPECT_EQ(parsed.max_files, 250); + EXPECT_EQ(parsed.compression, true); + EXPECT_EQ(parsed.legacy_gzip, false); +} + +TEST(json, test_metadata_plain_deprecated_omits_empty_description) { + const auto schema = rfl::json::to_schema(); + const auto props = + sole_def_object(schema).get("properties").value().to_object().value(); + const auto flag = props.get("old_flag").value().to_object().value(); + EXPECT_EQ(flag.get("deprecated").value().to_bool().value(), true); + EXPECT_EQ(flag.get("deprecationMessage").value().to_string().value(), + "Use new_flag"); + EXPECT_FALSE(flag.get("description").has_value()); +} + +TEST(json, test_metadata_tagged_union_alternatives) { + using Shape = rfl::TaggedUnion<"shape", CircleAlt, SquareAlt>; + const auto schema = + rfl::json::to_schema(); + const auto root = + rfl::json::read(schema).value().to_object().value(); + const auto defs = root.get("$defs").value().to_object().value(); + bool found_circle = false; + bool found_square = false; + for (const auto& [def_name, def_val] : defs) { + if (def_name.find("CircleAlt") != std::string::npos) { + found_circle = true; + const auto def_obj = def_val.to_object().value(); + EXPECT_EQ(def_obj.get("description").value().to_string().value(), + "A circle"); + const auto props = def_obj.get("properties").value().to_object().value(); + EXPECT_EQ(props.get("radiusM") + .value() + .to_object() + .value() + .get("description") + .value() + .to_string() + .value(), + "Radius in meters"); + } else if (def_name.find("SquareAlt") != std::string::npos) { + found_square = true; + const auto def_obj = def_val.to_object().value(); + EXPECT_FALSE(def_obj.get("description").has_value()); + } + } + EXPECT_TRUE(found_circle); + EXPECT_TRUE(found_square); +} + +TEST(json, test_metadata_flatten_empty_no_field_names_and_concepts) { + // Concepts: dangling by-value vector rejected; const vector& accepted; + // non-static members rejected. + static_assert(rfl::internal::HasAnyFieldMetaFn); + static_assert(!rfl::internal::HasFieldMetaFn); + static_assert(rfl::internal::HasFieldMetaFn); + static_assert(!rfl::internal::HasFieldMetaVar); + static_assert(!rfl::internal::HasStructDescriptionVar); + + const auto vec_schema = rfl::json::to_schema(); + EXPECT_NE( + vec_schema.find( + "\"description\":\"Returned via const vector lvalue reference\""), + std::string::npos); + + // Flatten: fields looked up on enclosing struct's Metadata. + const auto flat_schema = + rfl::json::to_schema(); + const auto flat_props = + sole_def_object(flat_schema).get("properties").value().to_object().value(); + EXPECT_EQ(flat_props.get("baseId").value().to_object().value() + .get("description").value().to_string().value(), + "Flattened identifier"); + EXPECT_EQ(flat_props.get("label").value().to_object().value() + .get("description").value().to_string().value(), + "Outer label"); + + // Empty struct with Metadata::description and empty fields array. + const auto empty_schema = rfl::json::to_schema(); + EXPECT_EQ( + sole_def_object(empty_schema).get("description").value().to_string().value(), + "Marker struct"); + + // NoFieldNames emits tuple schema with per-element descriptions intact. + const auto tuple_schema = + rfl::json::to_schema(); + EXPECT_NE(tuple_schema.find("\"description\":\"Root cache directory\""), + std::string::npos); + EXPECT_NE(tuple_schema.find("\"description\":\"Max number of files\""), + std::string::npos); +} + +} // namespace test_metadata diff --git a/tests/json_c_arrays_and_inheritance/test_c_array_schema_defaults.cpp b/tests/json_c_arrays_and_inheritance/test_c_array_schema_defaults.cpp new file mode 100644 index 000000000..82428d72e --- /dev/null +++ b/tests/json_c_arrays_and_inheritance/test_c_array_schema_defaults.cpp @@ -0,0 +1,35 @@ +#include + +#include +#include +#include +#include + +namespace test_c_array_schema_defaults { + +struct CArrayWithDefaults { + int coords[3] = {1, 2, 3}; + rfl::DefaultVal label = "origin"; +}; + +} // namespace test_c_array_schema_defaults + +template <> +struct rfl::Metadata { + static constexpr std::array fields = {{ + {"coords", "3D coordinates"}, + {"label", "Point label"}, + }}; +}; + +namespace test_c_array_schema_defaults { + +TEST(json, test_c_array_schema_with_defaults_and_metadata) { + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("\"description\":\"3D coordinates\""), + std::string::npos); + EXPECT_NE(schema.find("\"description\":\"Point label\""), std::string::npos); + EXPECT_NE(schema.find("\"default\":\"origin\""), std::string::npos); +} + +} // namespace test_c_array_schema_defaults