Skip to main content

layline_codegen/model/
message.rs

1//! Variable-length messages.
2
3use alloc::string::String;
4use alloc::vec;
5use alloc::vec::Vec;
6
7use super::Derive;
8
9use super::{BitOrder, By, Coverage, Discriminant, Endian, Field, Kind, Len, Scalar, Stated};
10
11/// How many elements a collection has.
12#[derive(Debug, Clone, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum Count {
15    /// Read from an earlier integer field: `count = field * scale + offset`.
16    Field {
17        /// The count field.
18        by: By,
19        /// The largest count allowed.
20        cap: Option<usize>,
21    },
22    /// The square of an earlier field's value. Encode derives the field from the length.
23    Squared {
24        /// The field holding the square root.
25        by: By,
26        /// The largest count allowed, after squaring.
27        cap: Option<usize>,
28    },
29    /// A count from one field and each element's byte size from another.
30    ///
31    /// Decode reads each element from the start of its stride. A stride shorter than the element
32    /// is [`ParseError::Malformed`](layline_core::ParseError).
33    Strided {
34        /// The count field.
35        by: By,
36        /// The largest count allowed.
37        cap: Option<usize>,
38        /// The field holding each element's size in bytes.
39        stride: By,
40    },
41    /// As many elements as fit a byte length.
42    ///
43    /// The elements must fill it exactly, or decode returns
44    /// [`ParseError::Malformed`](layline_core::ParseError). With [`Len::Until`], one-byte
45    /// elements run up to a terminator, which is not included. [`Len::Fill`] is not allowed:
46    /// use [`Count::Fill`].
47    Window(Len),
48    /// Elements up to and including the first with a `mask` bit set, as in HDLC addresses.
49    ///
50    /// The element type declares that bit as a `prefix`, and encode sets it. Fields can follow.
51    Terminated {
52        /// The bits that mark the last element.
53        mask: u8,
54    },
55    /// As many elements as fill the rest of the body exactly.
56    Fill {
57        /// The largest count allowed.
58        cap: Option<usize>,
59    },
60}
61
62/// When an optional field is present.
63///
64/// Encode sets the presence from whether the field is `Some`.
65#[derive(Debug, Clone, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum Presence {
68    /// When `field & mask != 0`.
69    Mask {
70        /// The flags field.
71        field: String,
72        /// The bits that mark the field present.
73        mask: u64,
74    },
75    /// When the `bool` `field` is `true`.
76    Flag {
77        /// The `bool` field.
78        field: String,
79    },
80    /// When an unnamed bit just before the field is set. Bit-addressed messages only.
81    Bit,
82    /// When the body has bytes left. Must be the last field.
83    Remaining,
84}
85
86/// What makes an optional [`Placed`](Segment::Placed) record absent.
87#[derive(Debug, Clone, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum Absence {
90    /// An offset of zero, in the field [`Segment::Placed::at`].
91    ZeroOffset,
92    /// A length of zero.
93    ZeroLength {
94        /// The earlier field holding the length in bytes.
95        by: String,
96    },
97}
98
99/// The Rust type of a collection. The wire format is the same.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
101#[non_exhaustive]
102pub enum Collection {
103    /// `Vec<T>`.
104    #[default]
105    Vec,
106    /// `Box<[T]>`.
107    Boxed,
108}
109
110/// One part of a message.
111#[derive(Debug, Clone, PartialEq, Eq)]
112#[non_exhaustive]
113pub enum Segment {
114    /// Fixed-width fields.
115    Block(Vec<Field>),
116    /// A [`Kind::Var`], [`Kind::Msg`] or [`Kind::Text`] value, whose size is read from the wire.
117    Value {
118        /// The field name.
119        name: String,
120        /// Documentation.
121        doc: Option<String>,
122        /// The `#[at]` position. Only allowed before any variable-length segment.
123        stated: Option<Stated>,
124        /// The type.
125        kind: Kind,
126    },
127    /// A collection of elements.
128    Repeat {
129        /// The field name.
130        name: String,
131        /// Documentation.
132        doc: Option<String>,
133        /// The `#[at]` position. Only allowed before any variable-length segment.
134        stated: Option<Stated>,
135        /// The element type.
136        element: Kind,
137        /// How many elements there are.
138        count: Count,
139        /// The earlier field holding the byte offset of the elements. Encode writes it.
140        at: Option<String>,
141        /// The Rust type.
142        collection: Collection,
143    },
144    /// One record at a byte offset read from an earlier field.
145    ///
146    /// The offset counts from the start of the body, which inside a [`Kind::Msg`] is that message.
147    Placed {
148        /// The field name.
149        name: String,
150        /// Documentation.
151        doc: Option<String>,
152        /// The `#[at]` position. Only allowed before any variable-length segment.
153        stated: Option<Stated>,
154        /// The record: a [`Kind::Nested`] or a [`Kind::Msg`].
155        kind: Kind,
156        /// The earlier field holding the offset. Encode writes it.
157        at: String,
158        /// What makes the record absent, for an `Option<T>` field.
159        absent: Option<Absence>,
160    },
161    /// A field whose arm an earlier value selects.
162    ///
163    /// The arms and their values are in a [`ChoiceDef`](crate::ChoiceDef). Nothing can follow
164    /// a switch that has no [`window`](Segment::Switch::window) and whose choice is
165    /// [open-ended](crate::ChoiceDef::open_ended).
166    Switch {
167        /// The field name.
168        name: String,
169        /// Documentation.
170        doc: Option<String>,
171        /// The `#[at]` position. Only allowed before any variable-length segment.
172        stated: Option<Stated>,
173        /// What selects the arm.
174        on: Discriminant,
175        /// The [`ChoiceDef`](crate::ChoiceDef) type.
176        choice: String,
177        /// A fixed size for the switch, independent of the arm.
178        ///
179        /// `None` takes the arm's size. [`Len::Bytes`] makes a union, checked by
180        /// [`arms_fit`](layline_core::table::arms_fit). [`Len::Field`] reads the size from an
181        /// earlier field, and encode writes it. With a window, fields can follow the switch.
182        window: Option<Len>,
183    },
184    /// An optional field.
185    ///
186    /// Encode sets the masked bits and leaves the rest of the flags field alone. Other fields
187    /// cannot refer to an optional field.
188    Opt {
189        /// When the field is present.
190        when: Presence,
191        /// The field.
192        field: Field,
193    },
194    /// A checksum over bytes of the same body.
195    ///
196    /// Encode computes it once the covered bytes are written. Decode verifies it and returns an
197    /// error on mismatch.
198    Checksum {
199        /// The field name.
200        name: String,
201        /// Documentation.
202        doc: Option<String>,
203        /// The `#[at]` position. Only allowed before any variable-length segment.
204        stated: Option<Stated>,
205        /// The integer type.
206        repr: Scalar,
207        /// The path of the `layline::Checksum` algorithm.
208        algorithm: String,
209        /// The bytes it covers.
210        over: Coverage,
211    },
212}
213
214impl Segment {
215    /// A [`Segment::Block`].
216    #[must_use]
217    pub fn block(fields: Vec<Field>) -> Self {
218        Segment::Block(fields)
219    }
220
221    /// A [`Segment::Value`] with no documentation or `#[at]`.
222    #[must_use]
223    pub fn value(name: &str, kind: Kind) -> Self {
224        Segment::Value { name: String::from(name), doc: None, stated: None, kind }
225    }
226
227    /// A [`Segment::Repeat`].
228    ///
229    /// `at` names the offset field, or is `None` to read the elements in place.
230    #[must_use]
231    pub fn repeat(
232        name: &str,
233        element: Kind,
234        count: Count,
235        at: Option<&str>,
236        collection: Collection,
237    ) -> Self {
238        Segment::Repeat {
239            name: String::from(name),
240            doc: None,
241            stated: None,
242            element,
243            count,
244            at: at.map(String::from),
245            collection,
246        }
247    }
248
249    /// A [`Segment::Placed`] at the offset in field `at`. Optional when `absent` is set.
250    #[must_use]
251    pub fn placed(name: &str, kind: Kind, at: &str, absent: Option<Absence>) -> Self {
252        Segment::Placed {
253            name: String::from(name),
254            doc: None,
255            stated: None,
256            kind,
257            at: String::from(at),
258            absent,
259        }
260    }
261
262    /// A [`Segment::Switch`] on `on`, with arms from the choice type `choice`.
263    #[must_use]
264    pub fn switch(name: &str, on: Discriminant, choice: &str, window: Option<Len>) -> Self {
265        Segment::Switch {
266            name: String::from(name),
267            doc: None,
268            stated: None,
269            on,
270            choice: String::from(choice),
271            window,
272        }
273    }
274
275    /// A [`Segment::Opt`].
276    #[must_use]
277    pub fn opt(when: Presence, field: Field) -> Self {
278        Segment::Opt { when, field }
279    }
280
281    /// A [`Segment::Checksum`].
282    #[must_use]
283    pub fn checksum(name: &str, repr: Scalar, algorithm: &str, over: Coverage) -> Self {
284        Segment::Checksum {
285            name: String::from(name),
286            doc: None,
287            stated: None,
288            repr,
289            algorithm: String::from(algorithm),
290            over,
291        }
292    }
293
294    /// Sets the documentation. Does nothing on a [`Block`](Segment::Block).
295    #[must_use]
296    pub fn with_doc(mut self, text: &str) -> Self {
297        match &mut self {
298            Segment::Block(_) => {}
299            Segment::Opt { field, .. } => field.doc = Some(String::from(text)),
300            Segment::Value { doc, .. }
301            | Segment::Repeat { doc, .. }
302            | Segment::Placed { doc, .. }
303            | Segment::Switch { doc, .. }
304            | Segment::Checksum { doc, .. } => *doc = Some(String::from(text)),
305        }
306        self
307    }
308
309    /// Sets the `#[at]` position. Does nothing on a [`Block`](Segment::Block).
310    #[must_use]
311    pub fn with_stated(mut self, at: Stated) -> Self {
312        match &mut self {
313            Segment::Block(_) => {}
314            Segment::Opt { field, .. } => field.stated = Some(at),
315            Segment::Value { stated, .. }
316            | Segment::Repeat { stated, .. }
317            | Segment::Placed { stated, .. }
318            | Segment::Switch { stated, .. }
319            | Segment::Checksum { stated, .. } => *stated = Some(at),
320        }
321        self
322    }
323
324    /// The names of the fields this segment always writes, in wire order.
325    ///
326    /// Optional fields are not included.
327    #[must_use]
328    pub fn places(&self) -> Vec<&str> {
329        match self {
330            Segment::Block(fields) => fields.iter().map(|f| f.name.as_str()).collect(),
331            Segment::Value { name, .. }
332            | Segment::Repeat { name, .. }
333            | Segment::Switch { name, .. }
334            | Segment::Checksum { name, .. } => vec![name.as_str()],
335            Segment::Placed { name, absent: None, .. } => vec![name.as_str()],
336            Segment::Placed { absent: Some(_), .. } => Vec::new(),
337            Segment::Opt { .. } => Vec::new(),
338        }
339    }
340
341    /// The name of the field, if it is optional.
342    #[must_use]
343    pub fn placed_optionally(&self) -> Option<&str> {
344        match self {
345            Segment::Opt { field, .. } => Some(field.name.as_str()),
346            Segment::Placed { name, absent: Some(_), .. } => Some(name.as_str()),
347            _ => None,
348        }
349    }
350
351    /// The field name, or `None` for a [`Block`](Segment::Block).
352    #[must_use]
353    pub fn name(&self) -> Option<&str> {
354        match self {
355            Segment::Block(_) => None,
356            Segment::Opt { field, .. } => Some(&field.name),
357            Segment::Value { name, .. }
358            | Segment::Repeat { name, .. }
359            | Segment::Placed { name, .. }
360            | Segment::Switch { name, .. }
361            | Segment::Checksum { name, .. } => Some(name),
362        }
363    }
364
365    /// The `#[at]` position, if any.
366    #[must_use]
367    pub fn stated(&self) -> Option<Stated> {
368        match self {
369            Segment::Block(_) => None,
370            Segment::Opt { field, .. } => field.stated,
371            Segment::Value { stated, .. }
372            | Segment::Repeat { stated, .. }
373            | Segment::Placed { stated, .. }
374            | Segment::Switch { stated, .. }
375            | Segment::Checksum { stated, .. } => *stated,
376        }
377    }
378
379    /// The size in bits, or `None` if it depends on the wire.
380    #[must_use]
381    pub fn fixed_bits(&self) -> Option<u64> {
382        match self {
383            Segment::Block(fields) => fields.iter().map(|f| f.kind.bits()).sum(),
384            Segment::Checksum { repr, .. } => Some(repr.bits()),
385            Segment::Value { kind, .. } => kind.bits(),
386            Segment::Repeat { count, at, .. } => match (count, at) {
387                (Count::Window(Len::Bytes(n)), None) => Some(*n as u64 * 8),
388                _ => None,
389            },
390            Segment::Switch { window: Some(Len::Bytes(n)), .. } => Some(*n as u64 * 8),
391            Segment::Switch { .. } | Segment::Placed { .. } | Segment::Opt { .. } => None,
392        }
393    }
394
395    /// Whether this segment reads to the end of the body.
396    ///
397    /// Always `false` for a [`Switch`](Segment::Switch) or [`Kind::Msg`]. Generated code checks
398    /// those against the other type.
399    #[must_use]
400    pub fn open_ended(&self) -> bool {
401        match self {
402            Segment::Repeat { count, .. } => matches!(count, Count::Fill { .. }),
403            Segment::Value { kind, .. } | Segment::Opt { field: Field { kind, .. }, .. } => {
404                matches!(kind, Kind::Text { len: Len::Fill, .. })
405            }
406            Segment::Block(_)
407            | Segment::Checksum { .. }
408            | Segment::Switch { .. }
409            | Segment::Placed { .. } => false,
410        }
411    }
412}
413
414/// A read-only integer the enclosing message passes in.
415///
416/// Fields can refer to it like an earlier field. Encode never writes it.
417#[derive(Debug, Clone, PartialEq, Eq, Hash)]
418#[non_exhaustive]
419pub struct Param {
420    /// The name fields refer to.
421    pub name: String,
422    /// The integer type.
423    pub repr: Scalar,
424}
425
426impl Param {
427    /// A parameter.
428    #[must_use]
429    pub fn new(name: &str, repr: Scalar) -> Self {
430        Self { name: String::from(name), repr }
431    }
432}
433
434/// A variable-length message.
435#[derive(Debug, Clone, PartialEq, Eq)]
436#[non_exhaustive]
437pub struct MessageDef {
438    /// The type name.
439    pub name: String,
440    /// The byte order.
441    pub endian: Endian,
442    /// The bit order, or `None` for a byte-addressed message.
443    ///
444    /// A bit-addressed message holds bit fields and inline [presence bits](Presence::Bit),
445    /// padded with zeros to a whole byte.
446    pub bits: Option<BitOrder>,
447    /// The parameters, which generate a `<Name>Ctx` struct used as `Message::Ctx`.
448    pub needs: Vec<Param>,
449    /// The segments, in wire order.
450    pub segments: Vec<Segment>,
451    /// Documentation.
452    pub doc: Option<String>,
453    /// Derives for this message, written after the module's.
454    pub derives: Vec<Derive>,
455}
456
457impl MessageDef {
458    /// A little-endian, byte-addressed message.
459    #[must_use]
460    pub fn new(name: &str, segments: Vec<Segment>) -> Self {
461        Self {
462            name: String::from(name),
463            endian: Endian::Le,
464            bits: None,
465            needs: Vec::new(),
466            segments,
467            doc: None,
468            derives: Vec::new(),
469        }
470    }
471
472    /// Sets the documentation.
473    #[must_use]
474    pub fn with_doc(self, doc: &str) -> Self {
475        Self { doc: Some(String::from(doc)), ..self }
476    }
477
478    /// Sets the derives written on this message, after the module's.
479    #[must_use]
480    pub fn with_derives(self, derives: Vec<Derive>) -> Self {
481        Self { derives, ..self }
482    }
483
484    /// Sets the parameters.
485    #[must_use]
486    pub fn with_needs(self, needs: Vec<Param>) -> Self {
487        Self { needs, ..self }
488    }
489
490    /// Sets the byte order.
491    #[must_use]
492    pub fn with_endian(self, endian: Endian) -> Self {
493        Self { endian, ..self }
494    }
495
496    /// Makes the message bit-addressed, in this bit order.
497    #[must_use]
498    pub fn with_bits(self, order: BitOrder) -> Self {
499        Self { bits: Some(order), ..self }
500    }
501}
502
503/// Splits a reference at its first dot: `head.n` is `("head", Some("n"))`.
504pub fn split_ref(name: &str) -> (&str, Option<&str>) {
505    match name.split_once('.') {
506        Some((outer, inner)) => (outer, Some(inner)),
507        None => (name, None),
508    }
509}