smtlite 0.2.0

A small, pure-Rust QF_BV SMT solver: bitvector expressions bit-blasted to CNF and solved by a self-contained DPLL core.
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
//! Tests for the public surface that is not an arithmetic encoding: model readback, provenance
//! queries, the solver's budgeting knobs, and the small value helpers.

use smtlite::{Bv, Solution, Solver, mask};

fn sat(s: &Solver) -> smtlite::Model {
    match s.check() {
        Solution::Sat(m) => m,
        other => panic!("expected SAT, got {other:?}"),
    }
}

// ---- Model readback -----------------------------------------------------------------------

#[test]
fn a_declared_variable_no_constraint_touches_still_reads_back() {
    // The model is total over the declaration, not just the variables a constraint encoded.
    let mut s = Solver::new();
    let x = s.var("x", 8);
    let _unused = s.var("unused", 16);
    s.assert(x.eq(&Bv::val(5, 8)));

    let m = sat(&s);
    assert_eq!(m.get("x"), Some(5));
    let u = m.get("unused").expect("a declared variable reads back");
    assert!(u <= 0xffff, "unused value {u} exceeds its 16-bit width");
}

#[test]
fn an_empty_constraint_set_yields_a_total_model() {
    let mut s = Solver::new();
    let _a = s.var("a", 1);
    let _b = s.var("b", 64);

    let m = sat(&s);
    assert!(m.get("a").is_some());
    assert!(m.get("b").is_some());
    assert!(m.get("never_declared").is_none());
}

#[test]
fn every_declared_width_reads_back_exactly() {
    // Walk widths 1..=64, pin each variable, and read it back verbatim.
    for w in 1..=64u32 {
        let v = mask(0xDEAD_BEEF_CAFE_BABE, w);
        let mut s = Solver::new();
        let x = s.var("x", w);
        s.assert(x.eq(&Bv::val(v, w)));
        let m = sat(&s);
        assert_eq!(m.get("x"), Some(v), "width {w} did not read back");
    }
}

// ---- Solver budgeting ---------------------------------------------------------------------

#[test]
fn zero_clause_cap_yields_unknown_without_solving() {
    // The blaster always allocates the pinned `true` literal, so even an empty formula exceeds a
    // zero cap and comes back Unknown rather than a verdict.
    let s = Solver::new().with_max_clauses(0);
    assert!(matches!(s.check(), Solution::Unknown));
}

#[test]
fn zero_budget_refutes_by_propagation_but_cannot_branch() {
    // Unsatisfiable by propagation alone: no decision is spent, so a zero budget still refutes it.
    let mut s = Solver::new();
    let x = s.var("x", 8);
    s.assert(x.eq(&Bv::val(5, 8)));
    s.assert(x.eq(&Bv::val(6, 8)));
    assert!(matches!(s.check_with_budget(0), Solution::Unsat));

    // Satisfiable, but only after branching. `y | z` has no unit clause, so the solver has to
    // decide one of them - and the first decision exceeds a zero budget.
    let mut t = Solver::new();
    let y = t.var("y", 1);
    let z = t.var("z", 1);
    assert!(matches!(
        t.check_all_with_budget(&[y.or(&z)], 0),
        Solution::Unknown
    ));
}

#[test]
fn an_unconstrained_solver_answers_without_spending_a_decision() {
    // A variable no clause mentions is free: it needs no decision, so even a zero budget settles
    // the query, and the model still carries a value for it.
    let mut s = Solver::new();
    let _y = s.var("y", 8);
    match s.check_with_budget(0) {
        Solution::Sat(m) => assert!(m.get("y").is_some(), "the model is total"),
        other => panic!("expected SAT, got {other:?}"),
    }
}

#[test]
fn an_elapsed_deadline_yields_unknown_not_unsat() {
    // `x != x` is unsatisfiable, but an already-elapsed deadline must answer Unknown - "no answer",
    // never a (here, coincidentally correct) "no solution".
    let mut s = Solver::new();
    let x = s.var("x", 8);
    let past = std::time::Instant::now()
        .checked_sub(std::time::Duration::from_secs(1))
        .unwrap_or_else(std::time::Instant::now);
    assert!(matches!(
        s.check_all_within(&[x.ne(&x)], 1_000_000, past),
        Solution::Unknown
    ));
}

