Skip to content

Fix invalid Rust emitted for defaults on types with flattened properties#1039

Open
danieleades wants to merge 1 commit into
oxidecomputer:mainfrom
danieleades:fix/flatten-default-ident
Open

Fix invalid Rust emitted for defaults on types with flattened properties#1039
danieleades wants to merge 1 commit into
oxidecomputer:mainfrom
danieleades:fix/flatten-default-ident

Conversation

@danieleades

Copy link
Copy Markdown
Contributor

Problem

When generating a Rust value expression for a type-level default on a struct that has a #[serde(flatten)] property (e.g. an object with additionalProperties alongside declared properties), the code in typify-impl/src/value.rs interpolated the flattened property's name as a string literal instead of an identifier:

let name = &prop.name;
Some(quote! { #name: #flat_value })

Since name is a String, quote! renders it as a string literal ("extra": ...) rather than a field name, producing invalid Rust inside the struct literal. This causes rustfmt/compilation to fail for any generated default value on a struct with a flattened property.

Fix

Build a proper identifier for the flattened field, matching the sibling non-flattened path a few lines above (format_ident!("{}", &prop.name)).

Testing

Added typify/tests/schemas/flatten-default.json, a minimal schema with a struct-typed property carrying a default where the struct has both declared properties and additionalProperties (flattened into a map). This is picked up automatically by the existing test_schemas harness, which regenerates and rustfmts the output and then compiles it via trybuild.

  • Confirmed on unpatched code this schema causes generation to fail with error: expected identifier, found "extra" (rustfmt).
  • With the fix, cargo test --workspace --locked passes, including trybuild compilation of the new golden file.
  • cargo fmt --all -- --check is clean.

…tput

When generating a Rust value expression for a type-level `default` on a
struct that has a `#[serde(flatten)]` property, the flattened property's
name was interpolated as a string literal instead of an identifier,
producing invalid Rust (e.g. `"extra": ...` inside a struct literal) that
fails to compile and cannot be formatted by rustfmt.

Use format_ident! for the flattened field, matching the sibling
non-flattened path just above it.

Added tests/schemas/flatten-default.json as a regression test, exercised
by the existing schemas test harness (compiled via trybuild).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant