Skip to content

Commit

Permalink
Merge pull request #1557 from dtolnay/snapshotparsequote
Browse files Browse the repository at this point in the history
Generalize snapshot parsing to types that do not implement Parse
  • Loading branch information
dtolnay authored Dec 25, 2023
2 parents f9ad833 + 553549f commit 3cf16c7
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
Expand Up @@ -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)*) => {{
Expand Down Expand Up @@ -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
Expand All @@ -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)]
Expand All @@ -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 3cf16c7

Please sign in to comment.