Skip to main content

fic/tast/
body.rs

1//! Process and event bodies, typed, and their variables. The shapes are
2//! `rast`'s: a body's scope rules were settled there.
3
4use std::collections::HashMap;
5use std::ops::Range;
6
7use serde::Serialize;
8
9use crate::ast::{ChannelKind, IrqKind};
10use crate::base::{
11    BodyVarId, BodyVarKind, ChanId, DbgArg, Endpoint, EventId, PdId, ProcId, VarRef,
12};
13use crate::error::Diagnostic;
14use crate::rast;
15
16use super::env::Channel;
17use super::expr::{call, expr, Call, Expr};
18use super::fold::{all_constants, constants};
19use super::program::VarTables;
20use super::scope::Scope;
21use super::ty::Ty;
22
23/// A variable of one body.
24#[derive(Debug, Clone, Serialize)]
25pub struct BodyVar {
26    /// Its name.
27    pub name: String,
28    /// Its type: as declared, or for a receive binder its channel's
29    /// payload.
30    pub ty: Ty,
31    /// What declared it.
32    pub kind: BodyVarKind,
33    /// Byte span of the declaration.
34    pub span: Range<usize>,
35}
36
37/// A process term.
38#[derive(Debug, Clone, Serialize)]
39pub enum Proc {
40    /// Successful termination.
41    Skip,
42    /// Divergence.
43    Div,
44    /// `c -> ρ`.
45    Prefix(Event, Box<Proc>),
46    /// `ρ₁ ; ... ; ρₙ`.
47    Seq(Vec<Proc>),
48    /// `ρ₁ [] ... [] ρₙ`; a `default` arm was desugared by `rast`.
49    Choice(Vec<Proc>),
50    /// `[g] ρ`; the guard is `bool`.
51    Guard(Expr, Box<Proc>),
52    /// `Name(args)`: a reference to a process of the same program, each
53    /// argument of its parameter's type.
54    Ref {
55        /// The process.
56        process: ProcId,
57        /// The arguments, one per parameter.
58        args: Vec<VarRef>,
59        /// Byte span of the reference.
60        span: Range<usize>,
61    },
62    /// `x: T;`: declares the body var.
63    Decl(BodyVarId),
64}
65
66/// The event a prefix fires.
67#[derive(Debug, Clone, Serialize)]
68pub enum Event {
69    /// A computation event `e` or `e.x.y`, each carrier of its declared
70    /// type.
71    Comp {
72        /// The event.
73        event: EventId,
74        /// The carriers passed at the use, one per declared carrier.
75        carriers: Vec<VarRef>,
76        /// Byte span of the use.
77        span: Range<usize>,
78    },
79    /// A channel event.
80    Comm(Comm),
81    /// `irq?N` / `irq!N`.
82    Irq {
83        /// The IRQ number.
84        irq: u32,
85        /// Await or acknowledge.
86        kind: IrqKind,
87    },
88}
89
90/// A channel event, at an end of the channel this program holds.
91#[derive(Debug, Clone, Serialize)]
92pub enum Comm {
93    /// `c!e`, the payload of `Σ(c)`; `c!` on an unbuffered channel.
94    Send {
95        /// The channel.
96        chan: ChanId,
97        /// The payload, if the channel carries one.
98        expr: Option<Expr>,
99        /// Byte span of the use.
100        span: Range<usize>,
101    },
102    /// `c?x`, the binder of `Σ(c)`; `c?` on an unbuffered channel.
103    Recv {
104        /// The channel.
105        chan: ChanId,
106        /// The binder, an entry of the process's `body_vars`, if the
107        /// channel carries a value.
108        binder: Option<BodyVarId>,
109        /// Byte span of the use.
110        span: Range<usize>,
111    },
112}
113
114/// An event statement.
115#[derive(Debug, Clone, Serialize)]
116pub enum Stmt {
117    /// `x: T;`: declares the body var.
118    Decl(BodyVarId),
119    /// `x = e;`, the value of the variable's type.
120    Assign {
121        /// The variable written.
122        target: VarRef,
123        /// The value.
124        rhs: Expr,
125        /// Byte span of the statement.
126        span: Range<usize>,
127    },
128    /// `alias.f(args);`, its value unused.
129    Call(Call),
130    /// `dbg(args);`, each expression an integer, of any integer type, or a
131    /// `bool`.
132    Dbg {
133        /// The arguments, in order.
134        args: Vec<DbgArg<Expr>>,
135        /// Byte span of the statement.
136        span: Range<usize>,
137    },
138}
139
140/// Type an event's statements: an assignment's value takes the variable's
141/// type, a call statement needs no value, a `dbg` argument is an integer;
142/// the constant parts of each are folded in their types. `None` when one
143/// does not type.
144pub(super) fn statements(
145    stmts: &[rast::Stmt],
146    cx: &Scope<'_>,
147    errors: &mut Vec<Diagnostic>,
148) -> Option<Vec<Stmt>> {
149    let mut out = Vec::with_capacity(stmts.len());
150    let mut ok = true;
151    for s in stmts {
152        match s {
153            rast::Stmt::Decl(id) => out.push(Stmt::Decl(*id)),
154            rast::Stmt::Assign { target, rhs, span } => {
155                let ty = cx.var_ty(*target).clone();
156                let at = cx.at(&format!("assignment to '{}': ", cx.var_name(*target)));
157                match expr(rhs, Some(&ty), &at, errors) {
158                    Some(rhs) if constants(&rhs, &at, errors) => out.push(Stmt::Assign {
159                        target: *target,
160                        rhs,
161                        span: span.clone(),
162                    }),
163                    _ => ok = false,
164                }
165            }
166            rast::Stmt::Call(e) => {
167                let rast::ExprKind::Call { callee, args } = &e.kind else {
168                    unreachable!("a call statement is a call")
169                };
170                match call(*callee, args, false, &e.span, cx, errors) {
171                    Some(c) if all_constants(&c.args, cx, errors) => out.push(Stmt::Call(c)),
172                    _ => ok = false,
173                }
174            }
175            rast::Stmt::Dbg { args, span } => {
176                let at = cx.at("dbg: ");
177                let mut typed = Vec::with_capacity(args.len());
178                for arg in args {
179                    match arg {
180                        DbgArg::Text(t) => typed.push(DbgArg::Text(t.clone())),
181                        DbgArg::Expr(e) => match expr(e, None, &at, errors) {
182                            Some(e) if e.ty.integer().is_none() && e.ty != Ty::BOOL => {
183                                let message = format!(
184                                    "expected an integer or a bool, found '{}'",
185                                    at.show(&e.ty)
186                                );
187                                at.fail(errors, &message, &e.span);
188                                ok = false;
189                            }
190                            Some(e) if constants(&e, &at, errors) => typed.push(DbgArg::Expr(e)),
191                            _ => ok = false,
192                        },
193                    }
194                }
195                out.push(Stmt::Dbg {
196                    args: typed,
197                    span: span.clone(),
198                });
199            }
200        }
201    }
202    ok.then_some(out)
203}
204
205/// Type a process term: a guard is `bool`; a send is at an end of the
206/// channel that may send, with a payload of the channel's type iff the
207/// channel is buffered; a receive at an end that may receive, with a
208/// binder iff the channel is buffered; a computation event's carriers and
209/// a process reference's arguments of the declared types. `None` when one
210/// does not type.
211pub(super) fn process(
212    p: &rast::Proc,
213    cx: &Scope<'_>,
214    errors: &mut Vec<Diagnostic>,
215) -> Option<Proc> {
216    Some(match p {
217        rast::Proc::Skip => Proc::Skip,
218        rast::Proc::Div => Proc::Div,
219        rast::Proc::Decl(id) => Proc::Decl(*id),
220        rast::Proc::Prefix(evt, rest) => {
221            let evt = event(evt, cx, errors);
222            let rest = process(rest, cx, errors);
223            Proc::Prefix(evt?, Box::new(rest?))
224        }
225        rast::Proc::Seq(parts) => Proc::Seq(all(parts, cx, errors)?),
226        rast::Proc::Choice(branches) => Proc::Choice(all(branches, cx, errors)?),
227        rast::Proc::Guard(g, inner) => {
228            let at = cx.at("guard: ");
229            let g = expr(g, Some(&Ty::BOOL), &at, errors).filter(|g| constants(g, &at, errors));
230            let inner = process(inner, cx, errors);
231            Proc::Guard(g?, Box::new(inner?))
232        }
233        rast::Proc::Ref {
234            process: id,
235            args,
236            span,
237        } => {
238            let target = &cx.written().processes[*id].sig;
239            let params = cx.tables().processes[*id].iter().take(target.params.len());
240            let ok = arguments("argument", &target.name, args, params, span, cx, errors);
241            ok.then(|| Proc::Ref {
242                process: *id,
243                args: args.clone(),
244                span: span.clone(),
245            })?
246        }
247    })
248}
249
250/// Each of `args`, the variables a process reference or a computation
251/// event passes, against the `declared` body var it binds (`what` names the
252/// position: `argument`, `carrier`); whether every one is a subtype.
253fn arguments<'a>(
254    what: &str,
255    callee: &str,
256    args: &[VarRef],
257    declared: impl Iterator<Item = &'a BodyVar>,
258    span: &Range<usize>,
259    cx: &Scope<'_>,
260    errors: &mut Vec<Diagnostic>,
261) -> bool {
262    let mut ok = true;
263    for (arg, local) in args.iter().zip(declared) {
264        let found = cx.var_ty(*arg);
265        if !found.is_subtype(&local.ty) {
266            let at = cx.at(&format!("{what} '{}' of '{callee}': ", cx.var_name(*arg)));
267            at.fail(
268                errors,
269                &format!(
270                    "expected '{}', found '{}'",
271                    cx.show(&local.ty),
272                    cx.show(found)
273                ),
274                span,
275            );
276            ok = false;
277        }
278    }
279    ok
280}
281
282/// Type every term of `parts`, reporting each that does not type.
283fn all(parts: &[rast::Proc], cx: &Scope<'_>, errors: &mut Vec<Diagnostic>) -> Option<Vec<Proc>> {
284    let typed: Vec<Option<Proc>> = parts.iter().map(|p| process(p, cx, errors)).collect();
285    typed.into_iter().collect()
286}
287
288fn event(evt: &rast::Event, cx: &Scope<'_>, errors: &mut Vec<Diagnostic>) -> Option<Event> {
289    Some(match evt {
290        rast::Event::Irq { irq, kind } => Event::Irq {
291            irq: *irq,
292            kind: *kind,
293        },
294        rast::Event::Comp {
295            event,
296            carriers,
297            span,
298        } => {
299            let decl = &cx.written().events[*event].sig;
300            let declared = cx.tables().events[*event].iter().take(decl.carriers.len());
301            let ok = arguments("carrier", &decl.name, carriers, declared, span, cx, errors);
302            ok.then(|| Event::Comp {
303                event: *event,
304                carriers: carriers.clone(),
305                span: span.clone(),
306            })?
307        }
308        rast::Event::Comm(rast::Comm::Send {
309            chan,
310            expr: e,
311            span,
312        }) => {
313            let ch = endpoint(*chan, Endpoint::Sender, span, cx, errors)?;
314            let channel = &cx.typed().chans[*chan];
315            let payload = channel.payload.as_ref();
316            let e = match (e, payload) {
317                (Some(e), Some(payload)) => {
318                    let at = cx.at(&format!("send on '{ch}': "));
319                    Some(
320                        expr(e, Some(payload), &at, errors)
321                            .filter(|e| constants(e, &at, errors))?,
322                    )
323                }
324                (None, None) => None,
325                (Some(_), None) => {
326                    cx.fail(errors, &no_value(channel, "!"), span);
327                    return None;
328                }
329                (None, Some(t)) => {
330                    cx.fail(errors, &carries(ch, &cx.show(t), "!e"), span);
331                    return None;
332                }
333            };
334            Event::Comm(Comm::Send {
335                chan: *chan,
336                expr: e,
337                span: span.clone(),
338            })
339        }
340        rast::Event::Comm(rast::Comm::Recv { chan, binder, span }) => {
341            let ch = endpoint(*chan, Endpoint::Receiver, span, cx, errors)?;
342            // A binder on an unbuffered channel is its body var's error.
343            if let (None, Some(t)) = (binder, &cx.typed().chans[*chan].payload) {
344                cx.fail(errors, &carries(ch, &cx.show(t), "?x"), span);
345                return None;
346            }
347            Event::Comm(Comm::Recv {
348                chan: *chan,
349                binder: *binder,
350                span: span.clone(),
351            })
352        }
353    })
354}
355
356/// A value or binder on a channel that carries none; `form` is the event to
357/// write instead (`!` or `?`). An async channel's value is its buffer's, a
358/// sync channel's its declared `Sync Chan<T>`.
359pub(super) fn no_value(chan: &Channel, form: &str) -> String {
360    let ch = &chan.name;
361    let declare = match chan.kind {
362        ChannelKind::SyncUni => ", or declare `Sync Chan<T>`",
363        ChannelKind::AsyncUni => ", or give it a buffer (`via region<T>`)",
364        ChannelKind::AsyncBi => "",
365    };
366    format!("channel '{ch}' carries no value: write `{ch}{form}`{declare}")
367}
368
369/// A send or receive without the value its buffered channel carries.
370fn carries(ch: &str, ty: &str, form: &str) -> String {
371    format!("channel '{ch}' carries a '{ty}': write `{ch}{form}`")
372}
373
374/// Check this program may use `chan` as `want` (send at a sending end,
375/// receive at a receiving end); a bidirectional channel's ends do both.
376/// Returns the channel's name.
377fn endpoint<'a>(
378    chan: ChanId,
379    want: Endpoint,
380    span: &Range<usize>,
381    cx: &Scope<'a>,
382    errors: &mut Vec<Diagnostic>,
383) -> Option<&'a str> {
384    let ch = &cx.typed().chans[chan];
385    let at = cx.pd();
386    let pd = &cx.env.pds[at].name;
387    let (role, other) = match want {
388        Endpoint::Sender => ("receiver", "send"),
389        Endpoint::Receiver => ("sender", "receive"),
390    };
391    match ch.end(at) {
392        None => {
393            cx.fail(
394                errors,
395                &format!(
396                    "channel '{}' does not connect protection domain '{pd}'",
397                    ch.name
398                ),
399                span,
400            );
401            None
402        }
403        Some((held, _)) if held != want && ch.kind != ChannelKind::AsyncBi => {
404            cx.fail(
405                errors,
406                &format!(
407                    "channel '{}': '{pd}' is its {role} and may not {other}",
408                    ch.name
409                ),
410                span,
411            );
412            None
413        }
414        Some(_) => Some(&ch.name),
415    }
416}
417
418/// The receive binders of one name, across a program's processes, share
419/// one type.
420pub(super) fn binders(
421    id: PdId,
422    tables: &VarTables,
423    written: &rast::Body,
424    env: &rast::Env,
425    errors: &mut Vec<Diagnostic>,
426) {
427    let mut first: HashMap<&str, (ChanId, &Ty)> = HashMap::new();
428    for (q, body_vars) in tables.processes.iter_enumerated() {
429        for l in body_vars.iter() {
430            let BodyVarKind::Binder { chan } = l.kind else {
431                continue;
432            };
433            match first.get(l.name.as_str()) {
434                Some((on, ty)) if **ty != l.ty => errors.push(Diagnostic::at(
435                    format!(
436                        "process '{}': receive binder '{}' is bound on '{}' as '{}' but on '{}' as '{}'",
437                        written.processes[q].sig.name,
438                        l.name,
439                        env.chans[*on].name,
440                        ty.display(env),
441                        env.chans[chan].name,
442                        l.ty.display(env)
443                    ),
444                    l.span.clone(),
445                    &env.pds[id].fi,
446                )),
447                Some(_) => {}
448                None => {
449                    first.insert(&l.name, (chan, &l.ty));
450                }
451            }
452        }
453    }
454}
455
456#[cfg(test)]
457mod tests {
458    use crate::tast::env::built;
459
460    const FIS: &str = "struct Slot { len: uint16; }
461        MemoryRegion ring(0x1000);
462        MemoryRegion ring2(0x1000);
463        ProtectionDomain a(1);
464        ProtectionDomain b(2);
465        ProtectionDomain c(3);
466        Chan uni = a --> b via ring<Slot>;
467        Chan bi = a <-> b;
468        Chan far = b --> c;
469        Chan bbuf = a --> b via ring2<uint8>;
470        Sync Chan call = a --> b;
471        Sync Chan<int32> ask = a --> b;";
472
473    /// The diagnostics of program `pd`'s `rest`, around the entry points.
474    fn errors(pd: &str, rest: &str) -> Vec<String> {
475        let src = format!(
476            "@bind(microkit.init) proc Init() {{ Skip; }}
477             @bind(microkit.notified) proc Notified() {{ Skip; }}
478             {rest}"
479        );
480        built(FIS, &[(pd, &src)])
481            .expect_err("rejected")
482            .0
483            .iter()
484            .map(|d| d.message().to_owned())
485            .collect()
486    }
487
488    fn rejects(pd: &str, rest: &str, needle: &str) {
489        let e = errors(pd, rest);
490        assert!(
491            e.iter().any(|m| m.contains(needle)),
492            "missing {needle:?} in {e:?}"
493        );
494    }
495
496    fn types(pd: &str, rest: &str) {
497        let src = format!(
498            "@bind(microkit.init) proc Init() {{ Skip; }}
499             @bind(microkit.notified) proc Notified() {{ Skip; }}
500             {rest}"
501        );
502        built(FIS, &[(pd, &src)]).expect("types");
503    }
504
505    #[test]
506    fn a_guard_is_a_bool() {
507        types(
508            "a",
509            "n: int; proc P() { [n < 3] bi! -> Skip default Skip; }",
510        );
511        rejects(
512            "a",
513            "n: int; proc P() { [n] bi! -> Skip default Skip; }",
514            "process 'P': guard: expected 'bool', found 'int64'",
515        );
516    }
517
518    #[test]
519    fn a_send_carries_the_channels_payload() {
520        types("a", "s: Slot; proc P() { uni!s -> Skip; }");
521        types("a", "proc P() { bbuf!7 -> Skip; }");
522        rejects(
523            "a",
524            "proc P() { uni!0 -> Skip; }",
525            "process 'P': send on 'uni': expected 'Slot', found 'int64'",
526        );
527        rejects(
528            "a",
529            "proc P() { bbuf!300 -> Skip; }",
530            "out of range for uint8",
531        );
532    }
533
534    #[test]
535    fn a_channel_is_used_only_at_its_ends_and_in_its_direction() {
536        // A one-way channel: its sender sends, its receiver receives.
537        types("b", "proc P() { uni?s -> far! -> Skip; }");
538        rejects(
539            "b",
540            "s: Slot; proc P() { uni!s -> Skip; }",
541            "process 'P': channel 'uni': 'b' is its receiver and may not send",
542        );
543        rejects(
544            "a",
545            "proc P() { uni?s -> Skip; }",
546            "process 'P': channel 'uni': 'a' is its sender and may not receive",
547        );
548        // A two-way channel: both ends do both.
549        types("b", "proc P() { bi? -> bi! -> Skip; }");
550        rejects(
551            "a",
552            "proc P() { far! -> Skip; }",
553            "process 'P': channel 'far' does not connect protection domain 'a'",
554        );
555    }
556
557    #[test]
558    fn carriers_and_arguments_have_the_declared_types() {
559        types(
560            "b",
561            "evt e.|s: Slot|: k: int; proc P() { uni?m -> e.m -> Skip; }",
562        );
563        rejects(
564            "b",
565            "evt e.|n: int|: y: int; proc P() { bbuf?x -> e.x -> Skip; }",
566            "process 'P': carrier 'x' of 'e': expected 'int64', found 'uint8'",
567        );
568        types("b", "proc Q(s: Slot) { Skip; } proc P() { uni?m -> Q(m); }");
569        rejects(
570            "b",
571            "proc Q(n: int) { Skip; } proc P() { bbuf?x -> Q(x); }",
572            "process 'P': argument 'x' of 'Q': expected 'int64', found 'uint8'",
573        );
574    }
575
576    #[test]
577    fn binders_of_one_name_share_a_type() {
578        rejects(
579            "b",
580            "proc P() { uni?m -> Skip; } proc Q() { bbuf?m -> Skip; }",
581            "receive binder 'm' is bound on 'uni' as 'Slot' but on 'bbuf' as 'uint8'",
582        );
583        types(
584            "b",
585            "proc P() { bbuf?m -> Skip; } proc Q() { bbuf?m -> Skip; }",
586        );
587    }
588
589    #[test]
590    fn only_a_buffered_channel_carries_a_value() {
591        rejects(
592            "a",
593            "proc P() { bi!1 -> Skip; }",
594            "process 'P': channel 'bi' carries no value: write `bi!`",
595        );
596        rejects(
597            "b",
598            "proc P() { bi?x -> Skip; }",
599            "process 'P', receive binder 'x': channel 'bi' carries no value: write `bi?`",
600        );
601        rejects(
602            "b",
603            "proc P() { far!1 -> Skip; }",
604            "channel 'far' carries no value: write `far!`, or give it a buffer (`via region<T>`)",
605        );
606    }
607
608    #[test]
609    fn a_sync_channel_carries_its_declared_value() {
610        rejects(
611            "a",
612            "proc P() { call!1 -> Skip; }",
613            "channel 'call' carries no value: write `call!`, or declare `Sync Chan<T>`",
614        );
615        rejects(
616            "b",
617            "proc P() { call?x -> Skip; }",
618            "channel 'call' carries no value: write `call?`, or declare `Sync Chan<T>`",
619        );
620        rejects(
621            "a",
622            "proc P() { ask! -> Skip; }",
623            "channel 'ask' carries a 'int32': write `ask!e`",
624        );
625        rejects(
626            "b",
627            "proc P() { ask? -> Skip; }",
628            "channel 'ask' carries a 'int32': write `ask?x`",
629        );
630        let src = "@bind(microkit.init) proc Init() { Skip; }
631                   @bind(microkit.notified) proc Notified() { ask!7 -> Skip; }";
632        built(FIS, &[("a", src)]).expect("a typed sync send");
633    }
634
635    #[test]
636    fn a_buffered_channel_always_carries_its_value() {
637        rejects(
638            "a",
639            "proc P() { uni! -> Skip; }",
640            "process 'P': channel 'uni' carries a 'Slot': write `uni!e`",
641        );
642        rejects(
643            "b",
644            "proc P() { uni? -> Skip; }",
645            "process 'P': channel 'uni' carries a 'Slot': write `uni?x`",
646        );
647    }
648}