Skip to main content

rucc_verify/
verify.rs

1//! Turning a rule into a question, and the answers into a report.
2
3use std::fmt;
4
5use rucc_rules::{Error, Rule, Term, TermKind};
6
7use crate::model::{Model, Widths, rule_width};
8use crate::solver::{Answer, Solver};
9
10/// What became of one rule.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Verdict {
13    /// Nothing makes the claim false.
14    Discharged,
15    /// Something does, and this is what the solver printed of it.
16    Refuted(String),
17    /// The claim holds at every width narrower than the rule's own, and the rule carries a
18    /// written reason for taking that as enough. A pass, and a counted one.
19    Bounded {
20        /// The widths it was proved at, narrowest first.
21        widths: Vec<u32>,
22        /// The reason the rule gives, which is what a reviewer signed for.
23        why: String,
24    },
25    /// The solver gave up. Not a pass.
26    Unknown,
27}
28
29impl Verdict {
30    /// Whether a rule with this verdict may enter the rule set.
31    #[must_use]
32    pub fn accepted(&self) -> bool {
33        matches!(self, Verdict::Discharged | Verdict::Bounded { .. })
34    }
35
36    /// Why it may not, as a sentence, or nothing when it may.
37    #[must_use]
38    pub fn refusal(&self) -> Option<String> {
39        match self {
40            Verdict::Discharged | Verdict::Bounded { .. } => None,
41            Verdict::Refuted(model) => {
42                Some(format!("this rule is not true, and here is what makes it false: {model}"))
43            }
44            Verdict::Unknown => Some(
45                "the solver could not settle this rule, and a rule nobody has proved does not \
46                 enter the rule set"
47                    .to_owned(),
48            ),
49        }
50    }
51}
52
53/// What became of a rule set.
54#[derive(Debug, Default, Clone, PartialEq, Eq)]
55pub struct Report {
56    /// One verdict per rule, in the order the rules were given.
57    pub verdicts: Vec<Verdict>,
58}
59
60impl Report {
61    /// How many rules were discharged at their own width.
62    #[must_use]
63    pub fn discharged(&self) -> usize {
64        self.verdicts.iter().filter(|v| **v == Verdict::Discharged).count()
65    }
66
67    /// How many rules got a bounded proof instead.
68    ///
69    /// `spec/15-testing.md` section 15.5 asks for this number to be reported rather than merely
70    /// known, because it going up is the signal that the rule set is drifting towards claims
71    /// nobody is checking at the width the compiler runs at.
72    #[must_use]
73    pub fn bounded(&self) -> usize {
74        self.verdicts.iter().filter(|v| matches!(v, Verdict::Bounded { .. })).count()
75    }
76
77    /// Whether every rule was discharged at its own width. A bounded proof is not one of these.
78    #[must_use]
79    pub fn all_discharged(&self) -> bool {
80        self.verdicts.iter().all(|v| *v == Verdict::Discharged)
81    }
82
83    /// Whether every rule may enter the rule set, which allows a bounded proof and allows
84    /// nothing else. A solver that gave up is not a pass, because "we could not tell" is not
85    /// "it is correct".
86    #[must_use]
87    pub fn accepted(&self) -> bool {
88        self.verdicts.iter().all(Verdict::accepted)
89    }
90}
91
92impl fmt::Display for Report {
93    /// One line, which is what a build prints and what a person reads in a log.
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        let refused = self.verdicts.len() - self.discharged() - self.bounded();
96        let rules = if self.verdicts.len() == 1 { "rule" } else { "rules" };
97        write!(
98            f,
99            "{} {rules}: {} discharged, {} by bounded proof, {} refused",
100            self.verdicts.len(),
101            self.discharged(),
102            self.bounded(),
103            refused
104        )
105    }
106}
107
108/// The SMT-LIB question one rule asks, at the width the rule works in.
109///
110/// This is separate from asking it so that the query can be read, kept in a test, and handed to
111/// a solver by hand when one is arguing with it.
112///
113/// # Errors
114///
115/// Anything the model cannot write out, which is any term nobody has said the meaning of.
116pub fn query(path: &str, rule: &Rule, model: &Model) -> Result<String, Error> {
117    query_at(path, rule, model, rule_width(&rule.pattern))
118}
119
120/// The same question asked at a width somebody chose.
121///
122/// This is what a bounded proof is made of: the rule's own claim, in narrower bitvectors than
123/// the ones it will run in. Every width in the rule scales by the one ratio, so a rule that
124/// converts between widths still converts between them here.
125///
126/// # Errors
127///
128/// Anything the model cannot write out, which is any term nobody has said the meaning of, and
129/// anything whose widths do not fit together.
130pub fn query_at(path: &str, rule: &Rule, model: &Model, width: u32) -> Result<String, Error> {
131    let widths = Widths::at(&rule.pattern, width);
132    let mut out = String::from("(set-logic QF_BV)\n");
133
134    // Each name at the width the pattern binds it at, which is not one width for the whole rule:
135    // a rule that lowers a thirty two bit add of two sixty four bit registers has both numbers
136    // in it and neither is the other.
137    for (name, at) in widths.names() {
138        out.push_str(&format!("(declare-const {name} (_ BitVec {at}))\n"));
139    }
140
141    if let Some(guard) = &rule.guard {
142        // An assumption, not part of the claim. A rule that only holds for some constants is
143        // only being asked about those constants.
144        out.push_str(&format!("(assert {})\n", model.write(path, guard, &widths)?.0));
145    }
146
147    // Two obligations, asked as one question. The first is the one that matters: what the
148    // pattern means and what the replacement means have to be the same thing, both read out of
149    // the model rather than out of anybody's description of them. The second is the rule's own
150    // `spec` clause, which is written by hand and so is worth checking rather than trusting: a
151    // rule whose stated claim is not what its pattern actually means would otherwise verify
152    // against its own mistake.
153    let (matched, over) = model.write(path, &rule.pattern, &widths)?;
154    let (produced, into) = model.write(path, &rule.replacement, &widths)?;
155    let same = agreement(path, &rule.replacement, &matched, &produced, over, into)?;
156    let substituted = substitute(&rule.spec, &produced);
157    let claim = model.write(path, &substituted, &widths.with(&produced, into))?.0;
158    out.push_str(&format!("(assert (not (and {same} {claim})))\n"));
159    out.push_str("(check-sat)\n(get-model)\n");
160    Ok(out)
161}
162
163/// What it takes for a machine term to compute what the IR term it replaces computes.
164///
165/// The same bitvector, when the two are the same width, which is every rule that does not
166/// convert. When the machine term is wider they have to agree on the bits the IR term has, which
167/// is what lowering a value into a register wider than the value means, and what the rest of the
168/// register holds is left to the rule's own `spec` clause to claim: on a target where a thirty
169/// two bit add sign extends into a sixty four bit register, that clause is the only place the
170/// sign extension is stated and so it is the only place it can be checked.
171///
172/// A machine term narrower than the IR term loses bits, and that is a mistake rather than a
173/// claim about anything.
174fn agreement(
175    path: &str,
176    at: &Term,
177    matched: &str,
178    produced: &str,
179    over: u32,
180    into: u32,
181) -> Result<String, Error> {
182    if over == into {
183        return Ok(format!("(= {matched} {produced})"));
184    }
185    if into < over {
186        let said = format!(
187            "what this replaces is {over} bits wide and this is {into}, so it cannot compute it"
188        );
189        return Err(Error {
190            path: path.to_owned(),
191            line: at.line,
192            column: at.column,
193            message: said,
194        });
195    }
196    Ok(format!("(= {matched} ((_ extract {} 0) {produced}))", over - 1))
197}
198
199/// The widths a bounded proof is taken over, narrowest first.
200///
201/// Two of them rather than one, because a claim that holds at a single width can hold for
202/// reasons that are about that width. Both of them small, because the claims that need a
203/// bounded proof at all are the ones mixing multiplication with division, and one of those is
204/// as far out of reach at sixteen bits as it is at sixty four: the rule the tests use is
205/// answered in hundredths of a second at eight bits and not at all at sixteen. Only widths
206/// narrower than the rule's own are used, so a rule that already works in four bits has nothing
207/// to fall back to.
208pub const BOUNDED_WIDTHS: [u32; 2] = [4, 8];
209
210/// Ask about every rule.
211///
212/// A rule that the solver settles at its own width is discharged and that is the end of it. A
213/// rule it gives up on is asked again at [`BOUNDED_WIDTHS`], but only if the rule carries a
214/// written reason for taking narrow widths as enough, because a bounded proof is a judgement
215/// somebody makes and not a fallback a tool takes on its own.
216///
217/// # Errors
218///
219/// Anything the model cannot write out, and anything that stops the solver from running.
220pub fn verify(
221    path: &str,
222    rules: &[Rule],
223    model: &Model,
224    solver: &Solver,
225) -> Result<Report, Vec<Error>> {
226    let mut report = Report::default();
227    let mut errors = Vec::new();
228
229    for rule in rules {
230        let width = rule_width(&rule.pattern);
231        match ask(path, rule, model, solver, width) {
232            Err(error) => errors.push(error),
233            Ok(Answer::Unsat) => report.verdicts.push(Verdict::Discharged),
234            Ok(Answer::Sat(found)) => report.verdicts.push(Verdict::Refuted(found)),
235            Ok(Answer::Unknown) => match &rule.bounded {
236                None => report.verdicts.push(Verdict::Unknown),
237                Some(why) => match bounded(path, rule, model, solver, width, why) {
238                    Ok(verdict) => report.verdicts.push(verdict),
239                    Err(error) => errors.push(error),
240                },
241            },
242        }
243    }
244
245    if errors.is_empty() { Ok(report) } else { Err(errors) }
246}
247
248/// Verify a rule set and refuse the whole of it if anything in it cannot enter.
249///
250/// This is the gate `spec/17-milestones.md` asks for. It refuses the file rather than dropping
251/// the rules that failed, because a compiler built from the rules that happened to pass is a
252/// compiler nobody described: what it does with the terms the dropped rules matched is then a
253/// question about the order of the rest.
254///
255/// # Errors
256///
257/// One error per rule that may not enter, at the line the rule starts on, and anything that
258/// stopped the verification from happening at all.
259pub fn admit(
260    path: &str,
261    rules: &[Rule],
262    model: &Model,
263    solver: &Solver,
264) -> Result<Report, Vec<Error>> {
265    let report = verify(path, rules, model, solver)?;
266    let mut errors = Vec::new();
267    for (rule, verdict) in rules.iter().zip(&report.verdicts) {
268        if let Some(said) = verdict.refusal() {
269            errors.push(Error {
270                path: path.to_owned(),
271                line: rule.line,
272                column: rule.column,
273                message: said,
274            });
275        }
276    }
277    if errors.is_empty() { Ok(report) } else { Err(errors) }
278}
279
280/// Put one question to the solver.
281fn ask(
282    path: &str,
283    rule: &Rule,
284    model: &Model,
285    solver: &Solver,
286    width: u32,
287) -> Result<Answer, Error> {
288    let asked = query_at(path, rule, model, width)?;
289    solver.ask(&asked).map_err(|problem| Error {
290        path: path.to_owned(),
291        line: rule.line,
292        column: rule.column,
293        message: format!("the solver could not be run: {problem}"),
294    })
295}
296
297/// Ask the rule again at the narrow widths, once the real one has come back a shrug.
298///
299/// Every width has to come back `unsat`. A counterexample at a narrow width is reported as the
300/// refutation it looks like, named with the width it was found at, because the two things it
301/// can be are a rule that is wrong and a rule whose constants do not fit in four bits, and both
302/// are for a person to look at rather than for this to decide.
303fn bounded(
304    path: &str,
305    rule: &Rule,
306    model: &Model,
307    solver: &Solver,
308    width: u32,
309    why: &str,
310) -> Result<Verdict, Error> {
311    let mut proved = Vec::new();
312    for narrow in BOUNDED_WIDTHS.iter().copied().filter(|narrow| *narrow < width) {
313        match ask(path, rule, model, solver, narrow)? {
314            Answer::Unsat => proved.push(narrow),
315            Answer::Sat(found) => {
316                let said = format!("at {narrow} bits, where the rule works in {width}: {found}");
317                return Ok(Verdict::Refuted(said));
318            }
319            Answer::Unknown => return Ok(Verdict::Unknown),
320        }
321    }
322    if proved.is_empty() {
323        return Ok(Verdict::Unknown);
324    }
325    Ok(Verdict::Bounded { widths: proved, why: why.to_owned() })
326}
327
328/// Put the replacement's meaning where the specification says `(result)`.
329///
330/// This is a substitution on the written form rather than on the term, because what the
331/// replacement means is SMT-LIB text by the time it is known and there is nothing to put back
332/// into a term.
333fn substitute(spec: &Term, produced: &str) -> Term {
334    match &spec.kind {
335        TermKind::App { head, args } if head == "result" && args.is_empty() => {
336            Term { kind: TermKind::Var(produced.to_owned()), line: spec.line, column: spec.column }
337        }
338        TermKind::App { head, args } => Term {
339            kind: TermKind::App {
340                head: head.clone(),
341                args: args.iter().map(|arg| substitute(arg, produced)).collect(),
342            },
343            line: spec.line,
344            column: spec.column,
345        },
346        _ => spec.clone(),
347    }
348}