Skip to main content

fic/wfcheck/
guarded_choice.rs

1//! The guard rule, the Lean's Wf3 (`choicesWf`, `Proc.choicesLead`), on the
2//! typed term of each entry point's body.
3//!
4//! A choice tree is a `[]` or a guard with the guards and choices nested
5//! directly in it (`branchesOf`): its leaves are what is left, each under
6//! the conjunction of the guards above it in the tree. Outside the head:
7//!
8//! - every leaf of a choice is guarded (`choicesLead`, and with it `[⊤]`
9//!   overlapping every other branch): a branch with no guard;
10//! - no two leaves' conjunctions hold together, unless both receive, on
11//!   different channels (`branchesApart`);
12//! - one of them always holds (`branchesExhaustive`); a lone guard is a tree
13//!   of one leaf, so it can block.
14//!
15//! Each choice is checked on its own guards: a choice after a `;`, a prefix
16//! or a call is a tree of its own, whatever guards enclose it. The graph
17//! does not tell them apart, since flattening conjoins an enclosing guard
18//! onto the first edges of the choice it guards.
19//!
20//! The term is where this check runs for now; the aim is to run it on the
21//! Ccfg, as the other graph checks are, once an edge records which choice
22//! each conjunct of its guard comes from (#691).
23//!
24//! The walk unfolds a process at its first reference and stops at one being
25//! walked, as flattening does (`μ` and `X`). The head, where the entry
26//! starts, is `recv_head.rs`'s and `protected.rs`'s: its trees are not
27//! checked here, but a branch there that is a call does not begin with an
28//! event (`choicesLead`). A `default` is already a guard (`rast/desugar.rs`).
29
30use std::ops::Range;
31
32use crate::base::ProcId;
33use crate::ccfg::{is_skip, pend_guard};
34use crate::tast::{Event, Expr, Proc};
35
36use super::recv_head::Receive;
37use super::wellformed::{satisfiable, when, Graph, Verdict};
38
39/// A leaf of a choice tree: the guards above it in the tree, and the term.
40struct Leaf<'a> {
41    guards: Vec<&'a Expr>,
42    term: &'a Proc,
43}
44
45impl Leaf<'_> {
46    /// Its guards' conjunction, enclosing guard on the left.
47    fn conjunction(&self) -> Option<Expr> {
48        self.guards
49            .iter()
50            .fold(None, |acc, g| Some(pend_guard(acc, g)))
51    }
52
53    /// What it receives from, when it begins with a receive.
54    fn receive(&self) -> Option<Receive> {
55        match self.term {
56            Proc::Prefix(event, _) => Receive::of_event(event),
57            _ => None,
58        }
59    }
60}
61
62impl<'a> Graph<'a> {
63    /// The guard rule on the body of `entry`, outside its head.
64    pub(super) fn choices(&mut self, entry: ProcId) {
65        let body = &self.view.body().processes[entry].body;
66        self.term(body, entry, true, &mut vec![entry]);
67    }
68
69    /// Every choice tree of `term`, written in `process`; `head` while the
70    /// entry has taken no step; `walking` the processes unfolded.
71    fn term(&mut self, term: &'a Proc, process: ProcId, head: bool, walking: &mut Vec<ProcId>) {
72        match term {
73            Proc::Skip | Proc::Div | Proc::Decl(_) => {}
74            Proc::Prefix(_, rest) => self.term(rest, process, false, walking),
75            Proc::Seq(parts) => {
76                let mut head = head;
77                for part in parts {
78                    self.term(part, process, head, walking);
79                    head &= is_skip(part);
80                }
81            }
82            Proc::Ref {
83                process: called, ..
84            } => {
85                if !walking.contains(called) {
86                    walking.push(*called);
87                    let body = &self.view.body().processes[*called].body;
88                    self.term(body, *called, head, walking);
89                    walking.pop();
90                }
91            }
92            Proc::Guard(..) | Proc::Choice(_) => {
93                let mut leaves = Vec::new();
94                collect(term, &mut Vec::new(), &mut leaves);
95                if head {
96                    self.calls_at_head(&leaves, process);
97                } else {
98                    self.tree(&leaves, process);
99                }
100                for leaf in &leaves {
101                    self.term(leaf.term, process, head, walking);
102                }
103            }
104        }
105    }
106
107    /// The guard rule on one tree's leaves, outside the head.
108    fn tree(&mut self, leaves: &[Leaf<'a>], process: ProcId) {
109        let mut found = Vec::new();
110        if leaves.len() > 1 {
111            for leaf in leaves.iter().filter(|l| l.guards.is_empty()) {
112                found.push((
113                    self.leaf_span(leaf, process),
114                    "a branch with no guard: outside the head a choice is decided by its guards — \
115                     guard it, or make it the `default`"
116                        .to_owned(),
117                ));
118            }
119        }
120        let render = |e: &Expr, p: ProcId, ids: bool| self.render(e, p, ids);
121        let guarded: Vec<(&Leaf, Expr)> = leaves
122            .iter()
123            .filter_map(|l| l.conjunction().map(|g| (l, g)))
124            .collect();
125        for (i, (a, ga)) in guarded.iter().enumerate() {
126            for (b, gb) in &guarded[i + 1..] {
127                if let (Some(ra), Some(rb)) = (a.receive(), b.receive()) {
128                    if ra != rb {
129                        continue;
130                    }
131                }
132                let what = match satisfiable(
133                    &[(ga, process, true), (gb, process, true)],
134                    self.view.tenv,
135                    &render,
136                ) {
137                    Verdict::Unsat => continue,
138                    Verdict::Sat(w) => format!("can both be enabled {}", when(&w)),
139                    Verdict::Unknown => {
140                        "could not be shown exclusive: too many conditions".to_owned()
141                    }
142                };
143                found.push((gb.span.clone(), format!("two branches {what}")));
144            }
145        }
146        // A leaf with no guard is always enabled: reported above, and exhaustive.
147        if guarded.len() == leaves.len() {
148            let conds: Vec<(&Expr, ProcId, bool)> =
149                guarded.iter().map(|(_, g)| (g, process, false)).collect();
150            let what = match satisfiable(&conds, self.view.tenv, &render) {
151                Verdict::Unsat => None,
152                Verdict::Sat(w) => Some(format!(
153                    "no branch is enabled {}, and the process blocks for ever — add a `default`",
154                    when(&w)
155                )),
156                Verdict::Unknown => {
157                    Some("its guards could not be shown exhaustive: too many conditions".to_owned())
158                }
159            };
160            if let (Some(what), Some((_, first))) = (what, guarded.first()) {
161                found.push((first.span.clone(), format!("a choice: {what}")));
162            }
163        }
164        for (span, message) in found {
165            self.report(process, span, &message);
166        }
167    }
168
169    /// At the head every branch receives; one that is a call merges the
170    /// called process's receives into the head, but a branch of a choice
171    /// begins with an event or a guard (`choicesLead`).
172    fn calls_at_head(&mut self, leaves: &[Leaf<'a>], process: ProcId) {
173        if leaves.len() < 2 {
174            return;
175        }
176        for leaf in leaves {
177            if let Proc::Ref { span, .. } = leaf.term {
178                if leaf.guards.is_empty() {
179                    self.report(
180                        process,
181                        span.clone(),
182                        "a branch of the head that is a call: a branch of a choice begins with \
183                         an event or a guard — write the call's receives here",
184                    );
185                }
186            }
187        }
188    }
189
190    /// Where a leaf is: its guard, else its first event, else the call.
191    fn leaf_span(&self, leaf: &Leaf, process: ProcId) -> Range<usize> {
192        if let Some(g) = leaf.conjunction() {
193            return g.span;
194        }
195        match leaf.term {
196            Proc::Prefix(event, _) => self.term_event_span(event, process),
197            Proc::Ref { span, .. } => span.clone(),
198            _ => self.view.body().processes[process].sig.span.clone(),
199        }
200    }
201
202    /// An event's span, else its process's.
203    fn term_event_span(&self, event: &Event, process: ProcId) -> Range<usize> {
204        use crate::tast::Comm;
205        match event {
206            Event::Comp { span, .. }
207            | Event::Comm(Comm::Send { span, .. } | Comm::Recv { span, .. }) => span.clone(),
208            Event::Irq { .. } => self.view.body().processes[process].sig.span.clone(),
209        }
210    }
211}
212
213/// The leaves of the tree at `term` (`branchesOf`), each under `guards`.
214fn collect<'a>(term: &'a Proc, guards: &mut Vec<&'a Expr>, leaves: &mut Vec<Leaf<'a>>) {
215    match term {
216        Proc::Guard(g, inner) => {
217            guards.push(g);
218            collect(inner, guards, leaves);
219            guards.pop();
220        }
221        Proc::Choice(sides) => {
222            for side in sides {
223                collect(side, guards, leaves);
224            }
225        }
226        _ => leaves.push(Leaf {
227            guards: guards.clone(),
228            term,
229        }),
230    }
231}