typed_builder_macro/
builder_attr.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::parse::Error;

use crate::field_info::FieldBuilderAttr;
use crate::mutator::Mutator;
use crate::util::{path_to_single_string, ApplyMeta, AttrArg};

#[derive(Debug, Default, Clone)]
pub struct CommonDeclarationSettings {
    pub vis: Option<syn::Visibility>,
    pub name: Option<syn::Expr>,
    pub doc: Option<syn::Expr>,
}

impl ApplyMeta for CommonDeclarationSettings {
    fn apply_meta(&mut self, expr: AttrArg) -> Result<(), Error> {
        match expr.name().to_string().as_str() {
            "vis" => {
                let expr_str = expr.key_value()?.parse_value::<syn::LitStr>()?.value();
                self.vis = Some(syn::parse_str(&expr_str)?);
                Ok(())
            }
            "name" => {
                self.name = Some(expr.key_value()?.parse_value()?);
                Ok(())
            }
            "doc" => {
                self.doc = Some(expr.key_value()?.parse_value()?);
                Ok(())
            }
            _ => Err(Error::new_spanned(
                expr.name(),
                format!("Unknown parameter {:?}", expr.name().to_string()),
            )),
        }
    }
}

impl CommonDeclarationSettings {
    pub fn get_name(&self) -> Option<TokenStream> {
        self.name.as_ref().map(|name| name.to_token_stream())
    }

    pub fn get_doc_or(&self, gen_doc: impl FnOnce() -> String) -> TokenStream {
        if let Some(ref doc) = self.doc {
            quote!(#[doc = #doc])
        } else {
            let doc = gen_doc();
            quote!(#[doc = #doc])
        }
    }
}

/// Setting of the `into` argument.
#[derive(Debug, Clone)]
pub enum IntoSetting {
    /// Do not run any conversion on the built value.
    NoConversion,
    /// Convert the build value into the generic parameter passed to the `build` method.
    GenericConversion,
    /// Convert the build value into a specific type specified in the attribute.
    TypeConversionToSpecificType(syn::TypePath),
}

impl Default for IntoSetting {
    fn default() -> Self {
        Self::NoConversion
    }
}

#[derive(Debug, Default, Clone)]
pub struct BuildMethodSettings {
    pub common: CommonDeclarationSettings,

    /// Whether to convert the built type into another while finishing the build.
    pub into: IntoSetting,
}

impl ApplyMeta for BuildMethodSettings {
    fn apply_meta(&mut self, expr: AttrArg) -> Result<(), Error> {
        match expr.name().to_string().as_str() {
            "into" => match expr {
                AttrArg::Flag(_) => {
                    self.into = IntoSetting::GenericConversion;
                    Ok(())
                }
                AttrArg::KeyValue(key_value) => {
                    let type_path = key_value.parse_value::<syn::TypePath>()?;
                    self.into = IntoSetting::TypeConversionToSpecificType(type_path);
                    Ok(())
                }
                _ => Err(expr.incorrect_type()),
            },
            _ => self.common.apply_meta(expr),
        }
    }
}

#[derive(Debug)]
pub struct TypeBuilderAttr<'a> {
    /// Whether to show docs for the `TypeBuilder` type (rather than hiding them).
    pub doc: bool,

    /// Customize builder method, ex. visibility, name
    pub builder_method: CommonDeclarationSettings,

    /// Customize builder type, ex. visibility, name
    pub builder_type: CommonDeclarationSettings,

    /// Customize build method, ex. visibility, name
    pub build_method: BuildMethodSettings,

    pub field_defaults: FieldBuilderAttr<'a>,

    pub crate_module_path: syn::Path,

    /// Functions that are able to mutate fields in the builder that are already set
    pub mutators: Vec<Mutator>,
}

impl Default for TypeBuilderAttr<'_> {
    fn default() -> Self {
        Self {
            doc: Default::default(),
            builder_method: Default::default(),
            builder_type: Default::default(),
            build_method: Default::default(),
            field_defaults: Default::default(),
            crate_module_path: syn::parse_quote!(::typed_builder),
            mutators: Default::default(),
        }
    }
}

impl<'a> TypeBuilderAttr<'a> {
    pub fn new(attrs: &[syn::Attribute]) -> Result<Self, Error> {
        let mut result = Self::default();

        for attr in attrs {
            let list = match &attr.meta {
                syn::Meta::List(list) => {
                    if path_to_single_string(&list.path).as_deref() != Some("builder") {
                        continue;
                    }

                    list
                }
                _ => continue,
            };

            result.apply_subsections(list)?;
        }

        if result.builder_type.doc.is_some() || result.build_method.common.doc.is_some() {
            result.doc = true;
        }

        Ok(result)
    }
}

impl ApplyMeta for TypeBuilderAttr<'_> {
    fn apply_meta(&mut self, expr: AttrArg) -> Result<(), Error> {
        match expr.name().to_string().as_str() {
            "crate_module_path" => {
                let crate_module_path = expr.key_value()?.parse_value::<syn::ExprPath>()?;
                self.crate_module_path = crate_module_path.path;
                Ok(())
            }
            "builder_method_doc" => Err(Error::new_spanned(
                expr.name(),
                "`builder_method_doc` is deprecated - use `builder_method(doc = \"...\")`",
            )),
            "builder_type_doc" => Err(Error::new_spanned(
                expr.name(),
                "`builder_typemethod_doc` is deprecated - use `builder_type(doc = \"...\")`",
            )),
            "build_method_doc" => Err(Error::new_spanned(
                expr.name(),
                "`build_method_doc` is deprecated - use `build_method(doc = \"...\")`",
            )),
            "doc" => {
                expr.flag()?;
                self.doc = true;
                Ok(())
            }
            "mutators" => {
                self.mutators.extend(expr.sub_attr()?.undelimited()?);
                Ok(())
            }
            "field_defaults" => self.field_defaults.apply_sub_attr(expr.sub_attr()?),
            "builder_method" => self.builder_method.apply_sub_attr(expr.sub_attr()?),
            "builder_type" => self.builder_type.apply_sub_attr(expr.sub_attr()?),
            "build_method" => self.build_method.apply_sub_attr(expr.sub_attr()?),
            _ => Err(Error::new_spanned(
                expr.name(),
                format!("Unknown parameter {:?}", expr.name().to_string()),
            )),
        }
    }
}