Skip to main content

fic/wfcheck/
tail_rec.rs

1//! `tailRec` (`WellFormed.lean`): every reference to a process being lowered
2//! is in tail position, as [`check_tail_rec`].
3
4use std::path::Path;
5
6use crate::base::ProcId;
7use crate::error::{Diagnostic, Diagnostics};
8use crate::tast::{Body, Proc, Tast};
9
10/// Every reference to a process being lowered is in tail position
11/// (`WellFormed.lean`'s `tailRec`), so it is a back-edge to that process's
12/// head and the graph is finite. Walked from each bound entry point: a
13/// first reference to a helper opens it (Lean's `μ`), and inside a non-last
14/// operand of `;` every open process is out of reach — its continuation
15/// would need a return stack.
16///
17/// # Errors
18///
19/// One diagnostic per such reference, at the reference.
20pub fn check_tail_rec(tast: &Tast) -> Result<(), Diagnostics> {
21    let Tast { tenv, bodies } = tast;
22    let mut errors = Vec::new();
23    for (pd, body) in bodies.iter_enumerated() {
24        for (id, entry) in body.processes.iter_enumerated() {
25            if body.entries.iter().any(|e| e.process == id) {
26                let mut open = vec![(id, false)];
27                let file = &tenv.pds[pd].fi;
28                tail_rec(&entry.body, &mut open, body, file, &mut errors);
29            }
30        }
31    }
32    Diagnostics::finish(errors, ())
33}
34
35/// `open`: the processes whose bodies enclose `term`, each with whether a
36/// reference to it here would be non-tail.
37fn tail_rec(
38    term: &Proc,
39    open: &mut Vec<(ProcId, bool)>,
40    body: &Body,
41    file: &Path,
42    errors: &mut Vec<Diagnostic>,
43) {
44    match term {
45        Proc::Skip | Proc::Div | Proc::Decl(_) => {}
46        Proc::Ref { process, span, .. } => {
47            if let Some((_, non_tail)) = open.iter().find(|(p, _)| p == process) {
48                if *non_tail {
49                    let name = &body.processes[*process].sig.name;
50                    let inside = open
51                        .last()
52                        .map_or("", |(p, _)| body.processes[*p].sig.name.as_str());
53                    errors.push(Diagnostic::at(
54                        format!(
55                            "process `{name}` is referenced in non-tail position inside `{inside}` — its continuation would need a return stack"
56                        ),
57                        span.clone(),
58                        file,
59                    ));
60                }
61            } else {
62                open.push((*process, false));
63                tail_rec(&body.processes[*process].body, open, body, file, errors);
64                open.pop();
65            }
66        }
67        Proc::Prefix(_, rest) | Proc::Guard(_, rest) => {
68            tail_rec(rest, open, body, file, errors);
69        }
70        Proc::Seq(parts) => {
71            let last = parts.len().saturating_sub(1);
72            for (i, part) in parts.iter().enumerate() {
73                if i == last {
74                    tail_rec(part, open, body, file, errors);
75                } else {
76                    let mut closed: Vec<_> = open.iter().map(|(p, _)| (*p, true)).collect();
77                    tail_rec(part, &mut closed, body, file, errors);
78                }
79            }
80        }
81        Proc::Choice(branches) => {
82            for branch in branches {
83                tail_rec(branch, open, body, file, errors);
84            }
85        }
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::tast::env::built;
93
94    const DECLS: &str =
95        "g: bool; h: bool; b: bool;\nevt a: {}\nevt b: {}\nevt poll: {}\nevt fwd: {}\n";
96
97    /// The check over one program `p`.
98    fn rast(fis: &str, fi: &str) -> Result<(), Diagnostics> {
99        let (tast, _) = built(fis, &[("p", &format!("{fi}\n{DECLS}"))]).expect("builds");
100        check_tail_rec(&tast)
101    }
102
103    const PD: &str =
104        "ProtectionDomain p(100);\nProtectionDomain q(101);\nChan c = q --> p;\nChan d = q --> p;";
105
106    #[test]
107    fn non_tail_reference_to_an_open_process_is_rejected() {
108        let err = rast(
109            PD,
110            "@bind(microkit.init) proc Init() { Skip; }\n\
111             @bind(microkit.notified) proc Notified() { Loop(); }\n\
112             proc Loop() { a -> Loop(); b -> Skip; }",
113        )
114        .unwrap_err();
115        assert!(
116            err.0[0]
117                .message()
118                .contains("`Loop` is referenced in non-tail position inside `Loop`"),
119            "{}",
120            err.0[0].message()
121        );
122        assert_eq!(err.0[0].filename(), Some("p.fi"));
123
124        let err = rast(
125            PD,
126            "@bind(microkit.init) proc Init() { Skip; }\n\
127             @bind(microkit.notified) proc Notified() { c? -> Notified(); a -> Skip; }",
128        )
129        .unwrap_err();
130        assert!(err.0[0]
131            .message()
132            .contains("`Notified` is referenced in non-tail position"));
133
134        // A helper inlined in non-tail position may not reach back to the entry.
135        let err = rast(
136            PD,
137            "@bind(microkit.init) proc Init() { Skip; }\n\
138             @bind(microkit.notified) proc Notified() { Step(); b -> Skip; }\n\
139             proc Step() { a -> Notified(); }",
140        )
141        .unwrap_err();
142        assert!(err.0[0]
143            .message()
144            .contains("`Notified` is referenced in non-tail position"));
145    }
146
147    #[test]
148    fn first_references_and_tail_references_are_fine() {
149        // `Drain()` non-tail inside `HandleRx` is a first reference (a closed
150        // loop of its own); `Drain()` inside `Drain` is a tail back-edge.
151        assert!(rast(
152            PD,
153            "@bind(microkit.init) proc Init() { Skip; }\n\
154             @bind(microkit.notified) proc Notified() { c? -> HandleRx(); Notified(); }\n\
155             proc HandleRx() { a -> Skip; Drain(); b -> Skip; }\n\
156             proc Drain() { poll -> Skip; [g] fwd -> Drain() [] [h] Drain() default Skip; }",
157        )
158        .is_ok());
159    }
160}