derive_builder_core/
default_expression.rs

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
use crate::BlockContents;
use proc_macro2::Span;
use quote::ToTokens;

/// A `DefaultExpression` can be either explicit or refer to the canonical trait.
#[derive(Debug, Clone)]
pub enum DefaultExpression {
    Explicit(BlockContents),
    Trait,
}

impl DefaultExpression {
    /// Add the crate root path so the default expression can be emitted
    /// to a `TokenStream`.
    ///
    /// This function is needed because the crate root is inherited from the container, so it cannot
    /// be provided at parse time to [`darling::FromMeta::from_word`] when reading, and [`ToTokens`] does not
    /// accept any additional parameters, so it annot be provided at emit time.
    pub fn with_crate_root<'a>(&'a self, crate_root: &'a syn::Path) -> impl 'a + ToTokens {
        DefaultExpressionWithCrateRoot {
            crate_root,
            expr: self,
        }
    }

    pub fn span(&self) -> Span {
        match self {
            DefaultExpression::Explicit(block) => block.span(),
            DefaultExpression::Trait => Span::call_site(),
        }
    }

    #[cfg(test)]
    pub fn explicit<I: Into<BlockContents>>(content: I) -> Self {
        DefaultExpression::Explicit(content.into())
    }
}

impl darling::FromMeta for DefaultExpression {
    fn from_word() -> darling::Result<Self> {
        Ok(DefaultExpression::Trait)
    }

    fn from_expr(expr: &syn::Expr) -> darling::Result<Self> {
        if let syn::Expr::Lit(el) = expr {
            if let syn::Lit::Str(_) = el.lit {
                return Self::from_value(&el.lit);
            }
        }

        Ok(Self::Explicit(expr.clone().into()))
    }

    fn from_value(value: &syn::Lit) -> darling::Result<Self> {
        Ok(Self::Explicit(BlockContents::from_value(value)?))
    }
}

/// Wrapper for `DefaultExpression`
struct DefaultExpressionWithCrateRoot<'a> {
    crate_root: &'a syn::Path,
    expr: &'a DefaultExpression,
}

impl<'a> ToTokens for DefaultExpressionWithCrateRoot<'a> {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let crate_root = self.crate_root;
        match self.expr {
            DefaultExpression::Explicit(ref block) => block.to_tokens(tokens),
            DefaultExpression::Trait => quote!(
                #crate_root::export::core::default::Default::default()
            )
            .to_tokens(tokens),
        }
    }
}