bon_macros/builder/builder_gen/member/
mod.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
mod config;
mod into_conversion;
mod named;

pub(crate) use config::*;
pub(crate) use named::*;

use super::top_level_config::OnConfig;
use crate::normalization::SyntaxVariant;
use crate::util::prelude::*;
use config::MemberConfig;
use darling::FromAttributes;
use std::fmt;

#[derive(Debug, Clone, Copy)]
pub(crate) enum MemberOrigin {
    FnArg,
    StructField,
}

impl fmt::Display for MemberOrigin {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FnArg => write!(f, "function argument"),
            Self::StructField => write!(f, "struct field"),
        }
    }
}

impl MemberOrigin {
    fn parent_construct(self) -> &'static str {
        match self {
            Self::FnArg => "function",
            Self::StructField => "struct",
        }
    }
}

#[derive(Debug)]
pub(crate) enum Member {
    /// Member that was marked with `#[builder(start_fn)]`
    StartFn(StartFnMember),

    /// Member that was marked with `#[builder(field)]`
    Field(CustomField),

    /// Member that was marked with `#[builder(finish_fn)]`
    FinishFn(PosFnMember),

    /// Regular named member included in the typestate.
    Named(NamedMember),

    /// Member that was marked with `#[builder(skip)]`
    Skip(SkipMember),
}

/// Member that was marked with `#[builder(start_fn)]`
#[derive(Debug)]
pub(crate) struct StartFnMember {
    pub(crate) base: PosFnMember,

    /// Index of the member relative to other positional members. The index is 0-based.
    pub(crate) index: syn::Index,
}

#[derive(Debug)]
pub(crate) struct CustomField {
    pub(crate) ident: syn::Ident,
    pub(crate) norm_ty: Box<syn::Type>,

    /// Initial value of the field
    pub(crate) init: Option<syn::Expr>,
}

#[derive(Debug)]
pub(crate) struct PosFnMember {
    /// Specifies what syntax the member comes from.
    pub(crate) origin: MemberOrigin,

    /// Original identifier of the member
    pub(crate) ident: syn::Ident,

    /// Type of the member
    pub(crate) ty: SyntaxVariant<Box<syn::Type>>,

    /// Parameters configured by the user explicitly via attributes
    pub(crate) config: MemberConfig,
}

/// Member that was skipped by the user with `#[builder(skip)]`
#[derive(Debug)]
pub(crate) struct SkipMember {
    pub(crate) ident: syn::Ident,

    /// Normalized type of the member
    pub(crate) norm_ty: Box<syn::Type>,

    /// Value to assign to the member
    pub(crate) value: Option<syn::Expr>,
}

pub(crate) struct RawMember<'a> {
    pub(crate) attrs: &'a [syn::Attribute],
    pub(crate) ident: syn::Ident,
    pub(crate) ty: SyntaxVariant<Box<syn::Type>>,
}

