verif 0.1.1

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
509
510
511
//! A small, comparable summary of a MIR dump — the unit the `rustc_public`
//! oracle checks the text frontend against.
//!
//! The frontend's known weakness (README, "The known gaps", gap 2) is that it
//! reads the *textual* `--emit=mir` dump rather than linking `rustc`. A rustc
//! release that changes the pretty-printer can therefore break the parser, and
//! the parser would be the only thing that noticed — which is to say, nothing
//! would.
//!
//! This module defines the smallest summary that is both
//!
//! * derivable from the text dump by the frontend's own parser, and
//! * derivable from the *typed* MIR by `rustc_public` in
//!   `tools/mir-oracle`,
//!
//! so the two can be compared. The oracle lives in a separate crate on purpose:
//! linking `rustc` internals needs `#![feature(rustc_private)]` and the nightly
//! `rustc-dev` component, and neither may leak into a crate that must build on
//! stable with no dependencies. So this crate exposes the summary as plain data
//! ([`FnShape`]), the oracle computes the same shape from the compiler's own IR,
//! and the gate fails if they disagree.
//!
//! What is compared is deliberately structural, not textual: how many basic
//! blocks each function lowered to, and which panic conditions `rustc` inserted,
//! in block order. Those are facts about the program, not about the printer, so
//! a match is real evidence and a mismatch points at the parser rather than at
//! whitespace.

use std::collections::BTreeMap;

use crate::mir::parse::{self, Term};

/// The kind of panic `rustc` guards against, normalised so the two MIR sources
/// can be compared without comparing their printers.
///
/// The variants mirror `rustc`'s own `AssertMessage` for the operations this
/// frontend models. `Other` carries the raw message for anything else, so a
/// shape mismatch is still diagnosable rather than silently dropped — and so
/// that an unmodelled assert is *visible* instead of absent.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum PanicKind {
    /// `a + b` overflow.
    OverflowAdd,
    /// `a - b` underflow.
    OverflowSub,
    /// `a * b` overflow.
    OverflowMul,
    /// `a / b` overflow, i.e. `MIN / -1`.
    OverflowDiv,
    /// `a % b` overflow, i.e. `MIN % -1`.
    OverflowRem,
    /// `-a` overflow, i.e. `-MIN`.
    OverflowNeg,
    /// A zero divisor in `/`.
    DivByZero,
    /// A zero divisor in `%`.
    RemByZero,
    /// A shift by at least the width.
    ShiftLeft,
    /// A right shift by at least the width.
    ShiftRight,
    /// An array or slice index past the end.
    Bounds,
    /// Anything else, carrying `rustc`'s message so it is not lost.
    Other(String),
}

impl PanicKind {
    /// Classify the message `rustc` prints inside `assert(…)` in a text dump.
    ///
    /// The text dump spells these out, with the operator inline in the template:
    ///
    /// ```text
    /// assert(!move (_5.1: bool), "attempt to compute `{} - {}`, which would overflow", …)
    /// assert(!move _6, "attempt to divide `{}` by zero", …)
    /// ```
    ///
    /// so this matches on the operator glyph and the verb. It is deliberately
    /// tolerant of the surrounding wording — a rustc release that reflows the
    /// sentence but keeps `` `{} - {}` `` still classifies — but it is *not*
    /// tolerant of the operator, because that is the fact being compared.
    pub fn from_text_message(msg: &str) -> PanicKind {
        let has = |s: &str| msg.contains(s);
        if has("by zero") || has("divisor of zero") {
            if has("remainder") {
                PanicKind::RemByZero
            } else {
                PanicKind::DivByZero
            }
        } else if has("negate") {
            PanicKind::OverflowNeg
        } else if has("shift left") {
            PanicKind::ShiftLeft
        } else if has("shift right") {
            PanicKind::ShiftRight
        } else if has("index out of bounds") || has("slice index") {
            PanicKind::Bounds
        } else if has("{} - {}") {
            PanicKind::OverflowSub
        } else if has("{} + {}") {
            PanicKind::OverflowAdd
        } else if has("{} * {}") {
            PanicKind::OverflowMul
        } else if has("{} / {}") {
            PanicKind::OverflowDiv
        } else if has("{} % {}") {
            PanicKind::OverflowRem
        } else {
            PanicKind::Other(msg.to_string())
        }
    }
}

