Skip to content

fix(gts-macros): read optional and renamed fields of derived structs - #163

Merged
aviator5 merged 4 commits into
GlobalTypeSystem:mainfrom
MikeFalcon77:fix/derived-optional-fields
Nov 20, 2026
Merged

aviator5 merged 4 commits into
GlobalTypeSystem:mainfrom
MikeFalcon77:fix/derived-optional-fields

Conversation

@MikeFalcon77

Copy link
Copy Markdown
Contributor

Description

Derived structs (#[struct_to_gts_schema(base = Parent, ...)]) are read through a generated GtsDeserialize impl. That impl disagreed with the generated schema and with serde derive:

  • Absent optional fields were rejected. Every absent member except an Option<P> generic slot was a missing_field error, although the schema leaves Option<T> and #[serde(default)] fields out of required and the README documents them as optional. Adding an optional field to a derived type therefore made existing instances unreadable, so consumers had to bump the type's major version.
  • Renamed fields never deserialized. Member names were matched against Rust idents, so a field with #[serde(rename = "wire")] reported missing field `wire` even when wire was present, and GtsSerialize output did not read back.
  • rename followed by another option was misparsed. get_serde_rename matched the raw token string: rename = "kind", default = "f" yielded the name kind", default = "f, and rename = "kind", default lost the rename.

Changes (in gts-macros):

  1. Read each member of a derived struct under its serialized name. When it differs from the key matched before, that key (serde's snake_case form of the unraw ident) stays accepted as an alias, so input that deserialized until now still does.
  2. Read an absent member as serde derive does: #[serde(default)] → Default::default(), #[serde(default = "path")] → path(), Option<T> → None, anything else → missing field. Schemas and serialization are unchanged.
  3. Parse #[serde(...)] field options as syn::Meta (shared by the rename, default and option-name helpers), and keep the visitor's members in prefixed locals so a field cannot shadow its default function or the visitor's map.
  4. Document in the README which serde rules derived structs apply.

Behavior notes

  • Swapped renames: with field a renamed to "b" and field b renamed to "c", the input {"a": …, "b": …} used to read and now fails with a duplicate-field error, while {"b": …, "c": …} (the documented wire form) now reads. This follows from the wire name taking precedence.
  • Base structs: the rename parsing fix also applies where get_serde_rename is used for base structs (type-field check, recorded generic field name). A base field written #[serde(rename = "x", default)] is now recognized under "x" instead of its Rust name. This is a correction of the same parsing bug.
  • Not changed, documented: an Option written through a type alias is not recognized, and skip_serializing_if, skip, rename(serialize = …, deserialize = …) and container rename_all are not applied to derived structs. The derived serializer still writes null for None.

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Testing

New gts-macros/tests/derived_optional_fields_tests.rs (16 tests): absent, null and present optional/default fields, missing required fields, renamed members and their legacy alias, alias + wire name as a duplicate, round-trip through GtsSerialize, schema/deserializer agreement on required, rename followed by default = "...", a default function named like its field, a field named map, and a generic middle type in a chain. 7 of the first 9 tests fail on main; the map case does not compile there.

cargo test --workspace
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings

Checklist

  • Tests pass (cargo test)
  • Code is formatted (cargo fmt)
  • No clippy warnings (cargo clippy)
  • Documentation is updated

The GtsDeserialize impl generated for a derived struct (base = Parent)
matched member names against the Rust field idents and ignored
a derived struct with a renamed field did not deserialize what it
serialized: the wire name was ignored and reported as a missing field.

Read each member under its serialized name. When that name differs from
the key matched before, accept the old key as an alias, so input that
deserialized until now still does.

Signed-off-by: MikeFalcon77 <3686170+MikeFalcon77@users.noreply.github.com>
The GtsDeserialize impl generated for a derived struct treated every
absent member as missing, except an Option<P> generic slot. An ordinary
Option<T> field, or a field with #[serde(default)], was therefore
required on input, although the generated schema leaves it out of
`required` and the README documents it as optional. Adding such a field
to a derived type made old instances unreadable.

Read an absent member as serde derive does for base structs: a field
with #[serde(default)] or #[serde(default = "path")] takes that default,
an Option<T> field is None, and any other field is missing. Schemas and
serialization are unchanged.

Document the serde field rules that apply to derived structs and add
tests covering defaults, null, renamed members, round-trip and schema
agreement.

Signed-off-by: MikeFalcon77 <3686170+MikeFalcon77@users.noreply.github.com>
get_serde_rename matched on the attribute's token string, so a rename
followed by another option was misread: `rename = "kind", default =
"f"` produced the name `kind", default = "f`, and `rename = "kind",
default` lost the rename. With absent members now defaulted, that turned
into a silently defaulted field. Parse #[serde(...)] options as syn
metas, shared by the rename, default and option-name helpers.

The derived-struct visitor kept members in locals named after the
fields, which shadowed a default function of the same name and the
visitor's own `map`. Use prefixed locals and build the struct from the
finished values directly.

The legacy key now follows serde's snake_case rule exactly, ASCII
lowercasing included. Document which serde rules derived structs apply
and test the cases above, the alias/wire-name duplicate and a generic
middle type.

Signed-off-by: MikeFalcon77 <3686170+MikeFalcon77@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4fcc97fe-9206-4552-a13c-3642cdcce256
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@code-ranker-app

code-ranker-app Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

code-ranker

Built on a fork. View full report ↗

rust
Metric Baseline Current Δ
Complexity
cognitive — Cognitive complexity 54.9 55 $\color{#c0392b}{+0.167}$
cyclomatic — Cyclomatic complexity 80.9 81.5 $\color{#c0392b}{+0.608}$
Coupling
hk — God-object risk 491.9K 492.2K $\color{#c0392b}{+282}$
Halstead
bugs — Estimated bugs 2.2 2.2 $\color{#c0392b}{+0.008}$
effort — Implementation effort 857.7K 866.4K $\color{#c0392b}{+8678}$
length — Total tokens 1432 1442 $\color{#c0392b}{+9.9}$
time — Coding time (s) 47.7K 48.1K $\color{#c0392b}{+482}$
vocabulary — Distinct symbols 155 155 $\color{#c0392b}{+0.41}$
volume — Code volume 11.7K 11.8K $\color{#c0392b}{+106}$
Lines of Code
blank — Blank lines 34 34.1 +0.131
cloc — Comment lines 85.5 85.8 +0.267
sloc — Source lines 311 313 +1.8

@codecov-commenter

codecov-commenter commented Nov 19, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 94.69027% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
gts-macros/src/lib.rs 94.69% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

Comment thread gts-macros/src/lib.rs
} else {
quote! {
let #ident = #ident.ok_or_else(|| serde::de::Error::missing_field(#name))?;
quote! { #[serde(rename = #name, alias = #legacy)] #ident }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With b renamed to c and then a renamed to b, reading our own {"c":"first","b":"second"} fails with a duplicate-field error because the first field claims b as an alias. Please skip legacy aliases that match another field’s wire name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. A legacy alias is no longer emitted when another field is written under that key. swapped_renames_read_back_in_declaration_order covers your order (b -> c before a -> b) with a round-trip.

Comment thread gts-macros/src/lib.rs
quote! { #ident: #local.unwrap_or_default() }
}
Some(FieldDefault::Path(path)) => {
quote! { #ident: #local.unwrap_or_else(#path) }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This breaks #[serde(default = "Self::default_level")] because Self here refers to StructVisitor. Please resolve the default path in the original struct’s context and add a regression test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Self in a default = "..." path is replaced with the struct type (as serde derive does), including generic structs. tests are updated

A legacy alias of a derived field could take another field's wire name:
with `b` renamed to `c` declared before `a` renamed to `b`, the alias `b`
of the first field matched before the second field's name, so the
struct's own serialized form failed with a duplicate field. Skip a
legacy alias that another field is written under.

A `default = "Self::f"` path was called from the generated visitor, where
`Self` is the visitor, and did not compile. Replace `Self` in default
paths with the struct type, as serde derive does.

Signed-off-by: MikeFalcon77 <3686170+MikeFalcon77@users.noreply.github.com>
@aviator5
aviator5 merged commit 8a000c8 into GlobalTypeSystem:main Nov 20, 2026
9 checks passed
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.

3 participants