Skip to main content

layline_codegen/
emit.rs

1//! Formatted Rust source generated from the [model](crate).
2//!
3//! [`Module::new`] uses [`Spelling::Bare`]: `Vec<Entry>`, `u32`, `Ok(..)`. Runtime paths stay
4//! qualified. A module with a message, choice or dispatch imports `Box`, `String` and `Vec`
5//! from `::layline::__private`, so it builds under `no_std` with `alloc`.
6
7mod committed;
8mod graph;
9mod verbatim;
10
11use std::fmt::Write as _;
12
13use proc_macro2::TokenStream;
14use quote::quote;
15
16pub use committed::{Change, Committed, Drift, Drifted};
17
18use crate::walk::{emit_choice, emit_dispatch, emit_enum, emit_layout, emit_message};
19use crate::{Error, Invalid, Item, Root, Spelling};
20
21/// A module to generate.
22#[derive(Debug, Clone)]
23#[non_exhaustive]
24pub struct Module {
25    /// Module doc lines, without `//!`, written after the `// @generated` marker.
26    ///
27    /// ```no_run
28    /// # use layline_codegen::emit::Module;
29    /// const COMMAND: &str = "cargo codegen";
30    /// Module::new(vec![]).with_doc(vec![
31    ///     "The block catalogue.".into(),
32    ///     String::new(),
33    ///     format!("Regenerate with `{COMMAND}`. Edit `codegen/src/spec.rs`."),
34    ///     String::new(),
35    ///     "Source: reference manual, revision 4, 2025-10-09.".into(),
36    /// ]);
37    /// ```
38    pub doc: Vec<String>,
39    /// `use` lines, each written as `use <line>;`.
40    pub uses: Vec<String>,
41    /// Extra derives for every struct and enum, after `Debug, Clone, PartialEq`.
42    pub derives: Vec<String>,
43    /// The items, in output order.
44    pub items: Vec<Item>,
45    /// The runtime path and prelude spelling.
46    pub root: Root,
47}
48
49impl Module {
50    /// A module of `items`, with root `::layline` in [`Spelling::Bare`] and nothing else set.
51    #[must_use]
52    pub fn new(items: Vec<Item>) -> Self {
53        Self {
54            doc: Vec::new(),
55            uses: Vec::new(),
56            derives: Vec::new(),
57            items,
58            root: Root::new(syn::parse_quote!(::layline), Spelling::Bare),
59        }
60    }
61
62    /// Sets [`root`](Self::root).
63    #[must_use]
64    pub fn with_root(self, root: Root) -> Self {
65        Self { root, ..self }
66    }
67
68    /// Sets [`doc`](Self::doc).
69    #[must_use]
70    pub fn with_doc(self, doc: Vec<String>) -> Self {
71        Self { doc, ..self }
72    }
73
74    /// Sets [`uses`](Self::uses).
75    #[must_use]
76    pub fn with_uses(self, uses: Vec<String>) -> Self {
77        Self { uses, ..self }
78    }
79
80    /// Sets [`derives`](Self::derives).
81    #[must_use]
82    pub fn with_derives(self, derives: Vec<String>) -> Self {
83        Self { derives, ..self }
84    }
85}
86
87/// A generated module and its audit artifact.
88#[derive(Debug, Clone, PartialEq, Eq)]
89#[non_exhaustive]
90pub struct Generated {
91    /// The formatted Rust source.
92    pub source: String,
93    /// The field tables, one record per line, in `layline_core::audit`'s format.
94    ///
95    /// Empty when the module has only enums and verbatim items.
96    pub audit: String,
97}
98
99/// Generates a module's source and audit artifact.
100///
101/// ```
102/// use layline_codegen::emit::{Module, generate};
103/// use layline_codegen::{Container, Endian, Field, Item, Kind, LayoutDef, Scalar};
104///
105/// let head = LayoutDef::new(
106///     "Head",
107///     Container::Bytes { bytes: 2, endian: Endian::Be },
108///     vec![Field::new("len", Kind::Scalar(Scalar::U(16)))],
109/// );
110/// let out = generate(&Module::new(vec![Item::Layout(head)])).unwrap();
111/// assert!(out.source.contains("pub struct Head"));
112/// assert!(out.audit.starts_with("L Head"));
113/// ```
114///
115/// # Errors
116///
117/// [`Error::Invalid`] when an item fails validation, or a `use` line or derive does not parse.
118/// [`Error::Refused`] when valid items do not work together, such as an endless recursion.
119/// [`Error::Internal`] when the generated source does not parse.
120pub fn generate(module: &Module) -> Result<Generated, Error> {
121    let mut audit = String::new();
122    let source = emit_source(module, &mut audit)?;
123    Ok(Generated { source, audit })
124}
125
126fn emit_source(module: &Module, audit: &mut String) -> Result<String, Error> {
127    let root = &module.root;
128    let mut tokens = TokenStream::new();
129
130    // `use` lines bypass the pretty-printer, so parse them here.
131    for u in &module.uses {
132        syn::parse_str::<syn::ItemUse>(&format!("use {u};")).map_err(|_| {
133            Error::Invalid(
134                String::from("uses"),
135                Invalid::Other(format!(
136                    "`{u}` is not a valid `use` path. \
137                     Write one path per entry, such as `crate::wire::Head`"
138                )),
139            )
140        })?;
141    }
142
143    if module.items.iter().any(|i| matches!(i, Item::Message(_) | Item::Choice(_))) {
144        tokens.extend(quote! {
145            /// The error a message decode returns.
146            #[allow(unused_imports)]
147            pub use #root::ParseError;
148        });
149    }
150    if module
151        .items
152        .iter()
153        .any(|i| matches!(i, Item::Message(_) | Item::Choice(_) | Item::Dispatch(_)))
154    {
155        tokens.extend(quote! {
156            #[allow(unused_imports)]
157            use #root::__private::{Box, String, Vec};
158        });
159    }
160
161    graph::recursion(module)?;
162    let cycles = graph::open_end_cycles(module)?;
163    let cyclic = |name: &str| {
164        cycles.iter().find(|(n, _)| n == name).map_or(&[][..], |(_, members)| members.as_slice())
165    };
166
167    let derives = &module.derives;
168    for item in &module.items {
169        tokens.extend(match item {
170            Item::Enum(e) => emit_enum(e, derives, root)?,
171            Item::Layout(l) => {
172                let code = emit_layout(l, derives, root)?;
173                audit.push_str(&crate::audit::layout(l));
174                code
175            }
176            Item::Dispatch(d) => emit_dispatch(d, derives, root)?,
177            Item::Choice(c) => {
178                let (code, arms) = emit_choice(c, derives, root, cyclic(&c.name))?;
179                audit.push_str(&crate::audit::choice(&c.name, &arms));
180                code
181            }
182            Item::Message(m) => {
183                graph::terminal_switches(module, m)?;
184                let (code, rows) = emit_message(m, derives, root, cyclic(&m.name))?;
185                audit.push_str(&crate::audit::message(&m.name, &m.needs, &rows));
186                code
187            }
188            Item::Verbatim(verbatim) => {
189                verbatim::refuse_codec(verbatim)?;
190                verbatim.clone()
191            }
192        });
193    }
194
195    let body = crate::source::render(tokens)?;
196
197    let mut out = String::new();
198    let _ = writeln!(out, "// @generated by layline-codegen — do not edit.");
199    for line in &module.doc {
200        let _ = writeln!(out, "//! {line}");
201    }
202    let _ = writeln!(out);
203    for u in &module.uses {
204        let _ = writeln!(out, "use {u};");
205    }
206    if !module.uses.is_empty() {
207        let _ = writeln!(out);
208    }
209    out.push_str(&body);
210    Ok(out)
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216    use crate::walk::message_parts;
217    use crate::{
218        Arm, By, ChoiceDef, Collection, Count, CoverTo, Coverage, Discriminant, Endian, Field,
219        Kind, MessageDef, Presence, Scalar, Segment,
220    };
221
222    fn emit_module(module: &Module) -> Result<String, Error> {
223        generate(module).map(|g| g.source)
224    }
225
226    #[test]
227    fn a_switch_may_discriminate_on_body_length() {
228        let module = Module {
229            items: vec![
230                Item::Choice(ChoiceDef {
231                    name: "VelocityForm".into(),
232                    endian: Endian::Le,
233                    arms: vec![
234                        Arm::new(
235                            16,
236                            "F32",
237                            vec![Segment::Block(vec![
238                                Field::new("velocity", Kind::array(Scalar::F32, 3)),
239                                Field::new("sigma", Kind::Scalar(Scalar::F32)),
240                            ])],
241                        ),
242                        Arm::new(
243                            24,
244                            "F64",
245                            vec![Segment::Block(vec![Field::new(
246                                "velocity",
247                                Kind::array(Scalar::F64, 3),
248                            )])],
249                        ),
250                    ],
251                    other: None,
252                    other_bytes: None,
253                    doc: None,
254                }),
255                Item::Message(MessageDef {
256                    name: "VelocityReport".into(),
257                    endian: Endian::Le,
258                    bits: None,
259                    needs: Vec::new(),
260                    segments: vec![Segment::Switch {
261                        stated: None,
262                        name: "form".into(),
263                        on: Discriminant::BodyLength,
264                        choice: "VelocityForm".into(),
265                        window: None,
266                        doc: None,
267                    }],
268                }),
269            ],
270            ..Module::new(Vec::new())
271        };
272        let out = emit_module(&module).expect("specification emits");
273        assert!(
274            out.contains("((__body.len() - __at) as i64)"),
275            "the discriminant is the body the switch can see:\n{out}"
276        );
277        assert!(out.contains("<VelocityForm as ::layline::Choice>::decode_with_nested"), "{out}");
278        assert!(out.contains("fn decode_with_nested("), "{out}");
279        assert!(out.contains(r#"field: "VelocityForm""#), "{out}");
280    }
281
282    #[test]
283    fn a_checksum_may_live_inside_one_arm_of_a_choice() {
284        let module = Module {
285            items: vec![Item::Choice(ChoiceDef {
286                name: "Body".into(),
287                endian: Endian::Le,
288                arms: vec![
289                    Arm::new(
290                        0,
291                        "Bare",
292                        vec![Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))])],
293                    ),
294                    Arm::new(
295                        1,
296                        "Checked",
297                        vec![
298                            Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))]),
299                            Segment::Checksum {
300                                stated: None,
301                                name: "crc".into(),
302                                repr: Scalar::U(16),
303                                algorithm: "::wire::Crc16Ccitt".into(),
304                                over: Coverage::whole(),
305                                doc: None,
306                            },
307                        ],
308                    ),
309                    Arm::new(
310                        2,
311                        "Excised",
312                        vec![
313                            Segment::Checksum {
314                                stated: None,
315                                name: "sum".into(),
316                                repr: Scalar::U(16),
317                                algorithm: "::wire::Sum16NegLe".into(),
318                                over: Coverage::whole().to(CoverTo::After("tail".into())),
319                                doc: None,
320                            },
321                            Segment::Repeat {
322                                stated: None,
323                                collection: Collection::Vec,
324                                name: "tail".into(),
325                                doc: None,
326                                element: Kind::Scalar(Scalar::U(8)),
327                                count: Count::Fill { cap: None },
328                                at: None,
329                            },
330                        ],
331                    ),
332                ],
333                other: None,
334                other_bytes: None,
335                doc: None,
336            })],
337            ..Module::new(Vec::new())
338        };
339        let out = emit_module(&module).expect("specification emits");
340        assert!(out.contains("__BodyCk0"), "the arm gets its own one-field layout:\n{out}");
341        assert!(
342            out.contains("&out.written()[__base..]") && out.contains(".get(0..__ck_to)"),
343            "the arm's range starts at the arm's own first byte:\n{out}"
344        );
345        assert!(out.contains("ParseError::Checksum"), "{out}");
346
347        assert!(
348            out.contains("Checksum>::init()") && out.contains("Checksum>::finish("),
349            "an excludes_self range is the fold:\n{out}"
350        );
351        assert!(out.contains("__BodyCk1 { sum: 0 }"), "the reserved bytes:\n{out}");
352        assert!(
353            out.contains("out.written_mut()[__out_sum..__out_sum + 2]"),
354            "…stamped once the range has landed:\n{out}"
355        );
356        assert!(
357            out.contains("const COVERED: &'static [::layline::table::ArmCover<'static>]"),
358            "the checksum column, per arm:\n{out}"
359        );
360        let covered: Vec<&str> =
361            out.split("ArmCover::new(").skip(1).filter_map(|s| s.split('"').nth(1)).collect();
362        assert_eq!(covered, ["Checked", "Excised"], "an arm with no checksum has no row:\n{out}");
363        assert!(out.contains("            true,\n"), "the hole is its own bytes:\n{out}");
364    }
365
366    #[test]
367    fn a_checksum_refuses_a_range_it_cannot_resolve() {
368        let msg = |over: Coverage| MessageDef {
369            name: "Packet".into(),
370            endian: Endian::Le,
371            bits: None,
372            needs: Vec::new(),
373            segments: vec![
374                Segment::Block(vec![Field::new("magic", Kind::Scalar(Scalar::U(16)))]),
375                Segment::Checksum {
376                    stated: None,
377                    name: "crc".into(),
378                    repr: Scalar::U(16),
379                    algorithm: "::wire::Crc16Ccitt".into(),
380                    over,
381                    doc: None,
382                },
383            ],
384        };
385        assert!(matches!(
386            message_parts(&msg(Coverage::from_field("nope")), &Root::default()),
387            Err(Error::Invalid(..)),
388        ));
389        assert!(message_parts(&msg(Coverage::from_field("magic")), &Root::default()).is_ok());
390        assert!(message_parts(&msg(Coverage::whole()), &Root::default()).is_ok());
391    }
392
393    #[test]
394    fn a_checksum_field_may_not_also_be_a_count() {
395        let out = message_parts(
396            &MessageDef {
397                name: "Packet".into(),
398                endian: Endian::Le,
399                bits: None,
400                needs: Vec::new(),
401                segments: vec![
402                    Segment::Checksum {
403                        stated: None,
404                        name: "crc".into(),
405                        repr: Scalar::U(16),
406                        algorithm: "::wire::Crc16Ccitt".into(),
407                        over: Coverage::whole(),
408                        doc: None,
409                    },
410                    Segment::Repeat {
411                        stated: None,
412                        collection: Collection::Vec,
413                        name: "items".into(),
414                        element: Kind::Scalar(Scalar::U(8)),
415                        count: Count::Field { by: By::field("crc"), cap: None },
416                        at: None,
417                        doc: None,
418                    },
419                ],
420            },
421            &Root::default(),
422        );
423        let Err(err) = out else {
424            panic!("a doubly-derived field must be refused");
425        };
426        let why = err.to_string();
427        assert!(why.contains("crc"), "{why}");
428    }
429
430    #[test]
431    fn a_bool_presence_flag_governs_exactly_one_field() {
432        let opt = |name: &str, kind| Segment::Opt {
433            when: Presence::Flag { field: "head.on".into() },
434            field: Field::new(name, kind),
435        };
436        let msg = |extra: Segment| MessageDef {
437            name: "Packet".into(),
438            endian: Endian::Le,
439            bits: None,
440            needs: Vec::new(),
441            segments: vec![
442                Segment::Block(vec![Field::new(
443                    "head",
444                    Kind::Nested { ty: "Head".into(), bytes: 1 },
445                )]),
446                opt("a", Kind::Scalar(Scalar::U(8))),
447                extra,
448            ],
449        };
450
451        let out = message_parts(&msg(opt("b", Kind::Scalar(Scalar::U(8)))), &Root::default());
452        let Err(Error::Refused(why)) = out else {
453            panic!("two presence writes over one `bool` must be refused");
454        };
455        assert!(why.contains("is the whole of `a`'s presence flag"), "{why}");
456
457        let out = message_parts(
458            &msg(Segment::Repeat {
459                stated: None,
460                collection: Collection::Vec,
461                name: "items".into(),
462                element: Kind::Scalar(Scalar::U(8)),
463                count: Count::Field { by: By::field("head.on"), cap: None },
464                at: None,
465                doc: None,
466            }),
467            &Root::default(),
468        );
469        assert!(matches!(out, Err(Error::Refused(_))), "a count over a presence flag");
470    }
471
472    #[test]
473    fn a_field_may_not_follow_an_open_ended_switch() {
474        let module = Module {
475            items: vec![
476                Item::Choice(ChoiceDef {
477                    name: "Body".into(),
478                    endian: Endian::Le,
479                    arms: vec![Arm::new(
480                        0,
481                        "Ping",
482                        vec![Segment::Block(vec![Field::new("seq", Kind::Scalar(Scalar::U(16)))])],
483                    )],
484                    other: Some("Unknown".into()),
485                    other_bytes: None,
486                    doc: None,
487                }),
488                Item::Message(MessageDef {
489                    name: "Packet".into(),
490                    endian: Endian::Le,
491                    bits: None,
492                    needs: Vec::new(),
493                    segments: vec![
494                        Segment::Block(vec![Field::new("kind", Kind::Scalar(Scalar::U(8)))]),
495                        Segment::Switch {
496                            stated: None,
497                            name: "body".into(),
498                            on: Discriminant::Field("kind".into()),
499                            choice: "Body".into(),
500                            window: None,
501                            doc: None,
502                        },
503                        Segment::Block(vec![Field::new("trailer", Kind::Scalar(Scalar::U(8)))]),
504                    ],
505                }),
506            ],
507            ..Module::new(Vec::new())
508        };
509        assert!(matches!(emit_module(&module), Err(Error::Invalid(_, Invalid::AfterOpenEnd(_)))));
510    }
511}