Skip to content

Commit

Permalink
Generalize snapshot parsing to types that do not implement Parse
Browse files Browse the repository at this point in the history
dtolnay committed Dec 25, 2023
1 parent f9ad833 commit 553549f
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions tests/macros/mod.rs
Original file line number Diff line number Diff line change
@@ -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<T: Parse>(self) -> Result<T>;
pub trait TryIntoTokens {
fn try_into_tokens(self) -> Result<proc_macro2::TokenStream>;
}

impl<'a> Tokens for &'a str {
fn parse<T: Parse>(self) -> Result<T> {
syn::parse_str(self)
impl<'a> TryIntoTokens for &'a str {
fn try_into_tokens(self) -> Result<proc_macro2::TokenStream> {
let tokens = proc_macro2::TokenStream::from_str(self)?;
Ok(tokens)
}
}

impl Tokens for proc_macro2::TokenStream {
fn parse<T: Parse>(self) -> Result<T> {
syn::parse2(self)
impl TryIntoTokens for proc_macro2::TokenStream {
fn try_into_tokens(self) -> Result<proc_macro2::TokenStream> {
Ok(self)
}
}

0 comments on commit 553549f

Please sign in to comment.