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 has no `bool`. Declare it in word mode")
122                }
123                Kind::Text { .. } => {
124                    no("byte mode has no text. Declare it in a `#[derive(Message)]`")
125                }
126                _ => Ok(()),
127            },
128            Container::Words { .. } => match kind {
129                Kind::Array(s, _) if !matches!(s, Scalar::U(8 | 16)) => {
130                    no("words mode allows only `[u16; K]` and `[u8; K]` arrays")
131                }
132                _ => Ok(()),
133            },
134            Container::Word { .. } => match kind {
135                Kind::Scalar(Scalar::F32 | Scalar::F64) => {
136                    no("word mode has no floats. Declare it in byte mode")
137                }
138                Kind::Nested { .. } | Kind::NestedArray { .. } => {
139                    no("word mode has no nested layouts. Declare it in byte mode")
140                }
141                Kind::Text { .. } | Kind::Var { .. } | Kind::Msg { .. } => no(
142                    "word mode needs a fixed width, and this field's size is read from the wire. \
143                     Declare it in a `#[derive(Message)]`",
144                ),
145                _ => Ok(()),
146            },
147        }
148    }
149
150    /// The unit of the size in `#[layout(..)]`.
151    #[must_use]
152    pub fn unit(&self) -> Unit {
153        match self {
154            Container::Word { .. } => Unit::Bits,
155            Container::Bytes { .. } => Unit::Bytes,
156            Container::Words { .. } => Unit::Words,
157        }
158    }
159
160    /// The size in [`unit`](Self::unit)s: the `N` of `#[layout(<unit> = N)]`.
161    #[must_use]
162    pub fn units(&self) -> u64 {
163        match self {
164            Container::Word { bits, .. } => *bits,
165            Container::Bytes { bytes, .. } => *bytes as u64,
166            Container::Words { words, .. } => *words as u64,
167        }
168    }
169
170    /// The byte order.
171    #[must_use]
172    pub fn endian(&self) -> Endian {
173        match self {
174            Container::Word { endian, .. }
175            | Container::Bytes { endian, .. }
176            | Container::Words { endian, .. } => *endian,
177        }
178    }
179
180    /// The bit order, or `None` in byte mode.
181    #[must_use]
182    pub fn order(&self) -> Option<BitOrder> {
183        match self {
184            Container::Word { order, .. } | Container::Words { order, .. } => Some(*order),
185            Container::Bytes { .. } => None,
186        }
187    }
188
189    /// Whether fields are addressed in bits.
190    #[must_use]
191    pub fn is_bit_addressed(&self) -> bool {
192        !matches!(self, Container::Bytes { .. })
193    }
194
195    /// The size in bits.
196    #[must_use]
197    pub fn bits(&self) -> u64 {
198        match self {
199            Container::Word { bits, .. } => *bits,
200            Container::Bytes { bytes, .. } => *bytes as u64 * 8,
201            Container::Words { words, .. } => *words as u64 * 16,
202        }
203    }
204
205    /// Leading bits the enclosing dispatch reads.
206    #[must_use]
207    pub fn prefix(&self) -> u64 {
208        match self {
209            Container::Word { prefix, .. } => *prefix,
210            Container::Bytes { .. } | Container::Words { .. } => 0,
211        }
212    }
213
214    /// The bits the fields must cover: [`bits`](Self::bits) minus [`prefix`](Self::prefix).
215    #[must_use]
216    pub fn field_bits(&self) -> u64 {
217        match self {
218            Container::Word { bits, prefix, .. } => bits.saturating_sub(*prefix),
219            other => other.bits(),
220        }
221    }
222
223    /// Bits in the unit a byte order applies to: the container, one word, or the field.
224    fn region_bits(&self, width: u64) -> u64 {
225        match self {
226            Container::Word { bits, .. } => *bits,
227            Container::Words { .. } => 16,
228            Container::Bytes { .. } => width,
229        }
230    }
231
232    /// First bit of the unit that holds the bit `start`.
233    fn region_start(&self, start: u64) -> u64 {
234        match self {
235            Container::Word { .. } => 0,
236            Container::Words { .. } => start - start % 16,
237            Container::Bytes { .. } => start,
238        }
239    }
240
241    /// The word size in words mode (`Some(16)`), and `None` otherwise.
242    #[must_use]
243    pub fn interior_boundary(&self) -> Option<u64> {
244        match self {
245            Container::Words { .. } => Some(16),
246            Container::Word { .. } | Container::Bytes { .. } => None,
247        }
248    }
249
250    /// The wire position of a field declared at bit `start`, after applying [`BitOrder`].
251    ///
252    /// Under `order = msb`, scalar and codec fields are mirrored within their word. `FIELDS` and
253    /// `STATED` use this position. [`check_stated`](Self::check_stated) uses declared positions.
254    #[must_use]
255    pub fn physical(&self, kind: &Kind, start: u64) -> u64 {
256        let (region, order) = match self {
257            Container::Word { bits, order, .. } => (*bits, *order),
258            Container::Words { order, .. } => (16, *order),
259            Container::Bytes { .. } => return start,
260        };
261        let packed = matches!(kind, Kind::Scalar(_) | Kind::Codec { .. });
262        if order == BitOrder::Lsb || !packed || region == 0 {
263            return start;
264        }
265        let base = start - start % region;
266        base + region.saturating_sub(start - base + kind.width())
267    }
268
269    /// Checks an `#[at]` position against the field's declared position.
270    ///
271    /// Under `msb`, `#[at]` counts in declared order, as a big-endian spec's table does.
272    ///
273    /// # Errors
274    ///
275    /// The diagnostic text. Under `msb` it gives both positions.
276    pub fn check_stated(
277        &self,
278        field: &str,
279        kind: &Kind,
280        stated: Stated,
281        declared: u64,
282    ) -> Result<(), String> {
283        let msb = matches!(
284            self,
285            Container::Word { order: BitOrder::Msb, .. }
286                | Container::Words { order: BitOrder::Msb, .. }
287        );
288        if !msb {
289            return stated.check(field, declared);
290        }
291        let claimed = stated.bits();
292        if claimed == declared {
293            return Ok(());
294        }
295        let width = kind.width();
296        let region = self.region_bits(width);
297        let place = |bits| place(stated.unit, bits);
298        let lands = if claimed + width <= self.region_start(claimed) + region {
299            format!("is physical {}", place(self.physical(kind, claimed)))
300        } else {
301            let unit = match self {
302                Container::Words { .. } => "word",
303                _ => "container",
304            };
305            format!("does not fit the {region}-bit {unit}")
306        };
307        Err(format!(
308            "field `{field}`: #[at({} = {})] (declared numbering, msb) {lands}, but the solver \
309             placed it at physical {} — declared {}",
310            stated.unit.name(),
311            stated.pos,
312            place(self.physical(kind, declared)),
313            place(declared),
314        ))
315    }
316}
317
318/// A bit position in `unit`, such as `byte 3`, or `bit 27 (not a byte boundary)`.
319fn place(unit: StatedUnit, bits: u64) -> String {
320    if bits.is_multiple_of(unit.bits()) {
321        format!("{} {}", unit.name(), bits / unit.bits())
322    } else {
323        format!("bit {bits} (not a byte boundary)")
324    }
325}
326
327/// A fixed-size layout whose fields cover every bit of its container.
328#[derive(Debug, Clone, PartialEq, Eq)]
329#[non_exhaustive]
330pub struct LayoutDef {
331    /// The type name.
332    pub name: String,
333    /// The container.
334    pub container: Container,
335    /// The fields, in wire order.
336    pub fields: Vec<Field>,
337    /// Whether to generate a `<Name>View` that reads fields in place: `#[layout(.., view)]`.
338    pub view: bool,
339    /// Documentation.
340    pub doc: Option<String>,
341    /// Derives for this layout, written after the module's.
342    pub derives: Vec<Derive>,
343}
344
345impl LayoutDef {
346    /// A layout with no view.
347    #[must_use]
348    pub fn new(name: &str, container: Container, fields: Vec<Field>) -> Self {
349        Self {
350            name: String::from(name),
351            container,
352            fields,
353            view: false,
354            doc: None,
355            derives: Vec::new(),
356        }
357    }
358
359    /// Sets the documentation.
360    #[must_use]
361    pub fn with_doc(self, doc: &str) -> Self {
362        Self { doc: Some(String::from(doc)), ..self }
363    }
364
365    /// Sets the derives written on this layout, after the module's.
366    #[must_use]
367    pub fn with_derives(self, derives: Vec<Derive>) -> Self {
368        Self { derives, ..self }
369    }
370
371    /// Adds a `<Name>View`.
372    #[must_use]
373    pub fn with_view(self) -> Self {
374        Self { view: true, ..self }
375    }
376}
377
378/// A field and its position in the container.
379#[derive(Debug, Clone, Copy)]
380pub(crate) struct Positioned<'a> {
381    pub(crate) field: &'a Field,
382    /// The sum of the earlier fields' widths.
383    pub(crate) declared: u64,
384    /// [`declared`](Self::declared), after [`Container::physical`].
385    pub(crate) physical: u64,
386}
387
388/// Each field with its declared and physical position.
389///
390/// The fields of a [`Segment::Block`](crate::Segment::Block) use this too.
391pub(crate) fn positioned<'a>(
392    fields: &'a [Field],
393    container: &'a Container,
394) -> impl Iterator<Item = Positioned<'a>> {
395    fields.iter().scan(container.prefix(), move |at, field| {
396        let declared = *at;
397        *at += field.kind.width();
398        Some(Positioned { field, declared, physical: container.physical(&field.kind, declared) })
399    })
400}