From 553549ff12358a6ad95baaed2601a9dab541d693 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 24 Dec 2023 20:05:39 -0800 Subject: [PATCH] Generalize snapshot parsing to types that do not implement Parse --- tests/macros/mod.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/tests/macros/mod.rs b/tests/macros/mod.rs index 3bfbe03898..d27c391339 100644 --- a/tests/macros/mod.rs +++ b/tests/macros/mod.rs @@ -3,7 +3,8 @@ #[path = "../debug/mod.rs"] pub mod debug; -use syn::parse::{Parse, Result}; +use std::str::FromStr; +use syn::parse::Result; macro_rules! errorf { ($($tt:tt)*) => {{ @@ -35,7 +36,8 @@ macro_rules! snapshot { macro_rules! snapshot_impl { (($expr:ident) as $t:ty, @$snapshot:literal) => { - let $expr = crate::macros::Tokens::parse::<$t>($expr).unwrap(); + let tokens = crate::macros::TryIntoTokens::try_into_tokens($expr).unwrap(); + let $expr: $t = syn::parse_quote!(#tokens); let debug = crate::macros::debug::Lite(&$expr); if !cfg!(miri) { #[allow(clippy::needless_raw_string_hashes)] // https://github.com/mitsuhiko/insta/issues/389 @@ -45,7 +47,8 @@ macro_rules! snapshot_impl { } }; (($($expr:tt)*) as $t:ty, @$snapshot:literal) => {{ - let syntax_tree = crate::macros::Tokens::parse::<$t>($($expr)*).unwrap(); + let tokens = crate::macros::TryIntoTokens::try_into_tokens($($expr)*).unwrap(); + let syntax_tree: $t = syn::parse_quote!(#tokens); let debug = crate::macros::debug::Lite(&syntax_tree); if !cfg!(miri) { #[allow(clippy::needless_raw_string_hashes)] @@ -71,18 +74,19 @@ macro_rules! snapshot_impl { }; } -pub trait Tokens { - fn parse(self) -> Result; +pub trait TryIntoTokens { + fn try_into_tokens(self) -> Result; } -impl<'a> Tokens for &'a str { - fn parse(self) -> Result { - syn::parse_str(self) +impl<'a> TryIntoTokens for &'a str { + fn try_into_tokens(self) -> Result { + let tokens = proc_macro2::TokenStream::from_str(self)?; + Ok(tokens) } } -impl Tokens for proc_macro2::TokenStream { - fn parse(self) -> Result { - syn::parse2(self) +impl TryIntoTokens for proc_macro2::TokenStream { + fn try_into_tokens(self) -> Result { + Ok(self) } }