Skip to main content

fic/rast/
body.rs

1//! Process and event bodies, resolved, and their variables: [`Bodies`],
2//! which `rast::build` returns beside the declarations and typing
3//! consumes.
4//!
5//! Each body owns one table of its variables, [`BodyVar`]s indexed by
6//! `BodyVarId`: a process's parameters, `x: T;` declarations and receive
7//! binders (its proc vars); an event's carriers and declarations (its evt
8//! vars). A use refers to its entry, so a backend allocates one slot per
9//! entry, and two variables of one name in
10//! different scopes are two entries.
11//!
12//! # Scopes
13//!
14//! A body's names are looked up in its frames, innermost first, then the
15//! program's locals, then the system's consts. Event and process scopes
16//! are disjoint: a process value reaches an event only through a carrier.
17//!
18//! - A process's parameters are in scope for its whole body; a `x: T;`
19//!   from there to the end of its sequence; a receive binder `c?x` for the
20//!   prefix's continuation only, so it is gone at the `;`.
21//! - Each branch of a choice starts from the same frames: a sibling's
22//!   binder is invisible.
23//! - A reference `P(args)` resolves its arguments where it is written and
24//!   does not enter `P`: a binder reaches a helper only as an argument.
25//! - An event's carriers are in scope for its whole body and read-only;
26//!   its `x: T;` from there to the end.
27//!
28//! Redeclaring a name of the same body that is still in scope is an
29//! error; shadowing a local, a mapping or a system const is a warning.
30
31use std::mem::take;
32use std::ops::Range;
33
34use serde::Serialize;
35
36use crate::ast::{self, CommKind, IrqKind, Statement, Type};
37use crate::base::{
38    BodyVarId, BodyVarKind, ChanId, DbgArg, Entry, EventDecl, EventId, IdVec, PdId, ProcId,
39    ProcessDecl, TypeRef, VarRef,
40};
41use crate::error::Diagnostic;
42
43use super::desugar::otherwise;
44use super::expr::{call, fail, lower, Scope};
45use super::scope::{BodyScope, Outer};
46use super::Expr;
47
48/// Every body of a project: one [`Body`] per program, by the
49/// program's id.
50pub type Bodies = IdVec<PdId, Body>;
51
52/// A program's code: its events and processes, each its signature beside
53/// its body, and its entry points.
54#[derive(Debug, Clone, Default, Serialize)]
55pub struct Body {
56    /// Each event, in source order.
57    pub events: IdVec<EventId, EventBody>,
58    /// Each process, in source order.
59    pub processes: IdVec<ProcId, ProcBody>,
60    /// Platform entry points, each bound to its process.
61    pub entries: Vec<Entry>,
62}
63
64/// An event: its signature, variables and statements.
65#[derive(Debug, Clone, Serialize)]
66pub struct EventBody {
67    /// Its signature.
68    pub sig: EventDecl,
69    /// Every variable: the carriers, in order, then the declarations in source order.
70    pub body_vars: IdVec<BodyVarId, BodyVar>,
71    /// The statements.
72    pub body: Vec<Stmt>,
73}
74
75/// A process: its signature, variables and term.
76#[derive(Debug, Clone, Serialize)]
77pub struct ProcBody {
78    /// Its signature.
79    pub sig: ProcessDecl,
80    /// Every variable: the parameters, in order, then `x: T;` declarations and
81    /// receive binders in source order.
82    pub body_vars: IdVec<BodyVarId, BodyVar>,
83    /// The process term.
84    pub body: Proc,
85}
86
87/// A variable of one body.
88#[derive(Debug, Clone, Serialize)]
89pub struct BodyVar {
90    /// Its name.
91    pub name: String,
92    /// Its declared type; `None` for a parameter or carrier, whose type is
93    /// its signature's, and for a receive binder, whose type is its
94    /// channel's payload.
95    pub ty: Option<TypeRef>,
96    /// What declared it.
97    pub kind: BodyVarKind,
98    /// Byte span of the declaration.
99    pub span: Range<usize>,
100}
101
102/// A process term.
103#[derive(Debug, Clone, Serialize)]
104pub enum Proc {
105    /// Successful termination.
106    Skip,
107    /// Divergence.
108    Div,
109    /// `c -> ρ`.
110    Prefix(Event, Box<Proc>),
111    /// `ρ₁ ; ... ; ρₙ`.
112    Seq(Vec<Proc>),
113    /// `ρ₁ [] ... [] ρₙ`. A `default` arm is one more branch, guarded by
114    /// the negation of the others' conditions (`desugar.rs`).
115    Choice(Vec<Proc>),
116    /// `[g] ρ`.
117    Guard(Expr, Box<Proc>),
118    /// `Name(args)`: a reference to a process of the same program.
119    Ref {
120        /// The process.
121        process: ProcId,
122        /// The arguments, one per parameter.
123        args: Vec<VarRef>,
124        /// Byte span of the reference.
125        span: Range<usize>,
126    },
127    /// `x: T;`: declares the body var.
128    Decl(BodyVarId),
129}
130
131/// The event a prefix fires.
132#[derive(Debug, Clone, Serialize)]
133pub enum Event {
134    /// A computation event `e` or `e.x.y`.
135    Comp {
136        /// The event.
137        event: EventId,
138        /// The carriers passed at the use, one per declared carrier.
139        carriers: Vec<VarRef>,
140        /// Byte span of the use.
141        span: Range<usize>,
142    },
143    /// A channel event.
144    Comm(Comm),
145    /// `irq?N` / `irq!N`.
146    Irq {
147        /// The IRQ number.
148        irq: u32,
149        /// Await or acknowledge.
150        kind: IrqKind,
151    },
152}
153
154/// A channel event.
155#[derive(Debug, Clone, Serialize)]
156pub enum Comm {
157    /// `c!e`, or `c!`.
158    Send {
159        /// The channel.
160        chan: ChanId,
161        /// The payload, if any.
162        expr: Option<Expr>,
163        /// Byte span of the use.
164        span: Range<usize>,
165    },
166    /// `c?x`, or `c?`.
167    Recv {
168        /// The channel.
169        chan: ChanId,
170        /// The binder, an entry of the process's `body_vars`, if any.
171        binder: Option<BodyVarId>,
172        /// Byte span of the use.
173        span: Range<usize>,
174    },
175}
176
177/// An event statement.
178#[derive(Debug, Clone, Serialize)]
179pub enum Stmt {
180    /// `x: T;`: declares the body var.
181    Decl(BodyVarId),
182    /// `x = e;`.
183    Assign {
184        /// The variable written.
185        target: VarRef,
186        /// The value.
187        rhs: Expr,
188        /// Byte span of the statement.
189        span: Range<usize>,
190    },
191    /// `alias.f(args);`, an [`ExprKind::Call`](super::ExprKind::Call).
192    Call(Expr),
193    /// `dbg(args);`: no argument calls a function.
194    Dbg {
195        /// The arguments, in order.
196        args: Vec<DbgArg<Expr>>,
197        /// Byte span of the statement.
198        span: Range<usize>,
199    },
200}
201
202/// Lower `ast`'s body, its parameters its first body vars.
203pub(super) fn process(
204    ast: &ast::ProcessDecl,
205    entry: bool,
206    outer: &Outer<'_, '_>,
207    errors: &mut Vec<Diagnostic>,
208) -> ProcBody {
209    let context = format!("process '{}': ", ast.name);
210    let mut w = Walker::new(outer, context, false, errors);
211    if entry && !ast.params.is_empty() {
212        w.error("an entry point takes no parameters", &ast.span);
213    }
214    let params = w.signature(&ast.params, BodyVarKind::Param, &ast.span, "parameter");
215    let body = w.proc(&ast.body).unwrap_or(Proc::Skip);
216    ProcBody {
217        sig: ProcessDecl {
218            name: ast.name.clone(),
219            params,
220            span: ast.span.clone(),
221        },
222        body_vars: take(&mut w.body_vars),
223        body,
224    }
225}
226
227/// Lower `ast`'s statements, its carriers its first body vars.
228pub(super) fn event(
229    ast: &ast::EvtDecl,
230    outer: &Outer<'_, '_>,
231    errors: &mut Vec<Diagnostic>,
232) -> EventBody {
233    let mut w = Walker::new(outer, format!("event '{}': ", ast.name), true, errors);
234    let carriers = w.signature(&ast.carriers, BodyVarKind::Carrier, &ast.span, "carrier");
235    let body = ast.body.iter().filter_map(|s| w.stmt(s)).collect();
236    let prints = ast.body.iter().any(|s| matches!(s, Statement::Dbg(_)));
237    let works = ast
238        .body
239        .iter()
240        .any(|s| matches!(s, Statement::Assign(_) | Statement::Call(_)));
241    if prints && !works {
242        w.errors.push(Diagnostic::warn_at(
243            format!(
244                "{}only prints: the model leaves 'dbg' out, so there the event does \
245                 nothing; put the 'dbg' in an event that does work",
246                w.scope.context
247            ),
248            ast.span.clone(),
249            outer.file,
250        ));
251    }
252    EventBody {
253        sig: EventDecl {
254            name: ast.name.clone(),
255            carriers,
256            span: ast.span.clone(),
257        },
258        body_vars: take(&mut w.body_vars),
259        body,
260    }
261}
262
263/// One body's walk: its variable table, and the frames in scope.
264struct Walker<'w, 'a, 's> {
265    scope: BodyScope<'w, 'a, 's>,
266    body_vars: IdVec<BodyVarId, BodyVar>,
267    errors: &'w mut Vec<Diagnostic>,
268}
269
270impl<'w, 'a, 's> Walker<'w, 'a, 's> {
271    fn new(
272        outer: &'w Outer<'a, 's>,
273        context: String,
274        event: bool,
275        errors: &'w mut Vec<Diagnostic>,
276    ) -> Self {
277        Self {
278            scope: BodyScope {
279                outer,
280                context,
281                event,
282                frames: Vec::new(),
283            },
284            body_vars: IdVec::new(),
285            errors,
286        }
287    }
288
289    fn error(&mut self, message: &str, span: &Range<usize>) {
290        fail::<()>(&self.scope, self.errors, message, span);
291    }
292
293    fn expr(&mut self, e: &ast::Expr) -> Option<Expr> {
294        lower(e, &self.scope, self.errors)
295    }
296
297    /// The variable `name`, reported at `span` when it denotes none.
298    fn var(&mut self, name: &str, span: &Range<usize>) -> Option<VarRef> {
299        let var = self.scope.var(name);
300        if var.is_none() {
301            let message = self.scope.undeclared(name);
302            self.error(&message, span);
303        }
304        var
305    }
306
307    /// A signature's variables, the body's first vars in order, each in
308    /// scope for the whole body, typed by the signature.
309    fn signature(
310        &mut self,
311        decls: &[(Type, String)],
312        kind: BodyVarKind,
313        span: &Range<usize>,
314        what: &str,
315    ) -> Vec<TypeRef> {
316        let mut types = Vec::new();
317        for (ty, name) in decls {
318            match self.scope.type_ref(ty) {
319                Ok(ty) => types.push(ty),
320                Err(message) => self.error(&message, span),
321            }
322            let id = self.body_vars.push(BodyVar {
323                name: name.clone(),
324                ty: None,
325                kind,
326                span: span.clone(),
327            });
328            self.open(id, what);
329        }
330        types
331    }
332
333    /// Bring `body_vars[id]` into scope; `what` names it in diagnostics.
334    fn open(&mut self, id: BodyVarId, what: &str) {
335        let (name, span) = (
336            self.body_vars[id].name.clone(),
337            self.body_vars[id].span.clone(),
338        );
339        if self.scope.frames.iter().any(|(n, _)| *n == name) {
340            let body = if self.scope.event { "event" } else { "process" };
341            self.error(
342                &format!("'{name}' is already declared in this {body}"),
343                &span,
344            );
345        } else if let Some(kind) = self.scope.outer.shadowed(&name) {
346            self.errors.push(Diagnostic::warn_at(
347                format!(
348                    "{}{what} '{name}' shadows {kind} '{name}'",
349                    self.scope.context
350                ),
351                span.clone(),
352                self.scope.outer.file,
353            ));
354        }
355        self.scope.frames.push((name, id));
356    }
357
358    /// Declare a new variable of this body and bring it into scope.
359    fn declare(
360        &mut self,
361        name: &str,
362        ty: Option<&Type>,
363        kind: BodyVarKind,
364        span: &Range<usize>,
365    ) -> BodyVarId {
366        let ty = ty.and_then(|t| match self.scope.type_ref(t) {
367            Ok(t) => Some(t),
368            Err(message) => {
369                self.error(&message, span);
370                None
371            }
372        });
373        let id = self.body_vars.push(BodyVar {
374            name: name.to_owned(),
375            ty,
376            kind,
377            span: span.clone(),
378        });
379        let what = if matches!(kind, BodyVarKind::Binder { .. }) {
380            "receive binder"
381        } else {
382            "variable"
383        };
384        self.open(id, what);
385        id
386    }
387
388    fn proc(&mut self, p: &ast::Process) -> Option<Proc> {
389        Some(match p {
390            ast::Process::Skip => Proc::Skip,
391            ast::Process::Div => Proc::Div,
392            ast::Process::Prefix(evt, rest) => {
393                let mark = self.scope.frames.len();
394                let event = self.event(evt);
395                let rest = self.proc(rest);
396                self.scope.frames.truncate(mark);
397                Proc::Prefix(event?, Box::new(rest?))
398            }
399            ast::Process::Seq(items) => {
400                let mark = self.scope.frames.len();
401                let items: Vec<_> = items.iter().map(|q| self.proc(q)).collect();
402                self.scope.frames.truncate(mark);
403                Proc::Seq(items.into_iter().collect::<Option<_>>()?)
404            }
405            ast::Process::Choice { branches, default } => {
406                let mark = self.scope.frames.len();
407                let arm = |w: &mut Self, q: &ast::Process| {
408                    let q = w.proc(q);
409                    w.scope.frames.truncate(mark);
410                    q
411                };
412                let branches: Vec<_> = branches.iter().map(|b| arm(self, b)).collect();
413                let default = default.as_ref().map(|d| arm(self, d));
414                let mut branches: Vec<Proc> = branches.into_iter().collect::<Option<_>>()?;
415                if let Some(d) = default {
416                    let guard = otherwise(&branches);
417                    branches.push(Proc::Guard(guard, Box::new(d?)));
418                }
419                Proc::Choice(branches)
420            }
421            ast::Process::Guard(g, inner) => {
422                let g = self.expr(g);
423                let inner = self.proc(inner);
424                Proc::Guard(g?, Box::new(inner?))
425            }
426            ast::Process::ProcessRef { name, params, span } => {
427                let process = self.scope.outer.processes.get(name.as_str()).copied();
428                let args: Vec<_> = params.iter().map(|a| self.var(a, span)).collect();
429                let Some(process) = process else {
430                    self.error(&format!("process '{name}' is not declared"), span);
431                    return None;
432                };
433                let expected = self.scope.outer.arity.0[process];
434                if params.len() != expected {
435                    let found = params.len();
436                    let message =
437                        format!("process '{name}' takes {expected} argument(s), found {found}");
438                    self.error(&message, span);
439                    return None;
440                }
441                Proc::Ref {
442                    process,
443                    args: args.into_iter().collect::<Option<_>>()?,
444                    span: span.clone(),
445                }
446            }
447            ast::Process::Decl(v) => Proc::Decl(self.declare(
448                &v.var_name,
449                Some(&v.type_name),
450                BodyVarKind::Decl,
451                &v.span,
452            )),
453        })
454    }
455
456    /// The event a prefix fires. A receive declares its binder, left in
457    /// scope for the caller to drop after the continuation.
458    fn event(&mut self, evt: &ast::Event) -> Option<Event> {
459        Some(match evt {
460            ast::Event::CPEvent {
461                name,
462                carriers,
463                span,
464            } => {
465                let event = self.scope.outer.events.get(name.as_str()).copied();
466                let carriers: Vec<_> = carriers.iter().map(|a| self.var(a, span)).collect();
467                let Some(event) = event else {
468                    self.error(&format!("event '{name}' is not declared"), span);
469                    return None;
470                };
471                let expected = self.scope.outer.arity.1[event];
472                if carriers.len() != expected {
473                    let found = carriers.len();
474                    let message =
475                        format!("event '{name}' expects {expected} carrier(s), found {found}");
476                    self.error(&message, span);
477                    return None;
478                }
479                Event::Comp {
480                    event,
481                    carriers: carriers.into_iter().collect::<Option<_>>()?,
482                    span: span.clone(),
483                }
484            }
485            ast::Event::CMEvent {
486                channel,
487                kind,
488                span,
489            } => {
490                let Some(&chan) = self.scope.outer.names.chans.get(channel.as_str()) else {
491                    self.error(&format!("channel '{channel}' is not declared"), span);
492                    return None;
493                };
494                Event::Comm(match kind {
495                    CommKind::Send { expr } => Comm::Send {
496                        chan,
497                        expr: match expr {
498                            Some(e) => Some(self.expr(e)?),
499                            None => None,
500                        },
501                        span: span.clone(),
502                    },
503                    CommKind::Recv { var } => Comm::Recv {
504                        chan,
505                        binder: var
506                            .as_ref()
507                            .map(|v| self.declare(v, None, BodyVarKind::Binder { chan }, span)),
508                        span: span.clone(),
509                    },
510                })
511            }
512            ast::Event::IEVENT { irq, kind } => Event::Irq {
513                irq: *irq,
514                kind: *kind,
515            },
516        })
517    }
518
519    fn stmt(&mut self, s: &Statement) -> Option<Stmt> {
520        Some(match s {
521            Statement::Decl(v) => Stmt::Decl(self.declare(
522                &v.var_name,
523                Some(&v.type_name),
524                BodyVarKind::EventDecl,
525                &v.span,
526            )),
527            Statement::Assign(a) => {
528                let target = self.var(&a.var_name, &a.span);
529                let rhs = self.expr(&a.rhs);
530                let target = target?;
531                let read_only = match target {
532                    VarRef::Body(id) if self.body_vars[id].kind == BodyVarKind::Carrier => {
533                        Some(format!(
534                            "cannot assign to carrier '{}' (carriers are read-only)",
535                            a.var_name
536                        ))
537                    }
538                    VarRef::Const(_) => Some(format!("cannot assign to constant '{}'", a.var_name)),
539                    _ => None,
540                };
541                if let Some(message) = read_only {
542                    self.error(&message, &a.span);
543                    return None;
544                }
545                Stmt::Assign {
546                    target,
547                    rhs: rhs?,
548                    span: a.span.clone(),
549                }
550            }
551            Statement::Call(c) => Stmt::Call(call(c, &self.scope, self.errors)?),
552            Statement::Dbg(d) => {
553                let mut args = Vec::with_capacity(d.args.len());
554                for arg in &d.args {
555                    args.push(match arg {
556                        ast::DbgArg::Text(t) => Some(DbgArg::Text(t.clone())),
557                        ast::DbgArg::Expr(e) => match first_call(e) {
558                            Some(c) => {
559                                let message = format!(
560                                    "dbg arguments must be free of side effects: \
561                                     '{}.{}' is a call",
562                                    c.alias, c.fn_name
563                                );
564                                self.error(&message, &c.span);
565                                None
566                            }
567                            None => self.expr(e).map(DbgArg::Expr),
568                        },
569                    });
570                }
571                Stmt::Dbg {
572                    args: args.into_iter().collect::<Option<_>>()?,
573                    span: d.span.clone(),
574                }
575            }
576        })
577    }
578}
579
580/// The first call in `e`, if any.
581fn first_call(e: &ast::Expr) -> Option<&ast::CExpr> {
582    match &e.kind {
583        ast::ExprKind::Call(c) => Some(c),
584        ast::ExprKind::Lit(_) | ast::ExprKind::Var(_) | ast::ExprKind::Sizeof(_) => None,
585        ast::ExprKind::Unary { operand, .. } => first_call(operand),
586        ast::ExprKind::Binary { lhs, rhs, .. } => first_call(lhs).or_else(|| first_call(rhs)),
587        ast::ExprKind::Field { expr, .. } | ast::ExprKind::Cast { expr, .. } => first_call(expr),
588    }
589}
590
591/// A declaration owning a body's variable table.
592#[cfg(test)]
593mod tests {
594    use super::*;
595    use crate::base::{Idx, LocalVarId, MappingId, PdId};
596    use crate::error::Diagnostics;
597    use crate::rast::env::{built, built_with};
598    use crate::rast::{ExprKind, Rast};
599
600    const FIS: &str = "const K: int = 1;
601        MemoryRegion mr(0x1000);
602        ProtectionDomain a(1);
603        ProtectionDomain b(2);
604        Chan c = a <-> b;";
605
606    /// Program `a` with the entry points around `rest`, its import `x.pnk`
607    /// exporting `f`.
608    fn program(rest: &str) -> Result<(Rast, Diagnostics), Diagnostics> {
609        let src = format!(
610            r#"import "x.pnk" as x;
611            Mapping m(mr, "rw");
612            g: int;
613            @bind(microkit.init)
614            proc Init() {{ Skip; }}
615            @bind(microkit.notified)
616            proc Notified() {{ Skip; }}
617            {rest}"#
618        );
619        built_with(
620            FIS,
621            &[("a", &src)],
622            &[("x.pnk", "export fun 1 f(1 x) { return x; }")],
623        )
624    }
625
626    fn errors(rest: &str) -> String {
627        program(rest).expect_err("rejected").to_string()
628    }
629
630    /// The body of process `name`, and its signature's parameter count.
631    fn proc<'r>(bodies: &'r Bodies, name: &str) -> &'r ProcBody {
632        let (_, body) = bodies[PdId::new(0)]
633            .processes
634            .iter_enumerated()
635            .find(|(_, q)| q.sig.name == name)
636            .expect("declared");
637        body
638    }
639
640    #[test]
641    fn a_binder_passed_to_a_helper_is_its_argument() {
642        let (Rast { bodies, .. }, _) = program(
643            "proc P() { c?v -> Helper(v); }
644             proc Helper(w: byte) { e.w -> Skip; }
645             evt e.|p: byte|: x.f(p);",
646        )
647        .expect("builds");
648        let p = proc(&bodies, "P");
649        let v = BodyVarId::new(0);
650        assert_eq!(
651            p.body_vars[v].kind,
652            BodyVarKind::Binder {
653                chan: ChanId::new(0)
654            }
655        );
656        let Proc::Prefix(Event::Comm(Comm::Recv { binder, .. }), rest) = &p.body else {
657            panic!("c?v -> ...: {:?}", p.body);
658        };
659        assert_eq!(*binder, Some(v));
660        assert!(matches!(&**rest, Proc::Ref { args, .. } if args == &[VarRef::Body(v)]));
661        let helper = proc(&bodies, "Helper");
662        let Proc::Prefix(Event::Comp { carriers, .. }, _) = &helper.body else {
663            panic!("e.w -> Skip");
664        };
665        // The parameter is the body's first var.
666        assert_eq!(carriers, &[VarRef::Body(BodyVarId::new(0))]);
667        assert_eq!(helper.body_vars[BodyVarId::new(0)].kind, BodyVarKind::Param);
668    }
669
670    #[test]
671    fn a_binder_is_gone_at_the_semicolon() {
672        let e = errors("proc P() { c?v -> Skip; e.v -> Skip; } evt e.|p: byte|: x.f(p);");
673        assert!(
674            e.contains("process 'P': variable 'v' is not declared"),
675            "{e}"
676        );
677    }
678
679    #[test]
680    fn a_helper_does_not_see_its_callers_binder() {
681        let e =
682            errors("proc P() { c?v -> H(); } proc H() { e.v -> Skip; } evt e.|p: byte|: x.f(p);");
683        assert!(
684            e.contains("process 'H': variable 'v' is not declared"),
685            "{e}"
686        );
687    }
688
689    #[test]
690    fn sibling_branches_bind_the_same_name_twice() {
691        let (Rast { bodies, .. }, warnings) = program(
692            "proc P() { [g > 0] c?v -> e.v -> Skip [] [g == 0] c?v -> e.v -> Skip; }
693             evt e.|p: byte|: x.f(p);",
694        )
695        .expect("builds");
696        assert!(warnings.is_empty());
697        assert_eq!(proc(&bodies, "P").body_vars.len(), 2);
698    }
699
700    #[test]
701    fn a_local_is_in_scope_for_the_rest_of_its_sequence() {
702        let (Rast { bodies, .. }, _) =
703            program("proc P() { t: int; [t > 0] Skip; }").expect("builds");
704        let p = proc(&bodies, "P");
705        let Proc::Seq(items) = &p.body else {
706            panic!("a sequence");
707        };
708        let Proc::Guard(g, _) = &items[1] else {
709            panic!("[t > 0] Skip");
710        };
711        let ExprKind::Binary { lhs, .. } = &g.kind else {
712            panic!("t > 0");
713        };
714        assert!(matches!(lhs.kind, ExprKind::Var(VarRef::Body(t)) if t == BodyVarId::new(0)));
715    }
716
717    #[test]
718    fn redeclaring_in_scope_is_an_error() {
719        let e = errors("proc P() { t: int; t: int; Skip; }");
720        assert!(
721            e.contains("process 'P': 't' is already declared in this process"),
722            "{e}"
723        );
724    }
725
726    #[test]
727    fn an_entry_point_takes_no_parameters() {
728        let src = "@bind(microkit.init)
729            proc Init(k: int) { Skip; }
730            @bind(microkit.notified)
731            proc Notified() { Skip; }";
732        let e = built(FIS, &[("a", src)]).expect_err("rejected").to_string();
733        assert!(
734            e.contains("process 'Init': an entry point takes no parameters"),
735            "{e}"
736        );
737    }
738
739    #[test]
740    fn a_process_call_passes_one_argument_per_parameter() {
741        let e = errors("proc P() { Q(); } proc Q(k: int) { Skip; }");
742        assert!(
743            e.contains("process 'P': process 'Q' takes 1 argument(s), found 0"),
744            "{e}"
745        );
746        program("proc P() { t: int; Q(t); } proc Q(k: int) { Skip; }").expect("arity matches");
747    }
748
749    #[test]
750    fn an_event_prefix_names_one_variable_per_carrier() {
751        let e = errors("proc P() { t: int; e.t.t -> Skip; } evt e.|n: int|: g = n;");
752        assert!(
753            e.contains("process 'P': event 'e' expects 1 carrier(s), found 2"),
754            "{e}"
755        );
756        program("proc P() { t: int; e.t -> Skip; } evt e.|n: int|: g = n;").expect("arity matches");
757    }
758
759    #[test]
760    fn an_event_sees_only_its_carriers() {
761        let e = errors("proc P() { c?v -> e -> Skip; } evt e: x.f(v);");
762        assert!(
763            e.contains("event 'e': variable 'v' is not declared (process 'P' declares 'v'"),
764            "{e}"
765        );
766    }
767
768    #[test]
769    fn carriers_and_consts_are_read_only() {
770        let e = errors("evt e.|p: int|: p = 1;");
771        assert!(e.contains("event 'e': cannot assign to carrier 'p'"), "{e}");
772        let e = errors("evt e: K = 1;");
773        assert!(
774            e.contains("event 'e': cannot assign to constant 'K'"),
775            "{e}"
776        );
777    }
778
779    #[test]
780    fn an_event_assigns_its_locals_and_the_globals() {
781        let (Rast { bodies, .. }, _) = program("evt e: { t: int; t = g; g = t; }").expect("builds");
782        let e = &bodies[PdId::new(0)].events[EventId::new(0)];
783        let targets: Vec<_> = e
784            .body
785            .iter()
786            .filter_map(|s| match s {
787                Stmt::Assign { target, .. } => Some(*target),
788                _ => None,
789            })
790            .collect();
791        assert_eq!(
792            targets,
793            [
794                VarRef::Body(BodyVarId::new(0)),
795                VarRef::Local(LocalVarId::new(0))
796            ]
797        );
798    }
799
800    #[test]
801    fn a_mapping_is_a_value_only_as_its_vaddr_or_paddr() {
802        let (Rast { bodies, .. }, _) = program("evt e: g = m.vaddr;").expect("builds");
803        let e = &bodies[PdId::new(0)].events[EventId::new(0)];
804        let Stmt::Assign { rhs, .. } = &e.body[0] else {
805            panic!("g = m.vaddr");
806        };
807        assert!(matches!(rhs.kind, ExprKind::Vaddr(m) if m == MappingId::new(0)));
808        let (Rast { env, bodies }, _) = program("evt e: g = m.paddr;").expect("builds");
809        let body = &bodies[PdId::new(0)].events[EventId::new(0)];
810        let Stmt::Assign { rhs, .. } = &body.body[0] else {
811            panic!("g = m.paddr");
812        };
813        assert!(matches!(rhs.kind, ExprKind::Paddr(m) if m == MappingId::new(0)));
814        assert_eq!(env.mappings[MappingId::new(0)].pd, PdId::new(0));
815        assert!(env.mappings[MappingId::new(0)].paddr_read);
816        let e = errors("evt e: g = m.size;");
817        assert!(
818            e.contains("'size' is not a field of a mapping; only 'vaddr' and 'paddr' are"),
819            "{e}"
820        );
821        let e = errors("evt e: g = m;");
822        assert!(
823            e.contains("event 'e': mapping 'm' is not a value; use 'm.vaddr'"),
824            "{e}"
825        );
826    }
827
828    #[test]
829    fn an_event_that_only_prints_warns() {
830        let (Rast { .. }, warnings) =
831            program(r#"evt say: dbg("hi"); evt tick: { dbg("tick"); g = g + 1; }"#)
832                .expect("builds: printing alone is not an error");
833        let w = warnings.to_string();
834        assert!(w.contains("event 'say': only prints"), "{w}");
835        assert!(!w.contains("event 'tick'"), "{w}");
836    }
837
838    #[test]
839    fn shadowing_a_global_a_mapping_or_a_const_warns() {
840        let (Rast { .. }, warnings) = program("proc P(g: int) { m: int; c?K -> Skip; }")
841            .expect("builds: shadowing is not an error");
842        let w = warnings.to_string();
843        assert!(
844            w.contains("process 'P': parameter 'g' shadows local variable 'g'"),
845            "{w}"
846        );
847        assert!(
848            w.contains("process 'P': variable 'm' shadows mapping 'm'"),
849            "{w}"
850        );
851        assert!(
852            w.contains("process 'P': receive binder 'K' shadows constant 'K'"),
853            "{w}"
854        );
855    }
856}