Skip to main content

layline_codegen/model/
layout.rs

1//! Fixed layouts and their containers.
2
3use alloc::format;
4use alloc::string::String;
5use alloc::vec::Vec;
6
7use super::Derive;
8
9use layline_core::table::StatedUnit;
10
11use super::{Field, Kind, Scalar, Stated};
12use crate::Invalid;
13
14/// Byte order. Little-endian by default.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
16pub enum Endian {
17    /// Little-endian.
18    #[default]
19    Le,
20    /// Big-endian.
21    Be,
22}
23
24/// Bit order within a bit-addressed container.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum BitOrder {
27    /// The first field takes the least significant bits.
28    Lsb,
29    /// The first field takes the most significant bits.
30    Msb,
31}
32
33/// How a layout addresses its fields.
34#[derive(Debug, Clone, PartialEq, Eq, Hash)]
35#[non_exhaustive]
36pub enum Container {
37    /// Word mode: bit fields in one container of whole bytes.
38    ///
39    /// The container can be any size, but a field is at most 64 bits.
40    Word {
41        /// The size in bits, a positive multiple of 8.
42        bits: u64,
43        /// Leading bits the enclosing dispatch reads, which this layout's fields do not cover.
44        ///
45        /// Encode writes zeros there unless [`prefix_value`](Container::Word::prefix_value) is
46        /// set.
47        prefix: u64,
48        /// The prefix's value. Encode writes it and decode refuses any other.
49        prefix_value: Option<u128>,
50        /// The byte order.
51        endian: Endian,
52        /// The bit order.
53        order: BitOrder,
54    },
55    /// Byte mode: byte-aligned scalars.
56    Bytes {
57        /// The size in bytes.
58        bytes: usize,
59        /// The byte order.
60        endian: Endian,
61    },
62    /// Words mode: bit fields in a sequence of 16-bit words.
63    Words {
64        /// The number of words.
65        words: usize,
66        /// Each word's byte order.
67        endian: Endian,
68        /// The bit order within each word.
69        order: BitOrder,
70    },
71}
72
73/// A size unit, and its attribute keyword.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[non_exhaustive]
76pub enum Unit {
77    /// `#[layout(bits = N)]`, `#[bits(N)]`.
78    Bits,
79    /// `#[layout(bytes = N)]`, `#[bytes(N)]`.
80    Bytes,
81    /// `#[layout(words = N)]`.
82    Words,
83}
84
85impl Unit {
86    /// The attribute keyword.
87    #[must_use]
88    pub fn keyword(self) -> &'static str {
89        match self {
90            Unit::Bits => "bits",
91            Unit::Bytes => "bytes",
92            Unit::Words => "words",
93        }
94    }
95}
96
97impl Container {
98    /// A [`Container::Word`] with no prefix.
99    #[must_use]
100    pub fn word(bits: u64, endian: Endian, order: BitOrder) -> Self {
101        Container::Word { bits, prefix: 0, prefix_value: None, endian, order }
102    }
103
104    /// Checks that this container allows a field of `kind`.
105    ///
106    /// # Errors
107    ///
108    /// [`Invalid::Field`] naming the field.
109    pub fn admits(&self, name: &str, kind: &Kind) -> Result<(), Invalid> {
110        let no = |what: &str| Err(Invalid::field(name, String::from(what)));
111
112        if let Kind::Array(_, dims) = kind
113            && dims.is_empty()
114        {
115            return no("an array with no dimensions. Give it a length, or declare a scalar");
116        }
117
118        match self {
119            Container::Bytes { .. } => match kind {
120                Kind::Scalar(Scalar::Bool) => {
121                    no("byte mode stores a `bool` in a whole byte. Declare it `Scalar::ByteBool`, \
122                     or declare the record in word mode")
123                }
124                Kind::Text { .. } => {
125                    no("byte mode has no text. Declare it in a `#[derive(Message)]`")
126                }
127                _ => Ok(()),
128            },
129            Container::Words { .. } | Container::Word { .. }
130                if matches!(kind, Kind::Scalar(Scalar::ByteBool)) =>
131            {
132                no("a whole-byte `bool` is byte mode's. Declare a one-bit `Scalar::Bool`")
133            }
134            Container::Words { .. } => match kind {
135                Kind::Array(s, _) if !matches!(s, Scalar::U(8 | 16)) => {
136                    no("words mode allows only `[u16; K]` and `[u8; K]` arrays")
137                }
138                _ => Ok(()),
139            },
140            Container::Word { .. } => match kind {
141                Kind::Scalar(Scalar::F32 | Scalar::F64) => {
142                    no("word mode has no floats. Declare it in byte mode")
143                }
144                Kind::Nested { .. } | Kind::NestedArray { .. } => {
145                    no("word mode has no nested layouts. Declare it in byte mode")
146                }
147                Kind::Text { .. } | Kind::Var { .. } | Kind::Msg { .. } => no(
148                    "word mode needs a fixed width, and this field's size is read from the wire. \
149                     Declare it in a `#[derive(Message)]`",
150                ),
151                _ => Ok(()),
152            },
153        }
154    }
155
156    /// The unit of the size in `#[layout(..)]`.
157    #[must_use]
158    pub fn unit(&self) -> Unit {
159        match self {
160            Container::Word { .. } => Unit::Bits,
161            Container::Bytes { .. } => Unit::Bytes,
162            Container::Words { .. } => Unit::Words,
163        }
164    }
165
166    /// The size in [`unit`](Self::unit)s: the `N` of `#[layout(<unit> = N)]`.
167    #[must_use]
168    pub fn units(&self) -> u64 {
169        match self {
170            Container::Word { bits, .. } => *bits,
171            Container::Bytes { bytes, .. } => *bytes as u64,
172            Container::Words { words, .. } => *words as u64,
173        }
174    }
175
176    /// The byte order.
177    #[must_use]
178    pub fn endian(&self) -> Endian {
179        match self {
180            Container::Word { endian, .. }
181            | Container::Bytes { endian, .. }
182            | Container::Words { endian, .. } => *endian,
183        }
184    }
185
186    /// The bit order, or `None` in byte mode.
187    #[must_use]
188    pub fn order(&self) -> Option<BitOrder> {
189        match self {
190            Container::Word { order, .. } | Container::Words { order, .. } => Some(*order),
191            Container::Bytes { .. } => None,
192        }
193    }
194
195    /// Whether fields are addressed in bits.
196    #[must_use]
197    pub fn is_bit_addressed(&self) -> bool {
198        !matches!(self, Container::Bytes { .. })
199    }
200
201    /// The size in bits.
202    #[must_use]
203    pub fn bits(&self) -> u64 {
204        match self {
205            Container::Word { bits, .. } => *bits,
206            Container::Bytes { bytes, .. } => *bytes as u64 * 8,
207            Container::Words { words, .. } => *words as u64 * 16,
208        }
209    }
210
211    /// Leading bits the enclosing dispatch reads.
212    #[must_use]
213    pub fn prefix(&self) -> u64 {
214        match self {
215            Container::Word { prefix, .. } => *prefix,
216            Container::Bytes { .. } | Container::Words { .. } => 0,
217        }
218    }
219
220    /// The bits the fields must cover: [`bits`](Self::bits) minus [`prefix`](Self::prefix).
221    #[must_use]
222    pub fn field_bits(&self) -> u64 {
223        match self {
224            Container::Word { bits, prefix, .. } => bits.saturating_sub(*prefix),
225            other => other.bits(),
226        }
227    }
228
229    /// Bits in the unit a byte order applies to: the container, one word, or the field.
230    fn region_bits(&self, width: u64) -> u64 {
231        match self {
232            Container::Word { bits, .. } => *bits,
233            Container::Words { .. } => 16,
234            Container::Bytes { .. } => width,
235        }
236    }
237
238    /// First bit of the unit that holds the bit `start`.
239    fn region_start(&self, start: u64) -> u64 {
240        match self {
241            Container::Word { .. } => 0,
242            Container::Words { .. } => start - start % 16,
243            Container::Bytes { .. } => start,
244        }
245    }
246
247    /// The word size in words mode (`Some(16)`), and `None` otherwise.
248    #[must_use]
249    pub fn interior_boundary(&self) -> Option<u64> {
250        match self {
251            Container::Words { .. } => Some(16),
252            Container::Word { .. } | Container::Bytes { .. } => None,
253        }
254    }
255
256    /// The wire position of a field declared at bit `start`, after applying [`BitOrder`].
257    ///
258    /// Under `order = msb`, scalar and codec fields are mirrored within their word. `FIELDS` and
259    /// `STATED` use this position. [`check_stated`](Self::check_stated) uses declared positions.
260    #[must_use]
261    pub fn physical(&self, kind: &Kind, start: u64) -> u64 {
262        let (region, order) = match self {
263            Container::Word { bits, order, .. } => (*bits, *order),
264            Container::Words { order, .. } => (16, *order),
265            Container::Bytes { .. } => return start,
266        };
267        let packed = matches!(kind, Kind::Scalar(_) | Kind::Codec { .. });
268        if order == BitOrder::Lsb || !packed || region == 0 {
269            return start;
270        }
271        let base = start - start % region;
272        base + region.saturating_sub(start - base + kind.width())
273    }
274
275    /// Checks an `#[at]` position against the field's declared position.
276    ///
277    /// Under `msb`, `#[at]` counts in declared order, as a big-endian spec's table does.
278    ///
279    /// # Errors
280    ///
281    /// The diagnostic text. Under `msb` it gives both positions.
282    pub fn check_stated(
283        &self,
284        field: &str,
285        kind: &Kind,
286        stated: Stated,
287        declared: u64,
288    ) -> Result<(), String> {
289        let msb = matches!(
290            self,
291            Container::Word { order: BitOrder::Msb, .. }
292                | Container::Words { order: BitOrder::Msb, .. }
293        );
294        if !msb {
295            return stated.check(field, declared);
296        }
297        let claimed = stated.bits();
298        if claimed == declared {
299            return Ok(());
300        }
301        let width = kind.width();
302        let region = self.region_bits(width);
303        let place = |bits| place(stated.unit, bits);
304        let lands = if claimed + width <= self.region_start(claimed) + region {
305            format!("is physical {}", place(self.physical(kind, claimed)))
306        } else {
307            let unit = match self {
308                Container::Words { .. } => "word",
309                _ => "container",
310            };
311            format!("does not fit the {region}-bit {unit}")
312        };
313        Err(format!(
314            "field `{field}`: #[at({} = {})] (declared numbering, msb) {lands}, but the solver \
315             placed it at physical {} — declared {}",
316            stated.unit.name(),
317            stated.pos,
318            place(self.physical(kind, declared)),
319            place(declared),
320        ))
321    }
322}
323
324/// A bit position in `unit`, such as `byte 3`, or `bit 27 (not a byte boundary)`.
325fn place(unit: StatedUnit, bits: u64) -> String {
326    if bits.is_multiple_of(unit.bits()) {
327        format!("{} {}", unit.name(), bits / unit.bits())
328    } else {
329        format!("bit {bits} (not a byte boundary)")
330    }
331}
332
333/// A fixed-size layout whose fields cover every bit of its container.
334#[derive(Debug, Clone, PartialEq, Eq)]
335#[non_exhaustive]
336pub struct LayoutDef {
337    /// The type name.
338    pub name: String,
339    /// The container.
340    pub container: Container,
341    /// The fields, in wire order.
342    pub fields: Vec<Field>,
343    /// Whether to generate a `<Name>View` that reads fields in place: `#[layout(.., view)]`.
344    pub view: bool,
345    /// Whether encode keeps the low bits of a value wider than its field instead of panicking:
346    /// `#[layout(.., truncate)]`.
347    pub truncate: bool,
348    /// Documentation.
349    pub doc: Option<String>,
350    /// Derives for this layout, written after the module's.
351    pub derives: Vec<Derive>,
352}
353
354impl LayoutDef {
355    /// A layout with no view.
356    #[must_use]
357    pub fn new(name: &str, container: Container, fields: Vec<Field>) -> Self {
358        Self {
359            name: String::from(name),
360            container,
361            fields,
362            view: false,
363            truncate: false,
364            doc: None,
365            derives: Vec::new(),
366        }
367    }
368
369    /// Sets the documentation.
370    #[must_use]
371    pub fn with_doc(self, doc: &str) -> Self {
372        Self { doc: Some(String::from(doc)), ..self }
373    }
374
375    /// Sets the derives written on this layout, after the module's.
376    #[must_use]
377    pub fn with_derives(self, derives: Vec<Derive>) -> Self {
378        Self { derives, ..self }
379    }
380
381    /// Adds a `<Name>View`.
382    #[must_use]
383    pub fn with_view(self) -> Self {
384        Self { view: true, ..self }
385    }
386
387    /// Makes encode keep the low bits of a value wider than its field, as a hardware register
388    /// does.
389    #[must_use]
390    pub fn with_truncate(self) -> Self {
391        Self { truncate: true, ..self }
392    }
393}
394
395/// A field and its position in the container.
396#[derive(Debug, Clone, Copy)]
397pub(crate) struct Positioned<'a> {
398    pub(crate) field: &'a Field,
399    /// The sum of the earlier fields' widths.
400    pub(crate) declared: u64,
401    /// [`declared`](Self::declared), after [`Container::physical`].
402    pub(crate) physical: u64,
403}
404
405/// Each field with its declared and physical position.
406///
407/// The fields of a [`Segment::Block`](crate::Segment::Block) use this too.
408pub(crate) fn positioned<'a>(
409    fields: &'a [Field],
410    container: &'a Container,
411) -> impl Iterator<Item = Positioned<'a>> {
412    fields.iter().scan(container.prefix(), move |at, field| {
413        let declared = *at;
414        *at += field.kind.width();
415        Some(Positioned { field, declared, physical: container.physical(&field.kind, declared) })
416    })
417}