blob: d53009bf27538284ce29f0bf479683fe8a508f34 [file] [log] [blame]
David Tolnay7d8b3312019-03-10 01:26:11 -08001extern crate proc_macro2;
2
3use syn;
4use syn::parse::{Parse, Result};
5
David Tolnaydd125562017-12-31 02:16:22 -05006#[macro_export]
7macro_rules! errorf {
8 ($($tt:tt)*) => {{
9 use ::std::io::Write;
10 let stderr = ::std::io::stderr();
11 write!(stderr.lock(), $($tt)*).unwrap();
12 }};
13}
14
15#[macro_export]
David Tolnayf2cfd722017-12-31 18:02:51 -050016macro_rules! punctuated {
David Tolnaya0834b42018-01-01 21:30:02 -080017 ($($e:expr,)+) => {{
David Tolnayf2cfd722017-12-31 18:02:51 -050018 let mut seq = ::syn::punctuated::Punctuated::new();
David Tolnaydd125562017-12-31 02:16:22 -050019 $(
David Tolnaya0834b42018-01-01 21:30:02 -080020 seq.push($e);
21 )+
David Tolnayf2cfd722017-12-31 18:02:51 -050022 seq
David Tolnaydd125562017-12-31 02:16:22 -050023 }};
24
25 ($($e:expr),+) => {
David Tolnayf2cfd722017-12-31 18:02:51 -050026 punctuated!($($e,)+)
David Tolnaydd125562017-12-31 02:16:22 -050027 };
28}
David Tolnay7d8b3312019-03-10 01:26:11 -080029
30#[macro_export]
31macro_rules! snapshot {
32 ($($args:tt)*) => {
33 snapshot_impl!(() $($args)*)
34 };
35}
36
37#[macro_export]
38macro_rules! snapshot_impl {
39 (($($expr:tt)*) as $t:ty) => {{
40 let syntax_tree = ::macros::Tokens::parse::<$t>($($expr)*).unwrap();
41 insta::assert_debug_snapshot_matches!(syntax_tree);
42 syntax_tree
43 }};
David Tolnayb765ca72019-05-07 13:16:46 -070044 (($($expr:tt)*) as $t:ty, @$snapshot:literal) => {{
45 let syntax_tree = ::macros::Tokens::parse::<$t>($($expr)*).unwrap();
46 insta::assert_debug_snapshot_matches!(syntax_tree, @$snapshot);
47 syntax_tree
48 }};
David Tolnay7d8b3312019-03-10 01:26:11 -080049 (($($expr:tt)*)) => {{
50 let syntax_tree = $($expr)*;
51 insta::assert_debug_snapshot_matches!(syntax_tree);
52 syntax_tree
53 }};
David Tolnayb765ca72019-05-07 13:16:46 -070054 (($($expr:tt)*) , @$snapshot:literal) => {{
55 let syntax_tree = $($expr)*;
56 insta::assert_debug_snapshot_matches!(syntax_tree, @$snapshot);
57 syntax_tree
58 }};
David Tolnay7d8b3312019-03-10 01:26:11 -080059 (($($expr:tt)*) $next:tt $($rest:tt)*) => {
60 snapshot_impl!(($($expr)* $next) $($rest)*)
61 };
62}
63
64pub trait Tokens {
65 fn parse<T: Parse>(self) -> Result<T>;
66}
67
68impl<'a> Tokens for &'a str {
69 fn parse<T: Parse>(self) -> Result<T> {
70 syn::parse_str(self)
71 }
72}
73
74impl Tokens for proc_macro2::TokenStream {
75 fn parse<T: Parse>(self) -> Result<T> {
76 syn::parse2(self)
77 }
78}