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: 8, 16, 32 or 64 in byte mode, any width in bit modes.
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}
99
100impl Scalar {
101    /// The width in bits.
102    #[must_use]
103    pub fn bits(self) -> u64 {
104        match self {
105            Scalar::U(n) | Scalar::I(n) => n,
106            Scalar::F32 => 32,
107            Scalar::F64 => 64,
108            Scalar::Bool => 1,
109        }
110    }
111
112    /// The smallest Rust primitive that holds this scalar, such as `u16` for 12 bits.
113    #[must_use]
114    pub fn primitive(self) -> &'static str {
115        match self {
116            Scalar::F32 => "f32",
117            Scalar::F64 => "f64",
118            Scalar::Bool => "bool",
119            Scalar::U(n) => match n {
120                0..=8 => "u8",
121                9..=16 => "u16",
122                17..=32 => "u32",
123                _ => "u64",
124            },
125            Scalar::I(n) => match n {
126                0..=8 => "i8",
127                9..=16 => "i16",
128                17..=32 => "i32",
129                _ => "i64",
130            },
131        }
132    }
133}
134
135/// A number taken from an earlier field: `field * scale + offset`.
136///
137/// The runtime equivalent is [`layline_core::table::By`].
138#[derive(Debug, Clone, PartialEq, Eq, Hash)]
139#[non_exhaustive]
140pub struct By {
141    /// The field to read. It must come before the field that uses it.
142    pub field: String,
143    /// The multiplier.
144    pub scale: u32,
145    /// The value added after scaling.
146    pub offset: i32,
147}
148
149impl By {
150    /// The field's value, unscaled.
151    #[must_use]
152    pub fn field(field: &str) -> Self {
153        Self { field: String::from(field), scale: 1, offset: 0 }
154    }
155
156    /// `field * scale + offset`.
157    #[must_use]
158    pub fn new(field: &str, scale: u32, offset: i32) -> Self {
159        Self { field: String::from(field), scale, offset }
160    }
161}
162
163/// A byte length.
164///
165/// [`Count`](crate::Count) counts elements instead.
166#[derive(Debug, Clone, PartialEq, Eq, Hash)]
167#[non_exhaustive]
168pub enum Len {
169    /// A fixed number of bytes.
170    Bytes(usize),
171    /// Read from an earlier field. Encode writes the field from the actual length.
172    Field {
173        /// The length field.
174        by: By,
175        /// The largest length allowed.
176        cap: Option<usize>,
177    },
178    /// Up to and including the first `terminator` byte.
179    Until {
180        /// The byte that ends the value.
181        terminator: u8,
182    },
183    /// To the end of the body.
184    Fill,
185}
186
187/// A field's type and width.
188#[derive(Debug, Clone, PartialEq, Eq, Hash)]
189#[non_exhaustive]
190pub enum Kind {
191    /// A scalar.
192    Scalar(Scalar),
193    /// An array of scalars, outermost length first: `[[f64; 3]; 2]` is `[2, 3]`.
194    Array(Scalar, Vec<usize>),
195    /// A `FieldCodec` type.
196    Codec {
197        /// The type path.
198        ty: String,
199        /// The width in bits.
200        bits: u64,
201    },
202    /// A nested layout.
203    Nested {
204        /// The type path.
205        ty: String,
206        /// The size in bytes.
207        bytes: usize,
208    },
209    /// An array of nested layouts.
210    NestedArray {
211        /// The element type path.
212        ty: String,
213        /// One element's size in bytes.
214        bytes: usize,
215        /// The number of elements.
216        len: usize,
217    },
218    /// A `VarCodec` type, whose size is read from the wire.
219    Var {
220        /// The type path.
221        ty: String,
222    },
223    /// A nested [`MessageDef`](crate::MessageDef).
224    Msg {
225        /// The type path.
226        ty: String,
227        /// Whether the Rust field is a `Box`, as a type that contains itself needs.
228        boxed: bool,
229        /// The fields passed as the message's [`needs`](crate::MessageDef::needs), in order.
230        with: Vec<String>,
231    },
232    /// A `#[checksum(..)]` field in a fixed layout.
233    ///
234    /// Messages use [`Segment::Checksum`](crate::Segment::Checksum).
235    Checksum {
236        /// The integer type.
237        repr: Scalar,
238        /// The path of the `layline::Checksum` algorithm.
239        algorithm: String,
240        /// The bytes it covers.
241        over: Coverage,
242    },
243    /// A `String`.
244    Text {
245        /// The length in bytes.
246        len: Len,
247        /// The `TextCodec` type path. `None` is UTF-8.
248        codec: Option<String>,
249    },
250}
251
252impl Kind {
253    /// `[u8; n]`.
254    ///
255    /// Same as `Array(Scalar::U(8), vec![n])`, but [`describe`](Kind::describe)s as raw bytes.
256    #[must_use]
257    pub fn bytes(n: usize) -> Self {
258        Kind::array(Scalar::U(8), n)
259    }
260
261    /// `[s; len]`.
262    #[must_use]
263    pub fn array(s: Scalar, len: usize) -> Self {
264        Kind::Array(s, vec![len])
265    }
266
267    /// `#[checksum(algorithm, over = ..)]`.
268    #[must_use]
269    pub fn checksum(repr: Scalar, algorithm: &str, over: Coverage) -> Self {
270        Kind::Checksum { repr, algorithm: String::from(algorithm), over }
271    }
272
273    /// The width in bits, or `None` if the size is read from the wire.
274    #[must_use]
275    pub fn bits(&self) -> Option<u64> {
276        Some(match self {
277            Kind::Scalar(s) | Kind::Checksum { repr: s, .. } => s.bits(),
278            Kind::Array(s, dims) => s.bits() * dims.iter().product::<usize>() as u64,
279            Kind::Codec { bits, .. } => *bits,
280            Kind::Nested { bytes, .. } => *bytes as u64 * 8,
281            Kind::NestedArray { bytes, len, .. } => (*bytes * *len) as u64 * 8,
282            Kind::Text { len: Len::Bytes(n), .. } => *n as u64 * 8,
283            Kind::Var { .. } | Kind::Msg { .. } | Kind::Text { .. } => return None,
284        })
285    }
286
287    /// [`bits`](Self::bits), or `0` if not fixed.
288    pub(crate) fn width(&self) -> u64 {
289        self.bits().unwrap_or(0)
290    }
291
292    /// Whether a count, length or offset can read its number from this field.
293    #[must_use]
294    pub fn is_integer(&self) -> bool {
295        match self {
296            Kind::Scalar(Scalar::U(_) | Scalar::I(_)) | Kind::Var { .. } | Kind::Codec { .. } => {
297                true
298            }
299            Kind::Scalar(Scalar::F32 | Scalar::F64 | Scalar::Bool)
300            | Kind::Array(..)
301            | Kind::Nested { .. }
302            | Kind::NestedArray { .. }
303            | Kind::Msg { .. }
304            | Kind::Text { .. }
305            | Kind::Checksum { .. } => false,
306        }
307    }
308
309    /// A short description for error messages, such as "an integer".
310    #[must_use]
311    pub fn describe(&self) -> &'static str {
312        match self {
313            Kind::Scalar(Scalar::U(_) | Scalar::I(_)) => "an integer",
314            Kind::Scalar(Scalar::F32 | Scalar::F64) => "a float",
315            Kind::Scalar(Scalar::Bool) => "a bool",
316            Kind::Array(Scalar::U(8), _) => "a run of raw bytes",
317            Kind::Array(..) => "an array",
318            Kind::Codec { .. } => "a `FieldCodec` value",
319            Kind::Nested { .. } => "a nested layout",
320            Kind::NestedArray { .. } => "an array of nested layouts",
321            Kind::Var { .. } => "a self-delimiting value",
322            Kind::Msg { .. } => "a nested message",
323            Kind::Checksum { .. } => "a check value over the bytes it covers",
324            Kind::Text { .. } => "text",
325        }
326    }
327}
328
329/// A named field.
330#[derive(Debug, Clone, PartialEq, Eq)]
331#[non_exhaustive]
332pub struct Field {
333    /// The field name.
334    pub name: String,
335    /// The type and width.
336    pub kind: Kind,
337    /// Documentation.
338    pub doc: Option<String>,
339    /// The `#[at]` position.
340    pub stated: Option<Stated>,
341    /// The `#[magic]` bytes the field must hold.
342    pub magic: Option<Vec<u8>>,
343    /// The `#[range]` of allowed values.
344    pub range: Option<Range>,
345    /// The field's visibility, such as `pub(crate)`. `None` is `pub`.
346    ///
347    /// A field the generated type keeps in step with something else, such as a label that a
348    /// catalogue arm already decided, is not the caller's to set.
349    pub visibility: Option<String>,
350}
351
352impl Field {
353    /// A field with no documentation or attributes.
354    #[must_use]
355    pub fn new(name: &str, kind: Kind) -> Self {
356        Self {
357            name: String::from(name),
358            kind,
359            doc: None,
360            stated: None,
361            magic: None,
362            range: None,
363            visibility: None,
364        }
365    }
366
367    /// Sets the visibility, such as `pub(crate)` or `""` for private.
368    #[must_use]
369    pub fn with_visibility(self, visibility: &str) -> Self {
370        Self { visibility: Some(String::from(visibility)), ..self }
371    }
372
373    /// Sets the documentation.
374    #[must_use]
375    pub fn with_doc(self, doc: &str) -> Self {
376        Self { doc: Some(String::from(doc)), ..self }
377    }
378
379    /// Sets the `#[at]` position.
380    #[must_use]
381    pub fn with_stated(self, stated: Stated) -> Self {
382        Self { stated: Some(stated), ..self }
383    }
384
385    /// Sets the `#[magic]` bytes.
386    #[must_use]
387    pub fn with_magic(self, bytes: &[u8]) -> Self {
388        Self { magic: Some(bytes.to_vec()), ..self }
389    }
390
391    /// Sets the `#[range]`.
392    #[must_use]
393    pub fn with_range(self, range: Range) -> Self {
394        Self { range: Some(range), ..self }
395    }
396}
397
398/// The values a `#[range]` allows.
399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
400#[non_exhaustive]
401pub struct Range {
402    /// The lowest allowed value. `None` is the type's minimum.
403    pub lo: Option<i64>,
404    /// The highest allowed value. `None` is the type's maximum.
405    pub hi: Option<i64>,
406}
407
408impl Range {
409    /// `lo..=hi`. A `None` end is unbounded.
410    #[must_use]
411    pub fn new(lo: Option<i64>, hi: Option<i64>) -> Self {
412        Self { lo, hi }
413    }
414}