derive_builder_core/
block.rs

1use std::convert::TryFrom;
2
3use proc_macro2::{Span, TokenStream};
4use quote::ToTokens;
5use syn::{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    pub fn span(&self) -> Span {
21        self.0.span()
22    }
23}
24
25impl ToTokens for BlockContents {
26    fn to_tokens(&self, tokens: &mut TokenStream) {
27        self.0.to_tokens(tokens)
28    }
29}
30
31impl TryFrom<&'_ LitStr> for BlockContents {
32    type Error = syn::Error;
33
34    fn try_from(s: &LitStr) -> Result<Self, Self::Error> {
35        let mut block_str = s.value();
36        block_str.insert(0, '{');
37        block_str.push('}');
38        LitStr::new(&block_str, s.span()).parse().map(Self)
39    }
40}
41
42impl From<syn::Expr> for BlockContents {
43    fn from(v: syn::Expr) -> Self {
44        Self(Block {
45            brace_token: syn::token::Brace(v.span()),
46            stmts: vec![syn::Stmt::Expr(v, None)],
47        })
48    }
49}
50
51impl darling::FromMeta for BlockContents {
52    fn from_value(value: &syn::Lit) -> darling::Result<Self> {
53        if let syn::Lit::Str(s) = value {
54            let contents = BlockContents::try_from(s)?;
55            if contents.is_empty() {
56                Err(darling::Error::unknown_value("").with_span(s))
57            } else {
58                Ok(contents)
59            }
60        } else {
61            Err(darling::Error::unexpected_lit_type(value))
62        }
63    }
64
65    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
66        if let syn::Expr::Lit(lit) = expr {
67            Self::from_value(&lit.lit)
68        } else {
69            Ok(Self::from(expr.clone()))
70        }
71    }
72}
73
74#[cfg(test)]
75mod test {
76    use std::convert::TryInto;
77
78    use super::*;
79
80    fn parse(s: &str) -> Result<BlockContents, syn::Error> {
81        (&LitStr::new(s, Span::call_site())).try_into()
82    }
83
84    #[test]
85    #[should_panic(expected = r#"cannot parse"#)]
86    fn block_invalid_token_trees() {
87        parse("let x = 2; { x+1").unwrap();
88    }
89
90    #[test]
91    fn block_delimited_token_tree() {
92        let expr = parse("let x = 2; { x+1 }").unwrap();
93        assert_eq!(
94            quote!(#expr).to_string(),
95            quote!({
96                let x = 2;
97                {
98                    x + 1
99                }
100            })
101            .to_string()
102        );
103    }
104
105    #[test]
106    fn block_single_token_tree() {
107        let expr = parse("42").unwrap();
108        assert_eq!(quote!(#expr).to_string(), quote!({ 42 }).to_string());
109    }
110}