Skip to main content

layline_codegen/model/
field.rs

1//! Fields and their types.
2
3use alloc::format;
4use alloc::string::String;
5use alloc::vec;
6use alloc::vec::Vec;
7
8use layline_core::table::StatedUnit;
9
10use super::Coverage;
11
12/// An `#[at]` position, checked against the position computed from field widths.
13///
14/// Counted from the start of the [`LayoutDef`](crate::LayoutDef) or
15/// [`MessageDef`](crate::MessageDef) body. It catches a mistyped field width.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[non_exhaustive]
18pub struct Stated {
19    /// The unit of [`pos`](Self::pos).
20    pub unit: StatedUnit,
21    /// The position.
22    pub pos: u64,
23}
24
25impl Stated {
26    /// `#[at(<unit> = pos)]`.
27    #[must_use]
28    pub fn new(unit: StatedUnit, pos: u64) -> Self {
29        Self { unit, pos }
30    }
31
32    /// `#[at(bit = pos)]`.
33    #[must_use]
34    pub fn bit(pos: u64) -> Self {
35        Self { unit: StatedUnit::Bit, pos }
36    }
37
38    /// `#[at(byte = pos)]`.
39    #[must_use]
40    pub fn byte(pos: u64) -> Self {
41        Self { unit: StatedUnit::Byte, pos }
42    }
43
44    /// The position in bits.
45    #[must_use]
46    pub fn bits(self) -> u64 {
47        self.pos * self.unit.bits()
48    }
49
50    /// The `STATED` table row for the bit position `physical`.
51    ///
52    /// Uses this position's unit if it divides `physical`, and bits otherwise.
53    #[must_use]
54    pub fn published(self, physical: u64) -> Stated {
55        if physical.is_multiple_of(self.unit.bits()) {
56            Stated { unit: self.unit, pos: physical / self.unit.bits() }
57        } else {
58            Stated::bit(physical)
59        }
60    }
61
62    /// Checks the position against `at`, with no bit-order mirroring.
63    ///
64    /// # Errors
65    ///
66    /// The diagnostic text.
67    pub(crate) fn check(self, field: &str, at: u64) -> Result<(), String> {
68        if self.bits() == at {
69            return Ok(());
70        }
71        let noun = self.unit.name();
72        let landed = if self.unit == StatedUnit::Byte && !at.is_multiple_of(8) {
73            format!("bit {at} — not a byte boundary")
74        } else {
75            format!("{noun} {}", at / self.unit.bits())
76        };
77        Err(format!(
78            "field `{field}`: #[at({noun} = {})] but the solver placed it at {landed}",
79            self.pos
80        ))
81    }
82}
83
84/// A scalar field type.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86#[non_exhaustive]
87pub enum Scalar {
88    /// An unsigned integer of this many bits, at most 128: 8, 16, 32, 64 or 128 in byte mode.
89    U(u64),
90    /// A signed integer of this many bits, sign-extended.
91    I(u64),
92    /// `f32`.
93    F32,
94    /// `f64`.
95    F64,
96    /// `bool`, one bit wide.
97    Bool,
98    /// `bool` as a whole byte, the form a byte-mode layout or message takes.
99    ///
100    /// Decode reads 0 as `false` and 1 as `true`, and refuses any other byte with
101    /// [`ParseError::Malformed`](layline_core::ParseError). Encode writes 0 or 1. For a flag the
102    /// format sets with any nonzero value, use a [`Kind::Codec`] of `layline::Nonzero`.
103    ByteBool,
104}
105
106impl Scalar {
107    /// The width in bits.
108    #[must_use]
109    pub fn bits(self) -> u64 {
110        match self {
111            Scalar::U(n) | Scalar::I(n) => n,
112            Scalar::F32 => 32,
113            Scalar::F64 => 64,
114            Scalar::Bool => 1,
115            Scalar::ByteBool => 8,
116        }
117    }
118
119    /// The smallest Rust primitive that holds this scalar, such as `u16` for 12 bits.
120    #[must_use]
121    pub fn primitive(self) -> &'static str {
122        match self {
123            Scalar::F32 => "f32",
124            Scalar::F64 => "f64",
125            Scalar::Bool | Scalar::ByteBool => "bool",
126            Scalar::U(n) => match n {
127                0..=8 => "u8",
128                9..=16 => "u16",
129                17..=32 => "u32",
130                33..=64 => "u64",
131                _ => "u128",
132            },
133            Scalar::I(n) => match n {
134                0..=8 => "i8",
135                9..=16 => "i16",
136                17..=32 => "i32",
137                33..=64 => "i64",
138                _ => "i128",
139            },
140        }
141    }
142}
143
144/// A number taken from an earlier field: `field * scale + offset`.
145///
146/// The runtime equivalent is [`layline_core::table::By`].
147#[derive(Debug, Clone, PartialEq, Eq, Hash)]
148#[non_exhaustive]
149pub struct By {
150    /// The field to read. It must come before the field that uses it.
151    pub field: String,
152    /// The multiplier.
153    pub scale: u32,
154    /// The value added after scaling.
155    pub offset: i32,
156}
157
158impl By {
159    /// The field's value, unscaled.
160    #[must_use]
161    pub fn field(field: &str) -> Self {
162        Self { field: String::from(field), scale: 1, offset: 0 }
163    }
164
165    /// `field * scale + offset`.
166    #[must_use]
167    pub fn new(field: &str, scale: u32, offset: i32) -> Self {
168        Self { field: String::from(field), scale, offset }
169    }
170}
171
172/// A byte length.
173///
174/// [`Count`](crate::Count) counts elements instead.
175#[derive(Debug, Clone, PartialEq, Eq, Hash)]
176#[non_exhaustive]
177pub enum Len {
178    /// A fixed number of bytes.
179    Bytes(usize),
180    /// Read from an earlier field. Encode writes the field from the actual length.
181    Field {
182        /// The length field.
183        by: By,
184        /// The largest length allowed.
185        cap: Option<usize>,
186        /// Padding that is not part of the length: `#[align(N)]`.
187        ///
188        /// The value takes exactly the stated length, and zero bytes follow it up to the next
189        /// multiple of `N` bytes, counted from the value's first byte. Decode skips them without
190        /// reading them, and encode writes them. The message's `SEGMENTS` give them a row of
191        /// their own, of [`Span::Pad`](layline_core::table::Span::Pad).
192        align: Option<u64>,
193    },
194    /// Up to and including the first `terminator` byte.
195    Until {
196        /// The byte that ends the value.
197        terminator: u8,
198    },
199    /// To the end of the body.
200    Fill,
201}
202
203/// A field's type and width.
204#[derive(Debug, Clone, PartialEq, Eq, Hash)]
205#[non_exhaustive]
206pub enum Kind {
207    /// A scalar.
208    Scalar(Scalar),
209    /// An array of scalars, outermost length first: `[[f64; 3]; 2]` is `[2, 3]`.
210    Array(Scalar, Vec<usize>),
211    /// A `FieldCodec` type.
212    Codec {
213        /// The type path.
214        ty: String,
215        /// The width in bits.
216        bits: u64,
217    },
218    /// A nested layout.
219    Nested {
220        /// The type path.
221        ty: String,
222        /// The size in bytes.
223        bytes: usize,
224    },
225    /// An array of nested layouts.
226    NestedArray {
227        /// The element type path.
228        ty: String,
229        /// One element's size in bytes.
230        bytes: usize,
231        /// The number of elements.
232        len: usize,
233    },
234    /// A `VarCodec` type, whose size is read from the wire.
235    Var {
236        /// The type path.
237        ty: String,
238    },
239    /// A nested [`MessageDef`](crate::MessageDef).
240    Msg {
241        /// The type path.
242        ty: String,
243        /// Whether the Rust field is a `Box`, as a type that contains itself needs.
244        boxed: bool,
245        /// The fields passed as the message's [`needs`](crate::MessageDef::needs), in order.
246        with: Vec<String>,
247    },
248    /// A `#[checksum(..)]` field in a fixed layout.
249    ///
250    /// Messages use [`Segment::Checksum`](crate::Segment::Checksum).
251    Checksum {
252        /// The integer type.
253        repr: Scalar,
254        /// The path of the `layline::Checksum` algorithm.
255        algorithm: String,
256        /// The bytes it covers.
257        over: Coverage,
258    },
259    /// A `String`.
260    Text {
261        /// The length in bytes.
262        len: Len,
263        /// The `TextCodec` type path. `None` is UTF-8.
264        codec: Option<String>,
265    },
266}
267
268impl Kind {
269    /// `[u8; n]`.
270    ///
271    /// Same as `Array(Scalar::U(8), vec![n])`, but [`describe`](Kind::describe)s as raw bytes.
272    #[must_use]
273    pub fn bytes(n: usize) -> Self {
274        Kind::array(Scalar::U(8), n)
275    }
276
277    /// `[s; len]`.
278    #[must_use]
279    pub fn array(s: Scalar, len: usize) -> Self {
280        Kind::Array(s, vec![len])
281    }
282
283    /// `#[checksum(algorithm, over = ..)]`.
284    #[must_use]
285    pub fn checksum(repr: Scalar, algorithm: &str, over: Coverage) -> Self {
286        Kind::Checksum { repr, algorithm: String::from(algorithm), over }
287    }
288
289    /// The width in bits, or `None` if the size is read from the wire.
290    #[must_use]
291    pub fn bits(&self) -> Option<u64> {
292        Some(match self {
293            Kind::Scalar(s) | Kind::Checksum { repr: s, .. } => s.bits(),
294            Kind::Array(s, dims) => s.bits() * dims.iter().product::<usize>() as u64,
295            Kind::Codec { bits, .. } => *bits,
296            Kind::Nested { bytes, .. } => *bytes as u64 * 8,
297            Kind::NestedArray { bytes, len, .. } => (*bytes * *len) as u64 * 8,
298            Kind::Text { len: Len::Bytes(n), .. } => *n as u64 * 8,
299            Kind::Var { .. } | Kind::Msg { .. } | Kind::Text { .. } => return None,
300        })
301    }
302
303    /// [`bits`](Self::bits), or `0` if not fixed.
304    pub(crate) fn width(&self) -> u64 {
305        self.bits().unwrap_or(0)
306    }
307
308    /// Whether a count, length or offset can read its number from this field.
309    #[must_use]
310    pub fn is_integer(&self) -> bool {
311        match self {
312            Kind::Scalar(Scalar::U(_) | Scalar::I(_)) | Kind::Var { .. } | Kind::Codec { .. } => {
313                true
314            }
315            Kind::Scalar(Scalar::F32 | Scalar::F64 | Scalar::Bool | Scalar::ByteBool)
316            | Kind::Array(..)
317            | Kind::Nested { .. }
318            | Kind::NestedArray { .. }
319            | Kind::Msg { .. }
320            | Kind::Text { .. }
321            | Kind::Checksum { .. } => false,
322        }
323    }
324
325    /// A short description for error messages, such as "an integer".
326    #[must_use]
327    pub fn describe(&self) -> &'static str {
328        match self {
329            Kind::Scalar(Scalar::U(_) | Scalar::I(_)) => "an integer",
330            Kind::Scalar(Scalar::F32 | Scalar::F64) => "a float",
331            Kind::Scalar(Scalar::Bool | Scalar::ByteBool) => "a bool",
332            Kind::Array(Scalar::U(8), _) => "a run of raw bytes",
333            Kind::Array(..) => "an array",
334            Kind::Codec { .. } => "a `FieldCodec` value",
335            Kind::Nested { .. } => "a nested layout",
336            Kind::NestedArray { .. } => "an array of nested layouts",
337            Kind::Var { .. } => "a self-delimiting value",
338            Kind::Msg { .. } => "a nested message",
339            Kind::Checksum { .. } => "a check value over the bytes it covers",
340            Kind::Text { .. } => "text",
341        }
342    }
343}
344
345/// A named field.
346#[derive(Debug, Clone, PartialEq, Eq)]
347#[non_exhaustive]
348pub struct Field {
349    /// The field name.
350    pub name: String,
351    /// The type and width.
352    pub kind: Kind,
353    /// Documentation.
354    pub doc: Option<String>,
355    /// The `#[at]` position.
356    pub stated: Option<Stated>,
357    /// The `#[magic]` bytes the field must hold.
358    pub magic: Option<Vec<u8>>,
359    /// The `#[range]` of allowed values.
360    pub range: Option<Range>,
361    /// Whether the field is spare: bits the format reserves that carry no information.
362    ///
363    /// The bits round-trip like any other field. Serde leaves a spare field out, under the same
364    /// `cfg` as the module's serde derive.
365    pub spare: bool,
366    /// The field's visibility, such as `pub(crate)`. `None` is `pub`.
367    ///
368    /// A field the generated type keeps in step with something else, such as a label that a
369    /// catalogue arm already decided, is not the caller's to set.
370    pub visibility: Option<String>,
371}
372
373impl Field {
374    /// A field with no documentation or attributes.
375    #[must_use]
376    pub fn new(name: &str, kind: Kind) -> Self {
377        Self {
378            name: String::from(name),
379            kind,
380            doc: None,
381            stated: None,
382            magic: None,
383            range: None,
384            spare: false,
385            visibility: None,
386        }
387    }
388
389    /// Marks the field spare: its bits carry no information.
390    #[must_use]
391    pub fn with_spare(self) -> Self {
392        Self { spare: true, ..self }
393    }
394
395    /// Sets the visibility, such as `pub(crate)` or `""` for private.
396    #[must_use]
397    pub fn with_visibility(self, visibility: &str) -> Self {
398        Self { visibility: Some(String::from(visibility)), ..self }
399    }
400
401    /// Sets the documentation.
402    #[must_use]
403    pub fn with_doc(self, doc: &str) -> Self {
404        Self { doc: Some(String::from(doc)), ..self }
405    }
406
407    /// Sets the `#[at]` position.
408    #[must_use]
409    pub fn with_stated(self, stated: Stated) -> Self {
410        Self { stated: Some(stated), ..self }
411    }
412
413    /// Sets the `#[magic]` bytes.
414    #[must_use]
415    pub fn with_magic(self, bytes: &[u8]) -> Self {
416        Self { magic: Some(bytes.to_vec()), ..self }
417    }
418
419    /// Sets the `#[range]`.
420    #[must_use]
421    pub fn with_range(self, range: Range) -> Self {
422        Self { range: Some(range), ..self }
423    }
424}
425
426/// The values a `#[range]` allows.
427#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
428#[non_exhaustive]
429pub struct Range {
430    /// The lowest allowed value. `None` is the type's minimum.
431    pub lo: Option<i64>,
432    /// The highest allowed value. `None` is the type's maximum.
433    pub hi: Option<i64>,
434}
435
436impl Range {
437    /// `lo..=hi`. A `None` end is unbounded.
438    #[must_use]
439    pub fn new(lo: Option<i64>, hi: Option<i64>) -> Self {
440        Self { lo, hi }
441    }
442}