Skip to main content

fic/tast/
ty.rs

1//! The value type every `tast` node carries, by id.
2//!
3//! `int` and `uint` are sized here (`int64`, `uint64`), `byte` is `uint8`
4//! (as C spells it, `uint8_t`); `Address` is
5//! `Addr(None)`, and an address known to point into a region, `m.vaddr`,
6//! is `Addr(Some(m))`, a subtype of `Addr(None)`. An array length is
7//! folded and keeps the const it was written as, which the C backend
8//! spells. A called foreign function's signature is lowered from its
9//! language by `rast` (`ty::foreign::signature`) and typed here as any
10//! declared type.
11
12use serde::Serialize;
13
14use crate::ast::PrimitiveType;
15use crate::base::{self, ConstId, IdVec, MrId, StructId, TypeRef};
16use crate::rast::Env;
17use crate::ty::value::ConstValue;
18use crate::ty::width::{width, Width};
19
20/// A value type.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
22pub enum Ty {
23    /// A sized scalar: never `int`, `uint`, `byte` or `Address`.
24    Prim(PrimitiveType),
25    /// An address; `Some(m)` when known to point into region `m`.
26    Addr(Option<MrId>),
27    /// A struct.
28    Struct(StructId),
29    /// `T[N]`.
30    Array {
31        /// Element type.
32        elem: Box<Ty>,
33        /// Element count.
34        len: ArrayLen,
35    },
36}
37
38/// A folded array length.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
40pub struct ArrayLen {
41    /// The count.
42    pub len: u64,
43    /// The const it was written as, if any.
44    pub written: Option<ConstId>,
45}
46
47/// A foreign function's signature, `τ̄ → τ`.
48#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
49pub struct FfnSig {
50    /// Parameter types, in order.
51    pub params: Vec<Ty>,
52    /// Result type; `None` for a procedure.
53    pub ret: Option<Ty>,
54    /// Trailing `...` (C only): extra arguments are untyped.
55    pub variadic: bool,
56}
57
58/// The consts folded so far, by id; `None` for one that did not fold.
59pub(super) type Values = IdVec<ConstId, Option<ConstValue>>;
60
61impl Ty {
62    /// `bool`.
63    pub const BOOL: Ty = Ty::Prim(PrimitiveType::Bool);
64    /// `int64`: what `int` is, and an integer with no expected type.
65    pub const INT: Ty = Ty::Prim(PrimitiveType::Int64);
66    /// `uint64`: what `uint` is, and `sizeof` with no expected type.
67    pub const UINT: Ty = Ty::Prim(PrimitiveType::UInt64);
68
69    /// `self <: other`: reflexive, plus `Addr(m) <: Addr` for every `m`.
70    #[must_use]
71    pub fn is_subtype(&self, other: &Ty) -> bool {
72        self == other || matches!((self, other), (Ty::Addr(Some(_)), Ty::Addr(None)))
73    }
74
75    /// The scalar, if this is an integer type (every primitive but `bool`).
76    #[must_use]
77    pub fn integer(&self) -> Option<PrimitiveType> {
78        match self {
79            Ty::Prim(p) if *p != PrimitiveType::Bool => Some(*p),
80            _ => None,
81        }
82    }
83
84    /// The Rust integer type this type's values are checked and folded
85    /// in; `None` for a type that holds no integer.
86    #[must_use]
87    pub(crate) fn width(&self) -> Option<&'static dyn Width> {
88        match self {
89            Ty::Prim(p) => width(*p),
90            Ty::Addr(_) => width(PrimitiveType::Address),
91            Ty::Struct(_) | Ty::Array { .. } => None,
92        }
93    }
94
95    /// A decimal literal against this type: it must enter the type's Rust
96    /// integer type (`T::try_from`).
97    ///
98    /// # Errors
99    ///
100    /// `v` is out of the type's range.
101    pub(super) fn fits_i64(&self, v: i64, env: &Env) -> Result<(), String> {
102        match self.width() {
103            Some(w) if w.signed(v).is_none() => Err(self.out_of_range(&v, w, env)),
104            _ => Ok(()),
105        }
106    }
107
108    /// A hex literal or a size against this type, as [`Ty::fits_i64`].
109    ///
110    /// # Errors
111    ///
112    /// `v` is out of the type's range.
113    pub(super) fn fits_u64(&self, v: u64, env: &Env) -> Result<(), String> {
114        match self.width() {
115            Some(w) if w.unsigned(v).is_none() => Err(self.out_of_range(&v, w, env)),
116            _ => Ok(()),
117        }
118    }
119
120    fn out_of_range(&self, v: &dyn std::fmt::Display, w: &dyn Width, env: &Env) -> String {
121        let (lo, hi) = w.bounds();
122        format!(
123            "value {v} is out of range for {} ({lo}..={hi})",
124            self.display(env)
125        )
126    }
127
128    /// The type as a diagnostic names it.
129    #[must_use]
130    pub fn display(&self, env: &Env) -> String {
131        match self {
132            Ty::Prim(p) => p.to_string(),
133            Ty::Addr(None) => "Address".to_owned(),
134            Ty::Addr(Some(m)) => format!("Addr({})", env.mrs[*m].name),
135            Ty::Struct(r) => env.structs[*r].name.clone(),
136            Ty::Array { elem, len } => format!("{}[{}]", elem.display(env), len.len),
137        }
138    }
139}
140
141/// The type of a primitive: the aliases sized, `Address` an address.
142pub(super) fn prim(p: PrimitiveType) -> Ty {
143    match p {
144        PrimitiveType::Int => Ty::Prim(PrimitiveType::Int64),
145        PrimitiveType::UInt => Ty::Prim(PrimitiveType::UInt64),
146        PrimitiveType::Byte => Ty::Prim(PrimitiveType::UInt8),
147        PrimitiveType::Address => Ty::Addr(None),
148        p => Ty::Prim(p),
149    }
150}
151
152/// Lower a written type.
153///
154/// # Errors
155///
156/// An array length that is not a folded, non-negative integer const.
157pub(super) fn lower(t: &TypeRef, consts: &Values, env: &Env) -> Result<Ty, String> {
158    Ok(match t {
159        TypeRef::Prim(p) => prim(*p),
160        TypeRef::Struct(r) => Ty::Struct(*r),
161        TypeRef::Array { elem, len } => Ty::Array {
162            elem: Box::new(lower(elem, consts, env)?),
163            len: array_len(len, consts, env)?,
164        },
165    })
166}
167
168/// Fold a written array length.
169///
170/// # Errors
171///
172/// A const that is not a count (negative, or above `u64::MAX`), a bool,
173/// or not yet folded (declared after the array).
174pub(super) fn array_len(
175    len: &base::ArrayLen,
176    consts: &Values,
177    env: &Env,
178) -> Result<ArrayLen, String> {
179    match len {
180        base::ArrayLen::Lit(n) => Ok(ArrayLen {
181            len: *n,
182            written: None,
183        }),
184        base::ArrayLen::Const(id) => {
185            let name = &env.consts[*id].name;
186            match consts.get(*id).copied().flatten() {
187                Some(ConstValue::Bool(_)) => {
188                    Err(format!("array length '{name}' is a bool, not an integer"))
189                }
190                Some(v) => v
191                    .count()
192                    .map(|len| ArrayLen {
193                        len,
194                        written: Some(*id),
195                    })
196                    .ok_or_else(|| format!("array length '{name}' is not a count ({v})")),
197                None => Err(format!(
198                    "array length '{name}' is not a declared constant (declare it before the array)"
199                )),
200            }
201        }
202    }
203}
204
205/// The byte size of a written type; `structs` sizes a struct by id.
206///
207/// # Errors
208///
209/// A primitive with no fixed width (`int`, `uint`, `Address`), a struct
210/// with no fixed size, or an array whose length does not fold or whose
211/// size overflows.
212pub(super) fn size_of(
213    t: &TypeRef,
214    consts: &Values,
215    env: &Env,
216    structs: &dyn Fn(StructId) -> Result<u64, String>,
217) -> Result<u64, String> {
218    match t {
219        TypeRef::Prim(p) => p.size_bytes().map(|n| n as u64).ok_or_else(|| {
220            format!("'{p}' has no fixed size \u{2014} use a sized type (e.g. int32, not int)")
221        }),
222        TypeRef::Struct(r) => structs(*r),
223        TypeRef::Array { elem, len } => {
224            let len = array_len(len, consts, env)?.len;
225            let elem = size_of(elem, consts, env, structs)?;
226            len.checked_mul(elem)
227                .ok_or_else(|| "array size overflows".to_owned())
228        }
229    }
230}
231
232/// The alignment of `t` on the target: a scalar's is its size, an array's
233/// its element's, a struct's (`structs`) its largest field's.
234pub(super) fn align_of(
235    t: &TypeRef,
236    structs: &dyn Fn(StructId) -> Result<u64, String>,
237) -> Result<u64, String> {
238    match t {
239        TypeRef::Prim(p) => p.size_bytes().map(|n| n as u64).ok_or_else(|| {
240            format!("'{p}' has no fixed size \u{2014} use a sized type (e.g. int32, not int)")
241        }),
242        TypeRef::Struct(r) => structs(*r),
243        TypeRef::Array { elem, .. } => align_of(elem, structs),
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use crate::base::Idx;
251
252    const FIS: &str = "struct Slot { tag: byte; }
253        const N: uint32 = 4;
254        const NEG: int = -1;
255        const FLAG: bool = true;
256        MemoryRegion ring(0x1000);
257        ProtectionDomain a(10);";
258
259    fn env() -> Env {
260        crate::rast::env::built(FIS, &[]).expect("resolves").0.env
261    }
262
263    fn values() -> Values {
264        [
265            Some(ConstValue::UInt32(4)),
266            Some(ConstValue::Int64(-1)),
267            Some(ConstValue::Bool(true)),
268        ]
269        .into_iter()
270        .collect()
271    }
272
273    #[test]
274    fn the_int_aliases_are_sized_and_address_is_addr() {
275        let env = env();
276        for (written, ty) in [
277            (PrimitiveType::Int, Ty::Prim(PrimitiveType::Int64)),
278            (PrimitiveType::UInt, Ty::Prim(PrimitiveType::UInt64)),
279            (PrimitiveType::Byte, Ty::Prim(PrimitiveType::UInt8)),
280            (PrimitiveType::Int32, Ty::Prim(PrimitiveType::Int32)),
281            (PrimitiveType::Address, Ty::Addr(None)),
282        ] {
283            assert_eq!(lower(&TypeRef::Prim(written), &values(), &env), Ok(ty));
284        }
285    }
286
287    #[test]
288    fn an_array_length_is_folded_and_keeps_its_const() {
289        let env = env();
290        let array = |len| TypeRef::Array {
291            elem: Box::new(TypeRef::Prim(PrimitiveType::Byte)),
292            len,
293        };
294        assert_eq!(
295            lower(
296                &array(base::ArrayLen::Const(ConstId::new(0))),
297                &values(),
298                &env
299            ),
300            Ok(Ty::Array {
301                elem: Box::new(Ty::Prim(PrimitiveType::UInt8)),
302                len: ArrayLen {
303                    len: 4,
304                    written: Some(ConstId::new(0)),
305                },
306            })
307        );
308        for (id, needle) in [(1, "is not a count (-1)"), (2, "is a bool, not an integer")] {
309            let err = lower(
310                &array(base::ArrayLen::Const(ConstId::new(id))),
311                &values(),
312                &env,
313            )
314            .unwrap_err();
315            assert!(err.contains(needle), "{err}");
316        }
317        // Not folded yet: declared after the array.
318        let err = lower(
319            &array(base::ArrayLen::Const(ConstId::new(0))),
320            &Values::new(),
321            &env,
322        )
323        .unwrap_err();
324        assert!(err.contains("declare it before the array"), "{err}");
325    }
326
327    #[test]
328    fn display_names_every_form() {
329        let env = env();
330        let cases = [
331            (Ty::Prim(PrimitiveType::Int64), "int64"),
332            (Ty::Addr(None), "Address"),
333            (Ty::Addr(Some(MrId::new(0))), "Addr(ring)"),
334            (Ty::Struct(StructId::new(0)), "Slot"),
335            (
336                Ty::Array {
337                    elem: Box::new(Ty::Prim(PrimitiveType::UInt8)),
338                    len: ArrayLen {
339                        len: 16,
340                        written: None,
341                    },
342                },
343                "uint8[16]",
344            ),
345        ];
346        for (ty, text) in cases {
347            assert_eq!(ty.display(&env), text);
348        }
349    }
350
351    #[test]
352    fn an_address_into_a_region_is_a_subtype_of_address() {
353        let refined = Ty::Addr(Some(MrId::new(0)));
354        assert!(refined.is_subtype(&Ty::Addr(None)));
355        assert!(!Ty::Addr(None).is_subtype(&refined));
356        assert!(!refined.is_subtype(&Ty::Prim(PrimitiveType::Int64)));
357        assert!(refined.is_subtype(&refined));
358        assert_eq!(
359            Ty::Prim(PrimitiveType::UInt8).integer(),
360            Some(PrimitiveType::UInt8)
361        );
362        assert_eq!(Ty::BOOL.integer(), None);
363        assert_eq!(Ty::Addr(None).integer(), None);
364    }
365}