#[test]
fn an_elapsed_deadline_covers_the_background_blast_and_does_not_poison_it() {
    // A 64-bit multiply is a large blast. An already-elapsed deadline must cut it off in the
    // encode phase - Unknown before any search - and the same solver with a fresh deadline must
    // then complete the same build, proving a deadline-bailed cache build is retried, not
    // remembered as a failure.
    let mut s = Solver::new().with_max_clauses(200_000);
    let x = s.var("x", 64);
    let y = s.var("y", 64);
    s.assert(x.mul(&y).eq(&Bv::val(6, 64)));

    let past = std::time::Instant::now()
        .checked_sub(std::time::Duration::from_secs(1))
        .unwrap_or_else(std::time::Instant::now);
    assert!(matches!(
        s.check_assumptions_within(&[], 1_000_000, past),
        Solution::Unknown
    ));

    let far = std::time::Instant::now() + std::time::Duration::from_secs(3600);
    match s.check_assumptions_within(&[], 1_000_000, far) {
        Solution::Sat(m) => {
            // The rebuilt blast is the real formula: the model's x*y really is 6.
            let (v, w) = (m.get("x").unwrap(), m.get("y").unwrap());
            assert_eq!(v.wrapping_mul(w), 6, "model {v} * {w} != 6");
        }
        other => panic!("expected SAT with a fresh deadline, got {other:?}"),
    }
}

#[test]
fn an_over_cap_background_answers_unknown_on_every_check() {
    // The over-cap background is remembered as oversize, so repeated checks answer Unknown
    // without re-blasting the same too-large formula each time.
    let mut s = Solver::new().with_max_clauses(8);
    let x = s.var("x", 8);
    let y = s.var("y", 8);
    s.assert(x.mul(&y).eq(&Bv::val(6, 8))); // an 8-bit mul alone is far over the cap

    for _ in 0..3 {
        assert!(matches!(s.check(), Solution::Unknown));
    }
}

#[test]
fn check_all_ignores_stored_asserts_and_does_not_mutate_them() {
    let mut s = Solver::new();
    let x = s.var("x", 8);
    s.assert(x.eq(&Bv::val(5, 8)));

    // The explicit set is the whole formula: the stored `x == 5` must not leak in to contradict it.
    assert!(matches!(
        s.check_all(&[x.eq(&Bv::val(9, 8))]),
        Solution::Sat(_)
    ));

    // The stored asserts survive the call and still hold.
    assert_eq!(sat(&s).get("x"), Some(5));
}

// ---- Incremental assumptions --------------------------------------------------------------

#[test]
fn assumptions_combine_with_the_stored_background_not_replace_it() {
    // `check_assumptions` solves asserts ++ assumptions; `check_all` solves assumptions alone.
    let mut s = Solver::new();
    let x = s.var("x", 8);
    s.assert(x.eq(&Bv::val(5, 8)));

    // Against the background x == 5, an assumption x == 9 is unsat...
    assert!(matches!(
        s.check_assumptions(&[x.eq(&Bv::val(9, 8))]),
        Solution::Unsat
    ));
    // ...whereas `check_all` treats x == 9 as the whole formula and finds it satisfiable.
    assert!(matches!(
        s.check_all(&[x.eq(&Bv::val(9, 8))]),
        Solution::Sat(_)
    ));
}

#[test]
fn assumptions_do_not_leak_into_the_next_solve() {
    let mut s = Solver::new();
    let x = s.var("x", 8);
    s.assert(x.ult(&Bv::val(10, 8))); // background: x < 10

    // x > 5 is satisfiable against the background...
    assert!(matches!(
        s.check_assumptions(&[x.ugt(&Bv::val(5, 8))]),
        Solution::Sat(_)
    ));
    // ...and it did not stick: x < 5 (which contradicts x > 5) is also satisfiable.
    assert!(matches!(
        s.check_assumptions(&[x.ult(&Bv::val(5, 8))]),
        Solution::Sat(_)
    ));
}

#[test]
fn assert_invalidates_the_cached_background() {
    let mut s = Solver::new();
    let x = s.var("x", 8);
    s.assert(x.eq(&Bv::val(5, 8)));
    assert!(matches!(s.check(), Solution::Sat(_)));

    // A later assert must take effect, not be hidden behind a stale blast of the old background.
    s.assert(x.eq(&Bv::val(6, 8)));
    assert!(matches!(s.check(), Solution::Unsat));
}

