verif 0.1.0

In-code formal verification for Rust: an embedded bit-blasting SMT decision procedure, a symbolic DSL, contracts and a machine-checked proof kernel. SPARK-inspired, no_std, no external dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! SMT-LIB2 export: hand a verification condition to an independent solver.
//!
//! The embedded decision procedure is good at masks, bounds and shifts, and bad
//! at wide multipliers. When it returns [`crate::smt::Verdict::Unknown`], the
//! honest move is to say so — but you do not have to stop there. This module
//! prints the *same* formula the engine reasons about as SMT-LIB2, so an external
//! solver can decide it, and so a reviewer can read what was actually proved.
//!
//! Independence matters for a safety argument. A proof produced by the same code
//! that generated the obligation is weaker evidence than a proof reproduced by a
//! different tool from a textual, auditable artifact. [`Query::write_smtlib2`]
//! produces that artifact.
//!
//! Nothing here depends on `std`: it writes into any [`core::fmt::Write`], which
//! includes a fixed buffer on bare metal. With the `std` feature there is also
//! `Query::to_smtlib2`, an owned-string convenience for host tooling.
//!
//! ```text
//! (set-logic QF_BV)
//! (declare-fun x () (_ BitVec 8))
//! (assert (bvult x (_ bv200 8)))
//! (assert (not (bvule x (_ bv100 8))))
//! (check-sat)
//! (get-model)
//! ```

use core::fmt::{self, Write};

use crate::smt::{self, Op, Pred, Term, Var};

/// A satisfiability query in the form an SMT solver expects: a list of
/// declarations, a list of asserted facts, and a goal to refute.
///
/// The intended reading is *"is there an input that satisfies every assumption
/// but falsifies the goal?"*. A solver answering `unsat` proves the goal under
/// the assumptions, which is exactly what [`crate::smt::prove_implies`] means.
#[derive(Debug, Clone, Copy)]
pub struct Query<'a> {
    /// The variables to declare, in order.
    pub vars: &'a [Var],
    /// Facts that hold before the goal is checked.
    pub assumptions: &'a [Pred],
    /// The predicate to refute.
    pub goal: Pred,
}

