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
  • Loading branch information
dtolnay committed Dec 25, 2023
1 parent f9ad833 commit 01072a1
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 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::Tokens::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::Tokens::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 @@ -72,17 +75,18 @@ macro_rules! snapshot_impl {
}

pub trait Tokens {
fn parse<T: Parse>(self) -> Result<T>;
fn tokens(self) -> Result<proc_macro2::TokenStream>;
}

impl<'a> Tokens for &'a str {
fn parse<T: Parse>(self) -> Result<T> {
syn::parse_str(self)
fn 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)
fn tokens(self) -> Result<proc_macro2::TokenStream> {
Ok(self)
}
}

0 comments on commit 01072a1

Please sign in to comment.