cuisiner_derive 0.0.4

Derive macros to support cuisiner
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
use proc_macro2::Span;
use syn::{Attribute, Error, Expr, ExprLit, Generics, Ident, Lit, Meta, Visibility};

use crate::{Ast, Fields};

/// Analyse the struct, and produce a model for future usage.
pub fn analyse(ast: Ast) -> Result<DeriveModel, Error> {
    // Parse the attributes to pull out the config.
    let config = DeriveConfig::try_from(ast.attrs())?;

    Ok(match ast {
        Ast::Struct(item_struct) => DeriveModel {
            name: item_struct.ident.clone(),
            visibility: item_struct.vis,
            item: DeriveModelItem::Struct {
                fields: Fields::try_from(&item_struct.fields)?,
                assert_size: config.assert_size,
                generics: item_struct.generics,
            },
        },
        Ast::Enum(item_enum) => DeriveModel {
            name: item_enum.ident.clone(),
            visibility: item_enum.vis,
            item: DeriveModelItem::Enum {
                repr: config.repr.ok_or(Error::new(
                    Span::call_site(),
                    "'repr = ...' attribute is missing",
                ))?,
                variants: item_enum
                    .variants
                    .into_iter()
                    .map(|variant| {
                        if !matches!(variant.fields, syn::Fields::Unit) {
                            return Err(Error::new_spanned(
                                variant.fields,
                                "enum variants must be unit",
                            ));
                        }

                        let value = variant
                            .discriminant
                            .as_ref()
                            // Extract the literal
                            .and_then(|(_, discriminant)| {
                                if let Expr::Lit(ExprLit { lit, .. }) = discriminant {
                                    Some(lit)
                                } else {
                                    None
                                }
                            })
                            .ok_or_else(|| Error::new_spanned(&variant, "discriminant required"))
                            // Parse the literal
                            .and_then(|lit| match lit {
                                Lit::Int(value) => value.base10_parse().map_err(|_| {
                                    Error::new_spanned(value, "cannot parse discriminant")
                                }),
                                Lit::Byte(value) => Ok(value.value() as usize),
                                _ => Err(Error::new_spanned(
                                    lit,
                                    "only int or byte literal discriminants are supported",
                                )),
                            })?;

                        Ok((variant.ident, value))
                    })
                    .collect::<Result<_, _>>()?,
            },
        },
    })
}

/// All information required to be pulled from the AST to implement the derive macro.
#[derive(Clone)]
pub struct DeriveModel {
    /// Original name of the struct.
    pub name: Ident,
    /// Visibility of the original struct.
    pub visibility: Visibility,
    /// Additional information specific to the variant of model.
    pub item: DeriveModelItem,
}

#[derive(Clone)]
pub enum DeriveModelItem {
    Struct {
        /// Collection of fields present in the original struct.
        fields: Fields,
        /// Expected size of struct for assertion.
        assert_size: Option<Expr>,
        /// Generics present on the original struct.
        generics: Generics,
    },
    Enum {
        /// All variants and their discriminant values.
        variants: Vec<(Ident, usize)>,
        /// Internal enum representation.
        repr: Repr,
    },
}

/// Configuration provided via attributes.
#[derive(Clone, Default)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
struct DeriveConfig {
    repr: Option<Repr>,
    assert_size: Option<Expr>,
}

impl TryFrom<&[Attribute]> for DeriveConfig {
    type Error = Error;

