derive_builder_core_fork_arti/
block.rs

1use std::convert::TryFrom;
2
3use proc_macro2::TokenStream;
4use quote::ToTokens;
5use syn::{self, spanned::Spanned, Block, LitStr};
6
7/// A wrapper for expressions/blocks which automatically adds the start and end
8/// braces.
9///
10/// - **full access** to variables environment.
11/// - **full access** to control-flow of the environment via `return`, `?` etc.
12#[derive(Debug, Clone)]
13pub struct BlockContents(Block);
14
15impl BlockContents {
16    pub fn is_empty(&self) -> bool {
17        self.0.stmts.is_empty()
18    }
19}
20
21impl ToTokens for BlockContents {
22    fn to_tokens(&self, tokens: &mut TokenStream) {
23        self.0.to_tokens(tokens)
24    }
25}
26
27impl TryFrom<&'_ LitStr> for BlockContents {
28    type Error = syn::Error;
29
30    fn try_from(s: &LitStr) -> Result<Self, Self::Error> {
31        let mut block_str = s.value();
32        block_str.insert(0, '{');
33        block_str.push('}');
34        LitStr::new(&block_str, s.span()).parse().map(Self)
35    }
36}
37
38impl From<syn::Expr> for BlockContents {
39    fn from(v: syn::Expr) -> Self {
40        Self(Block {
41            brace_token: syn::token::Brace(v.span()),
42            stmts: vec![syn::Stmt::Expr(v)],
43        })
44    }
45}
46
47impl darling::FromMeta for BlockContents {
48    fn from_value(value: &syn::Lit) -> darling::Result<Self> {
49        if let syn::Lit::Str(s) = value {
50            let contents = BlockContents::try_from(s)?;
51            if contents.is_empty() {
52                Err(darling::Error::unknown_value("").with_span(s))
53            } else {
54                Ok(contents)
55            }
56        } else {
57            Err(darling::Error::unexpected_lit_type(value))
58        }
59    }
60}
61
62#[cfg(test)]
63mod test {
64    use std::convert::TryInto;
65
66    use super::*;
67    use proc_macro2::Span;
68
69    fn parse(s: &str) -> Result<BlockContents, syn::Error> {
70        (&LitStr::new(s, Span::call_site())).try_into()
71    }
72
73    #[test]
74    #[should_panic(expected = r#"lex error"#)]
75    fn block_invalid_token_trees() {
76        parse("let x = 2; { x+1").unwrap();
77    }
78
79    #[test]
80    fn block_delimited_token_tree() {
81        let expr = parse("let x = 2; { x+1 }").unwrap();
82        assert_eq!(
83            quote!(#expr).to_string(),
84            quote!({
85                let x = 2;
86                {
87                    x + 1
88                }
89            })
90            .to_string()
91        );
92    }
93
94    #[test]
95    fn block_single_token_tree() {
96        let expr = parse("42").unwrap();
97        assert_eq!(quote!(#expr).to_string(), quote!({ 42 }).to_string());
98    }
99}