strux 0.2.3

Tabular declaration of similar structs
Documentation
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::{parse::*, punctuated::Punctuated, *};
mod rollup;

/// Generate multiple structs which accumulate fields,
/// and optionally functions which convert between them.
///
/// ```
/// strux::rollup! {
///     struct Red {
///         apple: usize,
///     }
///
///     struct RedYellow {
///         banana: bool,
///         lemon: f32,
///     }
///
///     // generate a conversion function RedYellow -> RedYellowGreen
///     fn add_green();
///
///                                   // you can add attributes and
///     #[derive(Default, PartialEq)] // visibility everywhere you'd expect
///     pub struct RedYellowGreen {
///         lime: String = String::from("I'm a lime!"),
///                   // ^ you must specify how the conversion
///                   //   fills in this field.
///
///         pub avocado: Vec<u8> = vec![],
///     }
///
///     // the generated function can also be a method.
///     /// some docs
///     pub fn add_blue(self);
///
///     pub struct RedYellowGreenBlue {
///         /// some more docs
///         sky: String = String::from("I've got clouds"),
///     }
/// }
///
///
/// let red = Red { apple: 0 };
/// let red_yellow = RedYellow {
///     apple: 0,     // contains fields from the preceding struct
///     banana: true, // AND the ones specified
///     lemon: 0.0,
/// };
///
/// let red_yellow_green = add_green(red_yellow);
///
/// assert!(red_yellow_green == RedYellowGreen {
///     banana: true,
///     lime: String::from("I'm a lime!"),
///     ..Default::default()
/// } );
///
/// let red_yellow_green_blue = red_yellow_green.add_blue();
/// ```
///
/// You may also start the chain with a struct defined elsewhere:
///
/// ```
/// mod elsewhere {
///     #[derive(Default)]
///     pub struct Red {
///         pub apple: usize,
///         pub cherry: u8,
///         _ignored: (),
///     }
/// }
///
/// use elsewhere::Red;
///
/// strux::rollup! {
///     extern struct Red {
///         apple: usize,
///         cherry: u8,
///         ..
///     }
///
///     fn add_yellow(self);
///
///     #[derive(Debug, PartialEq)]
///     struct RedYellow {
///         banana: bool = true,
///     }
/// }
///
/// assert_eq!(Red::default().add_yellow(), RedYellow {
///     apple: 0,
///     cherry: 0,
///     banana: true,
/// });
/// ```
#[proc_macro]
pub fn rollup(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    parse_macro_input!(input with rollup::_rollup).into()
}

#[proc_macro]
pub fn strux(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    syn::parse_macro_input!(item with _strux).into()
}