impl Member {
    // False-positive lint. We can't elide the lifetime in `RawMember` because
    // anonymous lifetimes in impl traits are unstable, and we shouldn't omit
    // the lifetime parameter because we want to be explicit about its existence
    // (there is an other lint that checks for this).
    #[allow(single_use_lifetimes)]
    pub(crate) fn from_raw<'a>(
        on: &[OnConfig],
        origin: MemberOrigin,
        members: impl IntoIterator<Item = RawMember<'a>>,
    ) -> Result<Vec<Self>> {
        let mut members = members
            .into_iter()
            .map(|member| {
                for attr in member.attrs {
                    if attr.meta.path().is_ident("builder") {
                        crate::parsing::require_non_empty_paren_meta_list_or_name_value(
                            &attr.meta,
                        )?;
                    }
                }

                let config = MemberConfig::from_attributes(member.attrs)?;
                config.validate(origin)?;
                Ok((member, config))
            })
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .peekable();

        let mut output = vec![];

        // Collect `start_fn` members
        for index in 0.. {
            let next = members.next_if(|(_, meta)| meta.start_fn.is_present());
            let (member, config) = match next {
                Some(item) => item,
                None => break,
            };
            let base = PosFnMember::new(origin, member, on, config)?;
            output.push(Self::StartFn(StartFnMember {
                base,
                index: index.into(),
            }));
        }

        // Collect `field` members
        while let Some((member, config)) = members.next_if(|(_, config)| config.field.is_some()) {
            let init = config
                .field
                .expect("validated `field.is_some()` in `next_if`")
                .value;

            let member = CustomField::new(member, init)?;
            output.push(Self::Field(member));
        }

        // Collect `finish_fn` members
        while let Some((member, config)) =
            members.next_if(|(_, config)| config.finish_fn.is_present())
        {
            let member = PosFnMember::new(origin, member, on, config)?;
            output.push(Self::FinishFn(member));
        }

        let mut named_count = 0;

        for (member, config) in members {
            let RawMember { attrs, ident, ty } = member;

            if let Some(value) = config.skip {
                output.push(Self::Skip(SkipMember {
                    ident,
                    norm_ty: ty.norm,
                    value: value.value,
                }));
                continue;
            }

            let active_flag = |flag: darling::util::Flag| flag.is_present().then(|| flag.span());

            let incorrect_order = None
                .or_else(|| active_flag(config.start_fn))
                .or_else(|| Some(config.field.as_ref()?.key.span()))
                .or_else(|| active_flag(config.finish_fn));

            if let Some(span) = incorrect_order {
                bail!(
                    &span,
                    "incorrect members ordering; expected ordering:\n\
                    (1) members annotated with #[builder(start_fn)]\n\
                    (2) members annotated with #[builder(field)]\n\
                    (3) members annotated with #[builder(finish_fn)]\n\
                    (4) all other members in any order",
                );
            }

            // XXX: docs are collected only for named members. There is no obvious
            // place where to put the docs for positional and skipped members.
            //
            // Even if there are some docs on them and the function syntax is used
            // then these docs will just be removed from the output function.
            // It's probably fine since the doc comments are there in the code
            // itself which is also useful for people reading the source code.
            let docs = attrs
                .iter()
                .filter(|attr| attr.is_doc_expr())
                .cloned()
                .collect();

            let mut member = NamedMember {
                index: named_count.into(),
                origin,
                name: MemberName::new(ident, &config),
                ty,
                config,
                docs,
            };

            member.merge_on_config(on)?;
            member.validate()?;

            output.push(Self::Named(member));
            named_count += 1;
        }

        Ok(output)
    }
}

impl Member {
    pub(crate) fn norm_ty(&self) -> &syn::Type {
        match self {
            Self::StartFn(me) => &me.base.ty.norm,
            Self::Field(me) => &me.norm_ty,
            Self::FinishFn(me) => &me.ty.norm,
            Self::Named(me) => &me.ty.norm,
            Self::Skip(me) => &me.norm_ty,
        }
    }

    pub(crate) fn orig_ident(&self) -> &syn::Ident {
        match self {
            Self::StartFn(me) => &me.base.ident,
            Self::Field(me) => &me.ident,
            Self::FinishFn(me) => &me.ident,
            Self::Named(me) => &me.name.orig,
            Self::Skip(me) => &me.ident,
        }
    }

    pub(crate) fn as_named(&self) -> Option<&NamedMember> {
        match self {
            Self::Named(me) => Some(me),
            _ => None,
        }
    }

    pub(crate) fn as_field(&self) -> Option<&CustomField> {
        match self {
            Self::Field(me) => Some(me),
            _ => None,
        }
    }

    pub(crate) fn as_start_fn(&self) -> Option<&StartFnMember> {
        match self {
            Self::StartFn(me) => Some(me),
            _ => None,
        }
    }

    pub(crate) fn as_finish_fn(&self) -> Option<&PosFnMember> {
        match self {
            Self::FinishFn(me) => Some(me),
            _ => None,
        }
    }
}

impl PosFnMember {
    fn new(
        origin: MemberOrigin,
        member: RawMember<'_>,
        on: &[OnConfig],
        config: MemberConfig,
    ) -> Result<Self> {
        let RawMember {
            attrs: _,
            ident,
            ty,
        } = member;

        let mut me = Self {
            origin,
            ident,
            ty,
            config,
        };

        me.merge_config_into(on)?;

        Ok(me)
    }
}

impl CustomField {
    fn new(member: RawMember<'_>, init: Option<syn::Expr>) -> Result<Self> {
        if member.ident.to_string().starts_with("__") {
            bail!(
                &member.ident,
                "field names starting with `__` are reserved for `bon`'s internal use; \
                please, select a different name",
            );
        }

        Ok(Self {
            ident: member.ident,
            norm_ty: member.ty.norm,
            init,
        })
    }
}