Skip to main content

fic/wfcheck/
wellformed.rs

1//! The entry to the receive and choice checks ([`check_graphs`]), their
2//! reporter ([`Graph`]) and the satisfiability procedure behind the guards
3//! ([`satisfiable`]).
4//!
5//! Where a message is taken is read off the graph of `microkit.notified`,
6//! whose head is the out-edges of `init` (`recv_head.rs`): a notified that
7//! receives at all receives at its head. The guard rule is read
8//! off the typed term of the notified and the protected body
9//! (`guarded_choice.rs`): the graph conjoins an enclosing guard onto the
10//! choice it guards, and the rule is per choice. `Init` (the Lean's
11//! `InitWf`) is not checked.
12//!
13//! A helper reached twice is checked twice; a finding is reported once per
14//! message and span. It names the process it is written in and points at
15//! the branch's guard, else its event, else the process.
16//!
17//! [`satisfiable`] over-approximates: a finding may be spurious, a clean
18//! result is a proof.
19
20use std::collections::BTreeMap;
21use std::ops::Range;
22use std::path::Path;
23
24use crate::ast::{BinaryOp, Lit, UnaryOp};
25use crate::base::{Idx, ProcId, VarRef};
26use crate::ccfg::graph::{Edge, Label};
27use crate::ccfg::System;
28use crate::error::{Diagnostic, Diagnostics};
29use crate::tast::{Comm, Event, Expr, ExprKind, ProgramView, Tast, TyEnv};
30use crate::ty::width::Width;
31
32/// Check every PD's notified graph (`recv_head.rs`, `guarded_choice.rs`)
33/// and, off its head, its protected graph (`guarded_choice.rs`).
34///
35/// # Errors
36///
37/// One diagnostic per finding.
38pub fn check_graphs(tast: &Tast, system: &System) -> Result<(), Diagnostics> {
39    let mut errors = Vec::new();
40    for (pd, orchestration) in system.programs.iter_enumerated() {
41        let mut graph = Graph {
42            view: ProgramView::new(tast, pd),
43            file: &tast.tenv.pds[pd].fi,
44            found: Vec::new(),
45        };
46        let notified = tast.bodies[pd]
47            .entries
48            .iter()
49            .find(|e| e.platform == "microkit" && e.entry == "notified");
50        if let Some(notified) = notified {
51            let ccfg = &orchestration.notified;
52            // A notified that never receives needs no receive at its head.
53            if ccfg.edges.iter().any(Edge::blocks) {
54                let head: Vec<&Edge> = ccfg.out_edges(ccfg.init).collect();
55                graph.head(notified.process, &head);
56            }
57            graph.choices(notified.process);
58            for edge in ccfg
59                .edges
60                .iter()
61                .filter(|e| e.src != ccfg.init && e.blocks())
62            {
63                graph.stray_receive(edge);
64            }
65        }
66        let protected = tast.bodies[pd]
67            .entries
68            .iter()
69            .find(|e| e.platform == "microkit" && e.entry == "protected");
70        if let Some(protected) = protected {
71            graph.choices(protected.process);
72        }
73        errors.append(&mut graph.found);
74    }
75    Diagnostics::finish(errors, ())
76}
77
78/// One PD's findings on its graphs, and how they read.
79pub(super) struct Graph<'a> {
80    pub(super) view: ProgramView<'a>,
81    pub(super) file: &'a Path,
82    pub(super) found: Vec<Diagnostic>,
83}
84
85impl Graph<'_> {
86    /// A finding on an edge written in `process`, once per message and span.
87    pub(super) fn report(&mut self, process: ProcId, span: Range<usize>, message: &str) {
88        let name = &self.view.body().processes[process].sig.name;
89        let message = format!("process `{name}`: {message}");
90        if !self
91            .found
92            .iter()
93            .any(|d| d.message() == message && *d.span() == span)
94        {
95            self.found.push(Diagnostic::at(message, span, self.file));
96        }
97    }
98
99    /// The edge's event, else its process.
100    pub(super) fn event_span(&self, edge: &Edge) -> Range<usize> {
101        match &edge.label {
102            Some(Label::Event(
103                Event::Comp { span, .. }
104                | Event::Comm(Comm::Send { span, .. } | Comm::Recv { span, .. }),
105            )) => span.clone(),
106            _ => self.view.body().processes[edge.process].sig.span.clone(),
107        }
108    }
109
110    /// `e`, written in `process`: by ids when `ids` (a key, a body variable
111    /// qualified by its process), else by names.
112    pub(super) fn render(&self, e: &Expr, process: ProcId, ids: bool) -> String {
113        let go = |e: &Expr| self.render(e, process, ids);
114        match &e.kind {
115            ExprKind::Lit(Lit::Int(v)) => v.to_string(),
116            ExprKind::Lit(Lit::Hex(v)) => format!("{v:#x}"),
117            ExprKind::Lit(Lit::Bool(v)) => v.to_string(),
118            ExprKind::Var(v @ VarRef::Body(_)) if ids => format!("{process:?}.{v:?}"),
119            ExprKind::Var(v) if ids => format!("{v:?}"),
120            ExprKind::Var(v) => self.view.var(process, *v).to_owned(),
121            ExprKind::Vaddr(m) => format!("{}.vaddr", self.view.tenv.mappings[*m].name),
122            ExprKind::Paddr(m) => format!("{}.paddr", self.view.tenv.mappings[*m].name),
123            ExprKind::Call(call) => {
124                let args: Vec<String> = call.args.iter().map(go).collect();
125                let callee = if ids {
126                    format!("{:?}", call.callee)
127                } else {
128                    self.view.tenv.ffis[call.callee].name.clone()
129                };
130                format!("{callee}({})", args.join(", "))
131            }
132            ExprKind::Cast { expr, ty } => format!("({} as {ty:?})", go(expr)),
133            ExprKind::Sizeof { ty, .. } => format!("sizeof({ty:?})"),
134            ExprKind::Unary { op, operand } => format!("{}{}", op.symbol(), go(operand)),
135            ExprKind::Binary { op, lhs, rhs } => {
136                format!("({} {} {})", go(lhs), op.symbol(), go(rhs))
137            }
138            ExprKind::Field { base, field, .. } if ids => format!("{}.#{field}", go(base)),
139            ExprKind::Field { base, field, .. } => {
140                format!("{}.{}", go(base), self.view.field(&base.ty, *field).name)
141            }
142        }
143    }
144}
145
146/// "when a and b", for a witnessing assignment.
147pub(super) fn when(witness: &[String]) -> String {
148    if witness.is_empty() {
149        "in some state".to_owned()
150    } else {
151        format!("when {}", witness.join(" and "))
152    }
153}
154
155/// The most atoms enumerated (2ⁿ assignments).
156const MAX_ATOMS: usize = 16;
157
158/// What the solver found.
159pub(super) enum Verdict {
160    /// No state satisfies the conjunction.
161    Unsat,
162    /// Some state may; the atoms of one such assignment, as text.
163    Sat(Vec<String>),
164    /// Too many atoms to enumerate.
165    Unknown,
166}
167
168/// A comparison's relation; `!=`, `>` and `>=` are negations or flips.
169#[derive(Clone, Copy, Debug)]
170enum Rel {
171    Eq,
172    Lt,
173    Le,
174}
175
176impl Rel {
177    fn symbol(self) -> &'static str {
178        match self {
179            Rel::Eq => "==",
180            Rel::Lt => "<",
181            Rel::Le => "<=",
182        }
183    }
184}
185
186enum Atom {
187    /// `term rel c`, the term's type holding `range`.
188    Cmp {
189        term: String,
190        rel: Rel,
191        c: i128,
192        range: (i128, i128),
193        text: String,
194    },
195    Opaque {
196        text: String,
197    },
198}
199
200impl Atom {
201    fn text(&self) -> &str {
202        match self {
203            Atom::Cmp { text, .. } | Atom::Opaque { text } => text,
204        }
205    }
206}
207
208enum Formula {
209    Const(bool),
210    Atom(usize),
211    Not(Box<Formula>),
212    And(Vec<Formula>),
213    Or(Vec<Formula>),
214}
215
216/// How to print an expression: `true` for its key (ids, no names, so
217/// equal expressions give equal strings), `false` for the reader.
218pub(super) type Render<'a> = &'a dyn Fn(&Expr, ProcId, bool) -> String;
219
220/// Whether some state makes every `(guard, process, truth)` hold: `guard`,
221/// written in `process`, evaluates to `truth`.
222///
223/// A guard is a propositional formula over **atoms**. An atom is a
224/// comparison `term ⋈ constant` (`⋈` among `==`, `<`, `<=`; the other
225/// three are their negations or flips), or an *opaque* bool: a bool
226/// variable, a call, a field, any comparison of two non-constants. Equal
227/// atoms (compared without spans) are one atom, so a pure call read twice
228/// in one state is one value, as the state is the same.
229///
230/// The atoms are enumerated, and an assignment counts only if it is
231/// consistent: the comparison atoms on one term leave a non-empty integer
232/// interval inside the term's type (`x == 1` with `x == 2`, `x < 0` of an
233/// unsigned `x`, are not). Opaque atoms are free. So "unsatisfiable" is a
234/// proof, and "satisfiable" may be spurious: the check can warn on a good
235/// choice, and never stays silent on a bad one. More than [`MAX_ATOMS`]
236/// atoms is [`Verdict::Unknown`], never an unsat.
237pub(super) fn satisfiable(
238    lits: &[(&Expr, ProcId, bool)],
239    tenv: &TyEnv,
240    render: Render<'_>,
241) -> Verdict {
242    let mut lowering = Lowering {
243        atoms: Vec::new(),
244        index: BTreeMap::new(),
245        render,
246        tenv,
247        process: ProcId::new(0),
248    };
249    let formulas: Vec<Formula> = lits
250        .iter()
251        .map(|(guard, process, truth)| {
252            lowering.process = *process;
253            let f = lowering.lower(guard);
254            if *truth {
255                f
256            } else {
257                Formula::Not(Box::new(f))
258            }
259        })
260        .collect();
261    let atoms = lowering.atoms;
262    if atoms.len() > MAX_ATOMS {
263        return Verdict::Unknown;
264    }
265    for bits in 0u32..(1 << atoms.len()) {
266        let value = |i: usize| bits >> i & 1 == 1;
267        if formulas.iter().all(|f| eval(f, &value)) && consistent(&atoms, &value) {
268            let witness = atoms
269                .iter()
270                .enumerate()
271                .map(|(i, a)| {
272                    if value(i) {
273                        a.text().to_owned()
274                    } else {
275                        format!("!({})", a.text())
276                    }
277                })
278                .collect();
279            return Verdict::Sat(witness);
280        }
281    }
282    Verdict::Unsat
283}
284
285fn eval(f: &Formula, value: &dyn Fn(usize) -> bool) -> bool {
286    match f {
287        Formula::Const(b) => *b,
288        Formula::Atom(i) => value(*i),
289        Formula::Not(f) => !eval(f, value),
290        Formula::And(fs) => fs.iter().all(|f| eval(f, value)),
291        Formula::Or(fs) => fs.iter().any(|f| eval(f, value)),
292    }
293}
294
295/// Whether the comparison atoms, so assigned, leave every term a value.
296fn consistent(atoms: &[Atom], value: &dyn Fn(usize) -> bool) -> bool {
297    // Per term: the interval and the points it may not take.
298    let mut terms: BTreeMap<&str, ((i128, i128), Vec<i128>)> = BTreeMap::new();
299    for (i, atom) in atoms.iter().enumerate() {
300        let Atom::Cmp {
301            term,
302            rel,
303            c,
304            range,
305            ..
306        } = atom
307        else {
308            continue;
309        };
310        let ((lo, hi), holes) = terms.entry(term).or_insert((*range, Vec::new()));
311        match (rel, value(i)) {
312            (Rel::Eq, true) => (*lo, *hi) = ((*lo).max(*c), (*hi).min(*c)),
313            (Rel::Eq, false) => holes.push(*c),
314            (Rel::Lt, true) => *hi = (*hi).min(*c - 1),
315            (Rel::Lt, false) => *lo = (*lo).max(*c),
316            (Rel::Le, false) => *lo = (*lo).max(*c + 1),
317            (Rel::Le, true) => *hi = (*hi).min(*c),
318        }
319    }
320    terms.values().all(|((lo, hi), holes)| {
321        let mut holes: Vec<i128> = holes
322            .iter()
323            .copied()
324            .filter(|h| lo <= h && h <= hi)
325            .collect();
326        holes.sort_unstable();
327        holes.dedup();
328        lo <= hi && !usize::try_from(hi - lo + 1).is_ok_and(|n| n <= holes.len())
329    })
330}
331
332struct Lowering<'a> {
333    atoms: Vec<Atom>,
334    index: BTreeMap<String, usize>,
335    render: Render<'a>,
336    /// The `const`s' values.
337    tenv: &'a TyEnv,
338    /// The process the guard being lowered was written in.
339    process: ProcId,
340}
341
342impl Lowering<'_> {
343    fn lower(&mut self, e: &Expr) -> Formula {
344        match &e.kind {
345            ExprKind::Lit(Lit::Bool(b)) => Formula::Const(*b),
346            ExprKind::Unary {
347                op: UnaryOp::Not,
348                operand,
349            } => Formula::Not(Box::new(self.lower(operand))),
350            ExprKind::Binary {
351                op: BinaryOp::And,
352                lhs,
353                rhs,
354            } => Formula::And(vec![self.lower(lhs), self.lower(rhs)]),
355            ExprKind::Binary {
356                op: BinaryOp::Or,
357                lhs,
358                rhs,
359            } => Formula::Or(vec![self.lower(lhs), self.lower(rhs)]),
360            ExprKind::Binary { op, lhs, rhs } if op.is_comparison() => self.compare(*op, lhs, rhs),
361            _ => self.opaque(e),
362        }
363    }
364
365    /// `lhs op rhs`, normalised to `a rel b` under a possible negation.
366    fn compare(&mut self, op: BinaryOp, lhs: &Expr, rhs: &Expr) -> Formula {
367        let (rel, a, b, negate) = match op {
368            BinaryOp::Eq => (Rel::Eq, lhs, rhs, false),
369            BinaryOp::Ne => (Rel::Eq, lhs, rhs, true),
370            BinaryOp::Lt => (Rel::Lt, lhs, rhs, false),
371            BinaryOp::Le => (Rel::Le, lhs, rhs, false),
372            BinaryOp::Gt => (Rel::Lt, rhs, lhs, false),
373            _ => (Rel::Le, rhs, lhs, false),
374        };
375        let f = match (constant(a, self.tenv), constant(b, self.tenv)) {
376            (Some(x), Some(y)) => Formula::Const(match rel {
377                Rel::Eq => x == y,
378                Rel::Lt => x < y,
379                Rel::Le => x <= y,
380            }),
381            (None, Some(c)) => self.cmp(a, rel, c),
382            // `c rel t`: `c == t` is `t == c`; `c < t` is `¬(t <= c)`;
383            // `c <= t` is `¬(t < c)`.
384            (Some(c), None) => match rel {
385                Rel::Eq => self.cmp(b, Rel::Eq, c),
386                Rel::Lt => Formula::Not(Box::new(self.cmp(b, Rel::Le, c))),
387                Rel::Le => Formula::Not(Box::new(self.cmp(b, Rel::Lt, c))),
388            },
389            (None, None) => {
390                let key = format!(
391                    "{} {} {}",
392                    (self.render)(a, self.process, true),
393                    rel.symbol(),
394                    (self.render)(b, self.process, true)
395                );
396                let text = format!(
397                    "{} {} {}",
398                    (self.render)(a, self.process, false),
399                    rel.symbol(),
400                    (self.render)(b, self.process, false)
401                );
402                self.atom(format!("o:{key}"), Atom::Opaque { text })
403            }
404        };
405        if negate {
406            Formula::Not(Box::new(f))
407        } else {
408            f
409        }
410    }
411
412    /// `term rel c`: a comparison atom, or opaque if `term` is no integer.
413    fn cmp(&mut self, term: &Expr, rel: Rel, c: i128) -> Formula {
414        let key = (self.render)(term, self.process, true);
415        let text = format!(
416            "{} {} {c}",
417            (self.render)(term, self.process, false),
418            rel.symbol()
419        );
420        match term.ty.width().map(Width::range) {
421            Some(range) => self.atom(
422                format!("c:{key}|{rel:?}|{c}"),
423                Atom::Cmp {
424                    term: key,
425                    rel,
426                    c,
427                    range,
428                    text,
429                },
430            ),
431            None => self.atom(format!("o:{key}|{rel:?}|{c}"), Atom::Opaque { text }),
432        }
433    }
434
435    fn opaque(&mut self, e: &Expr) -> Formula {
436        let key = format!("o:{}", (self.render)(e, self.process, true));
437        let text = (self.render)(e, self.process, false);
438        self.atom(key, Atom::Opaque { text })
439    }
440
441    fn atom(&mut self, key: String, atom: Atom) -> Formula {
442        let next = self.atoms.len();
443        let i = *self.index.entry(key).or_insert(next);
444        if i == next {
445            self.atoms.push(atom);
446        }
447        Formula::Atom(i)
448    }
449}
450
451/// The value of an integer literal or a `const`, `-` included.
452fn constant(e: &Expr, tenv: &TyEnv) -> Option<i128> {
453    match &e.kind {
454        ExprKind::Lit(Lit::Int(v)) => Some(i128::from(*v)),
455        ExprKind::Lit(Lit::Hex(v)) => Some(i128::from(*v)),
456        ExprKind::Var(VarRef::Const(id)) => tenv.consts[*id].value.integer(),
457        ExprKind::Unary {
458            op: UnaryOp::Neg,
459            operand,
460        } => constant(operand, tenv).map(|v| -v),
461        _ => None,
462    }
463}