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 `field & mask == 0`: the bits mark the field absent, as a "use the default" flag does.
81 ///
82 /// Encode clears the bits for `Some` and sets them for `None`.
83 MaskClear {
84 /// The flags field.
85 field: String,
86 /// The bits that mark the field absent.
87 mask: u64,
88 },
89 /// When the `bool` `field` is `false`. Encode writes `false` for `Some` and `true` for `None`.
90 FlagClear {
91 /// The `bool` field.
92 field: String,
93 },
94 /// When an unnamed bit just before the field is set. Bit-addressed messages only.
95 Bit,
96 /// When the body has bytes left. Must be the last field.
97 Remaining,
98}
99
100impl Presence {
101 /// For a test of an earlier field: its name, the bits tested, and whether set bits mean
102 /// present. A `bool` is its single bit.
103 pub(crate) fn tests(&self) -> Option<(&str, u64, bool)> {
104 match self {
105 Presence::Mask { field, mask } => Some((field, *mask, true)),
106 Presence::MaskClear { field, mask } => Some((field, *mask, false)),
107 Presence::Flag { field } => Some((field, 1, true)),
108 Presence::FlagClear { field } => Some((field, 1, false)),
109 Presence::Bit | Presence::Remaining => None,
110 }
111 }
112
113 /// Whether the test reads a `bool`, rather than bits of an integer.
114 pub(crate) fn reads_flag(&self) -> bool {
115 matches!(self, Presence::Flag { .. } | Presence::FlagClear { .. })
116 }
117}
118
119/// What makes an optional [`Placed`](Segment::Placed) record absent.
120#[derive(Debug, Clone, PartialEq, Eq)]
121#[non_exhaustive]
122pub enum Absence {
123 /// An offset of zero, in the field [`Segment::Placed::at`].
124 ZeroOffset,
125 /// A length of zero.
126 ZeroLength {
127 /// The earlier field holding the length in bytes.
128 by: String,
129 /// Padding that is not part of the length: `#[align(N)]`.
130 ///
131 /// The record lies in the stated length rounded up to a multiple of `N` bytes. It may end
132 /// anywhere from the stated length to that bound, since a record that states its own size
133 /// can count the padding, as an SDAT block does. Encode writes the record's length and
134 /// then zeros up to the bound.
135 align: Option<u64>,
136 },
137}
138
139/// The Rust type of a collection. The wire format is the same.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
141#[non_exhaustive]
142pub enum Collection {
143 /// `Vec<T>`.
144 #[default]
145 Vec,
146 /// `Box<[T]>`.
147 Boxed,
148 /// `&'a [u8]`, borrowed from the bytes the message decodes from. Needs a
149 /// [`lifetime`](MessageDef::lifetime), and `u8` elements counted by a field, a byte length or
150 /// the rest of the body.
151 Borrowed,
152 /// `&'a [u8; N]`, borrowed as [`Borrowed`](Self::Borrowed) is. Needs
153 /// [`Count::Window`] of [`Len::Bytes`]`(N)`.
154 BorrowedArray,
155}
156
157impl Collection {
158 /// Whether the collection borrows from the input.
159 #[must_use]
160 pub fn borrows(self) -> bool {
161 matches!(self, Collection::Borrowed | Collection::BorrowedArray)
162 }
163}
164
165/// One part of a message.
166#[derive(Debug, Clone, PartialEq, Eq)]
167#[non_exhaustive]
168pub enum Segment {
169 /// Fixed-width fields.
170 Block(Vec<Field>),
171 /// A [`Kind::Var`], [`Kind::Msg`] or [`Kind::Text`] value, whose size is read from the wire.
172 Value {
173 /// The field name.
174 name: String,
175 /// Documentation.
176 doc: Option<String>,
177 /// The `#[at]` position. Only allowed before any variable-length segment.
178 stated: Option<Stated>,
179 /// The type.
180 kind: Kind,
181 },
182 /// A collection of elements.
183 Repeat {
184 /// The field name.
185 name: String,
186 /// Documentation.
187 doc: Option<String>,
188 /// The `#[at]` position. Only allowed before any variable-length segment.
189 stated: Option<Stated>,
190 /// The element type.
191 element: Kind,
192 /// How many elements there are.
193 count: Count,
194 /// The earlier field holding the byte offset of the elements. Encode writes it.
195 at: Option<String>,
196 /// The Rust type.
197 collection: Collection,
198 },
199 /// One record at a byte offset read from an earlier field.
200 ///
201 /// The offset counts from the start of the body, which inside a [`Kind::Msg`] is that message.
202 Placed {
203 /// The field name.
204 name: String,
205 /// Documentation.
206 doc: Option<String>,
207 /// The `#[at]` position. Only allowed before any variable-length segment.
208 stated: Option<Stated>,
209 /// The record: a [`Kind::Nested`] or a [`Kind::Msg`].
210 kind: Kind,
211 /// The earlier field holding the offset. Encode writes it.
212 at: String,
213 /// What makes the record absent, for an `Option<T>` field.
214 absent: Option<Absence>,
215 },
216 /// A field whose arm an earlier value selects.
217 ///
218 /// The arms and their values are in a [`ChoiceDef`](crate::ChoiceDef). Nothing can follow
219 /// a switch that has no [`window`](Segment::Switch::window) and whose choice is
220 /// [open-ended](crate::ChoiceDef::open_ended).
221 Switch {
222 /// The field name.
223 name: String,
224 /// Documentation.
225 doc: Option<String>,
226 /// The `#[at]` position. Only allowed before any variable-length segment.
227 stated: Option<Stated>,
228 /// What selects the arm.
229 on: Discriminant,
230 /// The [`ChoiceDef`](crate::ChoiceDef) type.
231 choice: String,
232 /// A fixed size for the switch, independent of the arm.
233 ///
234 /// `None` takes the arm's size. [`Len::Bytes`] makes a union, checked by
235 /// [`arms_fit`](layline_core::table::arms_fit). [`Len::Field`] reads the size from an
236 /// earlier field, and encode writes it. With a window, fields can follow the switch.
237 window: Option<Len>,
238 },
239 /// An optional field.
240 ///
241 /// Encode sets the masked bits and leaves the rest of the flags field alone. Other fields
242 /// cannot refer to an optional field.
243 Opt {
244 /// When the field is present.
245 when: Presence,
246 /// The field.
247 field: Field,
248 },
249 /// A checksum over bytes of the same body.
250 ///
251 /// Encode computes it once the covered bytes are written. Decode verifies it and returns an
252 /// error on mismatch.
253 Checksum {
254 /// The field name.
255 name: String,
256 /// Documentation.
257 doc: Option<String>,
258 /// The `#[at]` position. Only allowed before any variable-length segment.
259 stated: Option<Stated>,
260 /// The integer type.
261 repr: Scalar,
262 /// The path of the `layline::Checksum` algorithm.
263 algorithm: String,
264 /// The bytes it covers.
265 over: Coverage,
266 },
267}
268
269impl Segment {
270 /// A [`Segment::Block`].
271 #[must_use]
272 pub fn block(fields: Vec<Field>) -> Self {
273 Segment::Block(fields)
274 }
275
276 /// A [`Segment::Value`] with no documentation or `#[at]`.
277 #[must_use]
278 pub fn value(name: &str, kind: Kind) -> Self {
279 Segment::Value { name: String::from(name), doc: None, stated: None, kind }
280 }
281
282 /// A [`Segment::Repeat`].
283 ///
284 /// `at` names the offset field, or is `None` to read the elements in place.
285 #[must_use]
286 pub fn repeat(
287 name: &str,
288 element: Kind,
289 count: Count,
290 at: Option<&str>,
291 collection: Collection,
292 ) -> Self {
293 Segment::Repeat {
294 name: String::from(name),
295 doc: None,
296 stated: None,
297 element,
298 count,
299 at: at.map(String::from),
300 collection,
301 }
302 }
303
304 /// A [`Segment::Placed`] at the offset in field `at`. Optional when `absent` is set.
305 #[must_use]
306 pub fn placed(name: &str, kind: Kind, at: &str, absent: Option<Absence>) -> Self {
307 Segment::Placed {
308 name: String::from(name),
309 doc: None,
310 stated: None,
311 kind,
312 at: String::from(at),
313 absent,
314 }
315 }
316
317 /// A [`Segment::Switch`] on `on`, with arms from the choice type `choice`.
318 #[must_use]
319 pub fn switch(name: &str, on: Discriminant, choice: &str, window: Option<Len>) -> Self {
320 Segment::Switch {
321 name: String::from(name),
322 doc: None,
323 stated: None,
324 on,
325 choice: String::from(choice),
326 window,
327 }
328 }
329
330 /// A [`Segment::Opt`].
331 #[must_use]
332 pub fn opt(when: Presence, field: Field) -> Self {
333 Segment::Opt { when, field }
334 }
335
336 /// A [`Segment::Checksum`].
337 #[must_use]
338 pub fn checksum(name: &str, repr: Scalar, algorithm: &str, over: Coverage) -> Self {
339 Segment::Checksum {
340 name: String::from(name),
341 doc: None,
342 stated: None,
343 repr,
344 algorithm: String::from(algorithm),
345 over,
346 }
347 }
348
349 /// Sets the documentation. Does nothing on a [`Block`](Segment::Block).
350 #[must_use]
351 pub fn with_doc(mut self, text: &str) -> Self {
352 match &mut self {
353 Segment::Block(_) => {}
354 Segment::Opt { field, .. } => field.doc = Some(String::from(text)),
355 Segment::Value { doc, .. }
356 | Segment::Repeat { doc, .. }
357 | Segment::Placed { doc, .. }
358 | Segment::Switch { doc, .. }
359 | Segment::Checksum { doc, .. } => *doc = Some(String::from(text)),
360 }
361 self
362 }
363
364 /// Sets the `#[at]` position. Does nothing on a [`Block`](Segment::Block).
365 #[must_use]
366 pub fn with_stated(mut self, at: Stated) -> Self {
367 match &mut self {
368 Segment::Block(_) => {}
369 Segment::Opt { field, .. } => field.stated = Some(at),
370 Segment::Value { stated, .. }
371 | Segment::Repeat { stated, .. }
372 | Segment::Placed { stated, .. }
373 | Segment::Switch { stated, .. }
374 | Segment::Checksum { stated, .. } => *stated = Some(at),
375 }
376 self
377 }
378
379 /// The names of the fields this segment always writes, in wire order.
380 ///
381 /// Optional fields are not included.
382 #[must_use]
383 pub fn places(&self) -> Vec<&str> {
384 match self {
385 Segment::Block(fields) => fields.iter().map(|f| f.name.as_str()).collect(),
386 Segment::Value { name, .. }
387 | Segment::Repeat { name, .. }
388 | Segment::Switch { name, .. }
389 | Segment::Checksum { name, .. } => vec![name.as_str()],
390 Segment::Placed { name, absent: None, .. } => vec![name.as_str()],
391 Segment::Placed { absent: Some(_), .. } => Vec::new(),
392 Segment::Opt { .. } => Vec::new(),
393 }
394 }
395
396 /// The `#[align(N)]` of the length that sizes this segment, if any.
397 #[must_use]
398 pub fn align(&self) -> Option<u64> {
399 match self {
400 Segment::Repeat { count: Count::Window(Len::Field { align, .. }), .. }
401 | Segment::Value { kind: Kind::Text { len: Len::Field { align, .. }, .. }, .. }
402 | Segment::Switch { window: Some(Len::Field { align, .. }), .. }
403 | Segment::Placed { absent: Some(Absence::ZeroLength { align, .. }), .. } => *align,
404 _ => None,
405 }
406 }
407
408 /// The name of the field, if it is optional.
409 #[must_use]
410 pub fn placed_optionally(&self) -> Option<&str> {
411 match self {
412 Segment::Opt { field, .. } => Some(field.name.as_str()),
413 Segment::Placed { name, absent: Some(_), .. } => Some(name.as_str()),
414 _ => None,
415 }
416 }
417
418 /// The field name, or `None` for a [`Block`](Segment::Block).
419 #[must_use]
420 pub fn name(&self) -> Option<&str> {
421 match self {
422 Segment::Block(_) => None,
423 Segment::Opt { field, .. } => Some(&field.name),
424 Segment::Value { name, .. }
425 | Segment::Repeat { name, .. }
426 | Segment::Placed { name, .. }
427 | Segment::Switch { name, .. }
428 | Segment::Checksum { name, .. } => Some(name),
429 }
430 }
431
432 /// The `#[at]` position, if any.
433 #[must_use]
434 pub fn stated(&self) -> Option<Stated> {
435 match self {
436 Segment::Block(_) => None,
437 Segment::Opt { field, .. } => field.stated,
438 Segment::Value { stated, .. }
439 | Segment::Repeat { stated, .. }
440 | Segment::Placed { stated, .. }
441 | Segment::Switch { stated, .. }
442 | Segment::Checksum { stated, .. } => *stated,
443 }
444 }
445
446 /// The size in bits, or `None` if it depends on the wire.
447 #[must_use]
448 pub fn fixed_bits(&self) -> Option<u64> {
449 match self {
450 Segment::Block(fields) => fields.iter().map(|f| f.kind.bits()).sum(),
451 Segment::Checksum { repr, .. } => Some(repr.bits()),
452 Segment::Value { kind, .. } => kind.bits(),
453 Segment::Repeat { count, at, .. } => match (count, at) {
454 (Count::Window(Len::Bytes(n)), None) => Some(*n as u64 * 8),
455 _ => None,
456 },
457 Segment::Switch { window: Some(Len::Bytes(n)), .. } => Some(*n as u64 * 8),
458 Segment::Switch { .. } | Segment::Placed { .. } | Segment::Opt { .. } => None,
459 }
460 }
461
462 /// Whether this segment reads to the end of the body.
463 ///
464 /// Always `false` for a [`Switch`](Segment::Switch) or [`Kind::Msg`]. Generated code checks
465 /// those against the other type.
466 #[must_use]
467 pub fn open_ended(&self) -> bool {
468 match self {
469 Segment::Repeat { count, .. } => matches!(count, Count::Fill { .. }),
470 Segment::Value { kind, .. } | Segment::Opt { field: Field { kind, .. }, .. } => {
471 matches!(kind, Kind::Text { len: Len::Fill, .. })
472 }
473 Segment::Block(_)
474 | Segment::Checksum { .. }
475 | Segment::Switch { .. }
476 | Segment::Placed { .. } => false,
477 }
478 }
479}
480
481/// A read-only integer the enclosing message passes in.
482///
483/// Fields can refer to it like an earlier field. Encode never writes it.
484#[derive(Debug, Clone, PartialEq, Eq, Hash)]
485#[non_exhaustive]
486pub struct Param {
487 /// The name fields refer to.
488 pub name: String,
489 /// The integer type.
490 pub repr: Scalar,
491}
492
493impl Param {
494 /// A parameter.
495 #[must_use]
496 pub fn new(name: &str, repr: Scalar) -> Self {
497 Self { name: String::from(name), repr }
498 }
499}
500
501/// A variable-length message.
502#[derive(Debug, Clone, PartialEq, Eq)]
503#[non_exhaustive]
504pub struct MessageDef {
505 /// The type name.
506 pub name: String,
507 /// The byte order.
508 pub endian: Endian,
509 /// The bit order, or `None` for a byte-addressed message.
510 ///
511 /// A bit-addressed message holds bit fields and inline [presence bits](Presence::Bit),
512 /// padded with zeros to a whole byte.
513 pub bits: Option<BitOrder>,
514 /// The parameters, which generate a `<Name>Ctx` struct used as `Message::Ctx`.
515 pub needs: Vec<Param>,
516 /// The segments, in wire order.
517 pub segments: Vec<Segment>,
518 /// Documentation.
519 pub doc: Option<String>,
520 /// Derives for this message, written after the module's.
521 pub derives: Vec<Derive>,
522 /// The lifetime of [borrowed](Collection::Borrowed) fields, without the `'`: `Some("a")`
523 /// declares `Name<'a>`.
524 ///
525 /// The message implements `layline::MessageRef<'a>` instead of `layline::Message`, so it
526 /// takes no [`needs`](Self::needs) and no other message can hold it.
527 pub lifetime: Option<String>,
528}
529
530impl MessageDef {
531 /// A little-endian, byte-addressed message.
532 #[must_use]
533 pub fn new(name: &str, segments: Vec<Segment>) -> Self {
534 Self {
535 name: String::from(name),
536 endian: Endian::Le,
537 bits: None,
538 needs: Vec::new(),
539 segments,
540 doc: None,
541 derives: Vec::new(),
542 lifetime: None,
543 }
544 }
545
546 /// Declares `Name<'lifetime>`, whose borrowed fields hold views of the input.
547 #[must_use]
548 pub fn with_lifetime(self, lifetime: &str) -> Self {
549 Self { lifetime: Some(String::from(lifetime)), ..self }
550 }
551
552 /// Sets the documentation.
553 #[must_use]
554 pub fn with_doc(self, doc: &str) -> Self {
555 Self { doc: Some(String::from(doc)), ..self }
556 }
557
558 /// Sets the derives written on this message, after the module's.
559 #[must_use]
560 pub fn with_derives(self, derives: Vec<Derive>) -> Self {
561 Self { derives, ..self }
562 }
563
564 /// Sets the parameters.
565 #[must_use]
566 pub fn with_needs(self, needs: Vec<Param>) -> Self {
567 Self { needs, ..self }
568 }
569
570 /// Sets the byte order.
571 #[must_use]
572 pub fn with_endian(self, endian: Endian) -> Self {
573 Self { endian, ..self }
574 }
575
576 /// Makes the message bit-addressed, in this bit order.
577 #[must_use]
578 pub fn with_bits(self, order: BitOrder) -> Self {
579 Self { bits: Some(order), ..self }
580 }
581}
582
583/// Splits a reference at its first dot: `head.n` is `("head", Some("n"))`.
584pub fn split_ref(name: &str) -> (&str, Option<&str>) {
585 match name.split_once('.') {
586 Some((outer, inner)) => (outer, Some(inner)),
587 None => (name, None),
588 }
589}