diff --git a/.changepacks/changepack_log_parser_round49.json b/.changepacks/changepack_log_parser_round49.json new file mode 100644 index 00000000..bae8c4fa --- /dev/null +++ b/.changepacks/changepack_log_parser_round49.json @@ -0,0 +1 @@ +{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"Parser round 49: under deny_unknown_fields a flattened struct that has a flatten field of its own no longer lists the enum keys it flattens (serde leaves every key of such a member in the buffer, so the closed request schema now rejects them as serde does); a route handler lookup prefers the routed fn over an attribute-less same-named cfg variant; a String path extractor is refined by a later integer one (doc fix); the generic instance encoding doc now lists the any-value types.","date":"2026-11-29T00:00:00.000Z"} diff --git a/crates/vespera/tests/flatten_optional_enum_deny.rs b/crates/vespera/tests/flatten_optional_enum_deny.rs index 36ae0caf..5f39a6b6 100644 --- a/crates/vespera/tests/flatten_optional_enum_deny.rs +++ b/crates/vespera/tests/flatten_optional_enum_deny.rs @@ -27,3 +27,31 @@ fn two_variant_keys_are_rejected_and_zero_or_one_accepted() { assert!(serde_json::from_str::(r#"{"id":1,"Text":"a"}"#).is_ok()); assert!(serde_json::from_str::(r#"{"id":1}"#).is_ok()); } + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +#[allow(dead_code)] +struct NestedReq { + id: i32, + #[serde(flatten)] + nested: Nested, +} + +#[derive(Deserialize)] +#[allow(dead_code)] +struct Nested { + #[serde(flatten)] + data: Option, +} + +/// R49-P3-M1: the same shape one level down, inside a REQUIRED flattened +/// struct, takes NO variant key under the outer `deny_unknown_fields`: the +/// nested struct reads its member through `deserialize_map`, so the keys stay +/// in the buffer and the outer struct rejects every one of them (one key or +/// two). Only an absent enum is accepted. +#[test] +fn nested_optional_enum_rejects_every_variant_key() { + assert!(serde_json::from_str::(r#"{"id":1,"Text":"a","Bytes":"b"}"#).is_err()); + assert!(serde_json::from_str::(r#"{"id":1,"Text":"a"}"#).is_err()); + assert!(serde_json::from_str::(r#"{"id":1}"#).is_ok()); +} diff --git a/crates/vespera/tests/schema_crate_alias.rs b/crates/vespera/tests/schema_crate_alias.rs index e2f93bc6..acba123e 100644 --- a/crates/vespera/tests/schema_crate_alias.rs +++ b/crates/vespera/tests/schema_crate_alias.rs @@ -35,7 +35,9 @@ fn aliased_serde_json_map_documents_the_bare_object() { #[test] fn aliased_serde_json_value_documents_like_the_bare_value() { - assert_eq!(documented("raw"), documented("bare_value")); + let raw = documented("raw"); + assert_eq!(raw, documented("bare_value")); + assert_eq!(raw, serde_json::json!({}), "{raw}"); } #[test] diff --git a/crates/vespera_macro/src/parser/extractor_validation.rs b/crates/vespera_macro/src/parser/extractor_validation.rs index c90f43bb..0862d0e5 100644 --- a/crates/vespera_macro/src/parser/extractor_validation.rs +++ b/crates/vespera_macro/src/parser/extractor_validation.rs @@ -256,21 +256,34 @@ fn is_test_only(metadata: &CollectedMetadata, route: &crate::metadata::RouteMeta /// `ast`, the one not gated by a test-only `cfg` whose `#[route()]` /// is the route's method. A `#[cfg(test)]` twin, or a same-named fn of /// another method, is never the handler, so its extractors are not checked -/// against the route. `None` when no such fn exists (nothing to check). +/// against the route. A fn carrying such a `#[route]` wins over an +/// attribute-less same-named fn (a `cfg`-gated variant of the handler, which +/// is not a route of its own); the attribute-less fn is the fallback only when +/// no routed twin exists. `None` when no such fn exists (nothing to check). fn handler_fn<'a>( ast: &'a syn::File, route: &crate::metadata::RouteMetadata, ) -> Option<&'a syn::ItemFn> { - ast.items.iter().find_map(|item| match item { - syn::Item::Fn(f) - if f.sig.ident == route.function_name - && !attrs_test_only(&f.attrs) - && is_handler_of(f, &route.method) => + let mut fallback = None; + for item in &ast.items { + let syn::Item::Fn(f) = item else { + continue; + }; + if f.sig.ident != route.function_name + || attrs_test_only(&f.attrs) + || !is_handler_of(f, &route.method) { - Some(f) + continue; } - _ => None, - }) + if f.attrs + .iter() + .any(|attr| crate::route::check_route_by_meta(&attr.meta)) + { + return Some(f); + } + fallback.get_or_insert(f); + } + fallback } /// Whether `f` can be the handler of a `method` route: its `#[route(..)]` diff --git a/crates/vespera_macro/src/parser/extractor_validation/tests_scope.rs b/crates/vespera_macro/src/parser/extractor_validation/tests_scope.rs index 3c39c0d8..1bdd121c 100644 --- a/crates/vespera_macro/src/parser/extractor_validation/tests_scope.rs +++ b/crates/vespera_macro/src/parser/extractor_validation/tests_scope.rs @@ -359,3 +359,28 @@ fn generic_parameters_shadow_module_items(#[case] handler: &str, #[case] ok: boo let src = format!("pub struct Body {{ pub a: i32 }} {handler}"); assert_eq!(run(&src).is_ok(), ok, "{handler}"); } + +/// R49-P0-L2: a `cfg`-gated attribute-less fn with the handler's name is not a +/// route, so it does not stand in for the routed POST handler that comes after +/// it in source order (the first-match lookup checked the legacy `Json` +/// and reported a false error). +#[test] +fn routed_twin_wins_over_an_attribute_less_same_named_fn() { + let mut metadata = CollectedMetadata::new(); + metadata.routes.push(handler_route("post")); + let src = "pub struct Local { pub a: i32 } #[derive(Schema)] pub struct Body { pub a: i32 } \ + #[cfg(feature = \"legacy\")] pub fn handler(Json(l): Json) {} \ + #[cfg(not(feature = \"legacy\"))] #[route(post)] pub fn handler(Json(b): Json) {}"; + assert!(check_with(&metadata, src).is_ok()); +} + +/// Without a routed twin the attribute-less fn is still the handler, so its +/// non-`Schema` extractor is flagged. +#[test] +fn attribute_less_fn_is_the_handler_without_a_routed_twin() { + let mut metadata = CollectedMetadata::new(); + metadata.routes.push(handler_route("post")); + let src = "pub struct Local { pub a: i32 } pub fn handler(Json(l): Json) {}"; + let message = check_with(&metadata, src).expect_err("handler").to_string(); + assert!(message.contains("`Json`"), "{message}"); +} diff --git a/crates/vespera_macro/src/parser/operation.rs b/crates/vespera_macro/src/parser/operation.rs index 352ef3ea..22a8c115 100644 --- a/crates/vespera_macro/src/parser/operation.rs +++ b/crates/vespera_macro/src/parser/operation.rs @@ -399,10 +399,11 @@ fn response_description_for_status(status_code: u16) -> String { } /// The path parameters of every `Path` extractor, one per segment name. The -/// first extractor's parameter wins, unless it is only the string placeholder -/// a struct / tuple that does not type the segment leaves behind, and a later -/// extractor types it (axum deserializes each extractor from the same route -/// segments, so the typed one is the segment's real type). +/// first extractor's parameter wins, unless it is a string schema (the +/// placeholder a struct / tuple that does not type the segment leaves behind, +/// or a `Path`) and a later extractor's non-string parameter names the +/// same segment: axum deserializes every extractor from the same route +/// segments, so that later, stricter type documents the segment. fn merge_path_extractor_parameters( extracted: impl IntoIterator>, ) -> Vec { diff --git a/crates/vespera_macro/src/parser/operation/tests_path_extractors.rs b/crates/vespera_macro/src/parser/operation/tests_path_extractors.rs index 0b920689..2bde5614 100644 --- a/crates/vespera_macro/src/parser/operation/tests_path_extractors.rs +++ b/crates/vespera_macro/src/parser/operation/tests_path_extractors.rs @@ -57,3 +57,16 @@ fn a_segment_no_extractor_types_is_a_string() { ); assert_eq!(schema["type"], "string"); } + +/// R49-P0-L1: a `Path` is a string schema like the placeholder, so a +/// later integer extractor for the same segment refines it (both extractors +/// accept the segment; the integer one is the stricter constraint). +#[test] +fn a_string_path_extractor_is_refined_by_a_later_integer() { + let schema = parameter_schema( + "async fn f(Path(a): Path, Path(b): Path) -> String", + "/{id}", + "id", + ); + assert_eq!(schema["type"], "integer"); +} diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs b/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs index 0f32234f..251318da 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs @@ -35,9 +35,10 @@ //! other variant key to the outer struct, so its request-view branches are //! an `anyOf` (several may match), never a `oneOf`. Under the outer //! `deny_unknown_fields` the request view lists the keys it takes (the -//! variant keys, or the tag and content of an adjacently tagged enum; a -//! struct flattening one lists its own) and its branches are a `oneOf` -//! (exactly one may match, see `list_keys`); +//! variant keys, or the tag and content of an adjacently tagged enum) and +//! its branches are a `oneOf` (exactly one may match, see `list_keys`). A +//! struct flattening one takes none of them (it leaves them in the buffer, +//! see the next bullet), so none are listed (R49-P3-M1); //! - the OUTER `deny_unknown_fields` rejects any key no member consumed //! (a map borrows, never consumes, so with it the map stays empty); //! - a flattened newtype (`deserialize_newtype_struct` passes the buffer @@ -81,10 +82,7 @@ use super::{ enum_schema::{parse_enum_to_schema, without_other_map, without_single_key_bounds}, request_view::{self, FlatRead}, schema_attrs::{SchemaConstraints, extract_schema_constraints}, - serde_attrs::{ - SerdeEnumRepr, SerdeSide, extract_enum_repr, extract_flatten, extract_serde_skip_flags, - extract_untagged, - }, + serde_attrs::{SerdeEnumRepr, SerdeSide, extract_enum_repr, extract_untagged}, type_schema::{generic_instances, parse_type_to_schema_ref}, wire_override::codec_applies, }, @@ -95,7 +93,7 @@ use crate::schema_macro::type_utils::option_inner; mod combinators; use combinators::{any_of_branches, both, either, lenient}; mod keyed; -use keyed::{exclusive_enum, exclusive_enums, optional_enum_keys}; +use keyed::exclusive_enum; thread_local! { /// Rust idents whose definitions are being resolved (cycle guard: a @@ -128,8 +126,6 @@ pub(super) enum FlatPart { parts: ObjectParts, optional: bool, leaves: bool, - /// Keys a deny-closed request view lists (see `list_keys`). - listed: Vec<(String, SchemaRef)>, }, /// A member whose keys cannot be known. Opaque { @@ -154,26 +150,6 @@ pub(super) fn flatten_part( omittable: bool, known_schemas: &HashSet + Eq + Hash>, struct_definitions: &HashMap + Eq + Hash, impl AsRef>, -) -> FlatPart { - classify_member( - field, - side, - omittable, - known_schemas, - struct_definitions, - WRAPPER_DEPTH, - ) -} - -/// [`flatten_part`] with `depth` bounding how many flattened members are -/// followed to list their keys (`nested_keys`). -fn classify_member( - field: &syn::Field, - side: SerdeSide, - omittable: bool, - known_schemas: &HashSet + Eq + Hash>, - struct_definitions: &HashMap + Eq + Hash, impl AsRef>, - depth: usize, ) -> FlatPart { let constraints = extract_schema_constraints(&field.attrs); // serde sees through `Box` / `Arc` / ... to a flattened `Option` too. @@ -210,11 +186,6 @@ fn classify_member( .as_ref() .and_then(|schema| decompose(schema, known_schemas, struct_definitions)) { - let listed = if request { - nested_keys(ty, side, known_schemas, struct_definitions, depth) - } else { - Vec::new() - }; return FlatPart::Known { // A unit struct (`null`) has no keys: its `$ref` would make an // `allOf` member nothing satisfies next to the object. @@ -226,7 +197,6 @@ fn classify_member( parts, optional, leaves, - listed: lenient_keys(listed, optional), }; } // A newtype / transparent wrapper around an enum is flattened like that @@ -386,47 +356,6 @@ fn variant_keys(schema: &SchemaRef) -> Vec<(String, SchemaRef)> { keys } -/// The keys a flattened struct `ty` lists for a deny-closed request view: the -/// listed keys of its own flattened members (a struct flattening an enum -/// leaves that enum's keys to the outer struct, see `classify_member`). -/// `depth` bounds the members followed. -fn nested_keys( - ty: &syn::Type, - side: SerdeSide, - known_schemas: &HashSet + Eq + Hash>, - struct_definitions: &HashMap + Eq + Hash, impl AsRef>, - depth: usize, -) -> Vec<(String, SchemaRef)> { - let Some(item) = flat_item(ty, struct_definitions) else { - return Vec::new(); - }; - match (request_view::flat_read(&item), &item) { - (FlatRead::Through(inner), _) if depth > 0 => { - nested_keys(inner, side, known_schemas, struct_definitions, depth - 1) - } - (FlatRead::Leaves { known_keys: true }, syn::Item::Struct(item)) if depth > 0 => item - .fields - .iter() - .filter(|field| { - let flags = extract_serde_skip_flags(&field.attrs); - extract_flatten(&field.attrs) && !flags.skip && !flags.skip_deserializing - }) - .flat_map(|field| { - classify_member( - field, - side, - false, - known_schemas, - struct_definitions, - depth - 1, - ) - .listed() - }) - .collect(), - _ => Vec::new(), - } -} - /// `keys` with each value made lenient when its member is optional (a failing /// optional member is `None`, so its keys are accepted). fn lenient_keys(keys: Vec<(String, SchemaRef)>, optional: bool) -> Vec<(String, SchemaRef)> { @@ -442,15 +371,6 @@ fn list_keys(own: &mut ObjectParts, keys: Vec<(String, SchemaRef)>) { } } -impl FlatPart { - /// The keys this member lists for a deny-closed request view. - fn listed(self) -> Vec<(String, SchemaRef)> { - match self { - Self::Known { listed, .. } | Self::Opaque { listed, .. } => listed, - } - } -} - /// The flattened form of an externally tagged enum `schema` with unit /// variants: serde writes (and reads) a flattened unit variant as the key /// `{"A": null}`, never as the string `"A"`, so every `{type: string, enum: @@ -886,25 +806,18 @@ pub(super) fn assemble( mut parts, optional, leaves, - listed, .. } => { // serde rejects every key such a member leaves behind, its - // unknown members' keys too: they do not open the object. + // unknown members' keys too: they do not open the object. Its + // nested enums' keys are left behind as well (R49-P3-M1: serde + // consumes none of them under the outer `deny_unknown_fields`), + // so, like its own keys, they are not listed. let rejected = request && deny_unknown_fields && leaves; if request { let left = leaves.then_some((later, deny_unknown_fields)); earlier_maps = request_member(&mut parts, optional, earlier_maps, left); } - if request && deny_unknown_fields { - // A nested enum's variant keys are exclusive too (serde - // takes one of them); an optional one's `parts` are dropped - // by `merge`, so its exclusive keys are kept as a member. - exclusive_enums(&mut parts.opaque, &listed); - own.opaque - .extend(optional_enum_keys(optional, &parts.opaque, &listed)); - list_keys(&mut own, listed); - } open |= merge(&mut own, parts, optional) && !rejected; } } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/flatten/combinators.rs b/crates/vespera_macro/src/parser/schema/struct_schema/flatten/combinators.rs index 5e6caaf6..c83a4899 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/flatten/combinators.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/flatten/combinators.rs @@ -30,28 +30,6 @@ pub(super) fn any_of_branches(schema: &mut SchemaRef) { } } -/// Turns the `anyOf` branches of an inline `schema` into `oneOf` ones, unless -/// one of them is the empty schema `{}` (the lenient branch of a flattened -/// `Option`, see [`lenient`]). -pub(super) fn exclusive_branches(schema: &mut SchemaRef) { - if let SchemaRef::Inline(inline) = schema - && inline.one_of.is_none() - && inline - .any_of - .as_ref() - .is_some_and(|branches| branches.iter().all(|branch| !is_empty_schema(branch))) - { - inline.one_of = inline.any_of.take(); - } -} - -/// Whether `schema` is the empty schema `{}` (it accepts every value). -fn is_empty_schema(schema: &SchemaRef) -> bool { - matches!(schema, SchemaRef::Inline(inline) - if serde_json::to_value(inline) - .is_ok_and(|value| value.as_object().is_some_and(serde_json::Map::is_empty))) -} - /// `anyOf: [schema, {}]` — documents `schema` without rejecting anything /// (a flattened `Option` is `None` when its value fails). pub(super) fn lenient(schema: SchemaRef) -> SchemaRef { diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/flatten/keyed.rs b/crates/vespera_macro/src/parser/schema/struct_schema/flatten/keyed.rs index 6a102e58..781c660b 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/flatten/keyed.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/flatten/keyed.rs @@ -12,27 +12,6 @@ use std::collections::BTreeMap; use vespera_core::schema::{Schema, SchemaRef, SchemaType}; -use super::combinators::exclusive_branches; - -/// The `(key, payload)` entries of `listed` whose key an externally tagged -/// enum schema among `opaque` documents as a variant key (the enum's own -/// keys; a plain struct member's keys in the same list are not exclusive). -pub(super) fn enum_keys_among( - opaque: &[SchemaRef], - listed: &[(String, SchemaRef)], -) -> Vec<(String, SchemaRef)> { - let variant_keys: Vec = opaque - .iter() - .flat_map(super::variant_keys) - .map(|(key, _)| key) - .collect(); - listed - .iter() - .filter(|(key, _)| variant_keys.contains(key)) - .cloned() - .collect() -} - /// `schema` with exactly one of its `listed` keys when `enforce` (an optional /// enum under the outer deny) and it lists some; otherwise `schema` as it is. pub(super) fn exclusive_enum( @@ -47,28 +26,6 @@ pub(super) fn exclusive_enum( } } -/// Makes the enum branches of `opaque` exclusive when `listed` names variant -/// keys (serde takes one of them). -pub(super) fn exclusive_enums(opaque: &mut [SchemaRef], listed: &[(String, SchemaRef)]) { - if !listed.is_empty() { - for schema in opaque { - exclusive_branches(schema); - } - } -} - -/// The exactly-one-key member of an optional `opaque` enum's keys among -/// `listed` (see [`exactly_one_key`]) when `optional`; `None` otherwise, or when -/// none of them is one. -pub(super) fn optional_enum_keys( - optional: bool, - opaque: &[SchemaRef], - listed: &[(String, SchemaRef)], -) -> Option { - let keyed = enum_keys_among(opaque, listed); - (optional && !keyed.is_empty()).then(|| exactly_one_key(&keyed)) -} - /// `oneOf` of one object per key (`{K: payload}` required), plus the object /// without any of the keys: exactly one of `keys` may be present. Each /// payload is taken as given (the caller makes it lenient when needed). diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/flatten/tests.rs b/crates/vespera_macro/src/parser/schema/struct_schema/flatten/tests.rs index 242dfa57..f2100708 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/flatten/tests.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/flatten/tests.rs @@ -280,10 +280,12 @@ fn deny_request_view_lists_the_variant_keys_and_closes() { } /// A struct that flattens an enum, flattened into a `deny_unknown_fields` -/// struct: its variant keys are listed too, and its branches are exclusive -/// (serde takes one key of the enum, the outer struct rejects the others). +/// struct: it has its own flattened member, so serde reads it through +/// `deserialize_map` and consumes NONE of its keys (`Text` is an unknown field +/// to the outer struct, `id2` too). Its variant keys are therefore not listed +/// (R49-P3-M1); the closed object rejects them, and so does serde. #[test] -fn deny_request_view_lists_a_nested_enums_keys_exclusively() { +fn deny_request_view_rejects_a_nested_enums_keys() { let known = HashSet::from(["Nested".to_string(), "DataOnly".to_string()]); let definitions = HashMap::from([ ( @@ -308,9 +310,13 @@ fn deny_request_view_lists_a_nested_enums_keys_exclusively() { serde_json::json!(false), "{json}" ); - assert_eq!(object["properties"]["Text"]["type"], "string", "{json}"); - assert_eq!(object["properties"]["Bytes"]["type"], "string", "{json}"); - assert!(json["allOf"][1]["oneOf"].is_array(), "{json}"); + assert!(object["properties"].get("Text").is_none(), "{json}"); + assert!(object["properties"].get("Bytes").is_none(), "{json}"); + assert_eq!( + object["properties"]["id2"]["not"], + serde_json::json!({}), + "{json}" + ); } /// The same struct without `deny_unknown_fields` keeps the object open: serde @@ -384,11 +390,12 @@ fn deny_optional_enum_takes_exactly_one_key() { ); } -/// The same for `Option` where `S` flattens the enum: the keys `S` lists -/// are exclusive as a group (`S`'s own plain keys stay separate), and the -/// `Option` keeps them lenient. +/// The same for `Option` where `S` flattens the enum: `S` reads its members +/// through `deserialize_map` and consumes none of their keys, so under the +/// outer `deny_unknown_fields` every key it leaves is rejected (R49-P3-M1): +/// the enum's keys are not listed and no `oneOf` over them is emitted. #[test] -fn deny_optional_struct_over_an_enum_takes_exactly_one_key() { +fn deny_optional_struct_over_an_enum_rejects_its_keys() { let known = HashSet::from(["Nested".to_string(), "DataOnly".to_string()]); let definitions = HashMap::from([ ( @@ -407,33 +414,54 @@ fn deny_optional_struct_over_an_enum_takes_exactly_one_key() { let schema = request_view::with_request_view(|| parse_struct_to_schema(&item, &known, &definitions)); let json = serde_json::to_value(&schema).unwrap(); + // Nothing left to merge: the closed object is the whole schema. + let object = &json; assert_eq!( - json["allOf"][0]["additionalProperties"], + object["additionalProperties"], serde_json::json!(false), "{json}" ); - assert!( - json["allOf"][0]["properties"].get("id2").is_some(), - "{json}" - ); - let exclusive = json["allOf"] - .as_array() - .expect("allOf members") - .iter() - .skip(1) - .find(|member| member.get("oneOf").is_some()) - .unwrap_or_else(|| panic!("a oneOf over the enum keys: {json}")); - assert!(exclusive.get("anyOf").is_none(), "{json}"); - let branches = exclusive["oneOf"].as_array().expect("branches"); - assert_eq!(branches.len(), 3, "{json}"); assert_eq!( - branches[0]["required"], - serde_json::json!(["Text"]), + object["properties"]["id2"]["not"], + serde_json::json!({}), "{json}" ); + assert!(object["properties"].get("Text").is_none(), "{json}"); + assert!(object["properties"].get("Bytes").is_none(), "{json}"); + assert!(!json.to_string().contains("oneOf"), "{json}"); +} + +/// R49-P3-M1 (the pending finding's shape): an OPTIONAL enum nested in a +/// REQUIRED flattened struct under the outer `deny_unknown_fields`. serde +/// consumes none of the keys, so the closed object lists none of them; the +/// nested enum's lenient branch cannot reopen the object, which is closed. +#[test] +fn deny_required_struct_over_an_optional_enum_rejects_its_keys() { + let known = HashSet::from(["Nested".to_string(), "DataOnly".to_string()]); + let definitions = HashMap::from([ + ( + "DataOnly".to_string(), + "enum DataOnly { Text(String), Bytes(String) }".to_string(), + ), + ( + "Nested".to_string(), + "struct Nested { #[serde(flatten)] opt: Option }".to_string(), + ), + ]); + let item: syn::ItemStruct = syn::parse_str( + "#[serde(deny_unknown_fields)] struct Req { id: i32, #[serde(flatten)] n: Nested }", + ) + .unwrap(); + let schema = + request_view::with_request_view(|| parse_struct_to_schema(&item, &known, &definitions)); + let json = serde_json::to_value(&schema).unwrap(); + let object = &json["allOf"][0]; assert_eq!( - branches[1]["required"], - serde_json::json!(["Bytes"]), + object["additionalProperties"], + serde_json::json!(false), "{json}" ); + assert!(object["properties"].get("Text").is_none(), "{json}"); + assert!(object["properties"].get("Bytes").is_none(), "{json}"); + assert_eq!(object["properties"]["id"]["format"], "int32", "{json}"); } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_nested_enum_outer_deny.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_nested_enum_outer_deny.snap index 9f6ce3d7..f27c4628 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_nested_enum_outer_deny.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_nested_enum_outer_deny.snap @@ -58,12 +58,6 @@ request: { { "type": "object", "properties": { - "Bytes": { - "type": "string" - }, - "Text": { - "type": "string" - }, "id": { "type": "integer", "format": "int32" @@ -79,7 +73,7 @@ request: { "additionalProperties": false }, { - "oneOf": [ + "anyOf": [ { "type": "object", "properties": { diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_newtype_nested_outer_deny.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_newtype_nested_outer_deny.snap index 08b236d6..a2d03c7d 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_newtype_nested_outer_deny.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_newtype_nested_outer_deny.snap @@ -58,12 +58,6 @@ request: { { "type": "object", "properties": { - "Bytes": { - "type": "string" - }, - "Text": { - "type": "string" - }, "id": { "type": "integer", "format": "int32" @@ -79,7 +73,7 @@ request: { "additionalProperties": false }, { - "oneOf": [ + "anyOf": [ { "type": "object", "properties": { diff --git a/crates/vespera_macro/src/parser/schema/type_schema/conversion/tests_instances.rs b/crates/vespera_macro/src/parser/schema/type_schema/conversion/tests_instances.rs index 98aae782..22cc2c11 100644 --- a/crates/vespera_macro/src/parser/schema/type_schema/conversion/tests_instances.rs +++ b/crates/vespera_macro/src/parser/schema/type_schema/conversion/tests_instances.rs @@ -220,7 +220,27 @@ fn polymorphic_recursion_is_capped_per_top_level_instance() { )]); let ty: Type = syn::parse_str("Nested").unwrap(); let schema = serde_json::to_string(&parse_type_to_schema_ref(&ty, &known, &defs)).unwrap(); - assert!(schema.contains("{}"), "the cut instances are any value"); + // Each expanded level is `{properties: {a: {items: }}, ..}`; + // the innermost level past the cap carries only the depth-limit + // description (no type, no properties): an any-value schema. + let mut level: serde_json::Value = serde_json::from_str(&schema).unwrap(); + let mut depth = 0; + while let Some(items) = level.pointer("/properties/a/items") { + level = items.clone(); + depth += 1; + } + assert!(depth > 1, "the instances expand before the cap: {depth}"); + assert_eq!( + level.as_object().map(serde_json::Map::len), + Some(1), + "{level}" + ); + assert!( + level["description"] + .as_str() + .is_some_and(|text| text.contains("recursion depth limit")), + "{level}" + ); assert!( schema.len() < 2_000_000, "the expansion is bounded: {} bytes", diff --git a/crates/vespera_macro/src/parser/schema/type_schema/generic_instances.rs b/crates/vespera_macro/src/parser/schema/type_schema/generic_instances.rs index 3c680237..f5458264 100644 --- a/crates/vespera_macro/src/parser/schema/type_schema/generic_instances.rs +++ b/crates/vespera_macro/src/parser/schema/type_schema/generic_instances.rs @@ -113,12 +113,14 @@ fn escape_name(name: &str) -> String { /// Append `_` for every name inside `ty` (prefix order: a generic /// segment's arguments follow it). /// -/// The encoding is injective for a fixed arity per type name: a name is -/// escaped by [`escape_name`] (`my_type` → `my-type`, so it never reads as -/// a separator; the base name too), and the structural markers carry a `.` (which no -/// identifier contains) together with their size — `[T; 4]` → `_Array.4_T`, -/// `[T]` → `_Slice._T`, `(A, B)` → `_Tuple.2_A_B`, anything else (`impl -/// Trait`, `dyn Trait`, …) → `_.Value`. +/// The encoding is injective for argument types whose schema depends on their +/// spelling: a name is escaped by [`escape_name`] (`my_type` → `my-type`, so it +/// never reads as a separator; the base name too), and the structural markers +/// carry a `.` (which no identifier contains) together with their size — +/// `[T; 4]` → `_Array.4_T`, `[T]` → `_Slice._T`, `(A, B)` → `_Tuple.2_A_B`. +/// Any other type (`fn(u8)`, `*const T`, `dyn Trait`, `impl Trait`, `_`, …) +/// shares `_.Value`: all of them are documented as any-value, so they need no +/// distinct instance. fn push_type_segments( name: &mut String, ty: &Type,