impl<'a> Query<'a> {
    /// Build a query with no assumptions: "can `goal` be falsified at all?".
    pub const fn new(vars: &'a [Var], goal: Pred) -> Query<'a> {
        Query {
            vars,
            assumptions: &[],
            goal,
        }
    }

    /// Add assumptions. The result is a new query; nothing is mutated.
    pub const fn assuming(mut self, assumptions: &'a [Pred]) -> Query<'a> {
        self.assumptions = assumptions;
        self
    }

    /// Write the query as SMT-LIB2.
    ///
    /// The emitted text asserts the assumptions and then the *negation* of the
    /// goal, so `unsat` from any compliant solver is a proof of the goal.
    pub fn write_smtlib2<W: Write>(&self, out: &mut W) -> fmt::Result {
        // A refused term still has a tree, and printing it produces a file no solver will
        // parse: a mixed-width operation like `(bvadd x0_12 x1_8)` is ill-sorted. Emitting
        // that is the worst of both worlds -- the engine said `Unknown`, so there is no
        // proof to check, and the artifact meant to let an independent solver help instead
        // fails to load, which reads as a broken proof rather than a refused term. So check
        // the same flag the engine does and say so in the file, in a form every solver
        // ignores, rather than writing a query that cannot be answered.
        if smt::is_ill_formed() {
            writeln!(out, "; refused: the term is ill-formed (mixed operand widths, an")?;
            writeln!(out, "; out-of-range constant, or a duplicate substitution target)")?;
            writeln!(out, "; the engine answers `Unknown` for this query, so there is nothing")?;
            writeln!(out, "; to hand to a solver")?;
            return Ok(());
        }
        writeln!(out, "; generated by verif (in-code formal verification)")?;
        writeln!(out, "(set-logic QF_BV)")?;
        writeln!(out, "(set-option :produce-models true)")?;
        for v in self.vars {
            writeln!(
                out,
                "(declare-fun {} () (_ BitVec {}))",
                var_name(*v),
                smt::bits(*v)
            )?;
        }
        for a in self.assumptions {
            writeln!(out, "(assert {})", as_bool(*a))?;
        }
        writeln!(out, "(assert (not {}))", as_bool(self.goal))?;
        writeln!(out, "(check-sat)")?;
        writeln!(out, "(get-model)")?;
        Ok(())
    }
}

/// Render `p` as a boolean SMT-LIB term.
///
/// The engine represents a boolean as a one-bit word, so a term has to be
/// coerced: a genuine boolean connective prints as-is, while a one-bit word is
/// compared against `#b0`.
fn as_bool(p: Pred) -> Bool {
    Bool(p.0)
}

/// Wrapper marking a term as boolean-typed for printing.
struct Bool(Term);

/// Wrapper marking a term as a bit-vector for printing.
struct Bits(Term);

/// Wrapper printing a comparison as its native, boolean-sorted SMT-LIB form.
///
/// Comparisons are the one class of term whose SMT-LIB sort is fixed -- always `Bool`,
/// never a bit-vector -- so both `Bool` and `Bits` need their spelling. Printing it in
/// one place keeps `Bool` from delegating to `Bits` which delegates back to `Bool` for
/// the same node, which recursed forever.
struct Cmp(Term);

impl fmt::Display for Cmp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = smt::pred_node(Pred(self.0));
        match n.op {
            Op::Eq => write!(f, "(= {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Ult => write!(f, "(bvult {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Ule => write!(f, "(bvule {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            _ => unreachable!("Cmp is only built for comparisons"),
        }
    }
}

/// Does this operation *always* produce a boolean rather than a word?
///
/// Only the comparisons do. `And`, `Or`, `Xor` and `Not` are ambiguous: they are a
/// boolean operator when their operand is a proposition and a one-bit-vector operator
/// when it is a word, and the engine gives them width 1 either way. The width alone
/// cannot decide the sort, and neither can the operator -- the *context* decides.
/// SMT-LIB is strongly sort-checked, so the two are not interchangeable even where
/// their truth tables agree; treating them as boolean (as this function's predecessor
/// did) emitted `(bvule (_ bv1 1) (or ...))`, ill-sorted and rejected by any compliant
/// solver. `Display for Bool` and `Display for Bits` therefore render from the expected
/// sort, and this predicate is used only to classify genuine comparisons.
fn is_comparison(op: Op) -> bool {
    matches!(op, Op::Eq | Op::Ult | Op::Ule)
}

/// Whether a term is a one-bit connective, which exists in both a boolean and a
/// one-bit-vector reading.
fn is_one_bit_connective(op: Op) -> bool {
    matches!(op, Op::Not | Op::And | Op::Or | Op::Xor)
}

impl fmt::Display for Bool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = smt::pred_node(Pred(self.0));
        if is_comparison(n.op) {
            return write!(f, "{}", Cmp(self.0));
        }
        if n.width == 1 && is_one_bit_connective(n.op) {
            // A one-bit connective is already a proposition in this reading.
            return match n.op {
                Op::Not => write!(f, "(not {})", Bool(Term(n.a))),
                Op::And => write!(f, "(and {} {})", Bool(Term(n.a)), Bool(Term(n.b))),
                Op::Or => write!(f, "(or {} {})", Bool(Term(n.a)), Bool(Term(n.b))),
                _ => write!(f, "(xor {} {})", Bool(Term(n.a)), Bool(Term(n.b))),
            };
        }
        // Any other word used as a proposition: `w != 0`.
        //
        // This used to print `(= w (_ bv0 w))`, the negation of what the comment
        // says. A constant goal came out inverted: `truth(false)` was written as
        // `(assert (not (= (_ bv0 1) (_ bv0 1))))`, i.e. `(assert false)`, which any
        // solver reports `unsat` -- so an external checker would call an impossible
        // obligation *proved*, the opposite of the engine's verdict. `distinct` is
        // the right spelling of `!=`.
        let w = n.width;
        write!(f, "(distinct {} (_ bv0 {}))", Bits(self.0), w)
    }
}

impl fmt::Display for Bits {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = smt::pred_node(Pred(self.0));
        let w = n.width;
        match n.op {
            Op::Var => write!(f, "{}", name_of_var(n.a, w)),
            Op::Const => {
                let v = (n.a as u64) | ((n.hi as u64) << 32);
                write!(f, "(_ bv{} {})", v, w)
            }
            // `Not`, `And`, `Or` and `Xor` exist in both readings. In a bit-vector
            // position the `bv*` spelling is the well-sorted one at every width,
            // including 1: the boolean spelling has sort Bool, which is not
            // `(_ BitVec 1)` even though the truth tables coincide. The boolean
            // reading is produced by `Display for Bool`, so no information is lost.
            Op::Not => write!(f, "(bvnot {})", Bits(Term(n.a))),
            Op::And => write!(f, "(bvand {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Or => write!(f, "(bvor {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Xor => write!(f, "(bvxor {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Add => write!(f, "(bvadd {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Sub => write!(f, "(bvsub {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Mul => write!(f, "(bvmul {} {})", Bits(Term(n.a)), Bits(Term(n.b))),
            Op::Shl => write!(f, "(bvshl {} {})", Bits(Term(n.a)), shift(n.b, w)),
            Op::LShr => write!(f, "(bvlshr {} {})", Bits(Term(n.a)), shift(n.b, w)),
            Op::Shr => write!(f, "(bvashr {} {})", Bits(Term(n.a)), shift(n.b, w)),
            // A comparison has sort Bool, so in a bit-vector position it is coerced to a
            // one-bit vector: `(bvadd (= a b) x)` is ill-sorted, and this is what a solver
            // accepts. The other half of the same sort bug as the `bv*` connectives below.
            Op::Eq | Op::Ult | Op::Ule => {
                write!(f, "(ite {} (_ bv1 1) (_ bv0 1))", Cmp(self.0))
            }
            // Truncate: keep the low bits, zero-fill the rest. The direction decides
            // the operator, and the source width `n.b` decides the direction.
            //
            // `(_ extract w-1 0 x)` needs `x` to be at least `w` bits wide, so it is only
            // valid when the result is *no wider* than the source. Emitting it for a
            // widening `truncate` produced `((_ extract 15 0) x0_8)` -- extracting bit 15
            // from an 8-bit vector, which is ill-sorted. Widening is `zero_extend`.
            Op::Trunc if w > n.b as u8 => write!(
                f,
                "((_ zero_extend {}) {})",
                w - n.b as u8,
                Bits(Term(n.a))
            ),
            Op::Trunc => write!(
                f,
                "((_ extract {} 0) {})",
                w.saturating_sub(1),
                Bits(Term(n.a))
            ),
            Op::Ite => write!(
                f,
                "(ite {} {} {})",
                Bool(Term(n.a)),
                Bits(Term(n.b)),
                Bits(Term(n.c))
            ),
        }
    }
}

fn shift(amount: u32, width: u8) -> ShiftAmount {
    ShiftAmount(amount, width)
}

struct ShiftAmount(u32, u8);

impl fmt::Display for ShiftAmount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The shift amount is a *value*, and it has to be a legal literal of the shift's
        // width. `(_ bv300 8)` is not: 300 does not fit 8 bits, so a solver either rejects
        // the file or reads 44 -- and when `amount >= 2^width` the meaning changes outright
        // (a shift by 256 on an 8-bit value became a shift by 0, i.e. the identity). The
        // engine's rule is `amount >= width` yields 0 (or the sign for `ashr`), so any
        // amount at or above `width` is clamped to `width`, which is a legal literal and
        // yields exactly that. This is the shift-amount twin of the out-of-range constant
        // bug (`word`): the same "a literal is a claim about a width" mistake, in a
        // different place.
        let w = self.1;
        let amount = if self.0 >= w as u32 { w as u32 } else { self.0 };
        write!(f, "(_ bv{} {})", amount, w)
    }
}

fn name_of_var(idx: u32, width: u8) -> Name {
    Name(idx, width)
}

/// An SMT-LIB identifier for a symbolic variable.
#[derive(Debug, Clone, Copy)]
pub struct Name(u32, u8);

impl fmt::Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "x{}_{}", self.0, self.1)
    }
}

/// The SMT-LIB name for a variable: `x<index>_<width>`.
pub fn var_name(v: Var) -> Name {
    Name(smt::index(v), smt::bits(v))
}

/// Whether the predicate prints as a comparison, i.e. a term whose SMT-LIB sort is
/// `Bool` natively rather than a one-bit word. Exposed so tests can assert the shape of
/// the output.
///
/// A one-bit `and`/`or`/`xor`/`not` is *not* counted: it is a word that `Bool` may render
/// as a boolean connective, but `Bits` renders it as a `bv*` term, so its sort depends on
/// context rather than on the node.
pub fn is_boolean_term(p: Pred) -> bool {
    let n = smt::pred_node(p);
    is_comparison(n.op)
}

#[cfg(feature = "std")]
impl<'a> Query<'a> {
    /// The query as an owned string. Convenience for host-side tooling.
    pub fn to_smtlib2(&self) -> std::string::String {
        let mut s = std::string::String::new();
        // Writing into a `String` cannot fail.
        let _ = self.write_smtlib2(&mut s);
        s
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::smt::{self, var};

    #[cfg(feature = "std")]
    #[test]
    fn exports_a_readable_query() {
        smt::with_fresh(|| {
            let x = var(8);
            let goal = x.lt_val(100);
            let vars = [x];
            let assumptions = [x.lt_val(200)];
            let q = Query::new(&vars, goal).assuming(&assumptions);
            let text = q.to_smtlib2();

            assert!(text.contains("(set-logic QF_BV)"), "missing logic: {}", text);
            assert!(
                text.contains("(declare-fun x0_8 () (_ BitVec 8))"),
                "missing declaration: {}",
                text
            );
            assert!(
                text.contains("(assert (bvult x0_8 (_ bv200 8)))"),
                "missing assumption: {}",
                text
            );
            // The goal is negated, so `unsat` means "proved".
            assert!(
                text.contains("(assert (not (bvult x0_8 (_ bv100 8))))"),
                "missing negated goal: {}",
                text
            );
            assert!(text.contains("(check-sat)"), "missing check-sat: {}", text);
        });
    }

    #[cfg(feature = "std")]
    #[test]
    fn exports_arithmetic_and_shifts() {
        smt::with_fresh(|| {
            let a = var(16);
            let b = var(16);
            let goal = smt::ule(smt::add(a, b), a);
            let vars = [a, b];
            let text = Query::new(&vars, goal).to_smtlib2();
            assert!(
                text.contains("(assert (not (bvule (bvadd x0_16 x1_16) x0_16)))"),
                "unexpected text: {}",
                text
            );

            let shifted = smt::ule(smt::lshr(a, 4), a);
            let vars = [a];
            let text = Query::new(&vars, shifted).to_smtlib2();
            assert!(
                text.contains("(bvlshr x0_16 (_ bv4 16))"),
                "unexpected shift text: {}",
                text
            );
        });
    }

    #[cfg(feature = "std")]
    #[test]
    fn one_bit_words_are_coerced_to_booleans() {
        smt::with_fresh(|| {
            let a = var(1);
            // `a` is a one-bit word, so using it as a goal must compare to zero.
            let vars = [a];
            let text = Query::new(&vars, a.eq_val(1)).to_smtlib2();
            assert!(text.contains("(assert (not (= x0_1 (_ bv1 1))))"), "{}", text);
        });
    }

    #[cfg(feature = "std")]
    #[test]
    fn a_one_bit_connective_in_a_bitvector_position_prints_as_a_bitvector() {
        // The sort bug the `is_comparison` note describes. A one-bit `and`/`or`/`xor`/
        // `not` is a word when it feeds a bit-vector operator and a proposition when it is
        // the goal. Printing it as a boolean operator in the bit-vector position emitted
        // `(bvule (_ bv1 1) (or ...))`, which z3 rejects as ill-sorted -- so an independent
        // check of the *wrong formula* would fail, silently, and the export would look
        // like a failed proof rather than a broken printer.
        smt::with_fresh(|| {
            let x = var(1);
            let y = var(1);
            let p = smt::eq(smt::band(x, y), smt::word(1, 1));
            let text = Query::new(&[x, y], p).to_smtlib2();
            assert!(
                text.contains("(assert (not (= (bvand x0_1 x1_1) (_ bv1 1))))"),
                "a one-bit word operand must use the bv spelling: {}",
                text
            );
        });
    }

    #[cfg(feature = "std")]
    #[test]
    fn a_comparison_used_as_a_word_is_coerced() {
        // The other half: a comparison has sort Bool, so in a bit-vector position it needs
        // `(ite <cmp> (_ bv1 1) (_ bv0 1))`. This shape is reachable through `smt::ite`
        // over one-bit branches, where a branch may be a comparison.
        smt::with_fresh(|| {
            let a = var(8);
            let b = var(8);
            let t = smt::ult(a, b);          // a Pred: boolean-sorted
            let one = smt::word(1, 1);
            let zero = smt::word(0, 1);
            // `ite(t, one, zero)` forces both branches to one bit, and `t` to a word.
            let w = smt::ite(t, one, zero);
            let p = smt::eq(w, one);
            let text = Query::new(&[a, b], p).to_smtlib2();
            assert!(
                text.contains("(ite (bvult x0_8 x1_8) (_ bv1 1) (_ bv0 1))"),
                "a comparison in a word position must be coerced: {}",
                text
            );
        });
    }

    #[cfg(feature = "std")]
    #[test]
    fn a_boolean_combination_of_comparisons_stays_boolean() {
        // The positive control: when the term *is* the goal, the boolean spelling is the
        // right one, and the fix must not have turned it into a `bv*` form.
        smt::with_fresh(|| {
            let x = var(1);
            let y = var(1);
            let p = smt::and(x.lt_val(1), y.le_val(1));
            let text = Query::new(&[x, y], p).to_smtlib2();
            assert!(
                text.contains("(assert (not (and (bvult x0_1 (_ bv1 1)) (bvule x1_1 (_ bv1 1)))))"),
                "a boolean goal must keep the boolean spelling: {}",
                text
            );
        });
    }

    #[test]
    fn every_operator_has_a_printer() {
        smt::with_fresh(|| {
            let a = var(8);
            let b = var(8);
            let preds = [
                smt::eq(a, b),
                smt::ult(a, b),
                smt::ule(a, b),
                smt::and(smt::ult(a, b), smt::ult(b, a)),
                smt::or(smt::ult(a, b), smt::not(smt::ult(a, b))),
                smt::eq(smt::add(a, b), smt::sub(a, b)),
                smt::eq(smt::mul(a, b), smt::band(a, b)),
                smt::eq(smt::bor(a, b), smt::bxor(a, b)),
                smt::eq(smt::shl(a, 1), smt::lshr(a, 1)),
                smt::eq(smt::ashr(a, 1), smt::ite(smt::ult(a, b), a, b)),
                smt::truth(true),
            ];
            for p in preds {
                // Rendering must not panic and must produce non-empty output.
                let mut buf = FixedBuf::new();
                let _ = write!(&mut buf, "{}", as_bool(p));
                assert!(!buf.contents().is_empty());
            }
        });
    }

    /// A tiny `core::fmt::Write` sink, to prove the exporter works without `std`.
    struct FixedBuf {
        buf: [u8; 512],
        len: usize,
    }

    impl FixedBuf {
        fn new() -> Self {
            FixedBuf {
                buf: [0; 512],
                len: 0,
            }
        }
        fn contents(&self) -> &str {
            core::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
        }
    }

    impl fmt::Write for FixedBuf {
        fn write_str(&mut self, s: &str) -> fmt::Result {
            let bytes = s.as_bytes();
            if self.len + bytes.len() > self.buf.len() {
                return Err(fmt::Error);
            }
            self.buf[self.len..self.len + bytes.len()].copy_from_slice(bytes);
            self.len += bytes.len();
            Ok(())
        }
    }
}