Skip to main content

bitwright/prove/
mod.rs

1//! A native prover (feature `prove`): expressions are bit-blasted into an and-inverter graph,
2//! encoded as clauses, and decided by bitwright's own CDCL SAT solver. A proof of validity comes
3//! with a certificate, the clauses and a DRUP proof of their unsatisfiability, that an
4//! independent checker ([`Certificate::check`]) verifies, and that any DRAT checker can read
5//! ([`Certificate::dimacs`], [`Certificate::drat`]). A refutation comes with a counterexample:
6//! a value for every symbol, checked by bitwright's evaluator before it is returned. A question
7//! the search does not settle within its budget says why ([`Unknown`]), and a [`Question`]
8//! goes on from where the search stopped, under a larger budget, without starting over.
9//! For a small joint output superset above unresolved predicates, [`domain::analyze`]
10//! preserves shared Boolean structure under explicit premises without solving reachability.
11//!
12//! No other solver is involved. Bit-vector operators are blasted with bitwright's total
13//! semantics (SMT-LIB's); floating-point operators with IEEE 754's and bitwright's canonical
14//! NaN ([`crate::fp`]); extension operations through their [`expand`](crate::ext::ExtOp::expand)
15//! definition, if they have one (otherwise the question is not decided).
16//!
17//! ```
18//! use bitwright::prove::{Config, Outcome, equal};
19//! use bitwright::{Context, ParseOptions, Width};
20//!
21//! let mut cx = Context::new();
22//! let o = ParseOptions::width(Width::W32);
23//! let (a, b) = (cx.parse("(x ^ y) + 2 * (x & y)", &o)?, cx.parse("x + y", &o)?);
24//! let Outcome::Proved(Some(cert)) = equal(&mut cx, a, b, &Config::default().with_certificate(true))? else {
25//!     panic!("not proved")
26//! };
27//! assert!(cert.check().is_ok());
28//! let c = cx.parse("x | y", &o)?;
29//! assert!(matches!(equal(&mut cx, a, c, &Config::default())?, Outcome::Refuted(_)));
30//! # Ok::<(), bitwright::Error>(())
31//! ```
32
33pub mod aig;
34pub mod blast;
35mod cuts;
36pub mod domain;
37pub mod drup;
38mod exhaustion;
39pub mod finite;
40mod fp;
41mod incremental;
42mod lean;
43pub mod lrat;
44mod relations;
45mod rule;
46mod sample_words;
47pub mod sat;
48mod sums;
49mod sweep;
50#[cfg(test)]
51mod tests;
52
53use crate::error::Error;
54use crate::expr::{Context, Expr, OpCode};
55use crate::facts::Assumptions;
56use crate::hash::IdMap;
57use crate::{BitVec, SymbolKey, Width};
58
59pub use exhaustion::Exhaustion;
60/// What an [`Incremental`] answers.
61pub use incremental::Answer as IncrementalAnswer;
62pub use incremental::Incremental;
63pub(crate) use lean::lean_equation;
64pub use lean::lean_theorem;
65pub use rule::{RuleOutcome, WidthReport, rule, rule_all_widths};
66
67use aig::{Aig, Cnf, L};
68use blast::Bits;
69use sat::{Answer, Lit, Solver, Step};
70pub use sat::{Backend, Limits};
71
72/// How assignments are selected before SAT search. Sampling can find a concrete
73/// counterexample. Complete ordered enumeration on the word path can also prove validity;
74/// partial coverage and pseudorandom samples cannot.
75#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
76pub enum SampleMode {
77    /// Seeded pseudorandom assignments, with all-zero and all-one unknown bits first.
78    #[default]
79    Random,
80    /// Enumerate assignments from zero upwards over the circuit's unknown input bits,
81    /// least significant input first. Useful for small integer witnesses in wide domains.
82    /// Multiple symbols' unknown bits are concatenated in circuit input order; declared
83    /// fixed bits retain their values. Higher unknown bits stay zero until reached.
84    Small,
85    /// Enumerate small values of reconstructed words: unknown bits of larger pure
86    /// concatenations and standalone symbols are visited from low to high. A bounded
87    /// portfolio varies words separately and together within the shared sample allowance.
88    /// Shared bits keep one assignment. Uses the bounded word sampler when supported, falling
89    /// back to [`Small`](Self::Small) circuit ordering for other graphs.
90    Words,
91}
92
93/// How hard to try, and what to keep.
94#[derive(Copy, Clone, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct Config {
97    /// The most conflicts the SAT solver may meet (then [`Unknown::Budget`]).
98    pub max_conflicts: u64,
99    /// The most propagations the SAT solver may do (then [`Unknown::Budget`]; `u64::MAX`, the
100    /// default: no limit). A conflict costs more propagation on a larger circuit, so this bounds
101    /// the time a question takes more closely than conflicts do, and as deterministically.
102    pub max_propagations: u64,
103    /// The most AIG nodes the question may take (then [`Unknown::TooLarge`]).
104    pub max_nodes: usize,
105    /// Keep a [`Certificate`] for a proof.
106    pub certificate: bool,
107    /// Simplify the question with bitwright's own engine before blasting it (the
108    /// deobfuscation strategy, with the MBA service and its opaque-constant sweep when the `mba`
109    /// feature is on): identities the engine settles at the word level (products of MBA, say,
110    /// which bit-level SAT finds hard) are answered at once, and the rest is blasted smaller.
111    /// Not with a certificate: a certificate is of the question as asked, with its symbols'
112    /// declared known bits.
113    pub simplify: bool,
114    /// Simplify without the one pass of the engine that commits rewrites it has derived but
115    /// neither proved nor matched against a proved rule: the limb-arithmetic pass
116    /// ([`Phase::Words`](crate::engine::Phase), integer identities checked at sample points).
117    /// An answer then rests only on proved rules, passes that are decision procedures or
118    /// prove what they commit, and the search. Off by default: that pass is what decides
119    /// limb multiplications no search finishes.
120    pub strict: bool,
121    /// Whether the simplifier's limb-arithmetic pass writes a result only once a circuit and
122    /// a search have proved it ([`Strategy::words_proved`](crate::engine::Strategy)): between
123    /// the default, which takes the pass's derivations as they are, and
124    /// [`strict`](Self::strict), which leaves the pass out.
125    pub proved_words: bool,
126    /// The engine's budget for [`simplify`](Self::simplify): caps in the units of
127    /// [`Budget`](crate::engine::Budget), counts of work and never time, so a question stops at
128    /// the same place on every run. [`Budget::default`](crate::engine::Budget::default) (the
129    /// default) is generous; [`with_simplify_fuel`](Self::with_simplify_fuel) scales every cap
130    /// by one number. A simplification its budget stops keeps the rewrites it made, and the
131    /// rest of the question is blasted as it stands; [`Stats::simplification`] says what was
132    /// spent and which cap stopped it.
133    pub simplify_budget: crate::engine::Budget,
134    /// Assignments of the symbols to evaluate before the search, 64 at a time
135    /// (in batches of 64, selected by [`sample_mode`](Self::sample_mode)): a refutation that a fraction of
136    /// the values give is found without the search, which needs many conflicts for it on a
137    /// large circuit. With [`word_sampling`](Self::word_sampling), supported samples precede
138    /// bit-blasting. 0: none.
139    pub samples: u32,
140    /// Assignment selection for [`samples`](Self::samples). Default: [`SampleMode::Random`].
141    pub sample_mode: SampleMode,
142    /// Add certified transitive bit-equality lemmas exposed by the asserted query. Cycle
143    /// contradictions are detected regardless; additional lemmas are opt-in because their
144    /// effect on arithmetic search depends on the workload.
145    pub relational_lemmas: bool,
146    /// Initially prefer the unknown bits of small shift counts as decisions. This specializes
147    /// variable shifts during search without restricting which selector values are allowed.
148    pub selector_branching: bool,
149    /// Cancel a shared input through bounded XOR paths at every bitwise boundary. This can
150    /// remove direct input dependencies through odd products, but changes arithmetic search
151    /// behavior; opt-in pending workload-specific measurement.
152    pub input_cancellation: bool,
153    /// Factor ORs of XORs with a shared operand at one-valued equality target bits.
154    /// Opt-in because the smaller encoding can alter longer arithmetic searches adversely.
155    pub join_factoring: bool,
156    /// Inline private intermediate XORs into three-input parity gates. This reduces encoding
157    /// variables without changing the clause count, but its search performance is workload-dependent.
158    pub xor3_encoding: bool,
159    /// Compress modular multiplication columns before one final carry-propagating addition.
160    /// Opt-in pending measurements on arithmetic search workloads.
161    pub carry_save_multiplication: bool,
162    /// Try samples directly on a bounded integer DAG of at most 64-bit words before
163    /// bit-blasting. Ordered modes can prove after enumerating every legal input assignment;
164    /// partial samples and unsupported DAGs use the circuit path. Certificates use that path
165    /// even after complete enumeration.
166    /// [`SampleMode::Words`] also enables this path.
167    pub word_sampling: bool,
168    /// Decide a question by evaluating it at every legal assignment when it has at most this
169    /// many unknown input bits, before bit-blasting. It applies to bounded integer DAGs of at
170    /// most 64-bit words, the same as [`word_sampling`](Self::word_sampling), and costs
171    /// `2^bits` evaluations, in parallel across threads; it is not bounded by the search
172    /// limits. A failing assignment is replayed on the original question. A proof asked for
173    /// with a [`certificate`](Self::certificate) comes with an [`Exhaustion`], which checks the
174    /// question's bit-blasted circuit at every assignment of its inputs, independently of the
175    /// word-level decision. If that circuit has more inputs than this bound (it may keep bits
176    /// the word program fixes from scoped assumptions as constrained inputs), the search
177    /// decides the question instead. 0 (the default): never.
178    pub exhaustive_inputs: u8,
179    /// Write the sums of the question one way before blasting it: both sides read as linear
180    /// forms over slices of their values (carries of limbs as the high digits they stand
181    /// for), and built again in one order, so that what the two sides add up the same way is
182    /// one circuit and what cancels is gone. An equality at every input; not for a
183    /// [`certificate`](Self::certificate), which is of the question as asked. Opt-in: it
184    /// helps where the two sides are one arithmetic written twice (a limb against its word),
185    /// and changes the search elsewhere.
186    pub shared_sums: bool,
187    /// Read the divisions by constants that a compiler wrote as products by magic numbers
188    /// (`trunc((zext(x) · M) >>u k)`, a multiply-high and a shift, the signed forms) as the
189    /// divisions they are, before the question is blasted: the simplifier's division pass
190    /// alone, for a question asked without the simplifier ([`simplify`](Self::simplify)
191    /// reads them already). A multiplier's circuit against a divider's is beyond a search
192    /// (the 32-bit quotient by 10 is undecided after 200,000 conflicts); read, both sides
193    /// are one division. An equality at every input; not for a
194    /// [`certificate`](Self::certificate). Opt-in.
195    pub divisions: bool,
196    /// Sweep the circuit before the first search: nodes that simulation shows equal (or
197    /// complementary) are proved so one pair at a time, from the inputs up, by a solver of
198    /// the circuit's clauses alone, and each equivalence is given to the search as clauses.
199    /// Two circuits for one function often share most of their inner nodes (a prefix adder
200    /// and `x + y` have the same carries), and a search over their miter alone rediscovers
201    /// each of them inside one refutation: swept, the 64-bit prefix adder against `x + y`
202    /// takes 0.29 M propagations instead of 0.54 M, the 32-bit SWAR population count against
203    /// `popcnt` 24 k instead of 148 k, and a 64-bit MBA rewriting of `x - y` 0.56 M instead of
204    /// 7.6 M.
205    ///
206    /// The circuit is simulated first, and only swept when the simulation shows enough of
207    /// that sharing: classes of nodes that agree joining the two sides of an equality, at
208    /// least 4 and one per 10 nodes private to a side (a question that is no equality: classes
209    /// of two nodes or more, against all its nodes). Products, or the shift-and-xor addition
210    /// loop against `x + y`, show little and are not swept; the simulation is all they cost.
211    /// A sweep is part of preparing the question: it takes at most half of the configured
212    /// limits ([`max_conflicts`](Self::max_conflicts), [`max_propagations`](Self::max_propagations))
213    /// before any search, whatever the searches' own, so a question resumed in steps is swept
214    /// as one asked at once; its work counts in the question's totals as work done before the
215    /// first search; and with a [`certificate`](Self::certificate) its lemmas are logged so the
216    /// certificate still checks. See [`Stats::sweeping`]. On by default.
217    pub sweeping: bool,
218}
219
220impl Default for Config {
221    fn default() -> Self {
222        Config {
223            max_conflicts: 1_000_000,
224            max_propagations: u64::MAX,
225            max_nodes: 4_000_000,
226            certificate: false,
227            simplify: true,
228            strict: false,
229            proved_words: false,
230            simplify_budget: crate::engine::Budget::default(),
231            samples: 256,
232            sample_mode: SampleMode::Random,
233            relational_lemmas: false,
234            selector_branching: false,
235            input_cancellation: false,
236            join_factoring: false,
237            xor3_encoding: false,
238            carry_save_multiplication: false,
239            word_sampling: false,
240            exhaustive_inputs: 0,
241            shared_sums: false,
242            divisions: false,
243            sweeping: true,
244        }
245    }
246}
247
248setters!(Config {
249    with_max_conflicts: max_conflicts: u64,
250    with_max_propagations: max_propagations: u64,
251    with_max_nodes: max_nodes: usize,
252    with_certificate: certificate: bool,
253    with_simplify: simplify: bool,
254    with_strict: strict: bool,
255    with_proved_words: proved_words: bool,
256    with_simplify_budget: simplify_budget: crate::engine::Budget,
257    with_samples: samples: u32,
258    with_sample_mode: sample_mode: SampleMode,
259    with_relational_lemmas: relational_lemmas: bool,
260    with_selector_branching: selector_branching: bool,
261    with_input_cancellation: input_cancellation: bool,
262    with_join_factoring: join_factoring: bool,
263    with_xor3_encoding: xor3_encoding: bool,
264    with_carry_save_multiplication: carry_save_multiplication: bool,
265    with_word_sampling: word_sampling: bool,
266    with_exhaustive_inputs: exhaustive_inputs: u8,
267    with_shared_sums: shared_sums: bool,
268    with_divisions: divisions: bool,
269    with_sweeping: sweeping: bool,
270});
271
272impl Config {
273    /// Sets [`simplify_budget`](Self::simplify_budget) to
274    /// [`Budget::fuel`](crate::engine::Budget::fuel)`(fuel)`: `fuel` node visits of the engine
275    /// and every other cap in proportion (the default is `1 << 22`).
276    pub fn with_simplify_fuel(self, fuel: u64) -> Self {
277        self.with_simplify_budget(crate::engine::Budget::fuel(fuel))
278    }
279
280    /// The search's limits: [`max_conflicts`](Self::max_conflicts) and
281    /// [`max_propagations`](Self::max_propagations).
282    pub fn limits(&self) -> Limits {
283        Limits {
284            conflicts: self.max_conflicts,
285            propagations: self.max_propagations,
286        }
287    }
288}
289
290/// The engines that simplify questions (see [`Config::simplify`]), owned by whoever asks:
291/// the deobfuscation strategy with the MBA service, built when first needed, and with them
292/// the one thing they remember, the MBA solver's memo. The entry points of this module that
293/// take none use one such set for the process; a caller that wants nothing shared with the
294/// rest of the process (its statistics, its memory) makes its own and asks through
295/// [`Question::valid_under_with`], [`valid_under_with`] or a [`batch::Session`](crate::batch),
296/// which owns one. Answers are the same either way: the solver's memo returns what solving
297/// again would, at the same cost.
298pub struct Simplifiers {
299    /// As asked for, strict, and with the limb pass proved.
300    engines: [std::sync::OnceLock<crate::engine::Engine>; 3],
301    divisions: std::sync::OnceLock<crate::engine::Engine>,
302    /// The MBA phase, when not the prover's own.
303    #[cfg(feature = "mba")]
304    mba: Option<crate::mba::MbaConfig>,
305    #[cfg(feature = "mba")]
306    solver: Option<std::sync::Arc<dyn crate::mba::MbaSolver>>,
307}
308
309impl core::fmt::Debug for Simplifiers {
310    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
311        f.debug_struct("Simplifiers").finish_non_exhaustive()
312    }
313}
314
315impl Default for Simplifiers {
316    fn default() -> Self {
317        Simplifiers::new()
318    }
319}
320
321impl Simplifiers {
322    /// Engines of the prover's own configuration: the MBA service with its opaque-constant
323    /// sweep, and a normal-form solver of their own.
324    pub const fn new() -> Simplifiers {
325        Simplifiers {
326            engines: [
327                std::sync::OnceLock::new(),
328                std::sync::OnceLock::new(),
329                std::sync::OnceLock::new(),
330            ],
331            divisions: std::sync::OnceLock::new(),
332            #[cfg(feature = "mba")]
333            mba: None,
334            #[cfg(feature = "mba")]
335            solver: None,
336        }
337    }
338
339    /// With this configuration of the MBA phase instead of the prover's own (the default
340    /// with the opaque-constant sweep). It changes what simplification makes of a question,
341    /// so which questions are decided before the search.
342    #[cfg(feature = "mba")]
343    pub fn with_mba(mut self, mba: crate::mba::MbaConfig) -> Self {
344        self.mba = Some(mba);
345        self
346    }
347
348    /// With this MBA solver instead of a [`NormalFormSolver`](crate::mba::NormalFormSolver)
349    /// of their own.
350    #[cfg(feature = "mba")]
351    pub fn with_mba_solver(mut self, solver: std::sync::Arc<dyn crate::mba::MbaSolver>) -> Self {
352        self.solver = Some(solver);
353        self
354    }
355
356    /// The engine for [`Config::strict`] and [`Config::proved_words`] as given: with `strict`
357    /// without the pass that commits rewrites it has derived but neither proved nor matched
358    /// against a proved rule ([`Phase::Words`](crate::engine::Phase)), or with `proved` with
359    /// that pass writing only what a circuit and a search prove.
360    pub fn engine(&self, strict: bool, proved: bool) -> &crate::engine::Engine {
361        let which = if strict { 1 } else { 2 * usize::from(proved) };
362        self.engines[which].get_or_init(|| {
363            #[cfg(feature = "mba")]
364            let mut strategy = crate::engine::Strategy::deobfuscate().with_mba(
365                (self.mba)
366                    .unwrap_or_else(|| crate::mba::MbaConfig::default().with_opaque_sweep(true)),
367            );
368            #[cfg(not(feature = "mba"))]
369            let mut strategy = crate::engine::Strategy::deobfuscate();
370            if strict {
371                (strategy.phases).retain(|p| !matches!(p, crate::engine::Phase::Words));
372            }
373            strategy.words_proved = proved;
374            let builder = crate::engine::Engine::builder()
375                .builtin()
376                .strategy(strategy);
377            #[cfg(feature = "mba")]
378            let builder = match &self.solver {
379                Some(s) => builder.mba_solver(s.clone()),
380                None => builder,
381            };
382            builder
383                .build()
384                .unwrap_or_else(|_| crate::engine::Engine::standard())
385        })
386    }
387
388    /// The division pass alone ([`Config::divisions`]).
389    fn divisions_only(&self) -> &crate::engine::Engine {
390        self.divisions.get_or_init(|| {
391            let strategy =
392                crate::engine::Strategy::new("divisions", vec![crate::engine::Phase::Division]);
393            crate::engine::Engine::builder()
394                .builtin()
395                .strategy(strategy)
396                .build()
397                .unwrap_or_else(|_| crate::engine::Engine::standard())
398        })
399    }
400}
401
402/// The engines of the entry points that are given none.
403static PROCESS: Simplifiers = Simplifiers::new();
404
405/// What a question is built with besides its configuration.
406#[derive(Copy, Clone)]
407pub(crate) struct Env<'a> {
408    /// The engines that simplify it.
409    pub(crate) simplifiers: &'a Simplifiers,
410    /// Stops the simplification, and has the question answer [`Unknown::Deadline`].
411    pub(crate) deadline: Option<crate::engine::Deadline<'a>>,
412}
413
414impl Env<'static> {
415    fn process() -> Self {
416        Env {
417            simplifiers: &PROCESS,
418            deadline: None,
419        }
420    }
421}
422
423/// `p` as the prover's simplifier leaves it within [`Config::simplify_budget`]: an expression
424/// equal to `p` at every value of the symbols, which is what the prover builds its circuit
425/// of. Asked again of an expression a question was posed about, it costs a lookup.
426pub fn simplified(cx: &mut Context, p: Expr, cfg: &Config) -> Result<Expr, Error> {
427    let run = crate::engine::Run::default().with_per_call(cfg.simplify_budget);
428    Ok(PROCESS
429        .engine(cfg.strict, cfg.proved_words)
430        .run(cx, &[p], run)?
431        .roots[0]
432        .expr)
433}
434
435/// Clauses and a DRUP proof that they are unsatisfiable, or, for a proof by complete
436/// enumeration ([`Config::exhaustive_inputs`]), the circuit to enumerate.
437#[derive(Clone, Debug)]
438pub struct Certificate {
439    /// The number of variables.
440    pub vars: u32,
441    /// The clauses.
442    pub clauses: Vec<Vec<Lit>>,
443    /// The proof.
444    pub proof: Vec<Step>,
445    /// The circuit of a proof by complete enumeration. Such a certificate has no clauses or
446    /// DRUP proof, so its [`dimacs`](Self::dimacs) and [`drat`](Self::drat) export nothing a
447    /// DRAT checker would accept.
448    pub exhaustion: Option<Exhaustion>,
449}
450
451impl Certificate {
452    /// Checks the proof with the independent checker: the DRUP proof against the clauses, or
453    /// the circuit of an [`Exhaustion`] at every assignment of its inputs.
454    pub fn check(&self) -> Result<(), String> {
455        match &self.exhaustion {
456            Some(exhaustion) => exhaustion.check(),
457            None => {
458                drup::check(&self.clauses, &self.proof)?;
459                // In the tests, every proof checked is checked as LRAT too.
460                #[cfg(test)]
461                lrat::check(&self.clauses, &self.lrat()?)?;
462                Ok(())
463            }
464        }
465    }
466
467    /// The clauses in DIMACS CNF.
468    pub fn dimacs(&self) -> String {
469        let mut s = format!("p cnf {} {}\n", self.vars, self.clauses.len());
470        for c in &self.clauses {
471            for l in c {
472                s.push_str(&l.dimacs().to_string());
473                s.push(' ');
474            }
475            s.push_str("0\n");
476        }
477        s
478    }
479
480    /// The proof as LRAT ([`lrat`]): every learned clause with the clauses it follows from,
481    /// found by checking the DRUP proof, for a checker that does no search (the text is
482    /// [`lrat::to_text`], beside [`dimacs`](Self::dimacs)). An error when the proof does not
483    /// check, or is one by enumeration.
484    pub fn lrat(&self) -> Result<Vec<lrat::Step>, String> {
485        match &self.exhaustion {
486            Some(_) => Err("a proof by enumeration has no clauses".into()),
487            None => lrat::from_drup(&self.clauses, &self.proof),
488        }
489    }
490
491    /// The proof in DRAT's text format (additions, and deletions prefixed `d`).
492    pub fn drat(&self) -> String {
493        let mut s = String::new();
494        for step in &self.proof {
495            let (pre, c) = match step {
496                Step::Add(c) => ("", c),
497                Step::Delete(c) => ("d ", c),
498            };
499            s.push_str(pre);
500            for l in c {
501                s.push_str(&l.dimacs().to_string());
502                s.push(' ');
503            }
504            s.push_str("0\n");
505        }
506        s
507    }
508}
509
510/// The answer to a question.
511#[derive(Clone, Debug)]
512#[non_exhaustive]
513pub enum Outcome {
514    /// It holds for every value of the symbols (with a certificate, if asked for).
515    Proved(Option<Certificate>),
516    /// It fails at these values of the symbols (checked by evaluation).
517    Refuted(Vec<(SymbolKey, BitVec)>),
518    /// Not decided: why.
519    Unknown(Unknown),
520}
521
522/// Why a question is not decided.
523#[derive(Clone, Debug, PartialEq, Eq)]
524#[non_exhaustive]
525pub enum Unknown {
526    /// The search reached a limit ([`Config::max_conflicts`] or
527    /// [`Config::max_propagations`]) after this much work on the question: more may decide
528    /// it, and a [`Question`] goes on from where it stopped.
529    Budget {
530        /// Conflicts met on the question.
531        conflicts: u64,
532        /// Propagations done on the question.
533        propagations: u64,
534    },
535    /// The circuit passed [`Config::max_nodes`]: `nodes` had been built when blasting stopped.
536    /// The same under any search budget with that cap.
537    TooLarge {
538        /// AIG nodes built.
539        nodes: usize,
540    },
541    /// Something the prover does not reason about (an extension operation without an
542    /// expansion, say). The same under any budget.
543    Unsupported(String),
544    /// A caller's deadline passed ([`crate::solve::Solver::check_within`]): more time may
545    /// decide it. Unlike the budgets, this depends on timing.
546    Deadline,
547}
548
549impl Unknown {
550    /// Whether a larger search budget may decide the question ([`Unknown::Budget`]).
551    pub fn is_budget(&self) -> bool {
552        matches!(self, Unknown::Budget { .. })
553    }
554}
555
556impl core::fmt::Display for Unknown {
557    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
558        match self {
559            Unknown::Budget {
560                conflicts,
561                propagations,
562            } => write!(
563                f,
564                "no answer within {conflicts} conflicts ({propagations} propagations)"
565            ),
566            Unknown::Deadline => write!(f, "the deadline passed"),
567            Unknown::TooLarge { nodes } => {
568                write!(f, "the circuit is too large ({nodes} nodes built)")
569            }
570            Unknown::Unsupported(why) => f.write_str(why),
571        }
572    }
573}
574
575/// The work a question took, so far. Every count is of work done, not of time, and the same on
576/// every run: a question asked the same way (in a context with the same history) reports the
577/// same numbers, and the totals of one resumed in steps are those of one asked at once.
578#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
579#[non_exhaustive]
580pub struct Stats {
581    /// What simplifying the question took ([`Config::simplify`]).
582    pub simplification: Simplification,
583    /// What sweeping the circuit did ([`Config::sweeping`]); its conflicts, decisions,
584    /// propagations and lemmas are also counted in the totals below.
585    pub sweeping: Sweeping,
586    /// AIG nodes of the circuit (inputs and gates).
587    pub nodes: usize,
588    /// Whether the circuit is of the question with its sums written again
589    /// ([`Config::shared_sums`]), and not of the question as asked (where that changed
590    /// nothing, or made a circuit past [`Config::max_nodes`]).
591    pub rewritten: bool,
592    /// Assignments evaluated before search, on words or the circuit ([`Config::samples`]).
593    pub samples: u64,
594    /// Variables of the clauses.
595    pub vars: u32,
596    /// Clauses of the question (not learned ones).
597    pub clauses: usize,
598    /// Learned clauses kept.
599    pub learned: usize,
600    /// Clauses learned in all, units included, whether kept or since deleted.
601    pub lemmas: u64,
602    /// Variables fixed for good: assigned with no decision made, by the clauses and the units
603    /// learned so far. Of [`vars`](Self::vars), the part of the circuit the search has settled.
604    pub fixed: usize,
605    /// Conflicts.
606    pub conflicts: u64,
607    /// Decisions.
608    pub decisions: u64,
609    /// Propagations.
610    pub propagations: u64,
611    /// Searches run: [`Question::solve`] calls that searched (one that finds the question
612    /// already decided, or that has a zero allowance, does not).
613    pub searches: u32,
614    /// The last search's conflicts: the marginal cost of its call. A search goes on from where
615    /// the one before stopped, so these add up to [`conflicts`](Self::conflicts) and nothing
616    /// is searched twice.
617    pub last_conflicts: u64,
618    /// The last search's decisions.
619    pub last_decisions: u64,
620    /// The last search's propagations (they add up to [`propagations`](Self::propagations)
621    /// with the propagation of the clauses before any search).
622    pub last_propagations: u64,
623    /// Clauses the last search learned.
624    pub last_lemmas: u64,
625}
626
627impl Stats {
628    /// These counts without the last search's own ([`searches`](Self::searches) and the
629    /// `last_*` fields cleared): the work done in all, which is the same for a question
630    /// resumed in steps and one asked at once under their combined limits.
631    pub fn totals(self) -> Stats {
632        Stats {
633            searches: 0,
634            last_conflicts: 0,
635            last_decisions: 0,
636            last_propagations: 0,
637            last_lemmas: 0,
638            ..self
639        }
640    }
641}
642
643/// What sweeping a question's circuit did ([`Config::sweeping`]).
644#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
645#[non_exhaustive]
646pub struct Sweeping {
647    /// Whether the circuit was swept: simulated, and its candidate pairs proved.
648    pub ran: bool,
649    /// Whether the circuit was simulated and judged not worth sweeping: too few classes of
650    /// nodes that agree join the two sides of an equality (see [`Config::sweeping`]).
651    pub skipped: bool,
652    /// Classes of the first simulation that join the two sides of an equality (of a question
653    /// that is not one: classes of two nodes or more).
654    pub crossings: u64,
655    /// Nodes proved equal to an earlier node, or its complement, or to a constant.
656    pub merged: u64,
657    /// Candidate pairs a counterexample told apart.
658    pub separated: u64,
659    /// Candidate pairs left undecided within their own conflict cap.
660    pub undecided: u64,
661    /// The sweep's conflicts.
662    pub conflicts: u64,
663    /// The sweep's propagations.
664    pub propagations: u64,
665}
666
667/// What simplifying a question with bitwright's own engine took ([`Config::simplify`]).
668#[derive(Copy, Clone, Debug, PartialEq, Eq)]
669#[non_exhaustive]
670pub struct Simplification {
671    /// Whether the engine ran on the question.
672    pub ran: bool,
673    /// The work it did, in the units of its budget ([`Config::simplify_budget`]): every
674    /// field counted, capped or not. Work the engine finished on the same nodes earlier in the
675    /// same context is remembered there and not done again.
676    pub spent: crate::engine::Budget,
677    /// The cap that stopped it, if one did. The rewrites it made until then are kept, and the
678    /// rest of the question is blasted as it stands; a larger budget may settle more.
679    pub stopped: Option<crate::engine::Exhausted>,
680    /// Whether it decided the question (the simplified question is true).
681    pub decided: bool,
682}
683
684impl Default for Simplification {
685    /// The engine did not run.
686    fn default() -> Self {
687        Simplification {
688            ran: false,
689            spent: crate::engine::Budget::ZERO,
690            stopped: None,
691            decided: false,
692        }
693    }
694}
695
696/// The bits of expressions, blasted on demand.
697pub(crate) struct Blaster<'c> {
698    pub(crate) cx: &'c mut Context,
699    pub(crate) g: Aig,
700    bits: IdMap<u32, Bits>,
701    /// Each symbol met, with its bits.
702    pub(crate) symbols: Vec<(u32, Bits)>,
703    selectors: Vec<L>,
704    selector_hints: bool,
705    input_cancellation: bool,
706    join_factoring: bool,
707    carry_save_multiplication: bool,
708    hardwire_declared: bool,
709    udivrem_cache: IdMap<(u32, u32), (Bits, Bits)>,
710    max_nodes: usize,
711    /// Blasting stopped at `max_nodes`.
712    too_large: bool,
713}
714
715impl<'c> Blaster<'c> {
716    pub(crate) fn new(cx: &'c mut Context, max_nodes: usize) -> Blaster<'c> {
717        Blaster {
718            cx,
719            g: Aig::new(),
720            bits: IdMap::default(),
721            symbols: Vec::new(),
722            selectors: Vec::new(),
723            selector_hints: false,
724            input_cancellation: false,
725            join_factoring: false,
726            carry_save_multiplication: false,
727            hardwire_declared: true,
728            udivrem_cache: IdMap::default(),
729            max_nodes,
730            too_large: false,
731        }
732    }
733
734    /// A blaster that goes on from a circuit built before: its graph, the bits of the nodes
735    /// blasted and the symbols met ([`into_parts`](Self::into_parts)). Symbol bits stay free
736    /// inputs so [`Incremental`] can assume whatever known bits are declared at each check.
737    pub(crate) fn resume(
738        cx: &'c mut Context,
739        g: Aig,
740        bits: IdMap<u32, Bits>,
741        symbols: Vec<(u32, Bits)>,
742        max_nodes: usize,
743    ) -> Blaster<'c> {
744        Blaster {
745            g,
746            bits,
747            symbols,
748            hardwire_declared: false,
749            ..Blaster::new(cx, max_nodes)
750        }
751    }
752
753    /// The circuit, to [`resume`](Self::resume) from.
754    pub(crate) fn into_parts(self) -> (Aig, IdMap<u32, Bits>, Vec<(u32, Bits)>) {
755        (self.g, self.bits, self.symbols)
756    }
757
758    /// The bits of node `root`.
759    pub(crate) fn blast(&mut self, root: u32) -> Result<Bits, Error> {
760        let bits = &self.bits;
761        let order = self
762            .cx
763            .post_order_ids_pruned(&[root], |e| bits.contains_key(&e.index()));
764        for i in order {
765            if self.bits.contains_key(&i) {
766                continue;
767            }
768            if self.g.len() > self.max_nodes {
769                self.too_large = true;
770                return Err(Error::Unsupported("the circuit is too large".into()));
771            }
772            let b = self.node(i)?;
773            self.bits.insert(i, b);
774        }
775        Ok(self.bits[&root].clone())
776    }
777
778    fn node(&mut self, i: u32) -> Result<Bits, Error> {
779        use blast::*;
780        let n = self.cx.node(i);
781        let w = usize::from(n.width);
782        let get = |s: &Self, j: u32| s.bits[&j].clone();
783        let g = &mut self.g;
784        Ok(match n.op {
785            OpCode::Const => konst(&self.cx.const_val(i).unwrap_or(BitVec::zero(Width::W1))),
786            OpCode::Sym => {
787                // Declarations are part of a symbol's meaning, including in certificate
788                // mode. Only its unknown bits are inputs of the circuit, unless the circuit
789                // is kept across checks (`Incremental`), where declarations are assumed per
790                // solve so changes or withdrawals stay sound.
791                let known = self
792                    .hardwire_declared
793                    .then(|| self.cx.declared_at(i))
794                    .flatten();
795                let b: Bits = (0..w)
796                    .map(|j| match known {
797                        Some(k) if k.known_one().bit(j as u16) == Some(true) => aig::TRUE,
798                        Some(k) if k.known_zero().bit(j as u16) == Some(true) => aig::FALSE,
799                        _ => g.input(),
800                    })
801                    .collect();
802                self.symbols.push((i, b.clone()));
803                b
804            }
805            OpCode::Not => not(g, &self.bits[&n.a]),
806            OpCode::Neg => {
807                let a = get(self, n.a);
808                neg(&mut self.g, &a)
809            }
810            OpCode::Popcnt => popcnt(g, &self.bits[&n.a]),
811            OpCode::Clz => clz(g, &self.bits[&n.a]),
812            OpCode::Ctz => ctz(g, &self.bits[&n.a]),
813            OpCode::Bswap => bswap(&self.bits[&n.a]),
814            OpCode::BitRev => bitrev(&self.bits[&n.a]),
815            OpCode::Zext => {
816                let mut a = get(self, n.a);
817                a.resize(w, aig::FALSE);
818                a
819            }
820            OpCode::Sext => {
821                let mut a = get(self, n.a);
822                let top = *a.last().unwrap_or(&aig::FALSE);
823                a.resize(w, top);
824                a
825            }
826            OpCode::Extract => {
827                let a = get(self, n.a);
828                let lo = n.b as usize;
829                a[lo..lo + w].to_vec()
830            }
831            OpCode::Concat => {
832                let (hi, mut lo) = (get(self, n.a), get(self, n.b));
833                lo.extend(hi);
834                lo
835            }
836            OpCode::Select => {
837                let (c, t, e) = (get(self, n.a)[0], get(self, n.b), get(self, n.c));
838                mux(&mut self.g, c, &t, &e)
839            }
840            OpCode::Eq | OpCode::Ne | OpCode::Ult | OpCode::Ule | OpCode::Slt | OpCode::Sle => {
841                let (a, b) = (get(self, n.a), get(self, n.b));
842                let g = &mut self.g;
843                let r = match n.op {
844                    OpCode::Eq if self.join_factoring => eq_factored(g, &a, &b),
845                    OpCode::Ne if self.join_factoring => eq_factored(g, &a, &b) ^ 1,
846                    OpCode::Eq => eq(g, &a, &b),
847                    OpCode::Ne => eq(g, &a, &b) ^ 1,
848                    OpCode::Ult => ult(g, &a, &b),
849                    OpCode::Ule => ule(g, &a, &b),
850                    OpCode::Slt => slt(g, &a, &b),
851                    _ => sle(g, &a, &b),
852                };
853                vec![r]
854            }
855            op if op.as_bin().is_some() => {
856                let (a, b) = (get(self, n.a), get(self, n.b));
857                if self.selector_hints && matches!(op, OpCode::Shl | OpCode::LShr | OpCode::AShr) {
858                    let unknown: Vec<_> = b
859                        .iter()
860                        .copied()
861                        .filter(|&l| l > aig::TRUE)
862                        .take(5)
863                        .collect();
864                    if !unknown.is_empty() && unknown.len() <= 4 {
865                        self.selectors.extend(unknown);
866                    }
867                }
868                let g = &mut self.g;
869                match op {
870                    OpCode::Add => add(g, &a, &b),
871                    OpCode::Sub => sub(g, &a, &b),
872                    OpCode::Mul if self.carry_save_multiplication => mul_carry_save(g, &a, &b),
873                    OpCode::Mul => mul(g, &a, &b),
874                    OpCode::UMulHi if self.carry_save_multiplication => {
875                        mulhi_carry_save(g, &a, &b, false)
876                    }
877                    OpCode::UMulHi => mulhi(g, &a, &b, false),
878                    OpCode::SMulHi if self.carry_save_multiplication => {
879                        mulhi_carry_save(g, &a, &b, true)
880                    }
881                    OpCode::SMulHi => mulhi(g, &a, &b, true),
882                    OpCode::UDiv | OpCode::URem => {
883                        let qr = match self.udivrem_cache.get(&(n.a, n.b)) {
884                            Some(qr) => qr.clone(),
885                            None => {
886                                let qr = udivrem(g, &a, &b);
887                                self.udivrem_cache.insert((n.a, n.b), qr.clone());
888                                qr
889                            }
890                        };
891                        if op == OpCode::UDiv { qr.0 } else { qr.1 }
892                    }
893                    OpCode::SDiv => sdiv(g, &a, &b),
894                    OpCode::SRem => srem(g, &a, &b),
895                    OpCode::And => and(g, &a, &b),
896                    OpCode::Or => or(g, &a, &b),
897                    OpCode::Xor if self.input_cancellation => xor_cancel_input(g, &a, &b),
898                    OpCode::Xor => xor(g, &a, &b),
899                    OpCode::Shl => shift(g, &a, &b, true, aig::FALSE),
900                    OpCode::LShr => shift(g, &a, &b, false, aig::FALSE),
901                    OpCode::AShr => {
902                        let s = *a.last().unwrap_or(&aig::FALSE);
903                        shift(g, &a, &b, false, s)
904                    }
905                    OpCode::RotL => rotate(g, &a, &b, true),
906                    OpCode::RotR => rotate(g, &a, &b, false),
907                    OpCode::Pdep => pdep(g, &a, &b),
908                    _ => pext(g, &a, &b),
909                }
910            }
911            op if op.as_ext().is_some() => self.ext(i)?,
912            _ => {
913                let kids: Vec<Bits> = n.children().map(|c| self.bits[&c].clone()).collect();
914                fp::blast(self, i, &kids)?
915            }
916        })
917    }
918
919    /// An extension output, through the operation's expansion.
920    fn ext(&mut self, i: u32) -> Result<Bits, Error> {
921        let n = self.cx.node(i);
922        let Some((_, k)) = n.op.as_ext() else {
923            return Err(Error::Unsupported("not an extension output".into()));
924        };
925        let args: Vec<Expr> = n.children().map(|c| self.cx.handle(c)).collect();
926        let reg = self
927            .cx
928            .registry
929            .clone()
930            .ok_or_else(|| Error::Unsupported("an extension without its registry".into()))?;
931        let op = reg
932            .op_at(n.aux)
933            .ok_or_else(|| Error::Unsupported("an extension without its operation".into()))?;
934        let Some(ex) = op.expand(self.cx, &args) else {
935            return Err(Error::Unsupported(format!(
936                "`{}` has no expansion to reason about",
937                op.name()
938            )));
939        };
940        let outs = ex?;
941        let e = self.cx.id(outs[k])?;
942        self.blast(e)
943    }
944
945    /// Why blasting failed with `e`: [`Unknown::TooLarge`] past `max_nodes`, else the reason
946    /// of an unsupported operation. Other errors are errors.
947    fn unknown(&self, e: Error) -> Result<Unknown, Error> {
948        match e {
949            _ if self.too_large => Ok(Unknown::TooLarge {
950                nodes: self.g.len(),
951            }),
952            Error::Unsupported(why) => Ok(Unknown::Unsupported(why)),
953            e => Err(e),
954        }
955    }
956}
957
958/// Where a SAT-solved question stands.
959struct Search {
960    solver: Solver,
961    cnf: Cnf,
962    /// What the sweep cost ([`Config::sweeping`]), counted in the totals.
963    swept: sweep::Work,
964}
965
966/// A question, blasted and encoded once, then decided in as many steps as its caller likes: a
967/// search that ends on its limits stops where it is, keeping what it learned, and the next
968/// [`solve`](Self::solve) goes on from there. Asking under 5,000 conflicts, then 15,000 more,
969/// costs what asking under 20,000 once does, and answers the same.
970///
971/// ```
972/// use bitwright::prove::{Config, Limits, Outcome, Question};
973/// use bitwright::{Context, ParseOptions, Width};
974///
975/// let mut cx = Context::new();
976/// let o = ParseOptions::width(Width::W16);
977/// let p = cx.parse("x * x != 0x1234", &o)?;
978/// // Without the engine's simplification first, which decides it by residues.
979/// let cfg = Config::default().with_samples(0).with_simplify(false);
980/// let mut q = Question::valid(&mut cx, p, &cfg)?;
981/// let mut out = q.solve(&mut cx, Limits::conflicts(10))?;
982/// while let Outcome::Unknown(why) = &out {
983///     assert!(why.is_budget());
984///     out = q.solve(&mut cx, Limits::conflicts(10))?;
985/// }
986/// assert!(matches!(out, Outcome::Proved(_))); // 0x1234 is not a square mod 2^16
987/// assert!(q.stats().conflicts > 0);
988/// # Ok::<(), bitwright::Error>(())
989/// ```
990pub struct Question {
991    /// The question as asked (with the constraints, as `¬(c1 ∧ …) ∨ p`), checked by evaluation.
992    root: Expr,
993    /// Each symbol of the question with its bits (one the circuit does not read takes its
994    /// declared ones, or 0 without a declaration).
995    symbols: Vec<(SymbolKey, Width, Bits)>,
996    search: Option<Box<Search>>,
997    outcome: Option<Outcome>,
998    stats: Stats,
999}
1000
1001impl core::fmt::Debug for Question {
1002    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1003        f.debug_struct("Question")
1004            .field("outcome", &self.outcome)
1005            .field("stats", &self.stats)
1006            .finish_non_exhaustive()
1007    }
1008}
1009
1010impl Question {
1011    /// Whether the 1-bit `p` is true for every value of its symbols agreeing with their
1012    /// declared known bits.
1013    pub fn valid(cx: &mut Context, p: Expr, cfg: &Config) -> Result<Question, Error> {
1014        Question::valid_under(cx, p, None, cfg)
1015    }
1016
1017    /// Whether `a` and `b` (of one width) are equal for every value of their symbols agreeing
1018    /// with their declared known bits.
1019    pub fn equal(cx: &mut Context, a: Expr, b: Expr, cfg: &Config) -> Result<Question, Error> {
1020        let (ai, bi) = (cx.id(a)?, cx.id(b)?);
1021        if cx.wid(ai) != cx.wid(bi) {
1022            return Err(crate::WidthError::Mismatch {
1023                left: cx.wid(ai),
1024                right: cx.wid(bi),
1025            }
1026            .into());
1027        }
1028        let p = cx.c_cmp(crate::CmpOp::Eq, ai, bi)?;
1029        let p = cx.handle(p);
1030        Question::valid(cx, p, cfg)
1031    }
1032
1033    /// Whether `p` is true wherever the constraints of `assumptions` hold. Complete original
1034    /// facts are retained, including partial masks, signed/unsigned
1035    /// intervals and unsigned strides; they remain in certificates and counterexample replay.
1036    /// The question is simplified (see [`Config::simplify`]), optionally sampled at the word level, then
1037    /// blasted, sampled (see [`Config::samples`]) and encoded here; each stage may decide it.
1038    pub fn valid_under(
1039        cx: &mut Context,
1040        p: Expr,
1041        assumptions: Option<&Assumptions>,
1042        cfg: &Config,
1043    ) -> Result<Question, Error> {
1044        Self::valid_under_with_pairs(cx, p, assumptions, &[], cfg)
1045    }
1046
1047    /// Ask the original question after applying explicitly supplied, exhaustively checked
1048    /// finite-domain pair facts. Verification costs are separate from this query's budget.
1049    /// Models are replayed on the original predicate. Certificate requests retain the
1050    /// original bit-blast path and do not use these word-level facts.
1051    pub fn valid_with_pairs(
1052        cx: &mut Context,
1053        p: Expr,
1054        pairs: &[finite::CheckedPair],
1055        cfg: &Config,
1056    ) -> Result<Question, Error> {
1057        Self::valid_under_with_pairs(cx, p, None, pairs, cfg)
1058    }
1059
1060    /// [`valid_with_pairs`](Self::valid_with_pairs) under explicit assumptions.
1061    pub fn valid_under_with_pairs(
1062        cx: &mut Context,
1063        p: Expr,
1064        assumptions: Option<&Assumptions>,
1065        pairs: &[finite::CheckedPair],
1066        cfg: &Config,
1067    ) -> Result<Question, Error> {
1068        Self::build(cx, p, assumptions, pairs, cfg, Env::process())
1069    }
1070
1071    /// [`valid_under`](Self::valid_under), simplified by the caller's engines and not the
1072    /// process's: the same question, answer and statistics.
1073    pub fn valid_under_with(
1074        cx: &mut Context,
1075        p: Expr,
1076        assumptions: Option<&Assumptions>,
1077        cfg: &Config,
1078        simplifiers: &Simplifiers,
1079    ) -> Result<Question, Error> {
1080        let env = Env {
1081            simplifiers,
1082            deadline: None,
1083        };
1084        Self::build(cx, p, assumptions, &[], cfg, env)
1085    }
1086
1087    /// The question, built with `env`.
1088    pub(crate) fn build(
1089        cx: &mut Context,
1090        p: Expr,
1091        assumptions: Option<&Assumptions>,
1092        pairs: &[finite::CheckedPair],
1093        cfg: &Config,
1094        env: Env<'_>,
1095    ) -> Result<Question, Error> {
1096        let pi = cx.id(p)?;
1097        if cx.wid(pi) != 1 {
1098            return Err(crate::WidthError::Mismatch {
1099                left: 1,
1100                right: cx.wid(pi),
1101            }
1102            .into());
1103        }
1104        let mut q = Question {
1105            root: p,
1106            symbols: Vec::new(),
1107            search: None,
1108            outcome: None,
1109            stats: Stats::default(),
1110        };
1111        let decided = |mut q: Question, o: Outcome| {
1112            q.outcome = Some(o);
1113            Ok(q)
1114        };
1115        // Exact original constraints, including masks, signed/unsigned bounds and strides.
1116        let mut cons: Vec<u32> = Vec::new();
1117        if let Some(a) = assumptions {
1118            for predicate in a.predicates(cx)? {
1119                cons.push(cx.id(predicate)?);
1120            }
1121        }
1122        // The root checked by evaluation: `p` where the constraints hold, as `¬(c1 ∧ …) ∨ p`.
1123        let mut root = pi;
1124        for &c in &cons {
1125            let nc = cx.c_un(crate::UnOp::Not, c)?;
1126            root = cx.c_bin(crate::BinOp::Or, nc, root)?;
1127        }
1128        q.root = cx.handle(root);
1129        // The question simplified (not for a certificate, which must be of the question itself).
1130        let mut goal_node = pi;
1131        if !cfg.certificate {
1132            for pair in pairs {
1133                let rewritten = pair.simplify(cx, cx.handle(goal_node))?;
1134                goal_node = cx.id(rewritten)?;
1135            }
1136            if cx
1137                .const_val(goal_node)
1138                .is_some_and(|value| !value.is_zero())
1139            {
1140                return decided(q, Outcome::Proved(None));
1141            }
1142        }
1143        if cfg.simplify && !cfg.certificate {
1144            let mut spent = crate::engine::Allowance::new(crate::engine::Budget::UNLIMITED);
1145            let run = crate::engine::Run::default()
1146                .with_per_call(cfg.simplify_budget)
1147                .with_allowance(&mut spent);
1148            let run = match assumptions {
1149                Some(a) => run.with_assumptions(a),
1150                None => run,
1151            };
1152            let run = match env.deadline {
1153                Some(d) => run.with_deadline(d),
1154                None => run,
1155            };
1156            let goal = cx.handle(goal_node);
1157            let out = (env.simplifiers)
1158                .engine(cfg.strict, cfg.proved_words)
1159                .run(cx, &[goal], run)?
1160                .roots[0];
1161            let s = cx.id(out.expr)?;
1162            let proved = cx.const_val(s).is_some_and(|v| !v.is_zero());
1163            q.stats.simplification = Simplification {
1164                ran: true,
1165                spent: spent.spent(),
1166                stopped: match out.end {
1167                    crate::engine::End::BudgetTerminated(why) => Some(why),
1168                    _ => None,
1169                },
1170                decided: proved,
1171            };
1172            if proved {
1173                return decided(q, Outcome::Proved(None));
1174            }
1175            // Stopped by its caller: what is left would be built and searched for nobody.
1176            if out.end == crate::engine::End::BudgetTerminated(crate::engine::Exhausted::Deadline) {
1177                return decided(q, Outcome::Unknown(Unknown::Deadline));
1178            }
1179            // A result that relies on constraints holds where they do, which is all a proof
1180            // under them needs.
1181            goal_node = s;
1182        }
1183        if cfg.divisions && !cfg.simplify && !cfg.certificate {
1184            let run = crate::engine::Run::default().with_per_call(cfg.simplify_budget);
1185            let run = match assumptions {
1186                Some(a) => run.with_assumptions(a),
1187                None => run,
1188            };
1189            let goal = cx.handle(goal_node);
1190            let out = env
1191                .simplifiers
1192                .divisions_only()
1193                .run(cx, &[goal], run)?
1194                .roots[0];
1195            goal_node = cx.id(out.expr)?;
1196            if cx.const_val(goal_node).is_some_and(|v| !v.is_zero()) {
1197                q.stats.rewritten = true;
1198                return decided(q, Outcome::Proved(None));
1199            }
1200        }
1201        let mut word_sampled = false;
1202        if (cfg.word_sampling || cfg.sample_mode == SampleMode::Words)
1203            && cfg.samples != 0
1204            && let Some(trial) = sample_words::try_sample(cx, goal_node, &cons, assumptions, cfg)
1205        {
1206            q.stats.samples = trial.samples;
1207            word_sampled = true;
1208            if let Some(mut model) = trial.model {
1209                complete_model(cx, q.root, &mut model)?;
1210                let outcome = q.refuted(cx, model)?;
1211                return decided(q, outcome);
1212            }
1213            if trial.complete && !cfg.certificate {
1214                return decided(q, Outcome::Proved(None));
1215            }
1216        }
1217        // Every legal assignment, when there are few enough. A proof that asks for a
1218        // certificate takes it from the circuit below, which is checked independently.
1219        let mut exhausted = false;
1220        if cfg.exhaustive_inputs != 0
1221            && let Some((failure, evaluated)) =
1222                sample_words::try_exhaust(cx, goal_node, &cons, assumptions, cfg.exhaustive_inputs)
1223        {
1224            q.stats.samples += evaluated;
1225            match failure {
1226                Some(mut model) => {
1227                    complete_model(cx, q.root, &mut model)?;
1228                    let outcome = q.refuted(cx, model)?;
1229                    return decided(q, outcome);
1230                }
1231                None if !cfg.certificate => return decided(q, Outcome::Proved(None)),
1232                None => exhausted = true,
1233            }
1234        }
1235        // The question as asked, where writing its sums again changes it.
1236        let asked = goal_node;
1237        if cfg.shared_sums && !cfg.certificate {
1238            goal_node = sums::shared(cx, goal_node)?;
1239            if cx
1240                .const_val(goal_node)
1241                .is_some_and(|value| !value.is_zero())
1242            {
1243                q.stats.rewritten = true;
1244                return decided(q, Outcome::Proved(None));
1245            }
1246        }
1247        let (mut b, goal, extra) = loop {
1248            let constant_goal = cuts::constant_true(cx, goal_node);
1249            let mut b = Blaster::new(cx, cfg.max_nodes);
1250            b.selector_hints = cfg.selector_branching;
1251            b.input_cancellation = cfg.input_cancellation;
1252            b.join_factoring = cfg.join_factoring;
1253            b.carry_save_multiplication = cfg.carry_save_multiplication;
1254            if constant_goal {
1255                b.bits.insert(goal_node, vec![aig::TRUE]);
1256            }
1257            let mut blasted = || -> Result<(L, Vec<L>), Error> {
1258                let goal = b.blast(goal_node)?[0];
1259                let mut extra = Vec::new();
1260                for &c in &cons {
1261                    extra.push(b.blast(c)?[0]);
1262                }
1263                Ok((goal, extra))
1264            };
1265            match blasted() {
1266                Ok((goal, extra)) if b.g.len() <= cfg.max_nodes => break (b, goal, extra),
1267                // (Written again the circuit is too large: the question as asked, then.)
1268                _ if goal_node != asked => goal_node = asked,
1269                Ok(_) => {
1270                    let why = Unknown::TooLarge { nodes: b.g.len() };
1271                    return decided(q, Outcome::Unknown(why));
1272                }
1273                Err(e) => {
1274                    let why = b.unknown(e)?;
1275                    return decided(q, Outcome::Unknown(why));
1276                }
1277            }
1278        };
1279        q.stats.nodes = b.g.len();
1280        q.stats.rewritten = goal_node != asked;
1281        // Every symbol of the question, with its bits if the circuit reads it. (Marked by
1282        // symbol index: a search of the list per symbol took 12 s on a question of 64 000
1283        // symbols that simplification had already decided.)
1284        let mut listed = vec![false; b.cx.symbol_count()];
1285        for (s, bits) in &b.symbols {
1286            let h = b.cx.handle(*s);
1287            let id =
1288                b.cx.symbol_id(h)?
1289                    .ok_or_else(|| Error::Contract("a symbol without its key".into()))?;
1290            let key =
1291                b.cx.symbol_key(id)
1292                    .cloned()
1293                    .ok_or_else(|| Error::Contract("a symbol without its key".into()))?;
1294            listed[id.index() as usize] = true;
1295            q.symbols.push((key, b.cx.width_of(*s), bits.clone()));
1296        }
1297        for id in b.cx.symbols_in(&[q.root])? {
1298            if !core::mem::replace(&mut listed[id.index() as usize], true)
1299                && let (Some(k), Some(w)) = (b.cx.symbol_key(id).cloned(), b.cx.symbol_width(id))
1300            {
1301                let bits =
1302                    b.cx.find_symbol(&k)
1303                        .and_then(|e| b.cx.declared_at(e.index()))
1304                        .map(|known| blast::konst(&known.known_one()))
1305                        .unwrap_or_default();
1306                q.symbols.push((k, w, bits));
1307            }
1308        }
1309        if exhausted {
1310            let exhaustion = Exhaustion::of(&b.g, goal, &extra);
1311            if exhaustion.inputs() <= u32::from(cfg.exhaustive_inputs.min(63)) {
1312                let cert = Certificate {
1313                    vars: 0,
1314                    clauses: Vec::new(),
1315                    proof: Vec::new(),
1316                    exhaustion: Some(exhaustion),
1317                };
1318                return decided(q, Outcome::Proved(Some(cert)));
1319            }
1320        }
1321        // Sampled: a lane where the constraints hold and the goal does not refutes it.
1322        let batches = if word_sampled {
1323            0
1324        } else {
1325            cfg.samples.div_ceil(64)
1326        };
1327        for batch in 0..batches {
1328            let vals = b.g.eval_words(|k| match cfg.sample_mode {
1329                SampleMode::Random => sample(batch, k),
1330                SampleMode::Small | SampleMode::Words => small_sample(batch, k),
1331            });
1332            q.stats.samples += 64;
1333            let mut bad = !Aig::word(&vals, goal);
1334            for &e in &extra {
1335                bad &= Aig::word(&vals, e);
1336            }
1337            if bad != 0 {
1338                let lane = bad.trailing_zeros();
1339                let ce = Question::counterexample(&q.symbols, |l| {
1340                    (Aig::word(&vals, l) >> lane) & 1 == 1
1341                });
1342                let o = q.refuted(b.cx, ce)?;
1343                return decided(q, o);
1344            }
1345        }
1346        let mut solver = Solver::new();
1347        if cfg.certificate {
1348            solver.log_proof();
1349        }
1350        let mut roots = vec![goal];
1351        roots.extend_from_slice(&extra);
1352        let mut cnf = Cnf::encode_with_xor3(
1353            &b.g,
1354            &roots,
1355            &mut solver,
1356            cfg.certificate,
1357            cfg.xor3_encoding,
1358        );
1359        for &e in &extra {
1360            cnf.assert(e, &mut solver);
1361        }
1362        cnf.assert(goal ^ 1, &mut solver);
1363        let mut asserted = vec![goal ^ 1];
1364        asserted.extend_from_slice(&extra);
1365        relations::strengthen(&b.g, &asserted, &cnf, &mut solver, cfg.relational_lemmas);
1366        if cfg.selector_branching {
1367            for &l in &b.selectors {
1368                if let Some(l) = cnf.mapped_lit(l) {
1369                    solver.prefer_selector(l);
1370                }
1371            }
1372        }
1373        // Swept once, as part of preparing the question: within half of the configured limits,
1374        // whatever the searches' own, so a question resumed in steps is swept as one asked at
1375        // once.
1376        let mut swept = sweep::Work::default();
1377        if cfg.sweeping {
1378            // The two sides of an equality, whose inner nodes a sweep can merge across.
1379            let sides = match b.cx.node(goal_node) {
1380                n if n.op == OpCode::Eq => match (b.bits.get(&n.a), b.bits.get(&n.b)) {
1381                    (Some(x), Some(y)) => Some((x.clone(), y.clone())),
1382                    _ => None,
1383                },
1384                _ => None,
1385            };
1386            let pending = sweep::Pending {
1387                sides,
1388                words: b.symbols.iter().map(|(_, bits)| bits.clone()).collect(),
1389                aig: core::mem::take(&mut b.g),
1390                roots,
1391                xor3: cfg.xor3_encoding,
1392                certificate: cfg.certificate,
1393            };
1394            let share = Limits {
1395                conflicts: cfg.max_conflicts / 2,
1396                propagations: cfg.max_propagations / 2,
1397            };
1398            swept = sweep::sweep(&pending, &cnf, &mut solver, share);
1399            q.stats.sweeping = Sweeping {
1400                ran: swept.ran,
1401                skipped: swept.skipped,
1402                crossings: swept.crossings,
1403                merged: swept.merged,
1404                separated: swept.separated,
1405                undecided: swept.undecided,
1406                conflicts: swept.conflicts,
1407                propagations: swept.propagations,
1408            };
1409        }
1410        q.stats.vars = solver.num_vars();
1411        q.stats.clauses = cnf.emitted();
1412        q.stats.learned = solver.num_learnts();
1413        q.stats.lemmas = solver.lemmas + swept.lemmas;
1414        q.stats.fixed = solver.num_fixed();
1415        q.stats.conflicts = swept.conflicts;
1416        q.stats.decisions = swept.decisions;
1417        q.stats.propagations = solver.propagations + swept.propagations;
1418        q.search = Some(Box::new(Search { solver, cnf, swept }));
1419        Ok(q)
1420    }
1421
1422    /// Searches within `limits` more work (counted from this call): the answer, or
1423    /// [`Unknown::Budget`] with the work done on the question so far, and the next call goes on
1424    /// from there. Once decided (here or when built), the answer is kept and returned again.
1425    /// `cx` is the context the question was built in.
1426    pub fn solve(&mut self, cx: &mut Context, limits: Limits) -> Result<Outcome, Error> {
1427        if let Some(o) = &self.outcome {
1428            return Ok(o.clone());
1429        }
1430        let Some(s) = self.search.as_mut() else {
1431            return Err(Error::Contract(
1432                "a question neither decided nor open".into(),
1433            ));
1434        };
1435        // The question's totals: its solver's and its sweep's.
1436        let totals = |s: &Search| {
1437            (
1438                s.solver.conflicts + s.swept.conflicts,
1439                s.solver.decisions + s.swept.decisions,
1440                s.solver.propagations + s.swept.propagations,
1441                s.solver.lemmas + s.swept.lemmas,
1442            )
1443        };
1444        let before = totals(s);
1445        // A zero allowance pauses the question without searching.
1446        let searching = limits.conflicts != 0 && limits.propagations != 0;
1447        let answer = s.solver.solve_within(limits);
1448        let after = totals(s);
1449        self.stats.learned = s.solver.num_learnts();
1450        self.stats.lemmas = after.3;
1451        self.stats.fixed = s.solver.num_fixed();
1452        self.stats.conflicts = after.0;
1453        self.stats.decisions = after.1;
1454        self.stats.propagations = after.2;
1455        if searching {
1456            self.stats.searches += 1;
1457            self.stats.last_conflicts = after.0 - before.0;
1458            self.stats.last_decisions = after.1 - before.1;
1459            self.stats.last_propagations = after.2 - before.2;
1460            self.stats.last_lemmas = after.3 - before.3;
1461        }
1462        let o = match answer {
1463            Answer::Unknown => {
1464                return Ok(Outcome::Unknown(Unknown::Budget {
1465                    conflicts: after.0,
1466                    propagations: after.2,
1467                }));
1468            }
1469            Answer::Unsat => {
1470                let cert = s.solver.take_proof().map(|proof| Certificate {
1471                    vars: s.solver.num_vars(),
1472                    clauses: core::mem::take(&mut s.cnf.clauses),
1473                    proof,
1474                    exhaustion: None,
1475                });
1476                Outcome::Proved(cert)
1477            }
1478            Answer::Sat(model) => {
1479                let cnf = &s.cnf;
1480                let ce = Question::counterexample(&self.symbols, |l| cnf.value(l, &model));
1481                self.refuted(cx, ce)?
1482            }
1483        };
1484        self.search = None;
1485        self.outcome = Some(o.clone());
1486        Ok(o)
1487    }
1488
1489    /// The answer, once decided.
1490    pub fn outcome(&self) -> Option<&Outcome> {
1491        self.outcome.as_ref()
1492    }
1493
1494    /// The work done on the question so far.
1495    pub fn stats(&self) -> Stats {
1496        self.stats
1497    }
1498
1499    /// The counterexample an assignment of the circuit's inputs gives.
1500    fn counterexample(symbols: &[(SymbolKey, Width, Bits)], bit: impl Fn(L) -> bool) -> Model {
1501        symbols
1502            .iter()
1503            .map(|(k, w, bits)| {
1504                let mut limbs = [0u64; 8];
1505                for (j, &b) in bits.iter().enumerate() {
1506                    if bit(b) {
1507                        limbs[j / 64] |= 1 << (j % 64);
1508                    }
1509                }
1510                (k.clone(), BitVec::wrapping_from_limbs(*w, &limbs))
1511            })
1512            .collect()
1513    }
1514
1515    /// `Refuted(ce)`, checked by bitwright's evaluator: a solver or blaster bug cannot produce a
1516    /// false refutation unnoticed.
1517    fn refuted(&self, cx: &mut Context, ce: Model) -> Result<Outcome, Error> {
1518        // (By key, the first value given for one: a model lists every symbol of the question.)
1519        let mut env: std::collections::HashMap<SymbolKey, BitVec> =
1520            std::collections::HashMap::with_capacity(ce.len());
1521        for (k, v) in &ce {
1522            env.entry(k.clone()).or_insert(*v);
1523        }
1524        let v = cx.eval(&[self.root], &env)?[0];
1525        if v.is_zero() {
1526            Ok(Outcome::Refuted(ce))
1527        } else {
1528            Err(Error::Contract(format!(
1529                "the prover's counterexample does not refute {}",
1530                cx.display(self.root)
1531            )))
1532        }
1533    }
1534}
1535
1536/// Simplification can omit original symbols: supply values consistent with their declarations
1537/// before replaying the original constrained predicate.
1538fn complete_model(cx: &mut Context, root: Expr, model: &mut Model) -> Result<(), Error> {
1539    let mut given: std::collections::HashSet<SymbolKey> =
1540        model.iter().map(|(k, _)| k.clone()).collect();
1541    for id in cx.symbols_in(&[root])? {
1542        let key = cx.symbol_key(id).unwrap().clone();
1543        if given.insert(key.clone()) {
1544            let symbol = cx.find_symbol(&key).unwrap();
1545            let value = cx.declared_known(symbol)?.map_or_else(
1546                || BitVec::zero(cx.symbol_width(id).unwrap()),
1547                |k| k.known_one(),
1548            );
1549            model.push((key, value));
1550        }
1551    }
1552    Ok(())
1553}
1554
1555/// The 64 consecutive assignments `64*batch .. 64*batch+64`, transposed into input words.
1556fn small_sample(batch: u32, k: u32) -> u64 {
1557    const LOW: [u64; 6] = [
1558        0xaaaa_aaaa_aaaa_aaaa,
1559        0xcccc_cccc_cccc_cccc,
1560        0xf0f0_f0f0_f0f0_f0f0,
1561        0xff00_ff00_ff00_ff00,
1562        0xffff_0000_ffff_0000,
1563        0xffff_ffff_0000_0000,
1564    ];
1565    if k < 6 {
1566        LOW[k as usize]
1567    } else if k - 6 < 32 && (batch >> (k - 6)) & 1 == 1 {
1568        u64::MAX
1569    } else {
1570        0
1571    }
1572}
1573
1574/// Input `k`'s word in sample batch `batch` (splitmix64 of the pair); batch 0's lanes 0 and 1
1575/// are all zeros and all ones.
1576fn sample(batch: u32, k: u32) -> u64 {
1577    let mut z = (u64::from(batch) << 32 | u64::from(k)).wrapping_add(0x9e37_79b9_7f4a_7c15);
1578    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1579    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1580    z ^= z >> 31;
1581    if batch == 0 { (z & !0b11) | 0b10 } else { z }
1582}
1583
1584/// Whether the 1-bit `p` is true for every value of its symbols agreeing with their declared
1585/// known bits.
1586pub fn valid(cx: &mut Context, p: Expr, cfg: &Config) -> Result<Outcome, Error> {
1587    valid_under(cx, p, None, cfg)
1588}
1589
1590/// Whether `p` is true wherever the constraints of `assumptions` and the symbols' declared
1591/// known bits hold.
1592pub fn valid_under(
1593    cx: &mut Context,
1594    p: Expr,
1595    assumptions: Option<&Assumptions>,
1596    cfg: &Config,
1597) -> Result<Outcome, Error> {
1598    Question::valid_under(cx, p, assumptions, cfg)?.solve(cx, cfg.limits())
1599}
1600
1601/// [`valid_under`], simplified by the caller's engines and not the process's
1602/// ([`Simplifiers`]): the same answer.
1603pub fn valid_under_with(
1604    cx: &mut Context,
1605    p: Expr,
1606    assumptions: Option<&Assumptions>,
1607    cfg: &Config,
1608    simplifiers: &Simplifiers,
1609) -> Result<Outcome, Error> {
1610    Question::valid_under_with(cx, p, assumptions, cfg, simplifiers)?.solve(cx, cfg.limits())
1611}
1612
1613/// Whether `a` and `b` (of one width) are equal for every value of their symbols agreeing with
1614/// their declared known bits.
1615pub fn equal(cx: &mut Context, a: Expr, b: Expr, cfg: &Config) -> Result<Outcome, Error> {
1616    Question::equal(cx, a, b, cfg)?.solve(cx, cfg.limits())
1617}
1618
1619/// Values of symbols, as a counterexample or a model gives them.
1620pub type Model = Vec<(SymbolKey, BitVec)>;
1621
1622/// A value of the symbols that makes the 1-bit `p` true, if there is one: `Refuted` of `¬p`
1623/// read back as a model (`Ok(Some)`), `Ok(None)` when `p` is unsatisfiable, and `Err` with the
1624/// reason when not decided.
1625pub fn satisfy(
1626    cx: &mut Context,
1627    p: Expr,
1628    cfg: &Config,
1629) -> Result<Result<Option<Model>, Unknown>, Error> {
1630    let np = cx.un(crate::UnOp::Not, p)?;
1631    Ok(match valid(cx, np, cfg)? {
1632        Outcome::Proved(_) => Ok(None),
1633        Outcome::Refuted(m) => Ok(Some(m)),
1634        Outcome::Unknown(why) => Err(why),
1635    })
1636}
1637
1638/// The prover the engine's passes are given ([`crate::engine::oracle`]): the circuit and the
1639/// search alone, without the simplifier (which is the engine that asks).
1640pub(crate) fn circuit_equality(
1641    cx: &mut Context,
1642    a: Expr,
1643    b: Expr,
1644    caps: &crate::engine::oracle::EqualityCaps,
1645) -> Result<crate::engine::oracle::EqualityAnswer, Error> {
1646    use crate::engine::oracle::{EqualityAnswer, EqualityVerdict};
1647    let cfg = Config::default()
1648        .with_simplify(false)
1649        .with_certificate(false)
1650        .with_samples(caps.samples)
1651        .with_max_nodes(caps.max_nodes)
1652        .with_max_conflicts(u64::MAX)
1653        .with_max_propagations(caps.max_propagations);
1654    let mut q = Question::equal(cx, a, b, &cfg)?;
1655    let out = q.solve(cx, cfg.limits())?;
1656    let stats = q.stats();
1657    let (verdict, nodes) = match out {
1658        Outcome::Proved(_) => (EqualityVerdict::Proved, stats.nodes),
1659        Outcome::Refuted(_) => (EqualityVerdict::Refuted, stats.nodes),
1660        Outcome::Unknown(Unknown::Budget { .. }) => (EqualityVerdict::Budget, stats.nodes),
1661        Outcome::Unknown(Unknown::TooLarge { nodes }) => (EqualityVerdict::Unknown, nodes),
1662        Outcome::Unknown(_) => (EqualityVerdict::Unknown, stats.nodes),
1663    };
1664    Ok(EqualityAnswer {
1665        verdict,
1666        nodes,
1667        propagations: stats.propagations,
1668    })
1669}