    fn try_from(attrs: &[Attribute]) -> Result<Self, Self::Error> {
        // Search for relevant attributes.
        let mut attrs = attrs.iter().filter(|attr| attr.path().is_ident("cuisiner"));

        let mut config = Self::default();

        let Some(attr) = attrs.next() else {
            // No attributes provided.
            return Ok(config);
        };

        // Make sure only one attribute is provided.
        if attrs.next().is_some() {
            return Err(Error::new(
                Span::call_site(),
                "only a single `cuisiner` attribute is supported",
            ));
        }

        match &attr.meta {
            // Accept attibute with no arguments, although it's useless.
            Meta::Path(_) => {}
            // Parse out arguments from list.
            Meta::List(_) => attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("repr") {
                    config.repr = Some(Repr::try_from(
                        meta.value()?.parse::<Ident>()?.to_string().as_str(),
                    )?);

                    return Ok(());
                }

                if meta.path.is_ident("assert_size") {
                    config.assert_size = Some(meta.value()?.parse()?);

                    return Ok(());
                }

                Err(Error::new_spanned(meta.path, "unknown attribute argument"))
            })?,
            // Reject all other formats
            _ => {
                return Err(Error::new_spanned(
                    attr,
                    "attribute must be in list format (eg `#[cuisiner(argument)]`)",
                ));
            }
        }

        Ok(config)
    }
}

#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
pub enum Repr {
    U8,
    U16,
    U32,
    U64,
    U128,
    Usize,
    I8,
    I16,
    I32,
    I64,
    I128,
    Isize,
}

impl TryFrom<&str> for Repr {
    type Error = Error;

    fn try_from(repr: &str) -> Result<Self, Self::Error> {
        match repr {
            "u8" => Ok(Self::U8),
            "u16" => Ok(Self::U16),
            "u32" => Ok(Self::U32),
            "u64" => Ok(Self::U64),
            "u128" => Ok(Self::U128),
            "usize" => Ok(Self::Usize),
            "i8" => Ok(Self::I8),
            "i16" => Ok(Self::I16),
            "i32" => Ok(Self::I32),
            "i64" => Ok(Self::I64),
            "i128" => Ok(Self::I128),
            "isize" => Ok(Self::Isize),
            repr => Err(Error::new(
                Span::call_site(),
                format!("unknown repr: {repr}"),
            )),
        }
    }
}

#[cfg(test)]
mod test {
    use syn::parse_quote;

    use super::*;

    fn test_analyse_struct(
        ast: Ast,
        expected_name: impl AsRef<str>,
        expected_field_count: Option<usize>,
        expected_assert_size: Option<Expr>,
    ) {
        let model = analyse(ast).unwrap();

        let DeriveModelItem::Struct {
            fields,
            assert_size,
            generics: _,
        } = &model.item
        else {
            panic!("expected struct derive model item");
        };

        assert_eq!(model.name, expected_name.as_ref());
        assert_eq!(
            match fields {
                Fields::Named(fields) => Some(fields.len()),
                Fields::Unnamed(fields) => Some(fields.len()),
                Fields::Unit => None,
            },
            expected_field_count
        );
        assert_eq!(assert_size, &expected_assert_size);
    }

    fn test_analyse_enum(ast: Ast, expected_repr: Repr, expected_variants: &[(Ident, usize)]) {
        let model = analyse(ast).unwrap();
        let DeriveModelItem::Enum { variants, repr } = model.item else {
            panic!("expected enum derive model item");
        };

        assert_eq!(repr, expected_repr);
        assert_eq!(variants, expected_variants);
    }

    #[test]
    fn analyse_valid_unit_struct() {
        test_analyse_struct(
            Ast::Struct(parse_quote! {
                struct MyStruct;
            }),
            "MyStruct",
            None,
            None,
        );
    }

    #[test]
    fn analyse_valid_tuple_struct() {
        test_analyse_struct(
            Ast::Struct(parse_quote! {
                struct MyStruct(u32);
            }),
            "MyStruct",
            Some(1),
            None,
        );
    }

    #[test]
    fn analyse_valid_struct() {
        test_analyse_struct(
            Ast::Struct(parse_quote! {
                struct MyStruct {
                    a: u32,
                    b: bool,
                }
            }),
            "MyStruct",
            Some(2),
            None,
        );
    }