/// Which way round an assert's condition is: whether the panic fires on the
/// condition being *true* or *false*.
///
/// This is a separate field from [`PanicKind`] because the two are independent
/// and both are load-bearing. `PanicKind` says *what* the guard is about — an
/// addition overflow, a zero divisor — and the polarity says whether `rustc`
/// printed the condition or its negation. rustc prints
/// `assert(!move _3, "…")` for the arithmetic guards, so the *same* message with
/// the `!` flipped describes the opposite program: one reports an overflowing add
/// as a panic, the other reports every non-overflowing add as a panic and misses
/// the overflowing one.
///
/// Recording only the message let a printer change that flipped a leading `!`
/// leave both block count and panic kind identical, so the oracle agreed while
/// the frontend checked the opposite guard. The frontend's parser has always
/// carried this (`Term::Assert { negated, … }`); the shape did not, which is
/// exactly the gap.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Polarity {
    /// `assert(cond, …)`: the panic fires when `cond` is false.
    True,
    /// `assert(!cond, …)`: the panic fires when `cond` is true.
    Negated,
}

impl Polarity {
    /// The polarity for a parsed leading `!`.
    pub const fn from_negated(negated: bool) -> Self {
        if negated {
            Polarity::Negated
        } else {
            Polarity::True
        }
    }
}

/// One panic guard: what it guards against, and which way round its condition is.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct AssertShape {
    /// The condition `rustc` is guarding, normalised.
    pub kind: PanicKind,
    /// Whether the panic fires on the condition being true or false.
    pub polarity: Polarity,
}

/// The comparable summary of one function.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FnShape {
    /// How many basic blocks the function lowered to.
    pub blocks: usize,
    /// The panic guards `rustc` inserted, in `(block, order within block)` order,
    /// each with its polarity.
    pub panics: Vec<AssertShape>,
}

/// The summaries of every function in a text MIR dump, grouped by bare name.
///
/// The key is the last path segment (`actuator::clamp` and `clamp` both key as
/// `clamp`) because the two MIR sources spell the path differently and the point
/// is to compare the functions, not their qualified names.
///
/// The value is a **list**, not one shape, because a bare name is not unique:
/// `impl A { fn check(…) }` and `impl B { fn check(…) }` in one file both key as
/// `check`. A single-slot map silently kept whichever came last, so a regression
/// in the dropped method was invisible. Keeping every shape and comparing the
/// groups as multisets is what makes a lost or altered method show up, and it
/// does not depend on the two sides agreeing about qualified names or about the
/// order the functions appear in.
pub fn of_text_mir(mir: &str) -> BTreeMap<String, Vec<FnShape>> {
    let program = parse::parse_program(mir);
    let mut out: BTreeMap<String, Vec<FnShape>> = BTreeMap::new();
    for f in &program.fns {
        let mut panics = Vec::new();
        // `blocks` is in dump order, and each block's statements and terminator
        // are in order, so the panic list is deterministic.
        for block in &f.blocks {
            if let Term::Assert { msg, negated, .. } = &block.term {
                panics.push(AssertShape {
                    kind: PanicKind::from_text_message(msg),
                    polarity: Polarity::from_negated(*negated),
                });
            }
        }
        let key = f.name.rsplit("::").next().unwrap_or(&f.name).to_string();
        out.entry(key).or_default().push(FnShape {
            blocks: f.blocks.len(),
            panics,
        });
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The text classifier, pinned against the exact strings `rustc --emit=mir`
    /// prints. These are copied from a real dump rather than invented, because
    /// the whole risk this module manages is that the wording moves.
    #[test]
    fn classifies_rustc_text_messages() {
        let cases = [
            ("attempt to compute `{} - {}`, which would overflow", PanicKind::OverflowSub),
            ("attempt to compute `{} + {}`, which would overflow", PanicKind::OverflowAdd),
            ("attempt to compute `{} * {}`, which would overflow", PanicKind::OverflowMul),
            ("attempt to compute `{} / {}`, which would overflow", PanicKind::OverflowDiv),
            ("attempt to compute `{} % {}`, which would overflow", PanicKind::OverflowRem),
            ("attempt to negate `{}`, which would overflow", PanicKind::OverflowNeg),
            ("attempt to divide `{}` by zero", PanicKind::DivByZero),
            ("attempt to calculate the remainder with a divisor of zero", PanicKind::RemByZero),
            ("attempt to shift left by `{}`, which would overflow", PanicKind::ShiftLeft),
            ("attempt to shift right by `{}`, which would overflow", PanicKind::ShiftRight),
            ("index out of bounds: the len is {} but the index is {}", PanicKind::Bounds),
        ];
        for (msg, want) in cases {
            assert_eq!(PanicKind::from_text_message(msg), want, "message: {msg}");
        }
    }

    /// A message the classifier does not recognise is kept, not discarded: an
    /// unmodelled panic must still compare unequal to a typed-side `Other`, so
    /// it fails the oracle rather than passing by omission.
    #[test]
    fn an_unknown_message_is_preserved() {
        let kind = PanicKind::from_text_message("something entirely new");
        assert_eq!(kind, PanicKind::Other("something entirely new".to_string()));
    }

    /// The block count is read from the parsed IR, and a two-arm branch is what
    /// makes it more than one — a smoke test that the shape is actually populated
    /// rather than always zero.
    #[test]
    fn shape_counts_blocks_from_a_real_dump() {
        let dump = "\
fn simple(_1: u32, _2: u32) -> u32 {
    let mut _0: u32;
    let mut _3: bool;

    bb0: {
        _3 = Lt(_1, _2);
        switchInt(move _3) -> [0: bb2, otherwise: bb1];
    }

    bb1: {
        _0 = _1;
        goto -> bb2;
    }

    bb2: {
        return;
    }
}
";
        let shapes = of_text_mir(dump);
        let s = shapes.get("simple").expect("function parsed");
        assert_eq!(s.len(), 1, "one function named `simple`");
        assert_eq!(s[0].blocks, 3);
        assert!(s[0].panics.is_empty());
    }

    /// The polarity is carried and is separate from the kind. A dump whose guard
    /// is `assert(!…)` must not shape the same as one whose guard is `assert(…)`
    /// with the same message, because they describe opposite programs.
    #[test]
    fn polarity_is_recorded_and_distinguishes_inverted_guards() {
        let dump = |cond: &str| {
            format!(
                "\
fn checked(_1: u32, _2: u32) -> u32 {{
    let mut _0: u32;
    let mut _3: bool;

    bb0: {{
        _3 = AddWithOverflow(_1, _2);
        assert({cond}move (_3.1: bool), \"attempt to compute `{{}} + {{}}`, which would overflow\") -> [success: bb1, unwind continue];
    }}

    bb1: {{
        _0 = _1;
        return;
    }}
}}
"
            )
        };
        let normal = of_text_mir(&dump(""));
        let inverted = of_text_mir(&dump("!"));

        let n = &normal.get("checked").unwrap()[0];
        let i = &inverted.get("checked").unwrap()[0];
        assert_eq!(n.panics.len(), 1);
        assert_eq!(n.panics[0].kind, PanicKind::OverflowAdd);
        assert_eq!(i.panics[0].kind, PanicKind::OverflowAdd);
        assert_eq!(n.panics[0].polarity, Polarity::True);
        assert_eq!(i.panics[0].polarity, Polarity::Negated);
        assert_ne!(
            n, i,
            "flipping the `!` must change the shape, or the oracle cannot see it"
        );
    }

    /// Two methods with the same bare name must both survive. The old single-slot
    /// map kept only the last, so a regression in the dropped one was invisible.
    #[test]
    fn same_named_functions_are_both_kept() {
        let dump = "\
fn check(_1: u32, _2: u32) -> u32 {
    let mut _0: u32;

    bb0: {
        _0 = _1;
        return;
    }
}

