logicaffeine_proof/sat.rs
1//! Propositional SAT-discharge of a `ProofExpr` obligation — the engine behind in-browser,
2//! Z3-free hardware proving.
3//!
4//! A bounded hardware property (an SVA assertion unrolled to discrete timesteps, or a
5//! Kripke-lowered FOL spec) reduces to a quantifier-free propositional formula over
6//! `signal@t` atoms. This module discharges two questions over that fragment, reusing the
7//! existing trust tiers ([`crate::cnf`] Tseitin → [`crate::cdcl`] CDCL → [`crate::rup`] RUP
8//! certification) so the answers are certified, not merely asserted:
9//!
10//! - [`find_model`] — is the obligation satisfiable, and if so, a distinguishing assignment.
11//! This is `∃trace. φ`, the core of bounded model checking and counterexample extraction.
12//! - [`prove_equivalence`] — do two formulas denote the same Boolean function? `F ≡ S` iff
13//! `F ↔ S` is a tautology, certified via RUP; otherwise a concrete counterexample trace.
14//!
15//! Everything here is pure Rust with no Z3 dependency, so it runs unchanged in the browser
16//! (wasm32) and in native tests where its verdicts are checked against Z3 as the oracle.
17
18use crate::cdcl::{BudgetedResult, Lit, SolveResult, Solver, Var};
19use crate::cnf::Cnf;
20use crate::rup;
21use crate::ProofExpr;
22use std::collections::BTreeSet;
23use std::collections::HashMap;
24
25/// The result of a satisfiability query over a propositional obligation.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub enum ModelOutcome {
28 /// Satisfiable, with a model over the source atoms (sorted by name). For a hardware
29 /// obligation these are the `signal@t` bindings of a witnessing trace.
30 Sat(Vec<(String, bool)>),
31 /// Unsatisfiable — no assignment satisfies the obligation.
32 Unsat,
33 /// Not a quantifier-free propositional formula over recognisable atoms, so the SAT
34 /// engine cannot speak to it (the caller must escalate, e.g. bit-blast first).
35 Unsupported,
36}
37
38/// The result of an unsatisfiability query — the shared primitive behind equivalence,
39/// bounded model checking, k-induction, and vacuity.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum UnsatOutcome {
42 /// The formula is unsatisfiable — RUP-certified (the refutation replays to empty).
43 Refuted,
44 /// The formula is satisfiable, with a witnessing model over its atoms.
45 Sat(Vec<(String, bool)>),
46 /// Not a quantifier-free propositional formula, or the refutation could not be
47 /// certified — fail-closed (never a false `Refuted`).
48 Unsupported,
49}
50
51/// The result of an equivalence query between two formulas.
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub enum EquivOutcome {
54 /// The two formulas denote the same Boolean function. The verdict is RUP-certified:
55 /// `F ↔ S` was replayed to the empty clause, not merely reported UNSAT.
56 Equivalent,
57 /// The formulas differ. The assignment is a concrete counterexample: under it exactly
58 /// one of the two formulas holds. For hardware, this is the distinguishing waveform.
59 Differ(Vec<(String, bool)>),
60 /// Not purely propositional over recognisable atoms — the caller must escalate.
61 Unsupported,
62}
63
64/// Is `e` satisfiable? Returns a witnessing model over its atoms if so.
65///
66/// `∃assignment. e`. Tseitin-clausifies `e`, runs CDCL, and on SAT decodes the model back
67/// to the source atoms appearing in `e` (Tseitin auxiliaries are dropped). Used directly by
68/// bounded model checking (`∃trace. ¬property`) and for counterexample extraction.
69pub fn find_model(e: &ProofExpr) -> ModelOutcome {
70 let mut cnf = Cnf::new();
71 if cnf.assert(e).is_none() {
72 return ModelOutcome::Unsupported;
73 }
74 // Move the atom table out alongside the solver — no clause-database clone just to decode.
75 let (mut solver, atom_of) = cnf.into_solver_with_atoms();
76 match solver.solve() {
77 SolveResult::Unsat => ModelOutcome::Unsat,
78 SolveResult::Sat(model) => ModelOutcome::Sat(decode_model_from(&atom_of, &model, &[e])),
79 }
80}
81
82/// Are `a` and `b` equivalent? `F ≡ S` iff `F ↔ S` is valid, i.e. `¬(F ↔ S)` is UNSAT.
83///
84/// One solve discharges both outcomes: a satisfying assignment is the counterexample
85/// (`Differ`); UNSAT is RUP-certified into `Equivalent` (the certified trust tier — a
86/// solver bug that can't be replayed yields `Unsupported`, never a false `Equivalent`).
87/// Structurally identical formulas short-circuit with no solve at all.
88pub fn prove_equivalence(a: &ProofExpr, b: &ProofExpr) -> EquivOutcome {
89 // Sound fast-path: identical formulas are trivially equivalent (no solve).
90 if a == b {
91 return EquivOutcome::Equivalent;
92 }
93 // `F ≡ S` iff `¬(F ↔ S)` is unsatisfiable.
94 let neg_iff = ProofExpr::Not(Box::new(ProofExpr::Iff(
95 Box::new(a.clone()),
96 Box::new(b.clone()),
97 )));
98 match prove_unsat(&neg_iff) {
99 UnsatOutcome::Refuted => EquivOutcome::Equivalent,
100 UnsatOutcome::Sat(model) => EquivOutcome::Differ(model),
101 UnsatOutcome::Unsupported => EquivOutcome::Unsupported,
102 }
103}
104
105/// Is `e` unsatisfiable? One CDCL solve decides it: `Sat` carries a witnessing model,
106/// `Unsat` is independently RUP-certified into `Refuted` (a refutation the trusted checker
107/// cannot replay yields `Unsupported`, never a false `Refuted`). This is the shared certified
108/// Does `e` reduce to an inconsistent mod-`m` linear system? Clausifies `e`, recovers the one-hot-encoded
109/// congruences ([`crate::modp::recover_from_cnf`]), and refutes them by certified modular Gaussian
110/// elimination — over the prime field `GF(p)` ([`crate::modp`]) when the recovered modulus is prime, or
111/// over `ℤ/m` by CRT across its prime factors ([`crate::modm`]) when it is composite. Fail-closed:
112/// recovery returns `None` on anything that is not a faithful mod-`m` encoding, and the produced linear
113/// refutation is independently re-checked, so a `true` is always a sound UNSAT. This is the engine behind
114/// the cascade's modular fast-path — the same lift `solve_structured` routes to `ModP`/`ModM`.
115fn refutes_modular(e: &ProofExpr) -> bool {
116 let mut cnf = Cnf::new();
117 if cnf.assert(e).is_none() {
118 return false;
119 }
120 let Some(rec) = crate::modp::recover_from_cnf(cnf.num_vars(), cnf.clauses()) else {
121 return false;
122 };
123 if crate::modp::is_prime(rec.modulus) {
124 match crate::modp::solve(&rec.equations, rec.num_vars, rec.modulus) {
125 crate::modp::ModpOutcome::Unsat(combo) => {
126 crate::modp::is_refutation(&rec.equations, rec.num_vars, rec.modulus, &combo)
127 }
128 _ => false,
129 }
130 } else {
131 match crate::modm::solve(&rec.equations, rec.num_vars, rec.modulus) {
132 Some(crate::modm::ModmOutcome::Unsat { modulus, combo }) => {
133 crate::modm::is_refutation(&rec.equations, rec.num_vars, modulus, &combo)
134 }
135 _ => false,
136 }
137 }
138}
139
140/// Does `e` collapse under an auto-discovered covering symmetry, an asymmetric cardinality cover, or a
141/// parity structure? Clausifies `e` and runs [`crate::lyapunov::auto_collapse`], which synthesizes a
142/// Lyapunov measure and certifies the descent to a contradiction. This catches the *irregularly-encoded*
143/// coverings and counting cores that the strict structural recognizers (pigeonhole, cutting-planes) miss
144/// — the small-`n` census finds 756 such minimal-UNSAT families at n=4 alone. Fail-closed: each
145/// `auto_collapse` variant is returned only once its contradiction is actually reached/checked
146/// (`ranked.refuted` / `reached_goal`), and its XOR/covering recovery is conservative, so a `true` is a
147/// sound UNSAT. Runs after the cheap structural cuts, before search.
148fn refutes_by_collapse(e: &ProofExpr) -> bool {
149 let mut cnf = Cnf::new();
150 if cnf.assert(e).is_none() {
151 return false;
152 }
153 !matches!(
154 crate::lyapunov::auto_collapse(cnf.num_vars(), cnf.clauses()),
155 crate::lyapunov::AutoCollapse::None
156 )
157}
158
159/// Does `e` have a low-degree **Nullstellensatz** refutation over GF(2)? Clausifies `e` and asks whether
160/// `1` lies in the degree-`d` GF(2)-span of the clause polynomials (`crate::polycalc`) — the universal
161/// algebraic cut that *subsumes* the narrow ones (parity is its degree-1 fragment) and, at degree ≥ 2,
162/// certifies the irregular low-degree-algebraic cores no structural recognizer matches. The degree is
163/// **size-gated**: we take the largest `d` whose monomial basis `Σ_{i≤d} C(n,i)` fits a fixed budget —
164/// degree 1 (cheap, general GF(2)-affine) for large formulas, higher degree only when `n` is small — so
165/// the cut never threatens the hot path. Nullstellensatz refutability is monotone in `d`, so the single
166/// call at the gated degree decides it. Sound: a certificate exists only for an unsatisfiable formula.
167/// The largest algebraic degree whose monomial basis `Σ_{i≤d} C(n,i)` fits a fixed budget — the
168/// size-gate shared by the Nullstellensatz and Polynomial-Calculus cuts. Degree 1 (cheap, general
169/// GF(2)-affine) for large formulas, higher degree only when `n` is small; `0` when even degree 1 is too
170/// wide (leave it to search). Keeps the algebraic cuts off the hot path.
171fn gated_algebraic_degree(n: usize) -> usize {
172 const MONO_BUDGET: u128 = 4000;
173 let mut dmax = 0usize;
174 let mut monos: u128 = 1; // the constant monomial (degree 0)
175 let mut binom: u128 = 1; // C(n, d), updated as C(n,d) = C(n,d-1)·(n-d+1)/d
176 for d in 1..=n {
177 binom = binom * (n - d + 1) as u128 / d as u128;
178 if monos + binom > MONO_BUDGET {
179 break;
180 }
181 monos += binom;
182 dmax = d;
183 }
184 dmax
185}
186
187fn refutes_by_nullstellensatz(e: &ProofExpr) -> bool {
188 let mut cnf = Cnf::new();
189 if cnf.assert(e).is_none() {
190 return false;
191 }
192 let n = cnf.num_vars();
193 let d = gated_algebraic_degree(n);
194 if d == 0 {
195 return false;
196 }
197 crate::polycalc::nullstellensatz_refutes(n, cnf.clauses(), d)
198}
199
200/// Does `e` have a low-degree **Polynomial Calculus** refutation over GF(2)? PC is the dynamic
201/// strengthening of Nullstellensatz — it closes the clause polynomials under linear combination *and*
202/// multiply-by-variable, so an intermediate cancellation lets it certify at the gated degree a strict
203/// superset of what the NS cut above reaches (measured: real families at n=3). Same size-gate, runs only
204/// when the cheaper NS cut has already declined, sound (`1` derivable ⟹ unsatisfiable).
205fn refutes_by_polynomial_calculus(e: &ProofExpr) -> bool {
206 let mut cnf = Cnf::new();
207 if cnf.assert(e).is_none() {
208 return false;
209 }
210 let n = cnf.num_vars();
211 let d = gated_algebraic_degree(n);
212 if d == 0 {
213 return false;
214 }
215 crate::polycalc::polynomial_calculus_refutes(n, cnf.clauses(), d)
216}
217
218/// Variable-count ceiling under which `prove_unsat` runs the certified recursive symmetry breaker as its
219/// terminal rung. The symmetric-UNSAT instances that survive every algebraic cut and reach that rung are
220/// small; above the cap the automorphism re-detection is not worth its cost, so the cheap single-pass row
221/// break takes over.
222const CERTIFIED_SYMMETRY_VAR_CAP: usize = 64;
223
224/// Conflict budget for the first, cheap pass of the complete search in [`prove_unsat`]. Easy
225/// instances finish far below it; a hard one exhausts it and thereby EARNS the expensive terminal
226/// certified-symmetry rung. Keeping the rung escalation-only is the invariant that keeps
227/// microsecond obligations at microseconds (the rung costs ~50ms even on tiny formulas).
228const EASY_SEARCH_CONFLICTS: u64 = 2_000;
229
230/// Refute `e` with the **certified recursive symmetry breaker** and return the proof. Each round
231/// re-detects the residual automorphism group, certifies ONE lex-leader lead clause as a PR step (its
232/// generator a fresh automorphism of the current database), and re-detects — looping to a fixpoint that
233/// breaks the COMPLETE group, not just the adjacent positive-row swaps [`crate::symmetry::break_symmetries`]
234/// sees. The returned stream is the certified PR breaks followed by the closing RUP learned clauses, and
235/// it is already `check_pr_refutation`-verified against `e`'s CNF. `None` if `e` is not CNF-assertable, is
236/// satisfiable, or the breaker did not certify a refutation — the wired, checkable companion of
237/// [`prove_unsat`]'s coarse verdict.
238pub fn prove_unsat_certified(e: &ProofExpr) -> Option<Vec<crate::proof::ProofStep>> {
239 let mut cnf = Cnf::new();
240 cnf.assert(e)?;
241 prove_unsat_certified_cnf(cnf.num_vars(), cnf.clauses())
242}
243
244/// [`prove_unsat_certified`] for a CNF the caller has ALREADY built — the seam for a producer
245/// that clausifies something other than a `ProofExpr` tree (a bit-blaster asserting a shared gate
246/// DAG, whose tree form is exponentially larger than the circuit). Same refutation, same steps:
247/// the certificate is a function of the clause set, never of how it was spelled.
248pub fn prove_unsat_certified_cnf(
249 num_vars: usize,
250 clauses: &[Vec<crate::cdcl::Lit>],
251) -> Option<Vec<crate::proof::ProofStep>> {
252 let r = crate::sym_certify::certified_unsat_auto(num_vars, clauses);
253 r.refuted.then_some(r.steps)
254}
255
256/// core for equivalence, bounded model checking, k-induction, and vacuity.
257pub fn prove_unsat(e: &ProofExpr) -> UnsatOutcome {
258 // Pigeonhole fast-path: a conjunction of at-least-one rows + fully-encoded at-most-one columns is
259 // a bipartite-matching question that costs CDCL *exponentially* many resolution steps, but the
260 // matching reasoner decides in *polynomial* time with a re-verified Hall witness — a sound UNSAT
261 // certificate. Fires only on a faithfully-recognized, infeasible pigeonhole structure (never a
262 // false `Refuted`); everything else falls through to the certified CDCL core below.
263 if crate::pigeonhole::decide_pigeonhole_unsat(e) {
264 return UnsatOutcome::Refuted;
265 }
266 // Ordering-principle fast-path: a complete GT(n) core — a strict total order (totality +
267 // antisymmetry + transitivity) with no maximal element — is unsatisfiable, since a finite strict
268 // total order always has a maximum. Recognized structurally and certified from that structure in
269 // polynomial time, where the general cascade searches super-polynomially. Faithful/fail-closed
270 // (never a false `Refuted`); falls through for anything that is not a complete ordering core.
271 if crate::ordering::refutes_ordering_principle(e) {
272 return UnsatOutcome::Refuted;
273 }
274 // Cutting-planes fast-path: recover the at-most-one cardinality from the exclusion cliques and
275 // sum-refute to `0 ≥ 1` — a POLYNOMIAL cutting-plane proof of a pigeonhole/cardinality CNF that
276 // resolution (CDCL) refutes only exponentially. Sound (each step a cutting-plane inference over
277 // verified at-most-one cliques, never a false `Refuted`); falls through for anything else.
278 if crate::pseudo_boolean::refute_clausal(e) {
279 return UnsatOutcome::Refuted;
280 }
281 // Parity (GF(2)) fast-path: a Tseitin/XOR cover is a linear system over GF(2). Its CNF encoding is
282 // resolution-hard (CDCL blows up exponentially on expander instances), but Gaussian elimination
283 // decides it in POLYNOMIAL time. We recognize the wrong-parity clause bundles, recover the XOR
284 // equations they imply, and refute the linear subsystem — sound (each equation a consequence of
285 // `e`, the refutation re-checkable), falling through for anything without inconsistent parity.
286 if crate::xorsat::refute_via_parity(e) {
287 return UnsatOutcome::Refuted;
288 }
289 // Modular (GF(p) / ℤ-mod-m) fast-path: the parity cut above speaks only GF(2), but a mod-`m`
290 // counting/Tseitin obstruction is a linear system over ℤ/m. Its one-hot CNF encoding is
291 // resolution-hard — CDCL blows up *exponentially* (and Z3/Kissat time out), and the GF(2) cut is
292 // blind to odd characteristic — yet Gaussian elimination over the *right* modulus decides it in
293 // polynomial time. We recover the congruence system and refute it over the prime field `GF(p)` when
294 // `m` is prime, or over ℤ/m by CRT across its prime factors when it is composite. Sound and
295 // fail-closed: recovery declines on non-encodings and every modular refutation is re-checked, so a
296 // `Refuted` here is never false. This carries the parity cut to every modulus.
297 if refutes_modular(e) {
298 return UnsatOutcome::Refuted;
299 }
300 // The apex algebraic rung — Sum-of-Squares / Positivstellensatz over the ordered field
301 // (`crate::sos`) — would slot here, certifying integrality gaps the GF(2) cuts above structurally
302 // cannot. It is *deliberately not wired*: with `sos::MAX_VARS = 6` it only runs where the
303 // Nullstellensatz cut already runs at full degree (`2ⁿ ≤ MONO_BUDGET`, i.e. `n ≤ 11`), and there NS
304 // is *complete* — so SoS would never fire. It earns a slot only once its reach extends into the
305 // `n ≥ 12` band where NS is gated below full degree, which needs the symmetry-reduced / PSD SoS that
306 // scales past the Fourier–Motzkin wall. The wiring is then one size-gated `sos::sos_refutes` call.
307 // Symmetry breaking: a symmetric formula forces CDCL to re-derive the same conflict once per
308 // symmetric copy (the pigeon symmetry multiplies the refutation by `n!`). Augmenting with sound,
309 // *verified-automorphism* lex-leader SBPs collapses each orbit so the solver searches the
310 // quotient. The SBPs preserve satisfiability, so refuting `e ∧ SBP` refutes `e`; the model decode
311 // and the `e` reported on `Sat` stay over the original atoms (auxiliaries are skipped).
312 let augmented = crate::symmetry::break_symmetries(e);
313 let mut cnf = Cnf::new();
314 if cnf.assert(&augmented).is_none() {
315 return UnsatOutcome::Unsupported;
316 }
317 let num_vars = cnf.num_vars();
318 // Move the atom table out alongside the solver (the RUP checker reads the original clauses
319 // back from the solver via `original_clauses()`, so no clone of the CNF is needed).
320 let (mut solver, atom_of) = cnf.into_solver_with_atoms();
321 // The complete search runs FIRST, conflict-budgeted: an easy instance — the overwhelming
322 // majority of equivalence/BMC obligations — gets its verdict in microseconds and never pays
323 // for the terminal rung below. Only an instance that exhausts the budget (the exponential
324 // families the rung exists for) escalates.
325 let first = match solver.solve_budgeted(EASY_SEARCH_CONFLICTS) {
326 BudgetedResult::Sat(model) => SolveResult::Sat(model),
327 BudgetedResult::Unsat => SolveResult::Unsat,
328 BudgetedResult::Budget => {
329 // The instance has EARNED escalation: the cheap complete search could not decide it
330 // within the budget, so it is exactly the class the expensive certified cuts exist
331 // for. Easy obligations never reach any of these.
332 //
333 // Covering / cardinality / algebraic collapse: auto-discover a covering *symmetry* (the
334 // pigeonhole class beyond the strict recognizer), an asymmetric cardinality cover (the
335 // mutilated-chessboard class), or a parity collapse, and certify it via a synthesized
336 // Lyapunov descent. The census proves it closes 756 minimal-UNSAT families at n=4 that
337 // every narrow upfront cut is blind to. Fail-closed.
338 if refutes_by_collapse(e) {
339 return UnsatOutcome::Refuted;
340 }
341 // Nullstellensatz: the universal *algebraic* cut. Where the structural recognizers each
342 // match one shape, this asks the shape-free question — is `1` in the low-degree
343 // GF(2)-span of the clause polynomials? — and certifies any instance with a low-degree
344 // algebraic refutation, the census's "rigid" residue that nonetheless has a degree-2/3
345 // certificate. Size-gated; sound (a certificate implies UNSAT).
346 if refutes_by_nullstellensatz(e) {
347 return UnsatOutcome::Refuted;
348 }
349 // Polynomial Calculus: the *dynamic* algebraic cut, one rung above Nullstellensatz. By
350 // closing the clause polynomials under linear combination AND multiply-by-variable
351 // (intermediate cancellations and all), it certifies at the same gated degree a strict
352 // superset of NS — the thin but real sliver NS leaves behind. Runs only after NS
353 // declines; size-gated; sound.
354 if refutes_by_polynomial_calculus(e) {
355 return UnsatOutcome::Refuted;
356 }
357 // Certified RECURSIVE symmetry break (the terminal certified rung). Detect the residual
358 // automorphism group of the current database, certify ONE lex-leader lead clause as a PR
359 // step, re-detect, and loop to a fixpoint — breaking the COMPLETE group rather than the
360 // adjacent positive-row swaps the single-pass break above sees (e.g. clique-coloring's
361 // COLOR-permutation symmetry, a column swap the row break is structurally blind to). The
362 // composed stream (certified PR breaks + closing RUP learned clauses) is
363 // `check_pr_refutation`-verified against this formula's CNF inside `certified_unsat_auto`,
364 // so a `refuted` here is a fully checked refutation. Size-gated — larger instances fall to
365 // the cheap single-pass row break — and only claims UNSAT (a satisfiable formula leaves
366 // `refuted == false`, so its model is recovered by resuming the search).
367 let mut base = Cnf::new();
368 if base.assert(e).is_some()
369 && base.num_vars() <= CERTIFIED_SYMMETRY_VAR_CAP
370 && crate::sym_certify::certified_unsat_auto(base.num_vars(), base.clauses()).refuted
371 {
372 return UnsatOutcome::Refuted;
373 }
374 // Complete the search on a FRESH solver over the original clauses: a budget-stopped
375 // solver is not re-enterable (inprocessing assumes a virgin DB), and rebuilding keeps
376 // the refutation certificate self-contained — the RUP checker replays only clauses
377 // this solve derived, against only the formula's own clauses.
378 let originals: Vec<Vec<Lit>> = solver.original_clauses().to_vec();
379 solver = Solver::new(num_vars);
380 for c in originals {
381 solver.add_clause(c);
382 }
383 solver.solve()
384 }
385 };
386 match first {
387 SolveResult::Sat(model) => UnsatOutcome::Sat(decode_model_from(&atom_of, &model, &[e])),
388 SolveResult::Unsat => {
389 let learned: Vec<Vec<Lit>> = solver.learned().iter().map(|c| c.lits.clone()).collect();
390 if rup::check_refutation(num_vars, solver.original_clauses(), &learned) {
391 UnsatOutcome::Refuted
392 } else {
393 UnsatOutcome::Unsupported
394 }
395 }
396 }
397}
398
399/// Decode a SAT `model` back to `(atom, value)` bindings for every source atom appearing in
400/// `exprs` (Tseitin auxiliaries carry no source meaning and are skipped), sorted by name.
401pub fn decode_model(cnf: &Cnf, model: &[bool], exprs: &[&ProofExpr]) -> Vec<(String, bool)> {
402 let mut atoms = BTreeSet::new();
403 for e in exprs {
404 collect_atoms(e, &mut atoms);
405 }
406 atoms
407 .into_iter()
408 .filter_map(|name| {
409 cnf.atom_value(&ProofExpr::Atom(name.clone()), model)
410 .map(|v| (name, v))
411 })
412 .collect()
413}
414
415/// Decode a SAT `model` from a pre-extracted atom→variable map (the table `Cnf` already holds),
416/// so a solve need not clone the whole clause database just to read its model back. Equivalent to
417/// [`decode_model`] for the propositional atoms `collect_atoms` gathers.
418pub fn decode_model_from(
419 atom_of: &HashMap<String, Var>,
420 model: &[bool],
421 exprs: &[&ProofExpr],
422) -> Vec<(String, bool)> {
423 let mut atoms = BTreeSet::new();
424 for e in exprs {
425 collect_atoms(e, &mut atoms);
426 }
427 atoms
428 .into_iter()
429 .filter_map(|name| {
430 // Atoms are interned under the `atom:` key (see `cnf::atom_key`).
431 atom_of
432 .get(&format!("atom:{name}"))
433 .and_then(|&v| model.get(v as usize).copied())
434 .map(|val| (name, val))
435 })
436 .collect()
437}
438
439/// Collect the names of every propositional [`ProofExpr::Atom`] reachable through the
440/// Boolean fragment (`∧ ∨ ¬ → ↔`). Non-Boolean nodes are ignored — they cannot appear in a
441/// bounded hardware obligation, and silently skipping them keeps the decode total.
442fn collect_atoms(e: &ProofExpr, out: &mut BTreeSet<String>) {
443 match e {
444 ProofExpr::Atom(name) => {
445 out.insert(name.clone());
446 }
447 ProofExpr::Not(p) => collect_atoms(p, out),
448 ProofExpr::And(p, q)
449 | ProofExpr::Or(p, q)
450 | ProofExpr::Implies(p, q)
451 | ProofExpr::Iff(p, q) => {
452 collect_atoms(p, out);
453 collect_atoms(q, out);
454 }
455 _ => {}
456 }
457}
458
459#[cfg(test)]
460#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/sat/tests.rs"]
461mod tests;