    #[test]
    fn analyse_valid_struct_with_size_assert() {
        test_analyse_struct(
            Ast::Struct(parse_quote! {
                #[cuisiner(assert_size = 5)]
                struct MyStruct {
                    a: u32,
                    b: bool,
                }
            }),
            "MyStruct",
            Some(2),
            Some(parse_quote!(5)),
        );
    }

    #[test]
    fn invalid_attribute() {
        assert!(
            analyse(Ast::Struct(parse_quote! {
                #[cuisiner(some_attribute)]
                struct MyStruct {
                    a: u32,
                }
            }))
            .is_err()
        );
    }

    #[test]
    fn analyse_valid_enum() {
        test_analyse_enum(
            Ast::Enum(parse_quote! {
                #[cuisiner(repr = u32)]
                enum MyEnum {
                    First = 1,
                    Second = 2,
                    Third = 3,
                }
            }),
            Repr::U32,
            &[
                (parse_quote!(First), 1),
                (parse_quote!(Second), 2),
                (parse_quote!(Third), 3),
            ],
        );
    }

    #[test]
    fn enum_missing_repr() {
        assert!(
            analyse(Ast::Enum(parse_quote! {
                enum MyEnum {
                    First = 1,
                    Second = 2,
                    Third = 3,
                }
            }))
            .is_err()
        );
    }

    #[test]
    fn enum_missing_discriminant() {
        assert!(
            analyse(Ast::Enum(parse_quote! {
                #[cuisiner(repr = u32)]
                enum MyEnum {
                    First,
                    Second,
                    Third,
                }
            }))
            .is_err()
        );
    }

    #[test]
    fn enum_some_discriminants() {
        assert!(
            analyse(Ast::Enum(parse_quote! {
                #[cuisiner(repr = u32)]
                enum MyEnum {
                    First = 1,
                    Second,
                    Third,
                }
            }))
            .is_err()
        );
    }

    mod derive_config {
        use syn::parse_quote;

        use super::*;

        #[test]
        fn from_empty_attributes() {
            assert_eq!(
                DeriveConfig::try_from([].as_slice()).unwrap(),
                DeriveConfig {
                    repr: None,
                    assert_size: None
                }
            );
        }

        #[test]
        fn single_attribute_path() {
            assert_eq!(
                DeriveConfig::try_from([parse_quote!(#[cuisiner])].as_slice()).unwrap(),
                DeriveConfig {
                    repr: None,
                    assert_size: None
                }
            );
        }

        #[test]
        fn single_attribute_empty_list() {
            assert_eq!(
                DeriveConfig::try_from([parse_quote!(#[cuisiner()])].as_slice()).unwrap(),
                DeriveConfig {
                    repr: None,
                    assert_size: None
                }
            );
        }

        #[test]
        fn with_repr() {
            assert_eq!(
                DeriveConfig::try_from([parse_quote!(#[cuisiner(repr = i64)])].as_slice()).unwrap(),
                DeriveConfig {
                    repr: Some(Repr::I64),
                    assert_size: None
                }
            )
        }

        #[test]
        fn extra_attributes() {
            assert_eq!(
                DeriveConfig::try_from(
                    [parse_quote!(#[repr(C)]), parse_quote!(#[some = attribute])].as_slice()
                )
                .unwrap(),
                DeriveConfig {
                    repr: None,
                    assert_size: None
                }
            );
        }

        #[test]
        fn multiple_attributes() {
            assert!(
                DeriveConfig::try_from(
                    [
                        parse_quote!(#[cuisiner]),
                        parse_quote!(#[cuisiner(another_attribute)]),
                    ]
                    .as_slice()
                )
                .is_err()
            );
        }

        #[test]
        fn unknown_attribute_argument() {
            assert!(
                DeriveConfig::try_from([parse_quote!(#[cuisiner(another_attribute)]),].as_slice())
                    .is_err()
            );
        }
    }
}