diff --git a/CHANGELOG.md b/CHANGELOG.md index b18099a..611146a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ * Lower the MSRV to 1.88: the newest compiler the crate itself needs (for `let` chains), and what its `regress` dependency needs. +* `TypespaceTrait::from_path` compares parsed paths, so a derive written with + spaced separators (`schemars :: JsonSchema`) is recognized as the trait. * An `Optional` whose type is a container (`Vec`, `Set`, `Map`) or the unit type (`()`) have settings (`optional_container` and `optional_unit`--to join `optional_nullable` for `Optional` `Option` types) that govern whether diff --git a/typespace/src/lib.rs b/typespace/src/lib.rs index 998d393..872b9df 100644 --- a/typespace/src/lib.rs +++ b/typespace/src/lib.rs @@ -406,16 +406,26 @@ impl TypespaceTrait { /// its leading `::`, and the `core` synonym of a `std` path. Anything else /// is not a trait typespace models. pub fn from_path(path: &str) -> Option { - let path = path.trim(); + // We compare parsed segments so that any token spacing matches, such + // as the `schemars :: JsonSchema` that `ToTokens` produces. + let path = syn::parse_str::(path).ok()?; + let segments = path + .segments + .iter() + .map(|segment| { + segment + .arguments + .is_none() + .then(|| segment.ident.to_string()) + }) + .collect::>>()?; Self::iter().find(|trait_| { - let canonical = trait_.canonical_path(); - let unrooted = &canonical[2..]; - path == trait_.to_string() - || path == canonical - || path == unrooted - || unrooted.strip_prefix("std::").is_some_and(|rest| { - path == format!("core::{rest}") || path == format!("::core::{rest}") - }) + let canonical = trait_.canonical_path()[2..].split("::").collect::>(); + (path.leading_colon.is_none() && segments == [trait_.to_string()]) + || segments == canonical + || (canonical[0] == "std" + && segments[0] == "core" + && segments[1..] == canonical[1..]) }) } } diff --git a/typespace/tests/trait_request.rs b/typespace/tests/trait_request.rs index 6c58371..fc7915a 100644 --- a/typespace/tests/trait_request.rs +++ b/typespace/tests/trait_request.rs @@ -87,6 +87,34 @@ fn parse_recognizes_a_modeled_trait() { } } +/// `from_path` recognizes a modeled trait however its path tokens are spaced, +/// as in the `schemars :: JsonSchema` that `ToTokens` produces. +#[test] +fn from_path_ignores_token_spacing() { + for spelling in [ + "schemars :: JsonSchema", + ":: schemars :: JsonSchema", + "::schemars::JsonSchema", + "schemars::JsonSchema", + " JsonSchema ", + ] { + assert_eq!( + TypespaceTrait::from_path(spelling), + Some(TypespaceTrait::JsonSchema), + "{spelling}" + ); + } + assert_eq!( + TypespaceTrait::from_path("core :: cmp :: Ord"), + Some(TypespaceTrait::Ord) + ); + assert_eq!(TypespaceTrait::from_path("deftly :: Deftly"), None); + assert!(matches!( + TraitSpec::parse("deftly :: Deftly"), + Ok(TraitSpec::Foreign(_)) + )); +} + /// `parse` reads bounds after a colon, each a modeled trait. #[test] fn parse_reads_bounds() {