fn _strux(input: ParseStream) -> syn::Result<TokenStream> {
    let (fwds, hdr, rows) = parse(input)?;
    for row in &rows {
        if row.cells.len() != hdr.cells.len() {
            let mut e = syn::Error::new(
                row.ident.span(),
                format!("{} columns in row", row.cells.len()),
            );
            e.combine(syn::Error::new(
                hdr.struct_token.span,
                format!("{} columns in header", hdr.cells.len()),
            ));
            return Err(e);
        }
    }
    let mut defns = vec![];
    for FwdDecl {
        attrs,
        vis,
        ident,
        fields,
    } in fwds
    {
        defns.push(Defn {
            attrs,
            vis,
            ident,
            fields: match fields {
                FwdFields::None(_) => vec![],
                FwdFields::Some { brace: _, fields } => fields
                    .into_iter()
                    .map(|field| {
                        let FwdField {
                            attrs,
                            vis,
                            ident,
                            kind,
                        } = field;
                        Ok(DefnField {
                            attrs,
                            vis,
                            ty: match kind {
                                FwdFieldKind::Unique { colon: _, ty } => ty,
                                FwdFieldKind::Shared => rows
                                    .iter()
                                    .find_map(|row| (row.ident == ident).then(|| row.ty.clone()))
                                    .ok_or_else(|| {
                                        syn::Error::new(ident.span(), "no type for shared field")
                                    })?,
                            },
                            ident,
                        })
                    })
                    .collect::<Result<_>>()?,
            },
        });
    }
    let Header {
        attrs,
        vis,
        struct_token: _,
        begin: _,
        cells: headings,
    } = &hdr;
    for defn in &mut defns {
        if matches!(defn.vis, Visibility::Inherited) {
            defn.vis.clone_from(vis);
        }
        prepend(&mut defn.attrs, attrs);
    }
    for (ident, _) in headings {
        if !defns.iter().any(|it| &it.ident == ident) {
            defns.push(Defn {
                attrs: attrs.clone(),
                vis: vis.clone(),
                ident: ident.clone(),
                fields: vec![],
            });
        }
    }

    for Row {
        attrs,
        padding: _,
        vis,
        ident,
        colon: _,
        ty,
        begin: _,
        cells,
    } in rows
    {
        for defn in &mut defns {
            let Some(ix) = headings
                .iter()
                .enumerate()
                .find_map(|(ix, (heading, _))| (heading == &defn.ident).then_some(ix))
            else {
                continue;
            };
            let is_selected = matches!(cells[ix], (Some(_), _));
            if !is_selected {
                continue;
            }

            match defn.fields.iter_mut().find(|it| it.ident == ident) {
                Some(field) => {
                    prepend(&mut field.attrs, &attrs);
                }
                None => defn.fields.push(DefnField {
                    attrs: attrs.clone(),
                    vis: vis.clone(),
                    ident: ident.clone(),
                    ty: ty.clone(),
                }),
            }
        }
    }

    Ok(quote!(#(#defns)*))
}

#[cfg_attr(test, derive(Debug))]
struct Defn {
    attrs: Vec<Attribute>,
    vis: Visibility,
    ident: Ident,
    fields: Vec<DefnField>,
}

impl ToTokens for Defn {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            attrs,
            vis,
            ident,
            fields,
        } = self;
        tokens.extend(quote! {
            #(#attrs)*
            #vis struct #ident {
                #(#fields,)*
            }
        });
    }
}

#[cfg_attr(test, derive(Debug))]
struct DefnField {
    attrs: Vec<Attribute>,
    vis: Visibility,
    ident: Ident,
    ty: Type,
}

impl ToTokens for DefnField {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            attrs,
            vis,
            ident,
            ty,
        } = self;
        tokens.extend(quote! {
            #(#attrs)*
            #vis #ident: #ty
        });
    }
}

fn parse(input: ParseStream<'_>) -> syn::Result<(Vec<FwdDecl>, Header, Vec<Row>)> {
    let mut fwd = vec![];
    let hdr = loop {
        let attrs = attrs(input)?;
        let vis = input.parse()?;
        let lo = input.lookahead1();
        if lo.peek(Ident) {
            let ident = input.parse::<Ident>()?;
            fwd.push(FwdDecl {
                attrs,
                vis,
                ident,
                fields: input.parse()?,
            });
        } else if lo.peek(Token![struct]) {
            break Header {
                attrs,
                vis,
                struct_token: input.parse::<Token![struct]>()?,
                begin: input.parse()?,
                cells: {
                    let mut cols = vec![];
                    while input.peek(Ident) && input.peek2(Token![|]) {
                        cols.push((input.parse::<Ident>()?, input.parse::<Token![|]>()?));
                    }
                    cols
                },
            };
        } else {
            return Err(lo.error());
        }
    };
    let mut rows = vec![];
    while !input.is_empty() {
        rows.push(Row {
            attrs: attrs(input)?,
            vis: input.parse()?,
            padding: {
                let mut padding = vec![];
                while input.peek(Token![.]) {
                    padding.push(input.parse::<Token![.]>()?);
                }
                padding
            },
            ident: input.parse()?,
            colon: input.parse()?,
            ty: input.parse()?,
            begin: input.parse()?,
            cells: {
                let mut cols = vec![];
                loop {
                    match input.parse()? {
                        x @ Some(_) => cols.push((x, input.parse::<Token![|]>()?)),
                        x @ None if input.peek(Token![|]) => cols.push((x, input.parse()?)),
                        _ => break,
                    }
                }
                cols
            },
        });
    }
    Ok((fwd, hdr, rows))
}