#[test]
fn var_invalidates_the_cached_background_so_the_model_stays_total() {
    let mut s = Solver::new();
    let x = s.var("x", 8);
    s.assert(x.eq(&Bv::val(5, 8)));
    assert!(matches!(s.check(), Solution::Sat(_)));

    // A variable declared after the background was blasted still reads back in later models.
    let y = s.var("y", 8);
    match s.check() {
        Solution::Sat(m) => {
            assert_eq!(m.get("x"), Some(5));
            assert!(m.get("y").is_some(), "a later-declared variable reads back");
        }
        other => panic!("expected SAT, got {other:?}"),
    }

    // And the new variable participates in constraints, too.
    s.assert(y.eq(&Bv::val(7, 8)));
    match s.check() {
        Solution::Sat(m) => assert_eq!(m.get("y"), Some(7)),
        other => panic!("expected SAT, got {other:?}"),
    }
}

#[test]
fn assumption_budget_and_deadline_variants_degrade_the_same_way() {
    let mut s = Solver::new();
    let x = s.var("x", 8);

    // Refuted by propagation alone: a zero budget still proves it unsat.
    assert!(matches!(
        s.check_assumptions_with_budget(&[x.eq(&Bv::val(1, 8)), x.eq(&Bv::val(2, 8))], 0),
        Solution::Unsat
    ));

    // An already-elapsed deadline answers Unknown, never a verdict.
    let past = std::time::Instant::now()
        .checked_sub(std::time::Duration::from_secs(1))
        .unwrap_or_else(std::time::Instant::now);
    assert!(matches!(
        s.check_assumptions_within(
            &[x.eq(&Bv::val(1, 8)), x.eq(&Bv::val(2, 8))],
            1_000_000,
            past
        ),
        Solution::Unknown
    ));
}

#[test]
fn assumption_models_read_back_background_only_variables() {
    // The cache seeds the assumption blaster with every declared variable's bits, so a model from
    // `check_assumptions` is total over the declaration: it reads back a variable only the stored
    // background mentions, and one only the assumption mentions.
    let mut s = Solver::new();
    let x = s.var("x", 8);
    let y = s.var("y", 8);
    s.assert(x.eq(&Bv::val(5, 8))); // background: x == 5, y untouched

    match s.check_assumptions(&[y.eq(&Bv::val(7, 8))]) {
        Solution::Sat(m) => {
            assert_eq!(m.get("x"), Some(5), "a background-only variable reads back");
            assert_eq!(
                m.get("y"),
                Some(7),
                "an assumption-only variable reads back"
            );
        }
        other => panic!("expected SAT, got {other:?}"),
    }
}

#[test]
fn the_incremental_path_matches_check_all_on_the_same_formula() {
    // The incremental path (stored background ++ assumptions) and the one-shot path (`check_all`)
    // do not blast identical clause sets - the assumption blaster works from a fresh memo and
    // re-encodes shared subgraphs as fresh Tseitin gates - but the two are equisatisfiable and
    // must agree on the verdict. The models agree on the declared variables only because the
    // background pins every one of them, so the test asserts the verdict kind plus the pinned
    // readbacks, not raw model equality.
    let mut inc = Solver::new();
    let x = inc.var("x", 8);
    let y = inc.var("y", 8);
    inc.assert(x.eq(&Bv::val(0x2a, 8))); // background pins x and y
    inc.assert(y.eq(&Bv::val(0x77, 8)));

    let mut direct = Solver::new();
    let dx = direct.var("x", 8);
    let dy = direct.var("y", 8);
    let whole_formula = [
        dx.eq(&Bv::val(0x2a, 8)),
        dy.eq(&Bv::val(0x77, 8)),
        dx.add(&dy).eq(&Bv::val(0x2a + 0x77, 8)),
    ];

    match (
        inc.check_assumptions(&[x.add(&y).eq(&Bv::val(0x2a + 0x77, 8))]),
        direct.check_all(&whole_formula),
    ) {
        (Solution::Sat(ma), Solution::Sat(md)) => {
            assert_eq!(ma.get("x"), Some(0x2a));
            assert_eq!(ma.get("y"), Some(0x77));
            assert_eq!(md.get("x"), Some(0x2a));
            assert_eq!(md.get("y"), Some(0x77));
        }
        (Solution::Unsat, Solution::Unsat) => {}
        (a, b) => panic!("the two paths disagreed: {a:?} vs {b:?}"),
    }
}

