Skip to content

Report an error instead of panicking on invalid map types#1031

Open
danieleades wants to merge 1 commit into
oxidecomputer:mainfrom
danieleades:fix/maptype-parse
Open

Report an error instead of panicking on invalid map types#1031
danieleades wants to merge 1 commit into
oxidecomputer:mainfrom
danieleades:fix/maptype-parse

Conversation

@danieleades

Copy link
Copy Markdown
Contributor

Problem

MapType::new parses its input with syn::parse_str(..).expect("valid ident"), and both the Deserialize impl and the From<&str>/From<String> conversions funnel through it. As a result:

  • cargo typify --map-type 'not a valid!!type' panics with expect instead of reporting an error.
  • Deserializing a MapType from an invalid string panics instead of returning a deserialization error. The impl also used <&str>::deserialize, which fails for inputs that need allocation (e.g. strings containing escape sequences).

Fix

  • Add impl FromStr for MapType, carrying the syn parse error message as Err.
  • Rework Deserialize to deserialize an owned String and map parse failures to serde::de::Error::custom.
  • Parse --map-type fallibly in cargo-typify::convert, so an invalid value produces a clean CLI error. MapType is re-exported from the typify crate to make that possible (with_map_type already exposed it in its bound).
  • Tests: FromStr rejects garbage and accepts ::std::collections::BTreeMap; Deserialize handles escaped strings and errors on invalid input; a CLI integration test confirms an invalid --map-type yields an error, not a panic.

Trade-offs

The FromStr impl is additive. MapType::new and the From<&str>/From<String> conversions keep their panicking behavior for backwards compatibility, but now document it with # Panics sections and point at str::parse as the non-panicking alternative.

Add a fallible std::str::FromStr implementation for MapType and use it
where invalid input is reachable:

- MapType's Deserialize implementation now maps parse failures to a
  deserialization error rather than panicking, and deserializes an
  owned String so inputs requiring allocation (e.g. strings with escape
  sequences) work.
- cargo-typify parses --map-type fallibly, so an invalid value produces
  a clean CLI error instead of a panic.

MapType::new and the From<&str>/From<String> conversions keep their
panicking behavior for compatibility; their panics are now documented.
MapType is additionally re-exported from the typify crate.
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