fn prepend<T: Clone>(dst: &mut Vec<T>, src: &[T]) {
    dst.splice(0..0, src.iter().cloned());
}

fn attrs(input: ParseStream<'_>) -> syn::Result<Vec<Attribute>> {
    Ok(match input.peek(Token![#]) {
        true => Attribute::parse_outer(input)?,
        false => vec![],
    })
}

#[cfg_attr(test, derive(Debug))]
struct FwdDecl {
    attrs: Vec<Attribute>,
    vis: Visibility,
    ident: Ident,
    fields: FwdFields,
}

#[cfg_attr(test, derive(Debug))]
enum FwdFields {
    #[expect(unused)]
    None(Token![;]),
    Some {
        #[expect(unused)]
        brace: token::Brace,
        fields: Punctuated<FwdField, Token![,]>,
    },
}

impl Parse for FwdFields {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lo = input.lookahead1();
        if lo.peek(Token![;]) {
            Ok(Self::None(input.parse::<Token![;]>()?))
        } else if lo.peek(token::Brace) {
            let content;
            Ok(Self::Some {
                brace: braced!(content in input),
                fields: Punctuated::parse_terminated(&content)?,
            })
        } else {
            Err(lo.error())
        }
    }
}

#[cfg_attr(test, derive(Debug))]
struct FwdField {
    attrs: Vec<Attribute>,
    vis: Visibility,
    ident: Ident,
    kind: FwdFieldKind,
}

#[cfg_attr(test, derive(Debug))]
#[allow(clippy::large_enum_variant)]
enum FwdFieldKind {
    Shared,
    Unique {
        #[expect(unused)]
        colon: Token![:],
        ty: Type,
    },
}

impl Parse for FwdField {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            attrs: attrs(input)?,
            vis: input.parse()?,
            ident: input.parse()?,
            kind: match input.parse()? {
                Some(colon) => FwdFieldKind::Unique {
                    colon,
                    ty: input.parse()?,
                },
                None => FwdFieldKind::Shared,
            },
        })
    }
}

#[cfg_attr(test, derive(Debug))]
struct Header {
    attrs: Vec<Attribute>,
    vis: Visibility,
    struct_token: Token![struct],
    #[expect(unused)]
    begin: Token![|],
    cells: Vec<(Ident, Token![|])>,
}

#[cfg_attr(test, derive(Debug))]
struct Row {
    attrs: Vec<Attribute>,
    #[expect(unused)]
    padding: Vec<Token![.]>,
    vis: Visibility,
    ident: Ident,
    #[expect(unused)]
    colon: Token![:],
    ty: Type,
    #[expect(unused)]
    begin: Token![|],
    cells: Vec<(Option<kw::X>, Token![|])>,
}

mod kw {
    syn::custom_keyword!(X);
}

#[cfg(test)]
mod tests {
    use expect_test::expect;

    use super::*;

    #[test]
    fn smoke() {
        let tokens = _strux
            .parse2(quote! {
                    /// Baz comment.
                    Baz {
                        /// Baz.s comment
                        s: &'static str,
                    }


                    /// Shared comment
                    struct     | Foo | Bar | Baz |
                    /// u comment
                    u: usize   |  X  |  X  |     |
                    s: String  |  X  |     |  X  |
                    v: Vec<u8> |     |  X  |     |
            })
            .unwrap();
        let s = prettyplease::unparse(&syn::parse2(tokens).unwrap());
        expect![[r#"
            /// Shared comment
            /// Baz comment.
            struct Baz {
                /// Baz.s comment
                s: &'static str,
            }
            /// Shared comment
            struct Foo {
                /// u comment
                u: usize,
                s: String,
            }
            /// Shared comment
            struct Bar {
                /// u comment
                u: usize,
                v: Vec<u8>,
            }
        "#]]
        .assert_eq(&s);
    }
}