Skip to main content

fic/tast/
system.rs

1//! Typing the `.fis` declarations: each channel's payload type, each
2//! struct's layout, each const's folded value. Memory regions and
3//! protection domains carry no type, so `TyEnv` holds `rast`'s own nodes.
4//!
5//! Consts are typed and folded in declaration order, each in its types
6//! (`fold.rs`), a forward reference being an error, with `sizeof` laying
7//! a struct out on demand against the consts folded so far. The structs
8//! left are laid out after, with the complete const table, each once. The
9//! layout is C's on the target: each field at its natural alignment, the
10//! size rounded up to the struct's. A struct is acyclic by `rast`'s check.
11
12use std::cell::RefCell;
13
14use crate::base::{ChanId, ConstId, IdVec, StructId, TypeRef};
15use crate::error::Diagnostic;
16use crate::rast::{self, Env};
17
18use super::expr::expr;
19use super::fold::fold;
20use super::scope::{Scope, Site};
21use super::ty::{align_of, array_len, lower, size_of, Values};
22use super::{Channel, Const, Field, Struct};
23
24/// Type and fold every const, in declaration order; `None` for one that
25/// fails. A const's value is typed against its declared type, then folded
26/// in its types.
27pub(super) fn type_consts(
28    env: &Env,
29    layouts: &Layouts<'_>,
30    errors: &mut Vec<Diagnostic>,
31) -> IdVec<ConstId, Option<Const>> {
32    let mut values = Values::new();
33    let mut out: IdVec<ConstId, Option<Const>> = IdVec::new();
34    for c in env.consts.iter() {
35        let node = {
36            let cx = Scope {
37                env,
38                values: &values,
39                site: Site::System {
40                    consts: &out,
41                    layouts,
42                },
43                context: format!("constant '{}': ", c.name),
44                base: format!("constant '{}': ", c.name),
45            };
46            let typed = match lower(&c.ty, &values, env) {
47                Ok(ty) => expr(&c.value, Some(&ty), &cx, errors).map(|e| (ty, e)),
48                Err(m) => {
49                    cx.fail(errors, &m, &c.span);
50                    None
51                }
52            };
53            typed.and_then(|(ty, e)| match fold(&e, &cx) {
54                Ok(value) => Some(Const {
55                    name: c.name.clone(),
56                    ty,
57                    value,
58                    span: c.span.clone(),
59                }),
60                Err(m) => {
61                    cx.fail(errors, &m, &e.span);
62                    None
63                }
64            })
65        };
66        values.push(node.as_ref().map(|n| n.value));
67        out.push(node);
68    }
69    out
70}
71
72/// The system's structs, laid out on demand: a struct is laid out once,
73/// when first sized (by a `sizeof` in a const, by a field of that type,
74/// or on its own turn in [`Layouts::lay_out`]), and kept.
75pub(super) struct Layouts<'a> {
76    env: &'a Env,
77    /// The structs laid out so far.
78    done: RefCell<IdVec<StructId, Option<Struct>>>,
79}
80
81impl<'a> Layouts<'a> {
82    pub(super) fn new(env: &'a Env) -> Self {
83        Self {
84            env,
85            done: RefCell::new(env.structs.iter().map(|_| None).collect()),
86        }
87    }
88
89    /// `sizeof(t)` against the consts folded so far.
90    pub(super) fn sizeof(&self, t: &TypeRef, values: &Values) -> Result<u64, String> {
91        size_of(t, values, self.env, &|id| self.size(id, values))
92    }
93
94    /// The alignment of `t` against the consts folded so far.
95    fn alignof(&self, t: &TypeRef, values: &Values) -> Result<u64, String> {
96        align_of(t, &|id| self.laid_out(id, values).map(|(_, align)| align))
97    }
98
99    /// The size of struct `id`, laid out now if it has not been.
100    pub(super) fn size(&self, id: StructId, values: &Values) -> Result<u64, String> {
101        self.laid_out(id, values).map(|(size, _)| size)
102    }
103
104    /// Struct `id`'s size and alignment, laid out now if it has not been.
105    fn laid_out(&self, id: StructId, values: &Values) -> Result<(u64, u64), String> {
106        if let Some(s) = &self.done.borrow()[id] {
107            return Ok((s.size, s.align));
108        }
109        let decl = &self.env.structs[id];
110        let s =
111            layout(decl, values, self).map_err(|_| format!("'{}' has no fixed size", decl.name))?;
112        let laid = (s.size, s.align);
113        self.done.borrow_mut()[id] = Some(s);
114        Ok(laid)
115    }
116
117    /// Lay out the rest with the complete const table; a struct with no
118    /// fixed size is reported at its declaration and `None`.
119    pub(super) fn lay_out(
120        self,
121        values: &Values,
122        errors: &mut Vec<Diagnostic>,
123    ) -> IdVec<StructId, Option<Struct>> {
124        for (id, s) in self.env.structs.iter_enumerated() {
125            if self.done.borrow()[id].is_some() {
126                continue;
127            }
128            match layout(s, values, &self) {
129                Ok(l) => self.done.borrow_mut()[id] = Some(l),
130                Err(m) => errors.push(Diagnostic::at(
131                    format!("struct '{}': {m}", s.name),
132                    s.span.clone(),
133                    self.env.file.clone(),
134                )),
135            }
136        }
137        self.done.into_inner()
138    }
139}
140
141/// C's layout of `s`: each field at the first offset after the one before
142/// that is a multiple of its alignment; the size rounded up to the largest.
143/// A packed struct's alignment, and so each of its fields', is 1.
144fn layout(s: &rast::Struct, values: &Values, layouts: &Layouts<'_>) -> Result<Struct, String> {
145    let overflow = || format!("size of '{}' overflows", s.name);
146    let mut fields = Vec::with_capacity(s.fields.len());
147    let mut size = 0u64;
148    let mut align = 1u64;
149    for f in &s.fields {
150        let field = |m: String| format!("field '{}': {m}", f.name);
151        let bytes = layouts.sizeof(&f.ty, values).map_err(field)?;
152        let field_align = if s.packed {
153            1
154        } else {
155            layouts.alignof(&f.ty, values).map_err(field)?
156        };
157        let ty = lower(&f.ty, values, layouts.env).map_err(field)?;
158        let offset = size
159            .checked_next_multiple_of(field_align)
160            .ok_or_else(overflow)?;
161        fields.push(Field {
162            name: f.name.clone(),
163            ty,
164            offset,
165            span: f.span.clone(),
166        });
167        size = offset.checked_add(bytes).ok_or_else(overflow)?;
168        align = align.max(field_align);
169    }
170    Ok(Struct {
171        name: s.name.clone(),
172        packed: s.packed,
173        fields,
174        size: size.checked_next_multiple_of(align).ok_or_else(overflow)?,
175        align,
176        span: s.span.clone(),
177    })
178}
179
180/// Type every channel's payload, `Σ(c)`, its buffer's type or a `Sync
181/// Chan<T>`'s `T`: an unbuffered
182/// channel carries none. `None` for one whose type does not lower.
183pub(super) fn type_channels(
184    env: &Env,
185    values: &Values,
186    errors: &mut Vec<Diagnostic>,
187) -> IdVec<ChanId, Option<Channel>> {
188    env.chans
189        .iter()
190        .map(|ch| {
191            let payload = match (&ch.buffer, &ch.payload) {
192                (Some(b), _) => lower(&b.payload, values, env).map(Some),
193                (None, Some(t)) => lower(t, values, env).map(Some),
194                (None, None) => Ok(None),
195            };
196            let capacity = ch
197                .buffer
198                .as_ref()
199                .and_then(|b| b.capacity.as_ref())
200                .map(|n| array_len(n, values, env).map(|n| n.len))
201                .transpose()
202                .map_err(|m| format!("capacity: {m}"));
203            match payload.and_then(|p| capacity.map(|c| (p, c))) {
204                Ok((payload, capacity)) => Some(Channel {
205                    name: ch.name.clone(),
206                    kind: ch.kind,
207                    sender: ch.sender,
208                    receiver: ch.receiver,
209                    payload,
210                    buffer: ch.buffer.clone(),
211                    capacity,
212                    span: ch.span.clone(),
213                }),
214                Err(m) => {
215                    errors.push(Diagnostic::at(
216                        format!("channel '{}': {m}", ch.name),
217                        ch.span.clone(),
218                        env.file.clone(),
219                    ));
220                    None
221                }
222            }
223        })
224        .collect()
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use crate::ast::PrimitiveType;
231    use crate::base::{Idx, MrId, PdId};
232    use crate::tast::env::built;
233    use crate::tast::{Ty, TyEnv};
234    use crate::ty::value::ConstValue;
235
236    fn system(fis: &str) -> TyEnv {
237        built(fis, &[]).expect("builds").0.tenv
238    }
239
240    fn rejected(fis: &str) -> String {
241        built(fis, &[]).expect_err("rejected").to_string()
242    }
243
244    fn size(tenv: &TyEnv, name: &str) -> u64 {
245        tenv.structs
246            .iter()
247            .find(|s| s.name == name)
248            .expect(name)
249            .size
250    }
251
252    fn value(tenv: &TyEnv, name: &str) -> ConstValue {
253        tenv.consts
254            .iter()
255            .find(|c| c.name == name)
256            .expect(name)
257            .value
258    }
259
260    #[test]
261    fn sizes_and_consts_fold() {
262        let tenv = system(
263            "struct Packet { id: uint32; length: uint16; flag: uint8; }
264             struct Header { packet: Packet; kind: uint8; }
265             const RBD_COUNT: uint = 64;
266             const RING_BYTES: uint = RBD_COUNT * sizeof(Header);",
267        );
268        // Packet: 7 bytes of fields, padded to uint32's 4; Header: Packet,
269        // then a byte, padded to 12.
270        assert_eq!(size(&tenv, "Packet"), 8);
271        assert_eq!(size(&tenv, "Header"), 12);
272        assert_eq!(value(&tenv, "RING_BYTES"), ConstValue::UInt64(768));
273        assert_eq!(
274            tenv.consts[ConstId::new(1)].ty,
275            Ty::Prim(PrimitiveType::UInt64)
276        );
277    }
278
279    fn offsets(tenv: &TyEnv, id: usize) -> Vec<(&str, u64)> {
280        tenv.structs[StructId::new(id)]
281            .fields
282            .iter()
283            .map(|f| (f.name.as_str(), f.offset))
284            .collect()
285    }
286
287    #[test]
288    fn fields_are_at_c_offsets_and_the_size_is_padded() {
289        let tenv =
290            system("struct Packet { id: uint32; length: uint16; flag: uint8; data: byte[4]; }");
291        assert_eq!(
292            offsets(&tenv, 0),
293            vec![("id", 0), ("length", 4), ("flag", 6), ("data", 7)]
294        );
295        assert_eq!(size(&tenv, "Packet"), 12, "rounded up to uint32's 4");
296    }
297
298    #[test]
299    fn a_field_waits_for_its_alignment() {
300        let tenv = system(
301            "struct Inner { tag: uint8; word: uint32; }
302             struct Outer { a: uint8; b: uint64; c: uint16; codes: uint16[3]; inner: Inner; }",
303        );
304        assert_eq!(offsets(&tenv, 0), vec![("tag", 0), ("word", 4)]);
305        assert_eq!(size(&tenv, "Inner"), 8);
306        assert_eq!(
307            offsets(&tenv, 1),
308            vec![("a", 0), ("b", 8), ("c", 16), ("codes", 18), ("inner", 24)]
309        );
310        assert_eq!(size(&tenv, "Outer"), 32);
311        assert_eq!(tenv.structs[StructId::new(1)].align, 8);
312    }
313
314    #[test]
315    fn a_packed_struct_has_no_padding() {
316        let tenv = system(
317            "struct Inner { tag: uint8; word: uint32; }
318             @attr(packed) struct Wire { a: uint8; b: uint32; inner: Inner; }
319             struct Outer { c: uint8; wire: Wire; }",
320        );
321        assert_eq!(offsets(&tenv, 1), vec![("a", 0), ("b", 1), ("inner", 5)]);
322        assert_eq!(size(&tenv, "Wire"), 13, "Inner keeps its own padding");
323        assert_eq!(tenv.structs[StructId::new(1)].align, 1);
324        assert_eq!(offsets(&tenv, 2), vec![("c", 0), ("wire", 1)]);
325        assert_eq!(size(&tenv, "Outer"), 14);
326    }
327
328    #[test]
329    fn an_unsized_field_is_rejected() {
330        let e = rejected("struct A { n: int; }");
331        assert!(
332            e.contains("struct 'A': field 'n': 'int' has no fixed size"),
333            "{e}"
334        );
335    }
336
337    /// A struct with no fixed size is reported once, at its declaration;
338    /// a struct nesting it is reported as nesting an unsized struct.
339    #[test]
340    fn an_unsized_nested_struct_is_reported_at_each_declaration() {
341        let e = rejected("struct Inner { x: int; } struct Outer { h: Inner; }");
342        assert!(
343            e.contains("struct 'Inner': field 'x': 'int' has no fixed size"),
344            "{e}"
345        );
346        assert!(
347            e.contains("struct 'Outer': field 'h': 'Inner' has no fixed size"),
348            "{e}"
349        );
350        assert_eq!(e.matches("no fixed size").count(), 2, "{e}");
351    }
352
353    #[test]
354    fn a_forward_const_reference_is_rejected() {
355        let e = rejected("const A: int = B + 1;\nconst B: int = 2;");
356        assert!(
357            e.contains("constant 'A': 'B' is not a declared constant"),
358            "{e}"
359        );
360    }
361
362    #[test]
363    fn a_const_is_checked_against_its_declared_type() {
364        let e = rejected("const FLAG: bool = 42;");
365        assert!(
366            e.contains("constant 'FLAG': expected 'bool', found 'int64'"),
367            "{e}"
368        );
369        let e = rejected("const N: int = true;");
370        assert!(e.contains("expected 'int64', found 'bool'"), "{e}");
371        // -128 fits int8; -129 does not. Literals are unsigned; the declared
372        // type bounds the folded value.
373        let tenv = system("const MIN: int8 = -128;");
374        assert_eq!(value(&tenv, "MIN"), ConstValue::Int8(-128));
375        let e = rejected("const TOO_SMALL: int8 = -129;");
376        assert!(
377            e.contains("constant 'TOO_SMALL': value -129 is out of range for int8 (-128..=127)"),
378            "{e}"
379        );
380        let e = rejected("const BIG: uint8 = 300;");
381        assert!(e.contains("out of range for uint8"), "{e}");
382        let e = rejected("const NEG: uint = -1;");
383        assert!(e.contains("out of range for uint"), "{e}");
384        let tenv = system("const ON: bool = true; const AT: Address = 0x4000_0000;");
385        assert_eq!(value(&tenv, "ON"), ConstValue::Bool(true));
386        assert_eq!(tenv.consts[ConstId::new(1)].ty, Ty::Addr(None));
387        // A `uint64` constant takes the type's full range.
388        let tenv =
389            system("const MASK: uint64 = 0xFFFF_FFFF_FFFF_FFFF; const HALF: uint64 = MASK / 2;");
390        assert_eq!(value(&tenv, "MASK"), ConstValue::UInt64(u64::MAX));
391        assert_eq!(value(&tenv, "HALF"), ConstValue::UInt64(u64::MAX / 2));
392        let e = rejected("const BIG: int64 = 0xFFFF_FFFF_FFFF_FFFF;");
393        assert!(
394            e.contains("value 18446744073709551615 is out of range for int64"),
395            "{e}"
396        );
397    }
398
399    /// A cast in a constant folds as Rust's `as`.
400    #[test]
401    fn a_const_cast_folds_as_rusts_as() {
402        let tenv = system("const A: uint8 = 300 as uint8; const B: int8 = 200 as uint8 as int8;");
403        assert_eq!(value(&tenv, "A"), ConstValue::UInt8(44));
404        assert_eq!(value(&tenv, "B"), ConstValue::Int8(-56));
405        let e = rejected("const C: bool = 1 as bool;");
406        assert!(e.contains("constant 'C': cannot cast to 'bool'"), "{e}");
407    }
408
409    /// A const folds in its type: Rust's checked arithmetic in that width.
410    #[test]
411    fn a_const_is_folded_in_its_type() {
412        let tenv = system("const A: uint8 = 200 + 55; const B: int8 = -128 + 127;");
413        assert_eq!(value(&tenv, "A"), ConstValue::UInt8(255));
414        assert_eq!(value(&tenv, "B"), ConstValue::Int8(-1));
415        let e = rejected("const X: uint8 = (200 + 100) - 100;");
416        assert!(
417            e.contains("constant 'X': '+' overflows uint8: 200 + 100"),
418            "{e}"
419        );
420        let e = rejected("const Z: int = 1 / 0;");
421        assert!(e.contains("constant 'Z': division by zero"), "{e}");
422        let e = rejected("const S: uint8 = 1 << 9;");
423        assert!(
424            e.contains("constant 'S': '<<' overflows uint8: 1 << 9"),
425            "{e}"
426        );
427        // Widths are strict in a const as in a body.
428        let e = rejected("const N: uint32 = 4; const M: int = N * 2;");
429        assert!(
430            e.contains("constant 'M': expected 'int64', found 'uint32'"),
431            "{e}"
432        );
433    }
434
435    #[test]
436    fn array_fields_take_literal_and_const_lengths() {
437        let tenv = system("struct Buf { tag: uint16; data: byte[4]; }");
438        assert_eq!(size(&tenv, "Buf"), 2 + 4);
439        // A length names an earlier const; a later const takes sizeof of
440        // the array-bearing struct.
441        let tenv = system(
442            "const PACKET_BUFFER_SIZE: uint = 2 * 1024;
443             struct Packet { length: uint16; payload: byte[PACKET_BUFFER_SIZE]; }
444             const RING_BYTES: uint = 4 * sizeof(Packet);",
445        );
446        assert_eq!(size(&tenv, "Packet"), 2 + 2048);
447        assert_eq!(value(&tenv, "RING_BYTES"), ConstValue::UInt64(4 * 2050));
448        let Ty::Array { len, .. } = &tenv.structs[StructId::new(0)].fields[1].ty else {
449            panic!("an array");
450        };
451        assert_eq!(len.written, Some(ConstId::new(0)));
452        let tenv = system("struct Cell { v: uint32; }\nstruct Grid { cells: Cell[3]; }");
453        assert_eq!(size(&tenv, "Grid"), 3 * 4);
454        let e = rejected("const NOPE: bool = true;\nstruct Buf { data: byte[NOPE]; }");
455        assert!(
456            e.contains("struct 'Buf': field 'data': array length 'NOPE' is a bool"),
457            "{e}"
458        );
459    }
460
461    #[test]
462    fn a_buffered_channel_carries_its_payload() {
463        let tenv = system(
464            "struct Slot { len: uint32; }\nMemoryRegion ring(0x1000);
465             ProtectionDomain a(10);\nProtectionDomain b(20);
466             Chan bare = a --> b;\nChan typed = a --> b via ring<Slot>;",
467        );
468        assert_eq!(tenv.chans[ChanId::new(0)].payload, None);
469        assert!(tenv.chans[ChanId::new(0)].buffer.is_none());
470        let typed = &tenv.chans[ChanId::new(1)];
471        assert_eq!(typed.payload, Some(Ty::Struct(StructId::new(0))));
472        assert_eq!(typed.buffer.as_ref().map(|b| b.region), Some(MrId::new(0)));
473        assert_eq!(
474            (typed.sender.pd, typed.receiver.pd),
475            (PdId::new(0), PdId::new(1))
476        );
477    }
478}