Skip to main content

fic/tast/
env.rs

1//! The typed AST, [`Tast`], and its environment, [`TyEnv`]: the
2//! declarations typing changes ([`Channel`], [`Struct`] and its
3//! [`Field`]s, [`Const`], [`LocalVar`]), and [`build`], which types the
4//! project. The typed bodies are [`Bodies`]
5//! (`program.rs`).
6//!
7//! `build` takes the environment over: it types the declarations against
8//! it (`system.rs` the `.fis`'s, `program.rs` each program's), then each program's variables, then the bodies, and assembles the
9//! `TyEnv` from the environment and the declarations' types, moving what
10//! typing leaves as it is. A declaration's id is its `rast` id; any error
11//! fails the build, so on success every declaration and body was typed.
12
13use std::ops::Range;
14
15use serde::Serialize;
16
17use crate::ast::{ChannelKind, MemoryRegionDecl, ProtectionDomainDecl};
18use crate::base::{
19    Buffer, ChanId, ChannelEnd, Composition, ConstId, Endpoint, FfnId, IdVec, Idx, LocalVarId,
20    Mapping, MappingId, MrId, PdId, StructId,
21};
22use crate::error::{Diagnostic, Diagnostics};
23use crate::rast::{self, Env, Rast};
24use crate::ty::value::ConstValue;
25
26use super::program::{Bodies, Body, EventBody, ProcBody, VarTables};
27use super::scope::{Scope, Site};
28use super::system::Layouts;
29use super::ty::{FfnSig, Ty, Values};
30use super::{body, program, system};
31use super::{Proc, Stmt};
32
33/// The typed AST: the typed environment and the typed bodies.
34#[derive(Debug, Clone, Serialize)]
35pub struct Tast {
36    /// Every declaration, typed.
37    pub tenv: TyEnv,
38    /// Every program's body, typed.
39    pub bodies: Bodies,
40}
41
42/// The typed environment: every declaration of the project, typed where
43/// typing has something to say, the rest as `rast` resolved it.
44#[derive(Debug, Clone, Serialize)]
45pub struct TyEnv {
46    /// The `.fis` file, for diagnostics.
47    pub file: String,
48    /// Memory regions, in source order.
49    pub mrs: IdVec<MrId, MemoryRegionDecl>,
50    /// Protection domains, in source order.
51    pub pds: IdVec<PdId, ProtectionDomainDecl>,
52    /// Channels, each with its payload type.
53    pub chans: IdVec<ChanId, Channel>,
54    /// System structs, laid out.
55    pub structs: IdVec<StructId, Struct>,
56    /// System consts, typed and folded.
57    pub consts: IdVec<ConstId, Const>,
58    /// The `System =` composition, if written.
59    pub composition: Option<Composition>,
60    /// Each PD's IRQ channel id, for a PD with an IRQ. Deprecated, with
61    /// `rast/mkids.rs`: Microkit's, not the language's.
62    pub irq_ids: IdVec<PdId, Option<u32>>,
63    /// Each program's local variables, typed, by its protection domain:
64    /// its PD's state.
65    pub locals: IdVec<PdId, LocalVars>,
66    /// Every mapping: each channel buffer at its two ends, then each
67    /// program's own.
68    pub mappings: IdVec<MappingId, Mapping>,
69    /// Every foreign function some program calls, typed.
70    pub ffis: IdVec<FfnId, ForeignFn>,
71}
72
73/// A foreign function a program calls, its signature in fic's types. The
74/// store says where it is
75/// ([`ForeignModules::function`](crate::foreign::ForeignModules::function)).
76#[derive(Debug, Clone, Serialize)]
77pub struct ForeignFn {
78    /// The symbol name.
79    pub name: String,
80    /// Its signature.
81    pub sig: FfnSig,
82}
83
84/// A channel between two protection domains.
85#[derive(Debug, Clone, Serialize)]
86pub struct Channel {
87    /// Its name.
88    pub name: String,
89    /// Synchrony and direction.
90    pub kind: ChannelKind,
91    /// The sending end.
92    pub sender: ChannelEnd,
93    /// The receiving end.
94    pub receiver: ChannelEnd,
95    /// `Σ(c)`: what is sent and received, its buffer's type; `None` for an
96    /// unbuffered channel, which carries no value.
97    pub payload: Option<Ty>,
98    /// The shared buffer: its region and its two mappings.
99    pub buffer: Option<Buffer>,
100    /// The declared capacity, folded; `None`: as many slots as fit.
101    pub capacity: Option<u64>,
102    /// Byte span in the `.fis`.
103    pub span: Range<usize>,
104}
105
106impl Channel {
107    /// The end protection domain `pd` holds, if it holds one.
108    #[must_use]
109    pub fn end(&self, pd: PdId) -> Option<(Endpoint, ChannelEnd)> {
110        if self.sender.pd == pd {
111            Some((Endpoint::Sender, self.sender))
112        } else if self.receiver.pd == pd {
113            Some((Endpoint::Receiver, self.receiver))
114        } else {
115            None
116        }
117    }
118}
119
120/// A struct, laid out.
121#[derive(Debug, Clone, Serialize)]
122pub struct Struct {
123    /// Its name.
124    pub name: String,
125    /// Packed, `@attr(packed)`: no padding.
126    pub packed: bool,
127    /// Fields, in source order.
128    pub fields: Vec<Field>,
129    /// Size in bytes, C's: padding included, unless packed.
130    pub size: u64,
131    /// Alignment in bytes: its largest field's, or 1 when packed.
132    pub align: u64,
133    /// Byte span in its file.
134    pub span: Range<usize>,
135}
136
137/// A struct field.
138#[derive(Debug, Clone, Serialize)]
139pub struct Field {
140    /// Its name.
141    pub name: String,
142    /// Its type.
143    pub ty: Ty,
144    /// Byte offset in the struct.
145    pub offset: u64,
146    /// Byte span in its file.
147    pub span: Range<usize>,
148}
149
150/// A system const, folded.
151#[derive(Debug, Clone, Serialize)]
152pub struct Const {
153    /// Its name.
154    pub name: String,
155    /// Its declared type.
156    pub ty: Ty,
157    /// Its value.
158    pub value: ConstValue,
159    /// Byte span in the `.fis`.
160    pub span: Range<usize>,
161}
162
163/// A local variable: the program's, its PD's state.
164#[derive(Debug, Clone, Serialize)]
165pub struct LocalVar {
166    /// Its name.
167    pub name: String,
168    /// Its type.
169    pub ty: Ty,
170    /// Byte span in the `.fi`.
171    pub span: Range<usize>,
172}
173
174/// A program's local variables, in source order.
175pub type LocalVars = IdVec<LocalVarId, LocalVar>;
176
177/// The declarations' types, while the bodies are typed against them.
178pub(super) struct Typed {
179    pub consts: IdVec<ConstId, Const>,
180    pub structs: IdVec<StructId, Struct>,
181    pub chans: IdVec<ChanId, Channel>,
182    pub locals: IdVec<PdId, LocalVars>,
183    pub ffis: IdVec<FfnId, ForeignFn>,
184}
185
186/// Type the resolved AST `rast` on its data layer typed by [`build_data`],
187/// taking both over.
188///
189/// Returns the typed AST and the warnings.
190///
191/// The system ([`build_system`]), then every program ([`build_programs`]),
192/// each stage reporting its faults before the next starts: a body's
193/// diagnostics follow the declarations' fixes, and a reference checks its
194/// arguments against another body's parameters.
195///
196/// # Errors
197///
198/// As [`build_system`], then [`build_programs`].
199pub fn build(rast: Rast, tenv: TyEnv) -> Result<(Tast, Diagnostics), Diagnostics> {
200    let (system, mut warnings) = build_system(&rast.env, tenv)?;
201    let (tast, more) = build_programs(rast, system)?;
202    warnings.0.extend(more.0);
203    Ok((tast, warnings))
204}
205
206/// Type the data layer of `env`, [`build`]'s first stage: its consts folded,
207/// its structs laid out, in a typed environment with no system or program
208/// yet (what the headers are written from). Returns it and its warnings.
209///
210/// # Errors
211///
212/// A const that does not fold or fit its declared type, a struct with no
213/// fixed size, a declared type whose array length does not fold.
214pub fn build_data(env: &Env) -> Result<(TyEnv, Diagnostics), Diagnostics> {
215    let mut errors = Vec::new();
216    let layouts = Layouts::new(env);
217    let consts = system::type_consts(env, &layouts, &mut errors);
218    let values: Values = consts.iter().map(|c| c.as_ref().map(|c| c.value)).collect();
219    let structs = layouts.lay_out(&values, &mut errors);
220    let warnings = Diagnostics::warnings(&mut errors);
221    if !errors.is_empty() {
222        return Err(failed(errors));
223    }
224    let tenv = TyEnv {
225        file: env.file.clone(),
226        mrs: IdVec::new(),
227        pds: IdVec::new(),
228        chans: IdVec::new(),
229        structs: complete(&structs),
230        consts: complete(&consts),
231        composition: None,
232        irq_ids: IdVec::new(),
233        locals: IdVec::new(),
234        mappings: IdVec::new(),
235        ffis: IdVec::new(),
236    };
237    Ok((tenv, warnings))
238}
239
240/// Type the system of `env` on its data layer, typed by [`build_data`]:
241/// [`build`]'s second stage, each channel's payload.
242///
243/// # Errors
244///
245/// A channel payload whose type does not lower.
246pub fn build_system(env: &Env, mut tenv: TyEnv) -> Result<(TyEnv, Diagnostics), Diagnostics> {
247    let mut errors = Vec::new();
248    let values: Values = tenv.consts.iter().map(|c| Some(c.value)).collect();
249    let chans = system::type_channels(env, &values, &mut errors);
250    let warnings = Diagnostics::warnings(&mut errors);
251    if !errors.is_empty() {
252        return Err(failed(errors));
253    }
254    tenv.chans = complete(&chans);
255    Ok((tenv, warnings))
256}
257
258/// Type `rast`'s programs on its system typed by [`build_system`], taking
259/// both over: [`build`]'s last stage, every program's variables, then the
260/// bodies.
261///
262/// # Errors
263///
264/// A variable whose type does not lower; then an expression or statement
265/// that does not type.
266pub fn build_programs(rast: Rast, data: TyEnv) -> Result<(Tast, Diagnostics), Diagnostics> {
267    let Rast {
268        env,
269        bodies: mut rast,
270    } = rast;
271    let mut errors = Vec::new();
272    let values: Values = data.consts.iter().map(|c| Some(c.value)).collect();
273    let locals: Vec<Option<LocalVars>> = env
274        .locals
275        .iter_enumerated()
276        .map(|(pd, _)| program::type_locals(&env, pd, &values, &mut errors))
277        .collect();
278    let mut warnings = Diagnostics::warnings(&mut errors);
279    if !errors.is_empty() {
280        return Err(failed(errors));
281    }
282    let typed = Typed {
283        consts: data.consts,
284        structs: data.structs,
285        chans: data.chans,
286        locals: locals.into_iter().map(|l| l.expect("typed")).collect(),
287        ffis: program::type_ffis(&env, &values),
288    };
289    let values: Values = typed.consts.iter().map(|c| Some(c.value)).collect();
290
291    let tables: Vec<Option<VarTables>> = rast
292        .iter_enumerated_mut()
293        .map(|(pd, b)| program::variables(&env, pd, b, &values, &typed.chans, &mut errors))
294        .collect();
295    warnings.0.extend(Diagnostics::warnings(&mut errors).0);
296    if !errors.is_empty() {
297        return Err(failed(errors));
298    }
299    let mut bodies = IdVec::new();
300    for ((id, written), tables) in rast.into_iter_enumerated().zip(tables) {
301        let tables = tables.expect("typed");
302        body::binders(id, &tables, &written, &env, &mut errors);
303        let code = Code { tables, written };
304        if let Some(p) = typed_body(&env, &typed, id, code, &values, &mut errors) {
305            bodies.push(p);
306        }
307    }
308    if !errors.is_empty() {
309        return Err(failed(errors));
310    }
311    let tenv = TyEnv {
312        file: env.file,
313        mrs: env.mrs,
314        pds: env.pds,
315        chans: typed.chans,
316        structs: typed.structs,
317        consts: typed.consts,
318        composition: env.composition,
319        irq_ids: env.irq_ids,
320        locals: typed.locals,
321        mappings: env.mappings,
322        ffis: typed.ffis,
323    };
324    Ok((Tast { tenv, bodies }, warnings))
325}
326
327/// One program's code while it is typed: its variables, typed, and its
328/// code as resolved.
329struct Code {
330    tables: VarTables,
331    written: rast::Body,
332}
333
334/// Type one program's body, moving its variables, signatures and
335/// entries in; `None` when one does not type.
336fn typed_body(
337    env: &Env,
338    typed: &Typed,
339    id: PdId,
340    code: Code,
341    values: &Values,
342    errors: &mut Vec<Diagnostic>,
343) -> Option<Body> {
344    let Code { tables, written } = code;
345    let scope = |context: String, body_vars| Scope {
346        env,
347        values,
348        site: Site::Body {
349            typed,
350            tables: &tables,
351            pd: id,
352            written: &written,
353            body_vars,
354        },
355        context: context.clone(),
356        base: context,
357    };
358    let terms: Vec<Option<Proc>> = tables
359        .processes
360        .iter_enumerated()
361        .map(|(q, body_vars)| {
362            let w = &written.processes[q];
363            let cx = scope(format!("process '{}': ", w.sig.name), body_vars);
364            body::process(&w.body, &cx, errors)
365        })
366        .collect();
367    let statements: Vec<Option<Vec<Stmt>>> = tables
368        .events
369        .iter_enumerated()
370        .map(|(e, body_vars)| {
371            let w = &written.events[e];
372            let cx = scope(format!("event '{}': ", w.sig.name), body_vars);
373            body::statements(&w.body, &cx, errors)
374        })
375        .collect();
376    let rast::Body {
377        events: written_events,
378        processes: written_processes,
379        entries,
380        ..
381    } = written;
382    let processes = tables
383        .processes
384        .into_iter_enumerated()
385        .map(|(_, t)| t)
386        .zip(written_processes.into_iter_enumerated().map(|(_, w)| w))
387        .zip(terms)
388        .map(|((body_vars, w), body)| {
389            Some(ProcBody {
390                sig: w.sig,
391                body_vars,
392                body: body?,
393            })
394        })
395        .collect::<Option<_>>()?;
396    let events = tables
397        .events
398        .into_iter_enumerated()
399        .map(|(_, t)| t)
400        .zip(written_events.into_iter_enumerated().map(|(_, w)| w))
401        .zip(statements)
402        .map(|((body_vars, w), body)| {
403            Some(EventBody {
404                sig: w.sig,
405                body_vars,
406                body: body?,
407            })
408        })
409        .collect::<Option<_>>()?;
410    Some(Body {
411        events,
412        processes,
413        entries,
414    })
415}
416
417/// The build's errors, with their sources loaded for rendering.
418fn failed(errors: Vec<Diagnostic>) -> Diagnostics {
419    let mut errors = Diagnostics(errors);
420    errors.resolve_sources();
421    errors
422}
423
424/// Every node of an arena that reported no error.
425fn complete<I: Idx, T: Clone>(arena: &IdVec<I, Option<T>>) -> IdVec<I, T> {
426    arena.iter().map(|n| n.clone().expect("built")).collect()
427}
428
429/// Test support: the typed environment and bodies of inline sources with
430/// no imports read.
431#[cfg(test)]
432pub(crate) fn built(
433    fis: &str,
434    programs: &[(&str, &str)],
435) -> Result<(Tast, Diagnostics), Diagnostics> {
436    use crate::rast::env::built;
437
438    let (rast, _) = built(fis, programs)?;
439    let (tenv, _) = build_data(&rast.env)?;
440    build(rast, tenv)
441}
442
443/// Test support: as [`built`], with `source` read as the imported file
444/// `path` (`io.pnk` for Pancake, a `.h` for C through libclang).
445#[cfg(test)]
446pub(crate) fn built_with(
447    fis: &str,
448    programs: &[(&str, &str)],
449    path: &str,
450    source: &str,
451) -> Result<(Tast, Diagnostics), Diagnostics> {
452    use crate::rast::env::{ast_of, store};
453
454    let rawast = ast_of(fis, programs);
455    let mut foreign = store(&rawast, &[(path, source)]);
456    let (env, _) = rast::build_data(&rawast)?;
457    let (tenv, _) = build_data(&env)?;
458    build(rast::build(&rawast, env, &mut foreign)?.0, tenv)
459}
460
461#[cfg(test)]
462mod tests {
463    use std::path::Path;
464
465    use super::*;
466    use crate::error::Diagnostic;
467
468    #[test]
469    fn the_typed_environment_takes_the_declarations_over() {
470        let (tast, warnings) = built(
471            "struct S { a: byte; }\nconst N: int = 1;\nMemoryRegion mr(0x1000);
472             ProtectionDomain a(1);\nProtectionDomain b(2);\nChan c = a --> b;\nSystem = a ||| b;",
473            &[("a", "proc Init() { Skip; }"), ("b", "")],
474        )
475        .expect("builds");
476        assert!(warnings.is_empty());
477        assert_eq!(tast.tenv.file, "test.fis");
478        assert_eq!(tast.tenv.mrs.len(), 1);
479        assert_eq!(tast.tenv.pds.len(), 2);
480        assert_eq!(tast.tenv.chans.len(), 1);
481        assert_eq!(tast.tenv.structs.len(), 1);
482        assert_eq!(tast.tenv.consts.len(), 1);
483        assert_eq!(tast.tenv.composition.as_ref().map(|c| c.pds.len()), Some(2));
484        assert_eq!(tast.tenv.locals.len(), 2);
485        assert_eq!(tast.bodies.len(), 2);
486        assert_eq!(tast.tenv.pds[PdId::new(1)].fi, Path::new("b.fi"));
487        // Serialises, as `--emit=tast` needs.
488        let json = serde_json::to_value(&tast.tenv).expect("serialises");
489        assert_eq!(
490            json["consts"][0]["value"],
491            serde_json::json!({ "Int64": 1 })
492        );
493        assert_eq!(json["structs"][0]["size"], 1);
494    }
495
496    /// Every fault in the data layer is reported together,
497    /// and stops the build before a program's variables are typed on them;
498    /// those are reported once they type.
499    #[test]
500    fn every_data_layer_error_is_reported_before_the_build_fails() {
501        let err = built(
502            "const A: int = B;\nconst B: int = 2;\nstruct S { n: int; }\nProtectionDomain a(1);",
503            &[("a", "x: byte[A];")],
504        )
505        .expect_err("rejected");
506        let messages: Vec<&str> = err.0.iter().map(Diagnostic::message).collect();
507        assert_eq!(messages.len(), 2, "{messages:?}");
508        assert!(messages[0].starts_with("constant 'A':"), "{messages:?}");
509        assert!(messages[1].starts_with("struct 'S':"), "{messages:?}");
510        let err = built(
511            "const A: bool = true;\nProtectionDomain a(1);",
512            &[("a", "x: byte[A];")],
513        )
514        .expect_err("rejected");
515        let messages: Vec<&str> = err.0.iter().map(Diagnostic::message).collect();
516        assert!(messages[0].starts_with("variable 'x':"), "{messages:?}");
517    }
518}