fn check(_1: u32) -> u32 {
    let mut _0: u32;
    let mut _2: u32;

    bb0: {
        _0 = _1;
        return;
    }

    bb1: {
        return;
    }
}
";
        let shapes = of_text_mir(dump);
        let group = shapes.get("check").expect("both methods present");
        assert_eq!(group.len(), 2, "both `check`s must be kept, not overwritten");
        let mut blocks: Vec<usize> = group.iter().map(|s| s.blocks).collect();
        blocks.sort_unstable();
        assert_eq!(blocks, vec![1, 2], "each shape is kept distinctly");
    }

    /// **The oracle's scope, pinned as a property rather than described in prose.**
    ///
    /// [`FnShape`] is two facts: the block count and the panic guards. That is
    /// deliberate -- both are facts about the *program*, so a match is evidence
    /// and a mismatch points at the parser -- but it also means the comparison
    /// cannot see everything the parser reads. This test states the boundary
    /// exactly, in both directions, so the prose in `README.md` and in
    /// `tools/mir-oracle` cannot drift into claiming more than the code does.
    ///
    /// The blind cases are not hypothetical: `Len((*_1))` became
    /// `PtrMetadata(copy _1)` in rustc 1.99, and that real change cost four
    /// verdicts on the 1.85 floor (see `AGENTS.md`, "The MIR frontend needs a
    /// `rustc`, not a *nightly* `rustc`"). The oracle's shape is identical
    /// across it, so gate 10 did not and could not catch it -- the MSRV gate did.
    ///
    /// **Every comparison here needs a parsing control, and that is not
    /// decoration.** An `assert_eq!` on two `Option`s passes when *both* are
    /// `None`, so a `shape_of` that failed to parse would satisfy the three
    /// "the shape is blind to X" assertions for the wrong reason -- the test
    /// would report that the oracle cannot see a place change when in fact it
    /// saw nothing at all. The three blind cases are therefore each preceded by
    /// `parsed(...)`, which requires the dump to have produced a function with
    /// the expected block count; only then does "the two shapes are equal" mean
    /// "the shape is identical despite the edit". The two structural cases get
    /// the same control, so `assert_ne!` cannot pass by comparing two `None`s
    /// either. Teeth: a `shape_of` that returns `None` unconditionally fails the
    /// first control rather than the fourth assertion.
    #[test]
    fn the_shape_sees_structure_and_guards_but_not_places() {
        let shape_of = |src: &str| of_text_mir(src).remove("f");
        // A parsing control: the dump must yield exactly one function named `f`
        // with the given block count, or a later equality is vacuous.
        let parsed = |src: &str, blocks: usize| {
            let mut group = shape_of(src).expect("the dump must parse to a function `f`");
            assert_eq!(group.len(), 1, "the dump must yield exactly one `f`");
            let s = group.remove(0);
            assert_eq!(
                s.blocks, blocks,
                "the parsing control expects {blocks} block(s), got {}",
                s.blocks
            );
            s
        };

        // A place spelled the old way and the new way: same shape.
        let len_old = "\
fn f(_1: &[u8], _2: usize) -> u8 {
    let mut _0: u8;
    let mut _3: usize;
    let mut _4: bool;

    bb0: {
        _3 = Len((*_1));
        _4 = Lt(copy _2, copy _3);
        assert(move _4, \"index out of bounds: the len is {} but the index is {}\") -> [success: bb1, unwind continue];
    }

    bb1: {
        _0 = const 1u8;
        return;
    }
}
";
        let len_new = len_old.replace("Len((*_1))", "PtrMetadata(copy _1)");
        // Parsing control: both spellings parse, to the same two blocks.
        let old_shape = parsed(len_old, 2);
        let new_shape = parsed(&len_new, 2);
        assert_eq!(
            old_shape, new_shape,
            "a place's spelling is invisible to the shape -- gate 10 cannot catch a \
             printer change that only re-spells a place"
        );

        // An operand read from the wrong local: same shape.
        let wrong_local = len_new.replace("Lt(copy _2, copy _3)", "Lt(copy _1, copy _3)");
        assert_eq!(
            new_shape,
            parsed(&wrong_local, 2),
            "which local an operand reads is invisible to the shape"
        );

        // A field index read wrong: same shape.
        let field_0 = "\
fn f(_1: (u8, u8)) -> u8 {
    let mut _0: u8;

    bb0: {
        _0 = copy (_1.0: u8);
        return;
    }
}
";
        let field_1 = field_0.replace("(_1.0: u8)", "(_1.1: u8)");
        assert_eq!(
            parsed(field_0, 1),
            parsed(&field_1, 1),
            "which field a projection reads is invisible to the shape"
        );

        // A *structural* change -- an extra block -- is what the shape is for.
        let one_block = "\
fn f(_1: u32) -> u32 {
    let mut _0: u32;

    bb0: {
        _0 = copy _1;
        return;
    }
}
";
        let three_blocks = "\
fn f(_1: u32) -> u32 {
    let mut _0: u32;
    let mut _2: bool;

    bb0: {
        _2 = Lt(copy _1, const 3u32);
        switchInt(move _2) -> [0: bb2, otherwise: bb1];
    }

    bb1: {
        _0 = copy _1;
        goto -> bb2;
    }

    bb2: {
        return;
    }
}
";
        assert_ne!(
            parsed(one_block, 1),
            parsed(three_blocks, 3),
            "the block count must distinguish a branch -- this is the shape's whole job"
        );

        // And a flipped guard polarity is visible, which is the other half.
        let guard = "\
fn f(_1: u32, _2: u32) -> u32 {
    let mut _0: u32;
    let mut _3: bool;

    bb0: {
        _3 = AddWithOverflow(_1, _2);
        assert(move (_3.1: bool), \"attempt to compute `{} + {}`, which would overflow\") -> [success: bb1, unwind continue];
    }

    bb1: {
        _0 = copy _1;
        return;
    }
}
";
        let flipped = guard.replace("assert(move (_3.1", "assert(!move (_3.1");
        assert_ne!(
            parsed(guard, 2),
            parsed(&flipped, 2),
            "a flipped guard polarity must be visible"
        );
    }
}