// ---- Provenance ---------------------------------------------------------------------------

#[test]
fn depends_on_matches_by_name_prefix() {
    let mut s = Solver::new();
    let hdr = s.var("hdr.len", 16);
    let init = s.var("init.base", 16);

    let from_hdr = hdr.add(&Bv::val(1, 16));
    assert!(s.depends_on(&from_hdr, "hdr."));
    assert!(!s.depends_on(&from_hdr, "init"));
    assert!(s.depends_on(&hdr, "hdr"));
    assert!(!s.depends_on(&Bv::val(1, 16), "hdr"));

    let both = hdr.add(&init);
    assert!(s.depends_on(&both, "hdr."));
    assert!(s.depends_on(&both, "init."));
}

#[test]
fn var_ids_deduplicates_shared_subgraphs() {
    let mut s = Solver::new();
    let a = s.var("a", 8);
    let b = s.var("b", 8);
    // `a` used twice is one node, visited once.
    assert_eq!(a.add(&a).var_ids().len(), 1);
    let mut ids = a.add(&b).var_ids();
    ids.sort_unstable();
    assert_eq!(ids, vec![0, 1]);
}

#[test]
fn var_ids_walks_a_deep_chain_without_overflowing_the_stack() {
    let mut s = Solver::new();
    let v = s.var("v", 8);
    let mut deep = v;
    // `shl` rather than `not`: the simplifier collapses `~~x` to `x`, so a `not` chain would
    // never grow. A constant shift is left as built and costs no width assert, so the chain stays
    // deep and each step is O(1).
    for _ in 0..100_000 {
        deep = deep.shl(1);
    }
    // The walk is iterative, so a chain this deep must not blow the stack.
    assert_eq!(deep.var_ids(), vec![0]);
    assert!(s.depends_on(&deep, "v"));
    // `Rc` drop, unlike the walk, *is* recursive - leak rather than overflow in a test.
    std::mem::forget(deep);
}

// ---- Value helpers ------------------------------------------------------------------------

#[test]
fn mask_truncates_to_the_low_bits() {
    assert_eq!(mask(0xabcd, 8), 0xcd);
    assert_eq!(mask(0xabcd, 16), 0xabcd);
    assert_eq!(mask(0xff, 4), 0xf);
    assert_eq!(mask(u64::MAX, 64), u64::MAX);
}

#[test]
fn ptr_eq_is_identity_not_structure() {
    let a = Bv::val(1, 8);
    assert!(a.ptr_eq(&a));
    // Structurally equal but separately built: not the same node.
    let b = Bv::val(1, 8);
    assert!(!a.ptr_eq(&b));
    let c = a.add(&b);
    assert!(c.ptr_eq(&c));
}

#[test]
fn as_const_folds_constant_expressions() {
    assert_eq!(Bv::val(7, 8).as_const(), Some(7));
    assert_eq!(Bv::val(0x1ff, 8).as_const(), Some(0xff)); // masked to width on construction
    // A constant expression folds on construction, so it reads back as a constant.
    assert_eq!(Bv::val(1, 8).add(&Bv::val(1, 8)).as_const(), Some(2));
    // Folding follows SMT-LIB zero-divisor semantics, not Rust's divide-by-zero panic.
    assert_eq!(Bv::val(9, 8).udiv(&Bv::val(0, 8)).as_const(), Some(0xff));
    // A rewrite that keeps a variable keeps returning `None`, as a variable is not a constant.
    let mut s = Solver::new();
    let x = s.var("x", 8);
    assert_eq!(x.add(&Bv::val(0, 8)).as_const(), None);
}

#[test]
fn display_and_debug_are_stable() {
    assert_eq!(Bv::val(5, 8).to_string(), "#5:8");
    assert_eq!(format!("{:?}", Bv::val(5, 8)), "Bv(#5:8)");
}

#[test]
fn widths_compose_as_documented() {
    let mut s = Solver::new();
    let x = s.var("x", 8);
    assert_eq!(x.width(), 8);
    assert_eq!(x.extract(3, 0).width(), 4);
    assert_eq!(x.zext(16).width(), 16);
    assert_eq!(x.sext(16).width(), 16);
    assert_eq!(x.concat(&x).width(), 16);
    assert_eq!(x.eq(&x).width(), 1);
    assert_eq!(Bv::ite(&x.eq(&x), &x, &x).width(), 8);
}