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