1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use std::str::FromStr;
use quote::{Tokens, ToTokens};
use syn::{self, TokenTree};
#[derive(Debug, Default, Clone)]
pub struct Block(Vec<TokenTree>);
impl ToTokens for Block {
fn to_tokens(&self, tokens: &mut Tokens) {
let inner = &self.0;
tokens.append(quote!(
{ #( #inner )* }
));
}
}
impl FromStr for Block {
type Err = String;
fn from_str(expr: &str) -> Result<Self, Self::Err> {
Ok(Block(syn::parse_token_trees(expr)?))
}
}
#[cfg(test)]
mod test {
#[allow(unused_imports)]
use super::*;
#[test]
#[should_panic(expected="called `Result::unwrap()` on an `Err` value: \
\"unparsed tokens after token trees: \\\"{ x+1\\\"")]
fn block_invalid_token_trees() {
Block::from_str("let x = 2; { x+1").unwrap();
}
#[test]
fn block_delimited_token_tree() {
let expr = Block::from_str("let x = 2; { x+1 }").unwrap();
assert_eq!(quote!(#expr), quote!(
{ let x = 2; { x+1 } }
));
}
#[test]
fn block_single_token_tree() {
let expr = Block::from_str("42").unwrap();
assert_eq!(quote!(#expr), quote!(
{ 42 }
));
}
}