layline-codegen 0.5.0

Rust source generation for layline.
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
use proc_macro2::{Literal, TokenStream};
use quote::quote;

#[cfg(feature = "emit")]
use super::derive_attr;
use super::tokens::ident;
use super::{doc_attr, emit_field, endian_arg, path};
use crate::Derive;
use crate::root::Prelude;
use crate::{BitOrder, Container, DispatchDef, EnumDef, Error, LayoutDef, Root, Scalar};

/// A [`LayoutDef`] as token parts, for a caller that writes its own struct line.
pub struct LayoutParts {
    /// `#[derive(layline::Layout)]` and its `#[layout(..)]` attribute.
    pub attrs: TokenStream,
    /// Field declarations in wire order, with docs, width attributes and `#[at]` positions.
    pub fields: TokenStream,
}

/// Converts a fixed layout to its derive attributes and field declarations.
///
/// Validates the layout first.
///
/// # Errors
///
/// [`Error::Invalid`], naming the layout, when [`validate`](crate::validate()) refuses it.
pub fn layout_parts(l: &LayoutDef, derives: &[Derive], root: &Root) -> Result<LayoutParts, Error> {
    crate::validate::validate_layout(l).map_err(|why| Error::Invalid(l.name.clone(), why))?;

    let c = &l.container;
    let key = ident(c.unit().keyword());
    let units = Literal::u64_unsuffixed(c.units());
    let endian = endian_arg(c.endian());
    let order = (c.order() == Some(BitOrder::Msb)).then(|| quote! { , order = msb });
    let (prefix, prefix_value) = match c {
        Container::Word { prefix: 0, .. } | Container::Bytes { .. } | Container::Words { .. } => {
            (None, None)
        }
        Container::Word { prefix, prefix_value, .. } => {
            let n = Literal::u64_unsuffixed(*prefix);
            let value = prefix_value.map(|v| {
                let width = *prefix as usize;
                let v: TokenStream = format!("0b{v:0width$b}").parse().expect("a binary literal");
                quote! { , prefix_value = #v }
            });
            (Some(quote! { , prefix = #n }), value)
        }
    };
    let view = l.view.then(|| quote! { , view });
    let truncate = l.truncate.then(|| quote! { , truncate });
    let crate_arg = root.crate_arg();
    let bit_addressed = c.is_bit_addressed();
    let skip = super::tokens::serde_skip(derives, &l.derives);
    let fields = l.fields.iter().map(|f| emit_field(f, bit_addressed, root, &skip));
    Ok(LayoutParts {
        attrs: quote! {
            #[derive(#root::Layout)]
            #[layout(#key = #units #prefix #prefix_value #view #truncate #endian #order #crate_arg)]
        },
        fields: quote! { #(#fields)* },
    })
}

/// Emits a fixed layout: [`layout_parts`] plus the struct line and derives.
///
/// # Errors
///
/// Whatever [`layout_parts`] refuses.
#[cfg(feature = "emit")]
pub(crate) fn emit_layout(
    l: &LayoutDef,
    derives: &[Derive],
    root: &Root,
) -> Result<TokenStream, Error> {
    let name = ident(&l.name);
    let der = derive_attr(derives, &l.derives)?;
    let doc = doc_attr(&l.doc);
    let LayoutParts { attrs, fields } = layout_parts(l, derives, root)?;
    Ok(quote! {
        #doc
        #der
        #attrs
        pub struct #name {
            #fields
        }
    })
}

/// An [`EnumDef`] as token parts.
pub struct EnumParts {
    /// Variant declarations in order, then the variant for unknown values if the enum is open.
    pub variants: TokenStream,
    /// `impl FieldCodec for Name`, total in both directions.
    pub codec: TokenStream,
    /// `impl Name { pub const fn code(self) -> Repr }`, the wire value in `const` contexts.
    pub code: TokenStream,
}

/// Converts an enum to its variants, codec and `const fn code`.
///
/// # Errors
///
/// [`Error::Invalid`], naming the enumeration, when [`validate`](crate::validate()) refuses it.
pub fn enum_parts(e: &EnumDef, root: &Root) -> Result<EnumParts, Error> {
    let Prelude { u32, u64, .. } = root.prelude();
    crate::validate::validate_enum(e).map_err(|why| Error::Invalid(e.name.clone(), why))?;
    let name = ident(&e.name);
    let repr = root.prelude().primitive(e.repr.primitive());
    let bits = Literal::u32_suffixed(match e.repr {
        Scalar::U(n) | Scalar::I(n) => n as u32,
        _ => 32,
    });

    let variants = e.variants.iter().map(|v| {
        let variant = ident(&v.name);
        let vdoc = doc_attr(&Some(v.doc.clone().unwrap_or_else(|| format!("{}.", v.value))));
        let default = (e.default.as_deref() == Some(v.name.as_str())).then(|| quote!(#[default]));
        quote! { #vdoc #default #variant, }
    });
    let other_ident = e.other.as_deref().map(ident);
    let other = other_ident.as_ref().map(|other| {
        let odoc = doc_attr(&Some(
            e.other_doc
                .clone()
                .unwrap_or_else(|| String::from("An undefined value, kept as its raw number.")),
        ));
        quote! { #odoc #other(#repr), }
    });

    let from_arms = e.variants.iter().map(|v| {
        let variant = ident(&v.name);
        let lit = Literal::i64_unsuffixed(v.value);
        quote! { #lit => Self::#variant, }
    });
    let from_fallback = match &other_ident {
        Some(other) => quote! { other => Self::#other(other), },
        None => {
            let first = ident(&e.variants[0].name);
            quote! { _ => Self::#first, }
        }
    };
    let to_arms = e.variants.iter().map(|v| {
        let variant = ident(&v.name);
        let lit = Literal::i64_unsuffixed(v.value);
        quote! { Self::#variant => #lit, }
    });
    let to_fallback = other_ident.as_ref().map(|other| quote! { Self::#other(raw) => *raw, });

    let code_arms = e.variants.iter().map(|v| {
        let variant = ident(&v.name);
        let lit = Literal::i64_unsuffixed(v.value);
        quote! { Self::#variant => #lit, }
    });
    let code_fallback = other_ident.as_ref().map(|other| quote! { Self::#other(raw) => raw, });

    Ok(EnumParts {
        variants: quote! {
            #(#variants)*
            #other
        },
        codec: quote! {
            impl #root::FieldCodec for #name {
                const BITS: #u32 = #bits;
                fn from_raw(raw: #u64) -> Self {
                    match raw as #repr {
                        #(#from_arms)*
                        #from_fallback
                    }
                }
                fn to_raw(&self) -> #u64 {
                    (match self {
                        #(#to_arms)*
                        #to_fallback
                    }) as #u64
                }
            }
        },
        code: quote! {
            impl #name {
                /// The wire value, usable in `const` contexts.
                #[must_use]
                pub const fn code(self) -> #repr {
                    match self {
                        #(#code_arms)*
                        #code_fallback
                    }
                }
            }
        },
    })
}

/// Emits an enum: [`enum_parts`] plus the enum line, docs and derives.
///
/// Leaves out [`EnumParts::code`].
///
/// # Errors
///
/// Whatever [`enum_parts`] refuses.
#[cfg(feature = "emit")]
pub(crate) fn emit_enum(
    e: &EnumDef,
    derives: &[Derive],
    root: &Root,
) -> Result<TokenStream, Error> {
    let name = ident(&e.name);
    default_agrees(e, derives)?;
    let der = derive_attr(derives, &e.derives)?;
    let doc = doc_attr(&e.doc);
    let EnumParts { variants, codec, .. } = enum_parts(e, root)?;
    Ok(quote! {
        #doc
        #der
        pub enum #name {
            #variants
        }

        #codec
    })
}

/// Refuses an enumeration whose `#[default]` variant and `Default` derive disagree.
///
/// A `cfg`-gated `Default` does not count: with the predicate off, `#[default]` has no derive to
/// belong to and the generated code does not compile.
#[cfg(feature = "emit")]
fn default_agrees(e: &EnumDef, module: &[Derive]) -> Result<(), Error> {
    let derived = module
        .iter()
        .chain(&e.derives)
        .any(|d| d.cfg.is_none() && d.path.rsplit("::").next() == Some("Default"));
    let invalid = |why: alloc::string::String| {
        Err(Error::Invalid(e.name.clone(), crate::Invalid::Other(why)))
    };
    match (&e.default, derived) {
        (Some(variant), false) => invalid(format!(
            "`{variant}` is the default variant, and nothing derives `Default`. \
             Add an ungated `Default` to the derives"
        )),
        (None, true) => invalid(alloc::string::String::from(
            "`Default` is derived and no variant is the default. \
             Mark one with `EnumDef::with_default`",
        )),
        _ => Ok(()),
    }
}

/// A [`DispatchDef`] as token parts, for a caller that writes its own enum line.
pub struct DispatchParts {
    /// The variants, each with `#[value(N)]` or `#[other]`.
    pub arms: TokenStream,
    /// The container attributes, including the derive.
    pub attrs: TokenStream,
}

/// Converts a dispatch catalogue to its variants and attributes.
///
/// `#[derive(Dispatch)]` writes the decoder.
///
/// # Errors
///
/// [`Error::Invalid`], naming the catalogue, when [`validate`](crate::validate()) refuses it.
pub fn dispatch_parts(d: &DispatchDef, root: &Root) -> Result<DispatchParts, Error> {
    let Prelude { vec, u8, .. } = root.prelude();
    crate::validate::validate_dispatch(d).map_err(|why| Error::Invalid(d.name.clone(), why))?;
    let crate_arg = root.crate_arg();
    let id_ty = root.prelude().primitive(d.id.primitive());
    let arms = d.arms.iter().map(|a| {
        let doc = doc_attr(&a.doc);
        let variant = ident(&a.name);
        let ty = path(&a.ty);
        let id = Literal::i64_unsuffixed(a.id);
        quote! { #doc #[value(#id)] #variant(#ty), }
    });
    let other = ident(&d.other);
    let body = match &d.other_body {
        Some(ty) => {
            let ty = path(ty);
            quote!(#ty)
        }
        None => quote!(#vec<#u8>),
    };
    let prefix = (d.prefix > 0).then(|| {
        let k = Literal::u32_unsuffixed(d.prefix);
        quote! { , prefix = #k }
    });
    let other_doc = doc_attr(&Some(
        d.other_doc.clone().unwrap_or_else(|| String::from("An unknown id, kept with its body.")),
    ));
    Ok(DispatchParts {
        arms: quote! {
            #(#arms)*
            #other_doc
            #[other]
            #other { id: #id_ty, body: #body },
        },
        attrs: quote! {
            #[derive(#root::Dispatch)]
            #[dispatch(id = #id_ty #prefix #crate_arg)]
        },
    })
}

/// Emits a dispatch catalogue with its derives.
///
/// # Errors
///
/// Whatever [`dispatch_parts`] refuses.
#[cfg(feature = "emit")]
pub(crate) fn emit_dispatch(
    d: &DispatchDef,
    derives: &[Derive],
    root: &Root,
) -> Result<TokenStream, Error> {
    let name = ident(&d.name);
    let der = derive_attr(derives, &d.derives)?;
    let doc = doc_attr(&d.doc);
    let DispatchParts { arms, attrs } = dispatch_parts(d, root)?;
    Ok(quote! {
        #doc
        #der
        #attrs
        pub enum #name {
            #arms
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "emit")]
    use crate::Variant;
    use crate::{Container, Endian, Field, Kind};

    #[test]
    fn layout_parts_refuses_a_container_its_fields_do_not_tile() {
        let short = LayoutDef::new(
            "Header",
            Container::Bytes { bytes: 8, endian: Endian::Le },
            vec![Field::new("magic", Kind::Scalar(Scalar::U(32)))],
        );
        let Err(Error::Invalid(name, crate::Invalid::Tiling { covered_bits, declared_bits })) =
            layout_parts(&short, &[], &Root::default())
        else {
            panic!("32 bits do not fill 64: the model is invalid, and validation names it");
        };
        assert_eq!((name.as_str(), covered_bits, declared_bits), ("Header", 32, 64));
    }

    #[test]
    #[cfg(feature = "emit")]
    fn the_parts_carry_nothing_the_caller_owns() {
        let l = LayoutDef::new(
            "Entry",
            Container::Bytes { bytes: 4, endian: Endian::Le },
            vec![Field::new("value", Kind::Scalar(Scalar::U(32)))],
        );
        let parts = layout_parts(&l, &[], &Root::default()).expect("it tiles");
        let attrs = parts.attrs.to_string();
        let fields = parts.fields.to_string();
        assert!(attrs.contains("layline :: Layout") && attrs.contains("bytes = 4"), "{attrs}");
        for owned in ["struct", "Entry", "Debug", "Clone"] {
            assert!(!attrs.contains(owned), "the attributes have no {owned}: {attrs}");
            assert!(!fields.contains(owned), "the fields carry no {owned}: {fields}");
        }
        assert_eq!(fields, "pub value : u32 ,");

        let whole = emit_layout(&l, &["serde::Serialize".into()], &Root::default())
            .expect("it tiles")
            .to_string();
        assert!(whole.contains("Debug , Clone , PartialEq , serde :: Serialize"), "{whole}");
        assert!(whole.contains(&attrs) && whole.contains(&fields), "{whole}");
    }

    #[test]
    fn enum_parts_refuses_a_closed_catalogue_with_no_variants() {
        let e = EnumDef::new("Mode", Scalar::U(8), vec![]);
        let Err(Error::Invalid(name, why)) = enum_parts(&e, &Root::default()) else {
            panic!("a closed catalogue with no variants has no total decode");
        };
        assert_eq!(name, "Mode");
        assert!(format!("{why}").contains("not total"), "{why}");
        assert!(enum_parts(&e.with_other("Other"), &Root::default()).is_ok());
    }

    #[test]
    #[cfg(feature = "emit")]
    fn the_const_discriminant_is_published_and_not_attached() {
        let e = EnumDef::new(
            "Mode",
            Scalar::U(8),
            vec![Variant::new(0, "Idle"), Variant::new(7, "Active")],
        )
        .with_other("Other");
        let parts = enum_parts(&e, &Root::default()).expect("a catalogue");
        let code = parts.code.to_string();
        assert!(code.contains("pub const fn code (self) -> :: core :: primitive :: u8"), "{code}");
        assert!(code.contains("Self :: Active => 7"), "{code}");
        assert!(code.contains("Self :: Other (raw) => raw"), "{code}");
        assert!(parts.codec.to_string().contains("Self :: Other (raw) => * raw"));

        let whole = emit_enum(&e, &[], &Root::default()).expect("a catalogue").to_string();
        assert!(!whole.contains("fn code"), "a whole-item emission is unchanged by it:\n{whole}");
        assert!(whole.contains(&parts.codec.to_string()), "{whole}");
    }

    #[test]
    fn a_layout_with_a_view_emits_the_key() {
        let mut l = LayoutDef::new(
            "Head",
            Container::Bytes { bytes: 2, endian: Endian::Le },
            vec![Field::new("n", Kind::Scalar(Scalar::U(16)))],
        );
        let without = layout_parts(&l, &[], &Root::default()).expect("lowers").attrs.to_string();
        assert!(!without.contains("view"), "{without}");
        l.view = true;
        let with = layout_parts(&l, &[], &Root::default()).expect("lowers").attrs.to_string();
        assert!(with.contains("# [layout (bytes = 2 , view)]"), "{with}");
    }

    #[test]
    fn a_truncating_layout_emits_the_key() {
        let l = LayoutDef::new(
            "Reg",
            Container::word(16, Endian::Le, crate::BitOrder::Lsb),
            vec![Field::new("n", Kind::Scalar(Scalar::U(16)))],
        )
        .with_view()
        .with_truncate();
        let attrs = layout_parts(&l, &[], &Root::default()).expect("lowers").attrs.to_string();
        assert!(attrs.contains("# [layout (bits = 16 , view , truncate)]"), "{attrs}");
    }
}