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