Skip to main content

cadical_sys/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use bridge::ffi;
4use cxx::memory::UniquePtrTarget;
5use cxx::UniquePtr;
6use std::cell::RefCell;
7use std::rc::Rc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::sync::Arc;
10
11// The raw FFI bindings. They are private: they take `UniquePtr`s that may be
12// null and C++ objects whose lifetimes they cannot check, so exposing them as
13// safe functions would let safe code cause undefined behaviour.
14mod bridge;
15
16/// The C++ shim reports success as an empty string and failure as an error message.
17fn into_result(message: String) -> Result<(), String> {
18    if message.is_empty() {
19        Ok(())
20    } else {
21        Err(message)
22    }
23}
24
25/// Literals must be non-zero and not `i32::MIN`; `CaDiCaL` aborts the process
26/// otherwise, so the safe API panics first.
27#[track_caller]
28fn require_valid_lit(function: &str, lit: i32) {
29    assert!(
30        lit != 0 && lit != i32::MIN,
31        "{function} called with invalid literal {lit}"
32    );
33}
34
35/// Whether `CaDiCaL` requires the variables of added clauses to be declared
36/// (see `Solver::add`).
37fn requires_declared_vars(factor: i32, factorcheck: i32) -> bool {
38    factorcheck == 2 || (factorcheck == 1 && factor != 0)
39}
40
41/// Like [`require_valid_lit`] for functions where zero terminates a clause.
42#[track_caller]
43fn require_valid_lit_or_zero(function: &str, lit: i32) {
44    assert!(
45        lit != i32::MIN,
46        "{function} called with invalid literal {lit}"
47    );
48}
49
50/// The SAT competition standardized the exit code of SAT solvers to the
51/// following which then is also used return code for 'solve' functions.
52/// In the following example we use those constants for brevity though.
53#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
54pub enum Status {
55    SATISFIABLE = 10,
56    UNSATISFIABLE = 20,
57    UNKNOWN = 0,
58}
59
60impl From<i32> for Status {
61    fn from(val: i32) -> Self {
62        match val {
63            10 => Status::SATISFIABLE,
64            20 => Status::UNSATISFIABLE,
65            0 => Status::UNKNOWN,
66            _ => unreachable!(),
67        }
68    }
69}
70
71/// States are represented by a bit-set in order to combine them.
72#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
73pub enum State {
74    /// during initialization (invalid)
75    INITIALIZING = 1,
76    /// configure options (with 'set')
77    CONFIGURING = 2,
78    /// ready to call 'solve'
79    STEADY = 4,
80    /// adding clause literals (zero missing)
81    ADDING = 8,
82    /// while solving (within 'solve')
83    SOLVING = 16,
84    /// satisfiable allows 'val'
85    SATISFIED = 32,
86    /// unsatisfiable allows 'failed'
87    UNSATISFIED = 64,
88    /// during and after deletion (invalid)
89    DELETING = 128,
90    /// unknown allows 'implied'
91    INCONCLUSIVE = 256,
92
93    /// These combined states are used to check contracts.
94    /// CONFIGURING | STEADY | SATISFIED | UNSATISFIED | INCONCLUSIVE,
95    READY = 358,
96    /// READY | ADDING
97    VALID = 366,
98    /// INITIALIZING | DELETING
99    INVALID = 129,
100}
101
102impl From<i32> for State {
103    fn from(val: i32) -> Self {
104        match val {
105            1 => State::INITIALIZING,
106            2 => State::CONFIGURING,
107            4 => State::STEADY,
108            8 => State::ADDING,
109            16 => State::SOLVING,
110            32 => State::SATISFIED,
111            64 => State::UNSATISFIED,
112            128 => State::DELETING,
113            256 => State::INCONCLUSIVE,
114            358 => State::READY,
115            366 => State::VALID,
116            129 => State::INVALID,
117            _ => unreachable!(),
118        }
119    }
120}
121
122/// A Rust callback object together with the C++ wrapper that calls into it.
123///
124/// The C++ wrapper only holds a raw pointer to the callback, so the callback
125/// is boxed and owned here rather than borrowed from the caller. This is what
126/// guarantees the callback outlives every call the solver makes into it.
127struct Connected<W: UniquePtrTarget> {
128    wrapper: UniquePtr<W>,
129    callback: *mut u8,
130    drop_callback: unsafe fn(*mut u8),
131}
132
133impl<W: UniquePtrTarget> Connected<W> {
134    /// Boxes `callback` and builds its C++ wrapper from a pointer to it.
135    fn new<T>(callback: T, make_wrapper: impl FnOnce(*mut u8) -> UniquePtr<W>) -> Self {
136        unsafe fn drop_box<T>(ptr: *mut u8) {
137            drop(unsafe { Box::from_raw(ptr.cast::<T>()) });
138        }
139        let callback = Box::into_raw(Box::new(callback)).cast::<u8>();
140        Self {
141            wrapper: make_wrapper(callback),
142            callback,
143            drop_callback: drop_box::<T>,
144        }
145    }
146}
147
148impl<W: UniquePtrTarget> Drop for Connected<W> {
149    fn drop(&mut self) {
150        // Free the wrapper before the callback it points to.
151        drop(std::mem::replace(&mut self.wrapper, UniquePtr::null()));
152        unsafe { (self.drop_callback)(self.callback) };
153    }
154}
155
156/// A `CaDiCaL` solver.
157///
158/// Methods that take a literal panic if it is `0` or `i32::MIN` (except
159/// [`CaDiCal::add`] and [`CaDiCal::constrain`], where `0` ends the clause), and
160/// methods with a state precondition panic when it does not hold. `CaDiCaL`
161/// itself would abort the whole process in both cases.
162///
163/// With the `factor` option (off by default), or `factorcheck` set to 2,
164/// clauses may only use variables declared with
165/// [`CaDiCal::declare_more_variables`] (or [`CaDiCal::resize`]); adding others
166/// panics. One case is not checked: with `factor` the solver adds extension
167/// variables of its own, and passing one of those to a method that takes a
168/// literal still aborts.
169///
170/// `CaDiCaL`'s own checking options, e.g. `checkfrozen` (which makes reusing
171/// a variable that was not frozen across `solve` calls fatal), abort the
172/// process when their check fails; that is what they are for.
173///
174/// `CaDiCaL` reads options from `CADICAL_<OPTION>` environment variables. The
175/// debugging variable `CADICAL_LIDRUP_TRACE` makes every solver write a proof
176/// to the given file, and `CaDiCaL` aborts the process when a second solver
177/// is created while it is set.
178pub struct CaDiCal {
179    // Declared first so the solver is destroyed before the callbacks it may call.
180    solver: UniquePtr<ffi::Solver>,
181    last_terminator: Option<Connected<ffi::Terminator>>,
182    last_learner: Option<Connected<ffi::Learner>>,
183    last_external_propagator: Option<Connected<ffi::ExternalPropagator>>,
184    last_fixed_listener: Option<Connected<ffi::FixedAssignmentListener>>,
185    last_tracer: Option<Connected<ffi::Tracer>>,
186    // Whether the last proof file opened with `trace_proof*` is still open.
187    proof_file_open: bool,
188    // Whether a proof file was closed. CaDiCaL then closes it again (and
189    // crashes) when a later proof file is closed, so no new one may be opened.
190    proof_file_closed: bool,
191    // The `factor` and `factorcheck` options, which decide whether CaDiCaL
192    // requires the variables of added clauses to be declared. Options only
193    // change while CONFIGURING, through `set`, `set_long_option`, `configure`,
194    // `read_dimacs*` and `copy`, which update these.
195    factor_option: i32,
196    factorcheck_option: i32,
197}
198
199/// Cloning copies the formula and options (see [`CaDiCal::copy`]) but not any
200/// connected callbacks; the clone starts with none connected. Like `copy`, it
201/// panics if the solver is not READY, e.g. in the middle of adding a clause.
202impl Clone for CaDiCal {
203    fn clone(&self) -> Self {
204        let mut r = Self::new();
205        Self::copy(self, &mut r);
206        r
207    }
208}
209
210impl Drop for CaDiCal {
211    fn drop(&mut self) {
212        // CaDiCaL deletes tracers that are still connected when it is destroyed,
213        // but ours is owned (and deleted) by `last_tracer`.
214        self.disconnect_proof_tracer1();
215    }
216}
217
218impl Default for CaDiCal {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl CaDiCal {
225    #[must_use]
226    #[inline]
227    pub fn new() -> Self {
228        let mut solver = Self {
229            solver: ffi::constructor(),
230            last_terminator: None,
231            last_learner: None,
232            last_external_propagator: None,
233            last_fixed_listener: None,
234            last_tracer: None,
235            proof_file_open: false,
236            proof_file_closed: false,
237            factor_option: 0,
238            factorcheck_option: 1,
239        };
240        // Options can also be set through `CADICAL_<OPTION>` environment
241        // variables, which CaDiCaL reads when the solver is created.
242        solver.update_declared_vars_only();
243        // With this (debugging) environment variable set, CaDiCaL opens a
244        // proof file itself when the solver is created.
245        solver.proof_file_open = std::env::var_os("CADICAL_LIDRUP_TRACE")
246            .or_else(|| std::env::var_os("CADICALLIDRUPTRACE"))
247            .is_some();
248        solver
249    }
250
251    /// Core functionality as in the IPASIR incremental SAT solver interface.
252    /// (recall 'READY = CONFIGURING | STEADY  | SATISFIED | UNSATISFIED | INCONCLUSIVE').
253    /// Further note that 'lit' is required to be different from '`INT_MIN`' and
254    /// different from '0' except for 'add'.
255    ///
256    /// Add valid literal to clause or zero to terminate clause.
257    ///
258    ///   require (VALID)                   recall 'VALID = READY | ADDING'
259    ///
260    ///   if (lit) ensure (ADDING)          and thus VALID but not READY
261    ///
262    ///   if (!lit) ensure (STEADY )        and thus READY
263    ///
264    #[inline]
265    #[track_caller]
266    pub fn add(&mut self, lit: i32) {
267        require_valid_lit_or_zero("add", lit);
268        if lit != 0 {
269            self.require_declared("add", lit);
270        }
271        ffi::add(&mut self.solver, lit);
272    }
273
274    /// Here are functions simplifying clause addition. The given literals
275    /// should all be valid (different from '`INT_MIN`' and different from '0').
276    ///
277    ///   require (VALID)
278    ///   ensure (STEADY )
279    ///
280    #[inline]
281    #[track_caller]
282    pub fn clause1(&mut self, l1: i32) {
283        require_valid_lit("clause1", l1);
284        self.require_declared("clause1", l1);
285        ffi::clause1(&mut self.solver, l1);
286    }
287
288    #[inline]
289    #[track_caller]
290    pub fn clause2(&mut self, l1: i32, l2: i32) {
291        for lit in [l1, l2] {
292            require_valid_lit("clause2", lit);
293            self.require_declared("clause2", lit);
294        }
295        ffi::clause2(&mut self.solver, l1, l2);
296    }
297
298    #[inline]
299    #[track_caller]
300    pub fn clause3(&mut self, l1: i32, l2: i32, l3: i32) {
301        for lit in [l1, l2, l3] {
302            require_valid_lit("clause3", lit);
303            self.require_declared("clause3", lit);
304        }
305        ffi::clause3(&mut self.solver, l1, l2, l3);
306    }
307
308    #[inline]
309    #[track_caller]
310    pub fn clause4(&mut self, l1: i32, l2: i32, l3: i32, l4: i32) {
311        for lit in [l1, l2, l3, l4] {
312            require_valid_lit("clause4", lit);
313            self.require_declared("clause4", lit);
314        }
315        ffi::clause4(&mut self.solver, l1, l2, l3, l4);
316    }
317
318    #[inline]
319    #[track_caller]
320    pub fn clause5(&mut self, l1: i32, l2: i32, l3: i32, l4: i32, l5: i32) {
321        for lit in [l1, l2, l3, l4, l5] {
322            require_valid_lit("clause5", lit);
323            self.require_declared("clause5", lit);
324        }
325        ffi::clause5(&mut self.solver, l1, l2, l3, l4, l5);
326    }
327
328    #[inline]
329    #[track_caller]
330    pub fn clause6(&mut self, v: &[i32]) {
331        for &lit in v {
332            require_valid_lit("clause6", lit);
333            self.require_declared("clause6", lit);
334        }
335        ffi::clause6(&mut self.solver, v);
336    }
337
338    /// This function can be used to check if the formula is already
339    /// inconsistent (contains the empty clause or was proven to be
340    /// root-level unsatisfiable).
341    #[inline]
342    pub fn inconsistent(&mut self) -> bool {
343        ffi::inconsistent(&mut self.solver)
344    }
345
346    /// Assume valid non zero literal for next call to 'solve'.  These
347    /// assumptions are reset after the call to 'solve' as well as after
348    /// returning from 'simplify' and 'lookahead.
349    ///
350    ///   require (READY)
351    ///   ensure (STEADY )
352    ///
353    #[inline]
354    #[track_caller]
355    pub fn assume(&mut self, lit: i32) {
356        require_valid_lit("assume", lit);
357        self.require_ready("assume");
358        ffi::assume(&mut self.solver, lit);
359    }
360
361    /// Try to solve the current formula.  Returns
362    ///
363    ///    0 = UNKNOWN      (limit reached or interrupted through 'terminate')
364    ///   10 = SATISFIABLE
365    ///   20 = UNSATISFIABLE
366    ///
367    ///   require (READY)
368    ///   ensure (INCONCLUSIVE  | SATISFIED | UNSATISFIED)
369    ///
370    /// Note, that while in this call the solver actually transitions to state
371    /// 'SOLVING', which however is only visible from a different context,
372    /// i.e., from a different thread or from a signal handler.  Only right
373    /// before returning from this call it goes into a 'READY' state.
374    ///
375    /// # Panics
376    ///
377    /// If the solver is in the middle of adding a clause or constraint (not READY). `CaDiCaL` would otherwise abort the process.
378    ///
379    #[inline]
380    #[track_caller]
381    pub fn solve(&mut self) -> Status {
382        self.require_ready("solve");
383        ffi::solve(&mut self.solver).into()
384    }
385
386    /// Get value (-lit=false, lit=true) of valid non-zero literal.
387    ///
388    ///   require (SATISFIED)
389    ///   ensure (SATISFIED)
390    ///
391    /// # Panics
392    ///
393    /// If the solver is not in the `SATISFIED` state or `lit` is not a valid
394    /// literal (zero or `i32::MIN`). `CaDiCaL` would otherwise abort the process.
395    ///
396    #[inline]
397    #[track_caller]
398    pub fn val(&mut self, lit: i32) -> i32 {
399        self.require("val", State::SATISFIED, lit);
400        ffi::val(&mut self.solver, lit)
401    }
402
403    /// Try to flip the value of the given literal without falsifying the
404    /// formula.  Returns 'true' if this was successful. Otherwise the model is
405    /// not changed and 'false' is returned.  If a literal was eliminated or
406    /// substituted flipping will fail on that literal and in particular the
407    /// solver will not taint it nor restore any clauses.
408    ///
409    /// The 'flip' function can only flip the value of a variables not acting
410    /// as witness on the reconstruction stack.
411    ///
412    /// As a side effect of calling this function first all assigned variables
413    /// are propagated again without using blocking literal.  Thus the first
414    /// call to this function after obtaining a model adds a substantial
415    /// overhead.  Subsequent calls will not need to properly propagate again.
416    ///
417    /// Furthermore if the reconstruction stack is non-empty and has been
418    /// traversed to reconstruct a full extended model for eliminated
419    /// variables (and to satisfy removed blocked clauses), the values of these
420    /// witness variables obtained via 'val' before become invalid. The user
421    /// thus will need to call 'val' again after calling 'flip' which will
422    /// trigger then a traversal of the reconstruction stack.
423    ///
424    /// So try to avoid mixing 'flip' and 'val' (for efficiency only).
425    /// Further, this functionality is currently not supported in the presence
426    /// of an external propagator.
427    ///
428    ///   require (SATISFIED)
429    ///   ensure (SATISFIED)
430    ///
431    /// # Panics
432    ///
433    /// If the solver is not in the `SATISFIED` state, `lit` is not a valid
434    /// literal, or an external propagator is connected. `CaDiCaL` would
435    /// otherwise abort the process.
436    ///
437    #[inline]
438    #[track_caller]
439    pub fn flip(&mut self, lit: i32) -> bool {
440        self.require("flip", State::SATISFIED, lit);
441        assert!(
442            self.last_external_propagator.is_none(),
443            "flip is not supported while an external propagator is connected"
444        );
445        ffi::flip(&mut self.solver, lit)
446    }
447
448    /// Same as 'flip' without actually flipping it. This functionality is
449    /// currently not supported in the presence of an external propagator.
450    ///
451    ///   require (SATISFIED)
452    ///   ensure (SATISFIED)
453    ///
454    /// # Panics
455    ///
456    /// If the solver is not in the `SATISFIED` state, `lit` is not a valid
457    /// literal, or an external propagator is connected. `CaDiCaL` would
458    /// otherwise abort the process.
459    ///
460    #[inline]
461    #[track_caller]
462    pub fn flippable(&mut self, lit: i32) -> bool {
463        self.require("flippable", State::SATISFIED, lit);
464        assert!(
465            self.last_external_propagator.is_none(),
466            "flippable is not supported while an external propagator is connected"
467        );
468        ffi::flippable(&mut self.solver, lit)
469    }
470
471    /// Determine whether the valid non-zero literal is in the core.
472    /// Returns 'true' if the literal is in the core and 'false' otherwise.
473    /// Note that the core does not have to be minimal.
474    ///
475    ///   require (UNSATISFIED)
476    ///   ensure (UNSATISFIED)
477    ///
478    /// # Panics
479    ///
480    /// If the solver is not in the `UNSATISFIED` state or `lit` is not a valid
481    /// literal (zero or `i32::MIN`). `CaDiCaL` would otherwise abort the process.
482    ///
483    #[inline]
484    #[track_caller]
485    pub fn failed(&mut self, lit: i32) -> bool {
486        self.require("failed", State::UNSATISFIED, lit);
487        ffi::failed(&mut self.solver, lit)
488    }
489
490    /// Add call-back which is checked regularly for termination.  There can
491    /// only be one terminator connected.  If a second (non-zero) one is added
492    /// the first one is implicitly disconnected.
493    ///
494    ///   require (VALID)
495    ///   ensure (VALID)
496    ///
497    /// The solver takes ownership of `terminator` and drops it when it is
498    /// disconnected, replaced, or the solver is dropped. To read its state
499    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
500    ///
501    /// The callback must be `'static`, so it cannot borrow from a value that
502    /// might be dropped while the solver still calls it:
503    ///
504    /// ```compile_fail,E0597
505    /// # use cadical_sys::{CaDiCal, Terminator};
506    /// # struct Cb<'a>(&'a mut u32);
507    /// # impl Terminator for Cb<'_> { fn terminated(&mut self) -> bool { false } }
508    /// let mut solver = CaDiCal::new();
509    /// let mut calls = 0;
510    /// solver.connect_terminator(Cb(&mut calls)); // error: `calls` does not live long enough
511    /// ```
512    ///
513    #[inline]
514    pub fn connect_terminator<T: Terminator + 'static>(&mut self, terminator: T) {
515        fn f<T: Terminator>(state: *mut u8) -> bool {
516            let ptr: *mut T = state.cast::<T>();
517            let i = unsafe { &mut *ptr };
518            i.terminated()
519        }
520        let mut terminator = Connected::new(terminator, |state| unsafe {
521            ffi::new_terminator(state, f::<T>)
522        });
523        ffi::connect_terminator(&mut self.solver, &mut terminator.wrapper);
524        // Only drop the previous terminator once the solver no longer points to it.
525        self.last_terminator = Some(terminator);
526    }
527
528    #[inline]
529    pub fn disconnect_terminator(&mut self) {
530        ffi::disconnect_terminator(&mut self.solver);
531        self.last_terminator = None;
532    }
533
534    /// Add call-back which allows to export learned clauses.
535    ///
536    ///   require (VALID)
537    ///   ensure (VALID)
538    ///
539    /// The solver takes ownership of `learner` and drops it when it is
540    /// disconnected, replaced, or the solver is dropped. To read its state
541    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
542    ///
543    /// The callback must be `'static`, so it cannot borrow from a value that
544    /// might be dropped while the solver still calls it:
545    ///
546    /// ```compile_fail,E0597
547    /// # use cadical_sys::{CaDiCal, Learner};
548    /// # struct Cb<'a>(&'a mut u32);
549    /// # impl Learner for Cb<'_> { fn learning(&mut self, _: i32) -> bool { false } fn learn(&mut self, _: i32) {} }
550    /// let mut solver = CaDiCal::new();
551    /// let mut calls = 0;
552    /// solver.connect_learner(Cb(&mut calls)); // error: `calls` does not live long enough
553    /// ```
554    ///
555    #[inline]
556    pub fn connect_learner<T: Learner + 'static>(&mut self, learner: T) {
557        fn learning<T: Learner>(state: *mut u8, size: i32) -> bool {
558            let ptr: *mut T = state.cast::<T>();
559            let i = unsafe { &mut *ptr };
560            i.learning(size)
561        }
562
563        fn learn<T: Learner>(state: *mut u8, lit: i32) {
564            let ptr: *mut T = state.cast::<T>();
565            let i = unsafe { &mut *ptr };
566            i.learn(lit);
567        }
568
569        let mut learner = Connected::new(learner, |state| unsafe {
570            ffi::new_learner(state, learning::<T>, learn::<T>)
571        });
572        ffi::connect_learner(&mut self.solver, &mut learner.wrapper);
573        self.last_learner = Some(learner);
574    }
575
576    #[inline]
577    pub fn disconnect_learner(&mut self) {
578        ffi::disconnect_learner(&mut self.solver);
579        self.last_learner = None;
580    }
581
582    /// Add call-back which allows to observe when a variable is fixed.
583    ///
584    ///   require (VALID)
585    ///   ensure (VALID)
586    ///
587    /// The solver takes ownership of `fixed_listener` and drops it when it is
588    /// disconnected, replaced, or the solver is dropped. To read its state
589    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
590    ///
591    /// The callback must be `'static`, so it cannot borrow from a value that
592    /// might be dropped while the solver still calls it:
593    ///
594    /// ```compile_fail,E0597
595    /// # use cadical_sys::{CaDiCal, FixedAssignmentListener};
596    /// # struct Cb<'a>(&'a mut u32);
597    /// # impl FixedAssignmentListener for Cb<'_> { fn notify_fixed_assignment(&mut self, _: i32) {} }
598    /// let mut solver = CaDiCal::new();
599    /// let mut calls = 0;
600    /// solver.connect_fixed_listener(Cb(&mut calls)); // error: `calls` does not live long enough
601    /// ```
602    ///
603    pub fn connect_fixed_listener<F: FixedAssignmentListener + 'static>(
604        &mut self,
605        fixed_listener: F,
606    ) {
607        fn notify_fixed_assignment<F: FixedAssignmentListener>(state: *mut u8, lit: i32) {
608            let ptr: *mut F = state.cast::<F>();
609            let i = unsafe { &mut *ptr };
610            i.notify_fixed_assignment(lit);
611        }
612
613        let mut listener = Connected::new(fixed_listener, |state| unsafe {
614            ffi::new_fixed_assignment_listener(state, notify_fixed_assignment::<F>)
615        });
616        ffi::connect_fixed_listener(&mut self.solver, &mut listener.wrapper);
617        self.last_fixed_listener = Some(listener);
618    }
619
620    #[inline]
621    pub fn disconnect_fixed_listener(&mut self) {
622        ffi::disconnect_fixed_listener(&mut self.solver);
623        self.last_fixed_listener = None;
624    }
625
626    /// Add call-back which allows to learn, propagate and backtrack based on
627    /// external constraints. Only one external propagator can be connected
628    /// and after connection every related variables must be 'observed' (use
629    /// '`add_observed_var`' function).
630    /// Disconnection of the external propagator resets all the observed
631    /// variables.
632    ///
633    ///   require (VALID)
634    ///   ensure (VALID)
635    ///
636    /// The solver takes ownership of `propagator` and drops it when it is
637    /// disconnected, replaced, or the solver is dropped. To read its state
638    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
639    /// Connecting a propagator disconnects any propagator connected earlier,
640    /// which also resets the observed variables.
641    ///
642    pub fn connect_external_propagator<T: ExternalPropagator + 'static>(
643        &mut self,
644        mut propagator: T,
645    ) {
646        fn notify_assignment<T: ExternalPropagator>(state: *mut u8, x: &[i32]) {
647            let ptr: *mut T = state.cast::<T>();
648            let i = unsafe { &mut *ptr };
649            i.notify_assignment(x);
650        }
651        fn notify_new_decision_level<T: ExternalPropagator>(state: *mut u8) {
652            let ptr: *mut T = state.cast::<T>();
653            let i = unsafe { &mut *ptr };
654            i.notify_new_decision_level();
655        }
656        fn notify_backtrack<T: ExternalPropagator>(state: *mut u8, x: usize) {
657            let ptr: *mut T = state.cast::<T>();
658            let i = unsafe { &mut *ptr };
659            i.notify_backtrack(x);
660        }
661        fn cb_check_found_model<T: ExternalPropagator>(state: *mut u8, x: &[i32]) -> bool {
662            let ptr: *mut T = state.cast::<T>();
663            let i = unsafe { &mut *ptr };
664            i.cb_check_found_model(x)
665        }
666        fn cb_decide<T: ExternalPropagator>(state: *mut u8) -> i32 {
667            let ptr: *mut T = state.cast::<T>();
668            let i = unsafe { &mut *ptr };
669            i.cb_decide()
670        }
671        fn cb_propagate<T: ExternalPropagator>(state: *mut u8) -> i32 {
672            let ptr: *mut T = state.cast::<T>();
673            let i = unsafe { &mut *ptr };
674            i.cb_propagate()
675        }
676        fn cb_add_reason_clause_lit<T: ExternalPropagator>(state: *mut u8, x: i32) -> i32 {
677            let ptr: *mut T = state.cast::<T>();
678            let i = unsafe { &mut *ptr };
679            i.cb_add_reason_clause_lit(x)
680        }
681        fn cb_has_external_clause<T: ExternalPropagator>(state: *mut u8, x: *mut bool) -> bool {
682            let ptr: *mut T = state.cast::<T>();
683            let i = unsafe { &mut *ptr };
684            i.cb_has_external_clause(unsafe { &mut *x })
685        }
686        fn cb_add_external_clause_lit<T: ExternalPropagator>(state: *mut u8) -> i32 {
687            let ptr: *mut T = state.cast::<T>();
688            let i = unsafe { &mut *ptr };
689            i.cb_add_external_clause_lit()
690        }
691        // CaDiCaL aborts when connecting a second propagator.
692        self.disconnect_external_propagator();
693
694        let is_lazy = propagator.is_lazy();
695        let are_reasons_forgettable = propagator.are_reasons_forgettable();
696
697        let mut external_propagator = Connected::new(propagator, |state| unsafe {
698            ffi::new_external_propagator(
699                state,
700                is_lazy,
701                are_reasons_forgettable,
702                notify_assignment::<T>,
703                notify_new_decision_level::<T>,
704                notify_backtrack::<T>,
705                cb_check_found_model::<T>,
706                cb_decide::<T>,
707                cb_propagate::<T>,
708                cb_add_reason_clause_lit::<T>,
709                cb_has_external_clause::<T>,
710                cb_add_external_clause_lit::<T>,
711            )
712        });
713        ffi::connect_external_propagator(&mut self.solver, &mut external_propagator.wrapper);
714        self.last_external_propagator = Some(external_propagator);
715    }
716    pub fn disconnect_external_propagator(&mut self) {
717        // CaDiCaL 3 aborts when disconnecting without a connected propagator.
718        // `_propagator` is only dropped after CaDiCaL has let go of it.
719        if let Some(_propagator) = self.last_external_propagator.take() {
720            ffi::disconnect_external_propagator(&mut self.solver);
721        }
722    }
723
724    /// Mark as 'observed' those variables that are relevant to the external
725    /// propagator. External propagation, clause addition during search and
726    /// notifications are all over these observed variabes.
727    /// A variable can not be observed witouth having an external propagator
728    /// connected. Observed variables are "frozen" internally, and so
729    /// inprocessing will not consider them as candidates for elimination.
730    /// An observed variable is allowed to be a fresh variable and it can be
731    /// added also during solving.
732    ///
733    ///   require (`VALID_OR_SOLVING`)
734    ///   ensure (`VALID_OR_SOLVING`)
735    ///
736    /// Observing a variable that preprocessing or inprocessing has already
737    /// eliminated is not checked and aborts the process. Observe variables
738    /// before solving, or [`CaDiCal::freeze`] them.
739    ///
740    /// # Panics
741    ///
742    /// If no external propagator is connected. `CaDiCaL` would otherwise
743    /// abort the process.
744    ///
745    #[inline]
746    #[track_caller]
747    pub fn add_observed_var(&mut self, var: i32) {
748        require_valid_lit("add_observed_var", var);
749        self.require_propagator("add_observed_var");
750        ffi::add_observed_var(&mut self.solver, var);
751    }
752
753    /// Removes the 'observed' flag from the given variable. A variable can be
754    /// set unobserved only between solve calls, not during it (to guarantee
755    /// that no yet unexplained external propagation involves it).
756    ///
757    ///   require (VALID)
758    ///   ensure (VALID)
759    ///
760    /// # Panics
761    ///
762    /// If no external propagator is connected. `CaDiCaL` would otherwise
763    /// abort the process.
764    ///
765    #[inline]
766    #[track_caller]
767    pub fn remove_observed_var(&mut self, var: i32) {
768        require_valid_lit("remove_observed_var", var);
769        self.require_propagator("remove_observed_var");
770        ffi::remove_observed_var(&mut self.solver, var);
771    }
772
773    /// Removes all the 'observed' flags from the variables. Disconnecting the
774    /// propagator invokes this step as well.
775    ///
776    ///   require (VALID)
777    ///   ensure (VALID)
778    ///
779    /// # Panics
780    ///
781    /// If no external propagator is connected. `CaDiCaL` would otherwise
782    /// abort the process.
783    ///
784    #[inline]
785    #[track_caller]
786    pub fn reset_observed_vars(&mut self) {
787        self.require_propagator("reset_observed_vars");
788        ffi::reset_observed_vars(&mut self.solver);
789    }
790
791    /// Get reason of valid observed literal (true = it is an observed variable
792    /// and it got assigned by a decision during the CDCL loop. Otherwise:
793    /// false.
794    ///
795    ///   require (`VALID_OR_SOLVING`)
796    ///   ensure (`VALID_OR_SOLVING`)
797    ///
798    #[inline]
799    #[track_caller]
800    pub fn is_decision(&mut self, lit: i32) -> bool {
801        require_valid_lit("is_decision", lit);
802        ffi::is_decision(&mut self.solver, lit)
803    }
804
805    //------------------------------------------------------------------------
806    /// Adds a literal to the constraint clause. Same functionality as 'add'
807    /// but the clause only exists for the next call to solve (same lifetime as
808    /// assumptions). Only one constraint may exists at a time. A new
809    /// constraint replaces the old. The main application of this functonality
810    /// is the model checking algorithm IC3. See our FMCAD'21 paper
811    /// [FroleyksBiere-FMCAD'19] for more details.
812    ///
813    /// Add valid literal to the constraint clause or zero to terminate it.
814    ///
815    ///   require (VALID)                     /// recall 'VALID = READY |
816    ///   ADDING' if (lit) ensure (ADDING)            /// and thus VALID but not
817    ///   READY if (!lit) && !`adding_clause` ensure (STEADY ) // and thus READY
818    ///
819    #[inline]
820    #[track_caller]
821    pub fn constrain(&mut self, lit: i32) {
822        require_valid_lit_or_zero("constrain", lit);
823        ffi::constrain(&mut self.solver, lit);
824    }
825
826    /// Determine whether the constraint was used to proof the
827    /// unsatisfiability. Note that the formula might still be unsatisfiable
828    /// without the constraint.
829    ///
830    ///   require (UNSATISFIED)
831    ///   ensure (UNSATISFIED)
832    ///
833    /// # Panics
834    ///
835    /// If the solver is not in the `UNSATISFIED` state. `CaDiCaL` would otherwise abort the process.
836    ///
837    #[inline]
838    #[track_caller]
839    pub fn constraint_failed(&mut self) -> bool {
840        self.require_state("constraint_failed", State::UNSATISFIED);
841        ffi::constraint_failed(&mut self.solver)
842    }
843
844    //------------------------------------------------------------------------
845    /// This function determines a good splitting literal.  The result can be
846    /// zero if the formula is proven to be satisfiable or unsatisfiable.  This
847    /// can then be checked by 'state ()'.  If the formula is empty and
848    /// the function is not able to determine satisfiability also zero is
849    /// returned but the state remains steady.
850    ///
851    ///   require (READY)
852    ///   ensure (STEADY |SATISFIED|UNSATISFIED)
853    ///
854    /// # Panics
855    ///
856    /// If the solver is in the middle of adding a clause or constraint (not
857    /// READY), which `CaDiCaL` would silently cut short.
858    ///
859    #[inline]
860    #[track_caller]
861    pub fn lookahead(&mut self) -> i32 {
862        self.require_ready("lookahead");
863        ffi::lookahead(&mut self.solver)
864    }
865
866    /// Generate cubes for cube-and-conquer, up to the given depth.
867    ///
868    /// Note: `CaDiCaL` 3.0.1 does not map the literals of the generated cubes
869    /// back to the user's variable numbering (`External::generate_cubes`
870    /// discards the mapped values), so after preprocessing has renumbered
871    /// variables the cubes may refer to internal variables.
872    ///
873    #[inline]
874    pub fn generate_cubes(&mut self, x: i32, min_depth: i32, result_cubes: &mut Vec<i32>) -> i32 {
875        ffi::generate_cubes(&mut self.solver, x, min_depth, result_cubes)
876    }
877
878    /// # Panics
879    ///
880    /// If the solver is in the middle of adding a clause or constraint (not
881    /// READY), which `CaDiCaL` would silently cut short.
882    ///
883    #[inline]
884    #[track_caller]
885    pub fn reset_assumptions(&mut self) {
886        self.require_ready("reset_assumptions");
887        ffi::reset_assumptions(&mut self.solver);
888    }
889
890    /// # Panics
891    ///
892    /// If the solver is in the middle of adding a clause or constraint (not
893    /// READY), which `CaDiCaL` would silently cut short.
894    ///
895    #[inline]
896    #[track_caller]
897    pub fn reset_constraint(&mut self) {
898        self.require_ready("reset_constraint");
899        ffi::reset_constraint(&mut self.solver);
900    }
901
902    /// Return the current state of the solver as defined above.
903    ///
904    #[must_use]
905    #[inline]
906    pub fn state(&self) -> State {
907        ffi::state(&self.solver).into()
908    }
909
910    /// Panics where `CaDiCaL` would abort the process on a contract violation,
911    /// so misuse of the safe API is reported as a catchable Rust panic.
912    #[track_caller]
913    fn require(&self, function: &str, expected: State, lit: i32) {
914        self.require_state(function, expected);
915        require_valid_lit(function, lit);
916    }
917
918    #[track_caller]
919    fn require_state(&self, function: &str, expected: State) {
920        let state = self.state();
921        assert!(
922            state == expected,
923            "{function} requires the solver to be in state {expected:?}, but it is in state {state:?}"
924        );
925    }
926
927    #[track_caller]
928    fn require_ready(&self, function: &str) {
929        let state = self.state();
930        assert!(
931            (state as i32) & (State::READY as i32) != 0,
932            "{function} requires the solver to be READY, but it is in state {state:?}"
933        );
934    }
935
936    #[track_caller]
937    fn require_one_of(&self, function: &str, expected: &[State]) {
938        let state = self.state();
939        assert!(
940            expected.contains(&state),
941            "{function} requires the solver to be in one of the states {expected:?}, but it is in state {state:?}"
942        );
943    }
944
945    #[track_caller]
946    fn require_proof_file(&self, function: &str) {
947        assert!(
948            self.proof_file_open,
949            "{function} requires an open proof file (see trace_proof1 and trace_proof2)"
950        );
951    }
952
953    fn update_declared_vars_only(&mut self) {
954        self.factor_option = self.get("factor");
955        self.factorcheck_option = self.get("factorcheck");
956    }
957
958    fn declared_vars_only(&self) -> bool {
959        requires_declared_vars(self.factor_option, self.factorcheck_option)
960    }
961
962    #[track_caller]
963    fn require_declared(&mut self, function: &str, lit: i32) {
964        if self.declared_vars_only() {
965            let vars = self.vars();
966            assert!(
967                lit.unsigned_abs() <= vars.unsigned_abs(),
968                "{function} called with literal {lit} of an undeclared variable (only {vars} are declared, see declare_more_variables), which the 'factor'/'factorcheck' options forbid"
969            );
970        }
971    }
972
973    #[track_caller]
974    fn require_no_closed_proof_file(&self, function: &str) {
975        assert!(
976            !self.proof_file_closed,
977            "{function} cannot open a proof file after a proof file was closed"
978        );
979    }
980
981    #[track_caller]
982    fn require_propagator(&self, function: &str) {
983        assert!(
984            self.last_external_propagator.is_some(),
985            "{function} requires a connected external propagator"
986        );
987    }
988
989    /// Similar to 'state ()' but using the staddard competition exit codes of
990    /// '10' for 'SATISFIABLE', '20' for 'UNSATISFIABLE' and '0' otherwise.
991    ///
992    #[must_use]
993    #[inline]
994    pub fn status(&self) -> Status {
995        ffi::status(&self.solver).into()
996    }
997
998    /// return version string
999    #[must_use]
1000    #[inline]
1001    pub fn version() -> String {
1002        ffi::version()
1003    }
1004
1005    /// return the name and version of the incremental SAT solving library
1006    #[must_use]
1007    #[inline]
1008    pub fn signature() -> String {
1009        ffi::signature()
1010    }
1011
1012    /*----------------------------------------------------------------------*/
1013    /// Copy 'this' into a fresh 'other'.  The copy procedure is not a deep
1014    /// clone, but only copies irredundant clauses and units.  It also makes
1015    /// sure that witness reconstruction works with the copy as with the
1016    /// original formula such that both solvers have the same models.
1017    /// Assumptions are not copied.  Options however are copied as well as
1018    /// flags which remember the current state of variables in preprocessing.
1019    ///
1020    ///   require (READY)          /// for 'this'
1021    ///   ensure (READY)           /// for 'this'
1022    ///
1023    ///   other.require (CONFIGURING)
1024    ///   other.ensure (CONFIGURING | STEADY )
1025    ///
1026    /// A pending constraint (see [`CaDiCal::constrain`]) is copied as an
1027    /// ordinary, permanent clause.
1028    ///
1029    /// # Panics
1030    ///
1031    /// If `source` is not READY (e.g. a clause was started with
1032    /// [`CaDiCal::add`] but not terminated), if `destination` is not in the
1033    /// `CONFIGURING` state, or if `source` has clauses (including frozen units)
1034    /// and the `factor` or `factorcheck` options of either solver require
1035    /// declared variables (the copy would add them before declaring any).
1036    /// `CaDiCaL` would otherwise abort the process.
1037    ///
1038    #[inline]
1039    #[track_caller]
1040    pub fn copy(source: &CaDiCal, destination: &mut CaDiCal) {
1041        source.require_ready("copy");
1042        destination.require_state("copy", State::CONFIGURING);
1043        // `Options::copy` only overwrites the destination's options where the
1044        // source's differ from the defaults (`factor` 0, `factorcheck` 1).
1045        let factor = if source.factor_option == 0 {
1046            destination.factor_option
1047        } else {
1048            source.factor_option
1049        };
1050        let factorcheck = if source.factorcheck_option == 1 {
1051            destination.factorcheck_option
1052        } else {
1053            source.factorcheck_option
1054        };
1055        if requires_declared_vars(factor, factorcheck) {
1056            // Traversal is aborted (returns false) at the first non-empty
1057            // clause, which would be added to the destination before it has
1058            // declared variables. (The empty clause of an inconsistent solver
1059            // has no literals, and units that are not frozen are copied as
1060            // witnesses instead.)
1061            struct StopAtFirstClause;
1062            impl ClauseIterator for StopAtFirstClause {
1063                fn clause(&mut self, clause: &[i32]) -> bool {
1064                    clause.is_empty()
1065                }
1066            }
1067            assert!(
1068                source.traverse_clauses(&mut StopAtFirstClause),
1069                "copy cannot copy clauses while the 'factor'/'factorcheck' options require declared variables"
1070            );
1071        }
1072        ffi::copy(&source.solver, &mut destination.solver);
1073        destination.update_declared_vars_only();
1074    }
1075
1076    /*----------------------------------------------------------------------*/
1077    /// Variables are usually added and initialized implicitly whenever a
1078    /// literal is used as an argument except for the functions 'val', 'fixed',
1079    /// 'failed' and 'frozen'.  However, the library internally keeps a maximum
1080    /// variable index, which can be queried.
1081    ///
1082    ///   require (VALID | SOLVING)
1083    ///   ensure (VALID | SOLVING)
1084    ///
1085    #[inline]
1086    pub fn vars(&mut self) -> i32 {
1087        ffi::vars(&mut self.solver)
1088    }
1089
1090    /// Increase the maximum variable index explicitly.  This function makes
1091    /// sure that at least '`min_max_var`' variables are initialized.  Since it
1092    /// might need to reallocate tables, it destroys a satisfying assignment
1093    /// and has the same state transition and conditions as 'assume' etc.
1094    ///
1095    ///   require (READY)
1096    ///   ensure (STEADY )
1097    ///
1098    /// # Panics
1099    ///
1100    /// If the solver is in the middle of adding a clause or constraint (not
1101    /// READY), which `CaDiCaL` would silently cut short.
1102    ///
1103    #[inline]
1104    #[track_caller]
1105    pub fn resize(&mut self, min_max_var: i32) {
1106        self.require_ready("resize");
1107        ffi::resize(&mut self.solver, min_max_var);
1108    }
1109
1110    /// Increase the maximum variable index by a number of new variables.
1111    /// initializes '`number_of_additional_new_vars`' new variables and protects
1112    /// them from being used by the solver as extension variables (BVA).
1113    ///
1114    /// It returns the new maximum variable index which is the highest
1115    /// variable name of the consecutive range of newly declared variables.
1116    /// It has the same state transition and conditions as 'resize' above.
1117    ///
1118    ///   require (READY)
1119    ///   ensure (STEADY)
1120    ///
1121    /// # Panics
1122    ///
1123    /// If the solver is in the middle of adding a clause or constraint (not
1124    /// READY), which `CaDiCaL` would silently cut short, or if
1125    /// `number_of_additional_new_vars` is negative or would overflow the
1126    /// variable index.
1127    ///
1128    #[inline]
1129    #[track_caller]
1130    pub fn declare_more_variables(&mut self, number_of_additional_new_vars: i32) -> i32 {
1131        self.require_ready("declare_more_variables");
1132        let vars = self.vars();
1133        assert!(
1134            number_of_additional_new_vars >= 0
1135                && vars.checked_add(number_of_additional_new_vars).is_some(),
1136            "declare_more_variables called with {number_of_additional_new_vars} variables, but {vars} already exist"
1137        );
1138        ffi::declare_more_variables(&mut self.solver, number_of_additional_new_vars)
1139    }
1140
1141    /// Returns the next fresh variable that was not used internally.
1142    ///
1143    /// # Panics
1144    ///
1145    /// If the solver is in the middle of adding a clause or constraint (not
1146    /// READY), which `CaDiCaL` would silently cut short.
1147    ///
1148    #[inline]
1149    #[track_caller]
1150    pub fn declare_one_more_variable(&mut self) -> i32 {
1151        self.require_ready("declare_one_more_variable");
1152        ffi::declare_one_more_variable(&mut self.solver)
1153    }
1154
1155    /// Get the value of some statistics or -1 if the statistics does not
1156    /// exist or is not supported. Only requires the state to be initialized.
1157    ///
1158    #[must_use]
1159    #[inline]
1160    pub fn get_statistic_value(&self, name: &str) -> i64 {
1161        ffi::get_statistic_value(&self.solver, name.to_owned())
1162    }
1163
1164    /// Renamed to [`CaDiCal::resize`] in `CaDiCaL` 3.
1165    #[deprecated(since = "0.8.0", note = "renamed to `resize` in CaDiCaL 3")]
1166    #[inline]
1167    pub fn reserve(&mut self, min_max_var: i32) {
1168        self.resize(min_max_var);
1169    }
1170
1171    // pub fn `trace_api_calls(&mut` self, file: String);
1172
1173    //------------------------------------------------------------------------
1174    /// Option handling.
1175    /// Determine whether 'name' is a valid option name.
1176    ///
1177    #[must_use]
1178    #[inline]
1179    pub fn is_valid_option(name: &str) -> bool {
1180        ffi::is_valid_option(name.to_owned())
1181    }
1182
1183    /// Determine whether 'name' enables a specific preprocessing technique.
1184    ///
1185    #[must_use]
1186    #[inline]
1187    pub fn is_preprocessing_option(name: &str) -> bool {
1188        ffi::is_preprocessing_option(name.to_owned())
1189    }
1190
1191    /// Determine whether 'arg' is a valid long option of the form `--<name>`,
1192    /// `--<name>=<val>` or `--no-<name>` similar to '`set_long_option`' below.
1193    /// Legal values are 'true', 'false', or `[-]<mantissa>[e<exponent>]`.
1194    #[must_use]
1195    #[inline]
1196    pub fn is_valid_long_option(arg: &str) -> bool {
1197        ffi::is_valid_long_option(arg.to_owned())
1198    }
1199
1200    /// Get the current value of the option 'name'.  If 'name' is invalid then
1201    /// zero is returned.  Here '--...' arguments as invalid options.
1202    ///
1203    #[inline]
1204    pub fn get(&mut self, name: &str) -> i32 {
1205        ffi::get(&mut self.solver, name.to_owned())
1206    }
1207
1208    /// Set the default verbose message prefix (default "c ").
1209    ///
1210    #[inline]
1211    pub fn prefix(&mut self, verbose_message_prefix: &str) {
1212        ffi::prefix(&mut self.solver, verbose_message_prefix.to_owned());
1213    }
1214
1215    /// This crate builds `CaDiCaL` with `QUIET`, which removes the options
1216    /// `quiet`, `verbose`, `report` and `log`; setting them returns false.
1217    ///
1218    /// Explicit version of setting an option.  If the option `<name>` exists
1219    /// and `<val>` can be parsed then 'true' is returned.  If the option value
1220    /// is out of range the actual value is computed as the closest (minimum or
1221    /// maximum) value possible, but still 'true' is returned.
1222    ///
1223    ///   require (CONFIGURING)
1224    ///   ensure (CONFIGURING)
1225    ///
1226    /// Thus options can only bet set right after initialization.
1227    ///
1228    /// # Panics
1229    ///
1230    /// If the solver is not in the `CONFIGURING` state, unless `name` is one of
1231    /// `log`, `quiet`, `report` and `verbose`. `CaDiCaL` would otherwise abort the process.
1232    ///
1233    #[inline]
1234    #[track_caller]
1235    pub fn set(&mut self, name: &str, val: i32) -> bool {
1236        if !matches!(name, "log" | "quiet" | "report" | "verbose") {
1237            self.require_state("set", State::CONFIGURING);
1238        }
1239        let res = ffi::set(&mut self.solver, name.to_owned(), val);
1240        self.update_declared_vars_only();
1241        res
1242    }
1243
1244    /// This function accepts options in command line syntax:
1245    ///
1246    ///   `--<name>=<val>`, `--<name>`, or `--no-<name>`
1247    ///
1248    /// It actually calls the previous 'set' function after parsing 'arg'.  The
1249    /// same values are expected as for '`is_valid_long_option`' above and as
1250    /// with 'set' any value outside of the range of legal values for a
1251    /// particular option are set to either the minimum or maximum depending on
1252    /// which side of the valid interval they lie.
1253    ///
1254    ///   require (CONFIGURING)
1255    ///   ensure (CONFIGURING)
1256    ///
1257    /// # Panics
1258    ///
1259    /// If the solver is not in the `CONFIGURING` state. `CaDiCaL` would otherwise abort the process.
1260    ///
1261    #[inline]
1262    #[track_caller]
1263    pub fn set_long_option(&mut self, arg: &str) -> bool {
1264        self.require_state("set_long_option", State::CONFIGURING);
1265        let res = ffi::set_long_option(&mut self.solver, arg.to_owned());
1266        self.update_declared_vars_only();
1267        res
1268    }
1269
1270    /// Determine whether 'name' is a valid configuration.
1271    ///
1272    #[must_use]
1273    #[inline]
1274    pub fn is_valid_configuration(name: &str) -> bool {
1275        ffi::is_valid_configuration(name.to_owned())
1276    }
1277
1278    /// Overwrite (some) options with the forced values of the configuration.
1279    /// The result is 'true' iff the 'name' is a valid configuration.
1280    ///
1281    ///   require (CONFIGURING)
1282    ///   ensure (CONFIGURING)
1283    ///
1284    /// # Panics
1285    ///
1286    /// If the solver is not in the `CONFIGURING` state. `CaDiCaL` would otherwise abort the process.
1287    ///
1288    #[inline]
1289    #[track_caller]
1290    pub fn configure(&mut self, name: &str) -> bool {
1291        self.require_state("configure", State::CONFIGURING);
1292        let res = ffi::configure(&mut self.solver, name.to_owned());
1293        self.update_declared_vars_only();
1294        res
1295    }
1296
1297    /// Increase preprocessing and inprocessing limits: each limit marked as
1298    /// optimizable is multiplied by `2^<val>` or `10^<val>` (depending on the
1299    /// option) and capped at its maximum. Values below '0' are ignored and
1300    /// values above '31' are reduced to '31'.
1301    ///
1302    ///   require (READY)
1303    ///   ensure (READY)
1304    ///
1305    #[inline]
1306    pub fn optimize(&mut self, val: i32) {
1307        ffi::optimize(&mut self.solver, val);
1308    }
1309
1310    /// Specify search limits, where currently 'name' can be "conflicts",
1311    /// "decisions", "preprocessing", or "localsearch".  The first two limits
1312    /// are unbounded by default.  Thus using a negative limit for conflicts or
1313    /// decisions switches back to the default of unlimited search (for that
1314    /// particular limit).  The preprocessing limit determines the number of
1315    /// preprocessing rounds, which is zero by default.  Similarly, the local
1316    /// search limit determines the number of local search rounds (also zero by
1317    /// default).  As with 'set', the return value denotes whether the limit
1318    /// 'name' is valid.  These limits are only valid for the next 'solve' or
1319    /// 'simplify' call and reset to their default after 'solve' returns (as
1320    /// well as overwritten and reset during calls to 'simplify' and
1321    /// 'lookahead').  We actually also have an internal "terminate" limit
1322    /// which however should only be used for testing and debugging.
1323    ///
1324    ///   require (READY)
1325    ///   ensure (READY)
1326    ///
1327    #[inline]
1328    pub fn limit(&mut self, arg: &str, val: i32) -> bool {
1329        ffi::limit(&mut self.solver, arg.to_owned(), val)
1330    }
1331    #[inline]
1332    pub fn is_valid_limit(&mut self, arg: &str) -> bool {
1333        ffi::is_valid_limit(&mut self.solver, arg.to_owned())
1334    }
1335
1336    /// The number of currently active variables and clauses can be queried by
1337    /// these functions.  Variables become active if a clause is added with it.
1338    /// They become inactive if they are eliminated or fixed at the root level
1339    /// Clauses become inactive if they are satisfied, subsumed, eliminated.
1340    /// Redundant clauses are reduced regularly and thus the 'redundant'
1341    /// function is less useful.
1342    ///
1343    ///   require (VALID)
1344    ///   ensure (VALID)
1345    ///
1346    /// Number of active variables.
1347    #[must_use]
1348    #[inline]
1349    pub fn active(&self) -> i32 {
1350        ffi::active(&self.solver)
1351    }
1352
1353    /// Number of active redundant clauses.
1354    #[must_use]
1355    #[inline]
1356    pub fn redundant(&self) -> i64 {
1357        ffi::redundant(&self.solver)
1358    }
1359
1360    /// Number of active irredundant clauses.
1361    #[must_use]
1362    #[inline]
1363    pub fn irredundant(&self) -> i64 {
1364        ffi::irredundant(&self.solver)
1365    }
1366
1367    //------------------------------------------------------------------------
1368    /// This function executes the given number of preprocessing rounds. It is
1369    /// similar to 'solve' with 'limits ("preprocessing", rounds)' except that
1370    /// no CDCL nor local search, nor lucky phases are executed.  The result
1371    /// values are also the same: 0=UNKNOWN, 10=SATISFIABLE, 20=UNSATISFIABLE.
1372    /// As 'solve' it resets current assumptions and limits before returning.
1373    /// The numbers of rounds should not be negative.  If the number of rounds
1374    /// is zero only clauses are restored (if necessary) and top level unit
1375    /// propagation is performed, which both take some time.
1376    ///
1377    ///   require (READY)
1378    ///   ensure (INCONCLUSIVE | SATISFIED | UNSATISFIED)
1379    ///
1380    /// # Panics
1381    ///
1382    /// If the solver is in the middle of adding a clause or constraint (not READY),
1383    /// or if `rounds` is negative. `CaDiCaL` would otherwise abort the process.
1384    ///
1385    #[inline]
1386    #[track_caller]
1387    pub fn simplify(&mut self, rounds: i32) -> Status {
1388        self.require_ready("simplify");
1389        assert!(rounds >= 0, "simplify called with negative rounds {rounds}");
1390        ffi::simplify(&mut self.solver, rounds).into()
1391    }
1392
1393    /// This function executes the given number of preprocessing rounds
1394    /// without search: it only performs unit propagation by assuming the
1395    /// currently defined (potentially empty) set of assumptions. In case unit
1396    /// propagation leads to a conflict it returns `UNSATISFIABLE`. Otherwise
1397    /// it usually returns `UNKNOWN`, and the implied literals can be queried
1398    /// with [`CaDiCal::implied`]. In rare cases (no decision needed) it
1399    /// returns `SATISFIABLE`.
1400    ///
1401    ///   require (READY)
1402    ///   ensure (INCONCLUSIVE | SATISFIED | UNSATISFIED)
1403    ///
1404    /// # Panics
1405    ///
1406    /// If the solver is in the middle of adding a clause or constraint (not
1407    /// READY), which `CaDiCaL` would silently cut short.
1408    ///
1409    #[inline]
1410    #[track_caller]
1411    pub fn propagate(&mut self) -> Status {
1412        self.require_ready("propagate");
1413        ffi::propagate(&mut self.solver).into()
1414    }
1415
1416    /// The literals implied by the last call to [`CaDiCal::propagate`].
1417    ///
1418    ///   require (INCONCLUSIVE | SATISFIED)
1419    ///   ensure (INCONCLUSIVE | SATISFIED)
1420    ///
1421    /// # Panics
1422    ///
1423    /// If the solver is not in the `INCONCLUSIVE` or `SATISFIED` state.
1424    /// `CaDiCaL` would otherwise abort the process.
1425    ///
1426    #[must_use]
1427    #[track_caller]
1428    pub fn implied(&mut self) -> Vec<i32> {
1429        self.require_one_of("implied", &[State::INCONCLUSIVE, State::SATISFIED]);
1430        let mut implicants = Vec::new();
1431        ffi::implied(&mut self.solver, &mut implicants);
1432        implicants
1433    }
1434
1435    //------------------------------------------------------------------------
1436    /// Force termination of 'solve' asynchronously.
1437    ///
1438    /// Since `solve` borrows the solver mutably, this can only be called
1439    /// between `solve` calls, where it makes the next `solve` return
1440    /// [`Status::UNKNOWN`] (unless the formula is trivially decided, e.g.
1441    /// already inconsistent). To stop a running `solve` from another thread,
1442    /// connect a [`TerminateFlag`] instead.
1443    ///
1444    ///  require (SOLVING | READY)
1445    ///  ensure (STEADY )           /// actually not immediately (synchronously)
1446    ///
1447    #[inline]
1448    pub fn terminate(&mut self) {
1449        ffi::terminate(&mut self.solver);
1450    }
1451
1452    //------------------------------------------------------------------------
1453
1454    /// We have the following common reference counting functions, which avoid
1455    /// to restore clauses but require substantial user guidance.  This was the
1456    /// only way to use inprocessing in incremental SAT solving in Lingeling
1457    /// (and before in `MiniSAT`'s 'freeze' / 'thaw') and which did not use
1458    /// automatic clause restoring.  In general this is slower than
1459    /// restoring clauses and should not be used.
1460    ///
1461    /// In essence the user freezes variables which potentially are still
1462    /// needed in clauses added or assumptions used after the next 'solve'
1463    /// call.  As in Lingeling you can freeze a variable multiple times, but
1464    /// then have to melt it the same number of times again in order to enable
1465    /// variable eliminating on it etc.  The arguments can be literals
1466    /// (negative indices) but conceptually variables are frozen.
1467    ///
1468    /// In the old way of doing things without restore you should not use a
1469    /// variable incrementally (in 'add' or 'assume'), which was used before
1470    /// and potentially could have been eliminated in a previous 'solve' call.
1471    /// This can lead to spurious satisfying assignment.  In order to check
1472    /// this API contract one can use the 'checkfrozen' option.  This has the
1473    /// drawback that restoring clauses implicitly would fail with a fatal
1474    /// error message even if in principle the solver could just restore
1475    /// clauses. Thus this option is disabled by default.
1476    ///
1477    /// See our SAT'19 paper [FazekasBiereScholl-SAT'19] for more details.
1478    ///
1479    ///   require (VALID)
1480    ///   ensure (VALID)
1481    ///
1482    #[must_use]
1483    #[inline]
1484    #[track_caller]
1485    pub fn frozen(&self, lit: i32) -> bool {
1486        require_valid_lit("frozen", lit);
1487        ffi::frozen(&self.solver, lit)
1488    }
1489
1490    #[inline]
1491    #[track_caller]
1492    pub fn freeze(&mut self, lit: i32) {
1493        require_valid_lit("freeze", lit);
1494        ffi::freeze(&mut self.solver, lit);
1495    }
1496
1497    /// Undo one [`CaDiCal::freeze`] of `lit`.
1498    ///
1499    /// # Panics
1500    ///
1501    /// If `lit` is not frozen. `CaDiCaL` would otherwise abort the process.
1502    ///
1503    #[inline]
1504    #[track_caller]
1505    pub fn melt(&mut self, lit: i32) {
1506        require_valid_lit("melt", lit);
1507        assert!(
1508            self.frozen(lit),
1509            "melt called on literal {lit}, which is not frozen"
1510        );
1511        ffi::melt(&mut self.solver, lit);
1512    }
1513
1514    //------------------------------------------------------------------------
1515    /// Root level assigned variables can be queried with this function.
1516    /// It returns '1' if the literal is implied by the formula, '-1' if its
1517    /// negation is implied, or '0' if this is unclear at this point.
1518    ///
1519    ///   require (VALID)
1520    ///   ensure (VALID)
1521    ///
1522    #[must_use]
1523    #[inline]
1524    #[track_caller]
1525    pub fn fixed(&self, lit: i32) -> i32 {
1526        require_valid_lit("fixed", lit);
1527        ffi::fixed(&self.solver, lit)
1528    }
1529
1530    //------------------------------------------------------------------------
1531    /// Force the default decision phase of a variable to a certain value.
1532    ///
1533    #[inline]
1534    #[track_caller]
1535    pub fn phase(&mut self, lit: i32) {
1536        require_valid_lit("phase", lit);
1537        ffi::phase(&mut self.solver, lit);
1538    }
1539
1540    #[inline]
1541    #[track_caller]
1542    pub fn unphase(&mut self, lit: i32) {
1543        require_valid_lit("unphase", lit);
1544        ffi::unphase(&mut self.solver, lit);
1545    }
1546
1547    //------------------------------------------------------------------------
1548    /// Enables clausal proof tracing in DRAT format and returns 'true' if
1549    /// successfully opened for writing.  Writing proofs has to be enabled
1550    /// before calling 'solve', 'add' and 'dimacs', that is in state
1551    /// 'CONFIGURING'.  Otherwise only partial proofs would be written.
1552    ///
1553    ///   require (CONFIGURING)
1554    ///   ensure (CONFIGURING)
1555    ///
1556    /// Write DRAT proof. `name` is ignored. As with [`CaDiCal::trace_proof2`],
1557    /// a `.gz`, `.bz2`, `.xz` or `.7z` suffix compresses the proof through
1558    /// the external program of that name, and `false` is returned if it is
1559    /// not in `PATH`.
1560    ///
1561    /// # Panics
1562    ///
1563    /// If the solver is not in the `CONFIGURING` state, or a proof file was
1564    /// already closed with [`CaDiCal::close_proof_trace`]. `CaDiCaL` would
1565    /// otherwise abort or crash.
1566    ///
1567    #[inline]
1568    #[track_caller]
1569    pub fn trace_proof1(&mut self, file: &str, name: &str) -> bool {
1570        self.require_state("trace_proof1", State::CONFIGURING);
1571        self.require_no_closed_proof_file("trace_proof1");
1572        let opened = ffi::trace_proof1(&mut self.solver, file.to_owned(), name.to_owned());
1573        self.proof_file_open |= opened;
1574        opened
1575    }
1576
1577    /// Open & write proof. A `.gz`, `.bz2`, `.xz` or `.7z` suffix compresses
1578    /// the proof through the external program of that name; `false` is
1579    /// returned if it is not in `PATH` or the file cannot be written.
1580    ///
1581    /// # Panics
1582    ///
1583    /// If the solver is not in the `CONFIGURING` state, or a proof file was
1584    /// already closed with [`CaDiCal::close_proof_trace`]. `CaDiCaL` would
1585    /// otherwise abort or crash.
1586    ///
1587    #[inline]
1588    #[track_caller]
1589    pub fn trace_proof2(&mut self, path: &str) -> bool {
1590        self.require_state("trace_proof2", State::CONFIGURING);
1591        self.require_no_closed_proof_file("trace_proof2");
1592        let opened = ffi::trace_proof2(&mut self.solver, path.to_owned());
1593        self.proof_file_open |= opened;
1594        opened
1595    }
1596
1597    /// Flushing the proof trace file eventually calls 'fflush' on the actual
1598    /// file or pipe and thus if this function returns all the proof steps
1599    /// should have been written (with the same guarantees as 'fflush').
1600    ///
1601    /// The additional optional argument forces to print the number of addition
1602    /// and deletion steps in the proof even if the verbosity level is zero but
1603    /// not if quiet is set as well.  The default for the stand-alone solver is
1604    /// to print this information (in the 'closing proof' section) but for API
1605    /// usage of the library we want to stay silent unless explicitly requested
1606    /// or verbosity is non-zero (and as explained quiet is not set).
1607    ///
1608    /// This function can be called multiple times.
1609    ///
1610    ///   require (VALID)
1611    ///   ensure (VALID)
1612    ///
1613    /// # Panics
1614    ///
1615    /// If no proof file is open (see [`CaDiCal::trace_proof2`]). `CaDiCaL`
1616    /// would otherwise abort the process.
1617    ///
1618    #[inline]
1619    #[track_caller]
1620    pub fn flush_proof_trace(&mut self, print: bool) {
1621        self.require_proof_file("flush_proof_trace");
1622        ffi::flush_proof_trace(&mut self.solver, print);
1623    }
1624
1625    /// Close proof trace early.  Similar to 'flush' we allow the user to
1626    /// control with 'print' in a more fine-grained way whether statistics
1627    /// about the size of the written proof file and if compressed on-the-fly
1628    /// the number of actual bytes written (including deflation percentage) are
1629    /// printed.  Before actually closing (or detaching in case of writing to
1630    /// `<stdout>`) we check whether '`flush_proof_trace`' was called since the
1631    /// last time a proof step (addition or deletion) was traced.  If this is
1632    /// not the case we would call '`flush_proof_trace`' with the same 'print'
1633    /// argument.
1634    ///
1635    ///   require (VALID)
1636    ///   ensure (VALID)
1637    ///
1638    /// # Panics
1639    ///
1640    /// If no proof file is open, including when it was already closed.
1641    /// `CaDiCaL` would otherwise abort the process.
1642    ///
1643    #[inline]
1644    #[track_caller]
1645    pub fn close_proof_trace(&mut self, print: bool) {
1646        self.require_proof_file("close_proof_trace");
1647        self.proof_file_open = false;
1648        self.proof_file_closed = true;
1649        ffi::close_proof_trace(&mut self.solver, print);
1650    }
1651
1652    /// Enables clausal proof tracing with or without antecedents using
1653    /// the Tracer interface defined in 'tracer.hpp'.
1654    ///
1655    /// `CaDiCaL`'s built-in `FileTracer` and `StatTracer` are not exposed
1656    /// directly; use [`CaDiCal::trace_proof1`] or [`CaDiCal::trace_proof2`]
1657    /// to write a proof file.
1658    ///
1659    ///   require (CONFIGURING)
1660    ///   ensure (CONFIGURING)
1661    ///
1662    /// The solver takes ownership of `tracer` and drops it when it is
1663    /// disconnected, replaced, or the solver is dropped. To read its state
1664    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
1665    /// Connecting a tracer disconnects any tracer connected earlier.
1666    ///
1667    /// [`ProofTracer::finalize_clause`] is only called when `finalize_clauses`
1668    /// is true.
1669    ///
1670    /// # Panics
1671    ///
1672    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
1673    /// already been added. `CaDiCaL` would otherwise abort the process.
1674    ///
1675    #[allow(clippy::too_many_lines)]
1676    #[track_caller]
1677    pub fn connect_proof_tracer1<T: ProofTracer + 'static>(
1678        &mut self,
1679        tracer: T,
1680        antecedents: bool,
1681        finalize_clauses: bool,
1682    ) {
1683        fn add_original_clause<T: ProofTracer>(
1684            state: *mut u8,
1685            id: i64,
1686            redundant: bool,
1687            clause: &[i32],
1688            restored: bool,
1689        ) {
1690            let ptr: *mut T = state.cast::<T>();
1691            let t = unsafe { &mut *ptr };
1692            t.add_original_clause(id, redundant, clause, restored);
1693        }
1694
1695        fn add_derived_clause<T: ProofTracer>(
1696            state: *mut u8,
1697            id: i64,
1698            redundant: bool,
1699            witness: i32,
1700            clause: &[i32],
1701            antecedents: &[i64],
1702        ) {
1703            let ptr: *mut T = state.cast::<T>();
1704            let t = unsafe { &mut *ptr };
1705            t.add_derived_clause(id, redundant, witness, clause, antecedents);
1706        }
1707
1708        fn delete_clause<T: ProofTracer>(state: *mut u8, id: i64, redundant: bool, clause: &[i32]) {
1709            let ptr: *mut T = state.cast::<T>();
1710            let t = unsafe { &mut *ptr };
1711            t.delete_clause(id, redundant, clause);
1712        }
1713
1714        fn weaken_minus<T: ProofTracer>(state: *mut u8, id: i64, clause: &[i32]) {
1715            let ptr: *mut T = state.cast::<T>();
1716            let t = unsafe { &mut *ptr };
1717            t.weaken_minus(id, clause);
1718        }
1719
1720        fn strengthen<T: ProofTracer>(state: *mut u8, id: i64) {
1721            let ptr: *mut T = state.cast::<T>();
1722            let t = unsafe { &mut *ptr };
1723            t.strengthen(id);
1724        }
1725
1726        fn finalize_clause<T: ProofTracer>(state: *mut u8, id: i64, clause: &[i32]) {
1727            let ptr: *mut T = state.cast::<T>();
1728            let t = unsafe { &mut *ptr };
1729            t.finalize_clause(id, clause);
1730        }
1731
1732        fn add_assumption<T: ProofTracer>(state: *mut u8, lit: i32) {
1733            let ptr: *mut T = state.cast::<T>();
1734            let t = unsafe { &mut *ptr };
1735            t.add_assumption(lit);
1736        }
1737
1738        fn add_constraint<T: ProofTracer>(state: *mut u8, clause: &[i32]) {
1739            let ptr: *mut T = state.cast::<T>();
1740            let t = unsafe { &mut *ptr };
1741            t.add_constraint(clause);
1742        }
1743
1744        fn reset_assumptions<T: ProofTracer>(state: *mut u8) {
1745            let ptr: *mut T = state.cast::<T>();
1746            let t = unsafe { &mut *ptr };
1747            t.reset_assumptions();
1748        }
1749
1750        fn add_assumption_clause<T: ProofTracer>(
1751            state: *mut u8,
1752            id: i64,
1753            clause: &[i32],
1754            antecedents: &[i64],
1755        ) {
1756            let ptr: *mut T = state.cast::<T>();
1757            let t = unsafe { &mut *ptr };
1758            t.add_assumption_clause(id, clause, antecedents);
1759        }
1760
1761        fn conclude_sat<T: ProofTracer>(state: *mut u8, conclusion_type: i32, model: &[i32]) {
1762            let ptr: *mut T = state.cast::<T>();
1763            let t = unsafe { &mut *ptr };
1764            t.conclude_sat(conclusion_type, model);
1765        }
1766
1767        fn conclude_unsat<T: ProofTracer>(
1768            state: *mut u8,
1769            conclusion_type: i32,
1770            clause_ids: &[i64],
1771        ) {
1772            let ptr: *mut T = state.cast::<T>();
1773            let t = unsafe { &mut *ptr };
1774            t.conclude_unsat(conclusion_type, clause_ids);
1775        }
1776
1777        fn conclude_unknown<T: ProofTracer>(state: *mut u8, trail: &[i32]) {
1778            let ptr: *mut T = state.cast::<T>();
1779            let t = unsafe { &mut *ptr };
1780            t.conclude_unknown(trail);
1781        }
1782
1783        fn demote_clause<T: ProofTracer>(state: *mut u8, id: i64, clause: &[i32]) {
1784            let ptr: *mut T = state.cast::<T>();
1785            let t = unsafe { &mut *ptr };
1786            t.demote_clause(id, clause);
1787        }
1788
1789        fn report_status<T: ProofTracer>(state: *mut u8, status: i32, id: i64) {
1790            let ptr: *mut T = state.cast::<T>();
1791            let t = unsafe { &mut *ptr };
1792            t.report_status(status, id);
1793        }
1794
1795        fn begin_proof<T: ProofTracer>(state: *mut u8, first_derived_id: i64) {
1796            let ptr: *mut T = state.cast::<T>();
1797            let t = unsafe { &mut *ptr };
1798            t.begin_proof(first_derived_id);
1799        }
1800
1801        fn solve_query<T: ProofTracer>(state: *mut u8) {
1802            let ptr: *mut T = state.cast::<T>();
1803            let t = unsafe { &mut *ptr };
1804            t.solve_query();
1805        }
1806
1807        fn notify_equivalence<T: ProofTracer>(state: *mut u8, lit: i32, other: i32) {
1808            let ptr: *mut T = state.cast::<T>();
1809            let t = unsafe { &mut *ptr };
1810            t.notify_equivalence(lit, other);
1811        }
1812
1813        let solver_state = self.state();
1814        assert!(
1815            solver_state == State::CONFIGURING,
1816            "connect_proof_tracer1 requires the solver to be in state CONFIGURING, but it is in state {solver_state:?}"
1817        );
1818        // Unlike the other callbacks, CaDiCaL keeps every connected tracer, so
1819        // the previous one must be disconnected before it is dropped.
1820        self.disconnect_proof_tracer1();
1821
1822        let mut tracer = Connected::new(tracer, |state| unsafe {
1823            ffi::new_tracer(
1824                state,
1825                add_original_clause::<T>,
1826                add_derived_clause::<T>,
1827                delete_clause::<T>,
1828                weaken_minus::<T>,
1829                strengthen::<T>,
1830                finalize_clause::<T>,
1831                add_assumption::<T>,
1832                add_constraint::<T>,
1833                reset_assumptions::<T>,
1834                add_assumption_clause::<T>,
1835                conclude_sat::<T>,
1836                conclude_unsat::<T>,
1837                conclude_unknown::<T>,
1838                demote_clause::<T>,
1839                report_status::<T>,
1840                begin_proof::<T>,
1841                solve_query::<T>,
1842                notify_equivalence::<T>,
1843            )
1844        });
1845        ffi::connect_proof_tracer1(
1846            &mut self.solver,
1847            &mut tracer.wrapper,
1848            antecedents,
1849            finalize_clauses,
1850        );
1851        self.last_tracer = Some(tracer);
1852    }
1853
1854    /// Triggers the conclusion of incremental proofs.
1855    /// if the solver is SATISFIED it will trigger extend ()
1856    /// and give the model to the proof tracer through `conclude_sat` ()
1857    /// if the solver is UNSATISFIED it will trigger failing ()
1858    /// which will learn new clauses as explained below:
1859    /// In case of failed assumptions will provide a core negated
1860    /// as a clause through the proof tracer interface.
1861    /// With a failing contraint these can be multiple clauses.
1862    /// Then it will trigger a `conclude_unsat` event with the id(s)
1863    /// of the newly learnt clauses or the id of the global conflict.
1864    ///
1865    ///   require (SATISFIED || UNSATISFIED)
1866    ///   ensure (SATISFIED || UNSATISFIED)
1867    ///
1868    /// # Panics
1869    ///
1870    /// If the solver has not finished a `solve` (it is not `SATISFIED`,
1871    /// `UNSATISFIED` or `INCONCLUSIVE`). `CaDiCaL` would otherwise abort the process.
1872    ///
1873    #[inline]
1874    #[track_caller]
1875    pub fn conclude(&mut self) {
1876        self.require_one_of(
1877            "conclude",
1878            &[State::SATISFIED, State::UNSATISFIED, State::INCONCLUSIVE],
1879        );
1880        ffi::conclude(&mut self.solver);
1881    }
1882
1883    /// Disconnect the proof tracer connected with
1884    /// [`CaDiCal::connect_proof_tracer1`] and drop it. Does nothing if no
1885    /// tracer is connected.
1886    ///
1887    ///   require (VALID)
1888    ///   ensure (VALID)
1889    ///
1890    pub fn disconnect_proof_tracer1(&mut self) {
1891        if let Some(mut tracer) = self.last_tracer.take() {
1892            ffi::disconnect_proof_tracer1(&mut self.solver, &mut tracer.wrapper);
1893        }
1894    }
1895
1896    /// print usage information for long options
1897    #[inline]
1898    pub fn usage() {
1899        ffi::usage();
1900    }
1901
1902    /// print configuration usage options
1903    #[inline]
1904    pub fn configurations() {
1905        ffi::configurations();
1906    }
1907
1908    ///   require (!DELETING)
1909    ///   ensure (!DELETING)
1910    ///
1911    /// print statistics
1912    ///
1913    /// This crate builds `CaDiCaL` with `QUIET`, so this prints nothing.
1914    #[inline]
1915    pub fn statistics(&mut self) {
1916        ffi::statistics(&mut self.solver);
1917    }
1918
1919    /// print resource usage (time and memory)
1920    ///
1921    /// This crate builds `CaDiCaL` with `QUIET`, so this prints nothing.
1922    #[inline]
1923    pub fn resources(&mut self) {
1924        ffi::resources(&mut self.solver);
1925    }
1926
1927    ///   require (VALID)
1928    ///   ensure (VALID)
1929    ///
1930    /// print current option and value list
1931    ///
1932    /// This crate builds `CaDiCaL` with `QUIET`, so this prints nothing.
1933    #[inline]
1934    pub fn options(&mut self) {
1935        ffi::options(&mut self.solver);
1936    }
1937
1938    //------------------------------------------------------------------------
1939    /// Traverse irredundant clauses or the extension stack in reverse order.
1940    ///
1941    /// The return value is false if traversal is aborted early due to one of
1942    /// the visitor functions returning false.  See description of the
1943    /// iterators below for more details on how to use these functions.
1944    ///
1945    ///   require (VALID)
1946    ///   ensure (VALID)
1947    ///
1948    #[inline]
1949    pub fn traverse_clauses<I: ClauseIterator>(&self, i: &mut I) -> bool {
1950        fn f<I: ClauseIterator>(state: *mut u8, clause: &[i32]) -> bool {
1951            let ptr: *mut I = state.cast::<I>();
1952            let i = unsafe { &mut *ptr };
1953            i.clause(clause)
1954        }
1955        let mut iter =
1956            unsafe { ffi::new_clause_iterator(std::ptr::from_mut(i).cast::<u8>(), f::<I>) };
1957        ffi::traverse_clauses(&self.solver, &mut iter)
1958    }
1959
1960    #[inline]
1961    pub fn traverse_witnesses_backward<I: WitnessIterator>(&self, i: &mut I) -> bool {
1962        fn f<I: WitnessIterator>(state: *mut u8, clause: &[i32], witness: &[i32], id: i64) -> bool {
1963            let ptr: *mut I = state.cast::<I>();
1964            let i = unsafe { &mut *ptr };
1965            i.witness(clause, witness, id)
1966        }
1967        let mut iter =
1968            unsafe { ffi::new_witness_iterator(std::ptr::from_mut(i).cast::<u8>(), f::<I>) };
1969        ffi::traverse_witnesses_backward(&self.solver, &mut iter)
1970    }
1971
1972    #[inline]
1973    pub fn traverse_witnesses_forward<I: WitnessIterator>(&self, i: &mut I) -> bool {
1974        fn f<I: WitnessIterator>(state: *mut u8, clause: &[i32], witness: &[i32], id: i64) -> bool {
1975            let ptr: *mut I = state.cast::<I>();
1976            let i = unsafe { &mut *ptr };
1977            i.witness(clause, witness, id)
1978        }
1979        let mut iter =
1980            unsafe { ffi::new_witness_iterator(std::ptr::from_mut(i).cast::<u8>(), f::<I>) };
1981        ffi::traverse_witnesses_forward(&self.solver, &mut iter)
1982    }
1983
1984    //------------------------------------------------------------------------
1985    /// Files with explicit path argument support compressed input and output
1986    /// if appropriate helper functions 'gzip' etc. are available.  They are
1987    /// called through opening a pipe to an external command.
1988    ///
1989    /// If the 'strict' argument is zero then the number of variables and
1990    /// clauses specified in the DIMACS headers are ignored, i.e., the header
1991    /// 'p cnf 0 0' is always legal.  If the 'strict' argument is larger '1'
1992    /// strict formatting of the header is required, i.e., single spaces
1993    /// everywhere and no trailing white space.
1994    ///
1995    /// Returns `Err` with `CaDiCaL`'s error message if unsuccessful.
1996    ///
1997    ///   require (VALID)
1998    ///   ensure (VALID)
1999    ///
2000    /// # Errors
2001    ///
2002    /// If the file cannot be opened or parsed.
2003    ///
2004    /// # Panics
2005    ///
2006    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
2007    /// already been added. `CaDiCaL` would otherwise abort the process.
2008    ///
2009    #[inline]
2010    #[track_caller]
2011    pub fn read_dimacs1(
2012        &mut self,
2013        file: &str,
2014        name: &str,
2015        vars: &mut i32,
2016        strict: i32,
2017    ) -> Result<(), String> {
2018        self.require_state("read_dimacs1", State::CONFIGURING);
2019        let res = ffi::read_dimacs1(
2020            &mut self.solver,
2021            file.to_owned(),
2022            name.to_owned(),
2023            vars,
2024            strict,
2025        );
2026        // 'c --option' lines in the header set options from C++.
2027        self.update_declared_vars_only();
2028        into_result(res)
2029    }
2030
2031    /// # Errors
2032    ///
2033    /// If the file cannot be opened or parsed.
2034    ///
2035    /// # Panics
2036    ///
2037    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
2038    /// already been added. `CaDiCaL` would otherwise abort the process.
2039    ///
2040    #[inline]
2041    #[track_caller]
2042    pub fn read_dimacs2(&mut self, path: &str, vars: &mut i32, strict: i32) -> Result<(), String> {
2043        self.require_state("read_dimacs2", State::CONFIGURING);
2044        let res = ffi::read_dimacs2(&mut self.solver, path.to_owned(), vars, strict);
2045        // 'c --option' lines in the header set options from C++.
2046        self.update_declared_vars_only();
2047        into_result(res)
2048    }
2049
2050    /// The following routines work the same way but parse both DIMACS and
2051    /// INCCNF files (with 'p inccnf' header and `a <cube>` lines).  If the
2052    /// parser finds and 'p inccnf' header or cubes then '*incremental' is set
2053    /// to true and the cubes are stored in the given vector (each cube
2054    /// terminated by a zero).
2055    ///
2056    /// # Errors
2057    ///
2058    /// If the file cannot be opened or parsed.
2059    ///
2060    /// # Panics
2061    ///
2062    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
2063    /// already been added. `CaDiCaL` would otherwise abort the process.
2064    ///
2065    #[inline]
2066    #[track_caller]
2067    pub fn read_dimacs3(
2068        &mut self,
2069        file: &str,
2070        name: &str,
2071        vars: &mut i32,
2072        strict: i32,
2073        incremental: &mut bool,
2074        cubes: &mut Vec<i32>,
2075    ) -> Result<(), String> {
2076        self.require_state("read_dimacs3", State::CONFIGURING);
2077        let res = ffi::read_dimacs3(
2078            &mut self.solver,
2079            file.to_owned(),
2080            name.to_owned(),
2081            vars,
2082            strict,
2083            incremental,
2084            cubes,
2085        );
2086        // 'c --option' lines in the header set options from C++.
2087        self.update_declared_vars_only();
2088        into_result(res)
2089    }
2090
2091    /// # Errors
2092    ///
2093    /// If the file cannot be opened or parsed.
2094    ///
2095    /// # Panics
2096    ///
2097    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
2098    /// already been added. `CaDiCaL` would otherwise abort the process.
2099    ///
2100    #[inline]
2101    #[track_caller]
2102    pub fn read_dimacs4(
2103        &mut self,
2104        path: &str,
2105        vars: &mut i32,
2106        strict: i32,
2107        incremental: &mut bool,
2108        cubes: &mut Vec<i32>,
2109    ) -> Result<(), String> {
2110        self.require_state("read_dimacs4", State::CONFIGURING);
2111        let res = ffi::read_dimacs4(
2112            &mut self.solver,
2113            path.to_owned(),
2114            vars,
2115            strict,
2116            incremental,
2117            cubes,
2118        );
2119        // 'c --option' lines in the header set options from C++.
2120        self.update_declared_vars_only();
2121        into_result(res)
2122    }
2123
2124    //------------------------------------------------------------------------
2125    /// Write current irredundant clauses and all derived unit clauses
2126    /// to a file in DIMACS format.  Clauses on the extension stack are
2127    /// not included, nor any redundant clauses.
2128    ///
2129    /// The '`min_max_var`' parameter gives a lower bound on the number `<vars>`
2130    /// of variables used in the DIMACS `p cnf <vars> ...` header.
2131    ///
2132    /// Returns `Err` with `CaDiCaL`'s error message if unsuccessful.
2133    ///
2134    ///   require (VALID)
2135    ///   ensure (VALID)
2136    ///
2137    /// # Errors
2138    ///
2139    /// If the file cannot be written.
2140    ///
2141    #[inline]
2142    pub fn write_dimacs(&mut self, path: &str, min_max_var: i32) -> Result<(), String> {
2143        into_result(ffi::write_dimacs(
2144            &mut self.solver,
2145            path.to_owned(),
2146            min_max_var,
2147        ))
2148    }
2149
2150    /// The extension stack for reconstruction a solution can be written too.
2151    ///
2152    /// # Errors
2153    ///
2154    /// If the file cannot be written.
2155    ///
2156    #[inline]
2157    pub fn write_extension(&mut self, path: &str) -> Result<(), String> {
2158        into_result(ffi::write_extension(&mut self.solver, path.to_owned()))
2159    }
2160
2161    /// Print build configuration to a file with prefix 'c '.  If the file
2162    /// is `<stdout>` or `<stderr>` then terminal color codes might be used.
2163    ///
2164    /// # Errors
2165    ///
2166    /// If the file cannot be opened.
2167    ///
2168    #[inline]
2169    pub fn build(file: &str, prefix: &str) -> Result<(), String> {
2170        into_result(ffi::build(file.to_owned(), prefix.to_owned()))
2171    }
2172}
2173
2174/// Connected terminators are checked for termination regularly.  If the
2175/// 'terminate' function of the terminator returns true the solver is
2176/// terminated synchronously as soon it calls this function.
2177pub trait Terminator {
2178    fn terminated(&mut self) -> bool;
2179}
2180
2181/// A [`Terminator`] that can be triggered from any thread, e.g. to stop a
2182/// long-running [`CaDiCal::solve`] after a timeout. Clones share the same flag.
2183#[derive(Debug, Clone, Default)]
2184pub struct TerminateFlag(Arc<AtomicBool>);
2185
2186impl TerminateFlag {
2187    #[must_use]
2188    pub fn new() -> Self {
2189        Self::default()
2190    }
2191
2192    /// Ask the solver to stop as soon as possible; `solve` then returns
2193    /// [`Status::UNKNOWN`] unless it has already decided the formula.
2194    pub fn terminate(&self) {
2195        self.0.store(true, Ordering::Relaxed);
2196    }
2197
2198    /// Clear the flag so that the solver can be used again.
2199    pub fn reset(&self) {
2200        self.0.store(false, Ordering::Relaxed);
2201    }
2202
2203    #[must_use]
2204    pub fn is_terminated(&self) -> bool {
2205        self.0.load(Ordering::Relaxed)
2206    }
2207}
2208
2209impl Terminator for TerminateFlag {
2210    fn terminated(&mut self) -> bool {
2211        self.is_terminated()
2212    }
2213}
2214
2215/// Connected learners which can be used to export learned clauses.
2216/// The 'learning' can check the size of the learn clause and only if it
2217/// returns true then the individual literals of the learned clause are given
2218/// to the learn through 'learn' one by one terminated by a zero literal.
2219pub trait Learner {
2220    fn learning(&mut self, size: i32) -> bool;
2221    fn learn(&mut self, lit: i32);
2222}
2223
2224/// Connected listener gets notified whenever the truth value of a variable is
2225/// fixed (for example during inprocessing or due to some derived unit clauses).
2226pub trait FixedAssignmentListener {
2227    fn notify_fixed_assignment(&mut self, lit: i32);
2228}
2229
2230use std::vec::Vec;
2231
2232/// Allows to connect an external propagator to propagate values to variables
2233/// with an external clause as a reason or to learn new clauses during the
2234/// CDCL loop (without restart).
2235pub trait ExternalPropagator {
2236    /// lazy propagator only checks complete assignments
2237    fn is_lazy(&mut self) -> bool {
2238        false
2239    }
2240
2241    /// Reason external clauses can be deleted
2242    fn are_reasons_forgettable(&mut self) -> bool {
2243        false
2244    }
2245
2246    /// Notify the propagator about assignments to observed variables.
2247    /// The notification is not necessarily eager. It usually happens before
2248    /// the call of propagator callbacks and when a driving clause is leading
2249    /// to an assignment.
2250    fn notify_assignment(&mut self, lits: &[i32]);
2251
2252    fn notify_new_decision_level(&mut self);
2253
2254    fn notify_backtrack(&mut self, new_level: usize);
2255
2256    /// Check by the external propagator the found complete solution (after
2257    /// solution reconstruction). If it returns false, the propagator must
2258    /// provide an external clause during the next callback.
2259    fn cb_check_found_model(&mut self, model: &[i32]) -> bool;
2260
2261    /// Ask the external propagator for the next decision literal. If it
2262    /// returns 0, the solver makes its own choice.
2263    fn cb_decide(&mut self) -> i32 {
2264        0
2265    }
2266
2267    /// Ask the external propagator if there is an external propagation to make
2268    /// under the current assignment. It returns either a literal to be
2269    /// propagated or 0, indicating that there is no external propagation under
2270    /// the current assignment.
2271    fn cb_propagate(&mut self) -> i32 {
2272        0
2273    }
2274
2275    /// Ask the external propagator for the reason clause of a previous
2276    /// external propagation step (done by `cb_propagate`). The clause must be
2277    /// added literal-by-literal closed with a 0. Further, the clause must
2278    /// contain the propagated literal.
2279    ///
2280    /// The clause will be learned as an Irredundant Non-Forgettable Clause (see
2281    /// below at '`cb_has_external_clause`' more details about it).
2282    fn cb_add_reason_clause_lit(&mut self, _propagated_lit: i32) -> i32 {
2283        0
2284    }
2285
2286    /// The following two functions are used to add external clauses to the
2287    /// solver during the CDCL loop. The external clause is added
2288    /// literal-by-literal and learned by the solver as an irredundant
2289    /// (original) input clause. The clause can be arbitrary, but if it is
2290    /// root-satisfied or tautology, the solver will ignore it without learning
2291    /// it. Root-falsified literals are eagerly removed from the clause.
2292    /// Falsified clauses trigger conflict analysis, propagating clauses
2293    /// trigger propagation. In case chrono is 0, the solver backtracks to
2294    /// propagate the new literal on the right decision level, otherwise it
2295    /// potentially will be an out-of-order assignment on the current level.
2296    /// Unit clauses always (unless root-satisfied, see above) trigger
2297    /// backtracking (independently from the value of the chrono option and
2298    /// independently from being falsified or satisfied or unassigned) to level
2299    /// 0. Empty clause (or root falsified clause, see above) makes the problem
2300    /// unsat and stops the search immediately. A literal 0 must close the
2301    /// clause.
2302    ///
2303    /// The external propagator indicates that there is a clause to add.
2304    /// The parameter of the function allows the user to indicate that how
2305    /// 'forgettable' is the external clause. Forgettable clauses are allowed
2306    /// to be removed by the SAT solver during clause database reduction.
2307    /// However, it is up to the solver to decide when actually the clause is
2308    /// deleted. For example, unit clauses, even forgettable ones, will not be
2309    /// deleted. In case the clause is not 'forgettable' (the parameter is false),
2310    /// the solver considers the clause to be irredundant.
2311    ///
2312    /// In case the solver produces incremental proofs, these external clauses
2313    /// are added to the proof during solving at real-time, i.e., the proof
2314    /// checker can ignore them until that point (so added as input clause, but
2315    /// input after the query line).
2316    ///
2317    /// Reason clauses of external propagation steps are assumed to be
2318    /// forgettable, parameter '`reason_forgettable`' can be used to change it.
2319    ///
2320    /// Currently, every external clause is expected to be over observed
2321    /// (therefore frozen) variables, hence no tainting or restore steps
2322    /// are performed upon their addition. This will be changed in later
2323    /// versions probably.
2324    fn cb_has_external_clause(&mut self, is_forgettable: &mut bool) -> bool;
2325
2326    /// The actual function called to add the external clause.
2327    fn cb_add_external_clause_lit(&mut self) -> i32;
2328}
2329
2330/// Allows to traverse all remaining irredundant clauses.  Satisfied and
2331/// eliminated clauses are not included, nor any derived units unless such
2332/// a unit literal is frozen. Falsified literals are skipped.  If the solver
2333/// is inconsistent only the empty clause is traversed.
2334///
2335/// If 'clause' returns false traversal aborts early.
2336pub trait ClauseIterator {
2337    fn clause(&mut self, clause: &[i32]) -> bool;
2338}
2339
2340/// Allows to traverse all clauses on the extension stack together with their
2341/// witness cubes.  If the solver is inconsistent, i.e., an empty clause is
2342/// found and the formula is unsatisfiable, then nothing is traversed.
2343///
2344/// The clauses traversed in '`traverse_clauses`' together with the clauses on
2345/// the extension stack are logically equivalent to the original clauses.
2346/// See our SAT'19 paper for more details.
2347///
2348/// The witness literals can be used to extend and fix an assignment on the
2349/// remaining clauses to satisfy the clauses on the extension stack too.
2350///
2351/// All derived units of non-frozen variables are included too.
2352///
2353/// If 'witness' returns false traversal aborts early.
2354pub trait WitnessIterator {
2355    fn witness(&mut self, clause: &[i32], witness: &[i32], id: i64) -> bool;
2356}
2357
2358/// Trait for proof tracing that allows you to track proof events in real-time.
2359/// This is useful for SMT solvers that need to interleave SAT solver clauses
2360/// with theory clauses to generate eDRAT proofs.
2361pub trait ProofTracer {
2362    /// Called when an original clause is added to the solver
2363    fn add_original_clause(&mut self, id: i64, redundant: bool, clause: &[i32], restored: bool);
2364
2365    /// Called when a derived clause is learned by the SAT solver. If `witness`
2366    /// is not zero the clause is a RAT clause with that witness literal.
2367    fn add_derived_clause(
2368        &mut self,
2369        id: i64,
2370        redundant: bool,
2371        witness: i32,
2372        clause: &[i32],
2373        antecedents: &[i64],
2374    );
2375
2376    /// Called when a clause is deleted
2377    fn delete_clause(&mut self, id: i64, redundant: bool, clause: &[i32]);
2378
2379    /// Called when a clause is weakened (might be restored later)
2380    fn weaken_minus(&mut self, id: i64, clause: &[i32]);
2381
2382    /// Called when a clause is strengthened
2383    fn strengthen(&mut self, id: i64);
2384
2385    /// Called when a clause is finalized
2386    fn finalize_clause(&mut self, id: i64, clause: &[i32]);
2387
2388    /// Called when an assumption is added
2389    fn add_assumption(&mut self, lit: i32);
2390
2391    /// Called when a constraint is added
2392    fn add_constraint(&mut self, clause: &[i32]);
2393
2394    /// Called when assumptions are reset
2395    fn reset_assumptions(&mut self);
2396
2397    /// Called when an assumption clause is added (negation of failing assumptions)
2398    fn add_assumption_clause(&mut self, id: i64, clause: &[i32], antecedents: &[i64]);
2399
2400    /// Called when the solver concludes SAT
2401    fn conclude_sat(&mut self, conclusion_type: i32, model: &[i32]);
2402
2403    /// Called when the solver concludes UNSAT
2404    fn conclude_unsat(&mut self, conclusion_type: i32, clause_ids: &[i64]);
2405
2406    /// Called when the solver concludes UNKNOWN
2407    fn conclude_unknown(&mut self, trail: &[i32]);
2408
2409    /// Called when a clause is demoted from irredundant to redundant
2410    fn demote_clause(&mut self, _id: i64, _clause: &[i32]) {}
2411
2412    /// Called when a solve call ends with the given status. If the status is
2413    /// UNSAT and an empty clause has been derived, `id` is its id.
2414    fn report_status(&mut self, _status: i32, _id: i64) {}
2415
2416    /// Called when the proof begins; ids below `first_derived_id` are
2417    /// reserved for original clauses
2418    fn begin_proof(&mut self, _first_derived_id: i64) {}
2419
2420    /// Called when a solve call (query) starts
2421    fn solve_query(&mut self) {}
2422
2423    /// Called when two literals are found to be equivalent (possibly
2424    /// including variables added by the solver, e.g. through BVA)
2425    fn notify_equivalence(&mut self, _lit: i32, _other: i32) {}
2426}
2427
2428// ************************************************************************************************
2429// Shared callbacks
2430// ************************************************************************************************
2431
2432// The solver owns its callbacks, so these impls let the caller keep an `Rc` to
2433// a callback and inspect it while it is connected (e.g. after `solve`).
2434
2435impl<T: Terminator> Terminator for Rc<RefCell<T>> {
2436    fn terminated(&mut self) -> bool {
2437        self.borrow_mut().terminated()
2438    }
2439}
2440
2441impl<T: Learner> Learner for Rc<RefCell<T>> {
2442    fn learning(&mut self, size: i32) -> bool {
2443        self.borrow_mut().learning(size)
2444    }
2445    fn learn(&mut self, lit: i32) {
2446        self.borrow_mut().learn(lit);
2447    }
2448}
2449
2450impl<T: FixedAssignmentListener> FixedAssignmentListener for Rc<RefCell<T>> {
2451    fn notify_fixed_assignment(&mut self, lit: i32) {
2452        self.borrow_mut().notify_fixed_assignment(lit);
2453    }
2454}
2455
2456impl<T: ExternalPropagator> ExternalPropagator for Rc<RefCell<T>> {
2457    fn is_lazy(&mut self) -> bool {
2458        self.borrow_mut().is_lazy()
2459    }
2460    fn are_reasons_forgettable(&mut self) -> bool {
2461        self.borrow_mut().are_reasons_forgettable()
2462    }
2463    fn notify_assignment(&mut self, lits: &[i32]) {
2464        self.borrow_mut().notify_assignment(lits);
2465    }
2466    fn notify_new_decision_level(&mut self) {
2467        self.borrow_mut().notify_new_decision_level();
2468    }
2469    fn notify_backtrack(&mut self, new_level: usize) {
2470        self.borrow_mut().notify_backtrack(new_level);
2471    }
2472    fn cb_check_found_model(&mut self, model: &[i32]) -> bool {
2473        self.borrow_mut().cb_check_found_model(model)
2474    }
2475    fn cb_decide(&mut self) -> i32 {
2476        self.borrow_mut().cb_decide()
2477    }
2478    fn cb_propagate(&mut self) -> i32 {
2479        self.borrow_mut().cb_propagate()
2480    }
2481    fn cb_add_reason_clause_lit(&mut self, propagated_lit: i32) -> i32 {
2482        self.borrow_mut().cb_add_reason_clause_lit(propagated_lit)
2483    }
2484    fn cb_has_external_clause(&mut self, is_forgettable: &mut bool) -> bool {
2485        self.borrow_mut().cb_has_external_clause(is_forgettable)
2486    }
2487    fn cb_add_external_clause_lit(&mut self) -> i32 {
2488        self.borrow_mut().cb_add_external_clause_lit()
2489    }
2490}
2491
2492impl<T: ProofTracer> ProofTracer for Rc<RefCell<T>> {
2493    fn add_original_clause(&mut self, id: i64, redundant: bool, clause: &[i32], restored: bool) {
2494        self.borrow_mut()
2495            .add_original_clause(id, redundant, clause, restored);
2496    }
2497    fn add_derived_clause(
2498        &mut self,
2499        id: i64,
2500        redundant: bool,
2501        witness: i32,
2502        clause: &[i32],
2503        antecedents: &[i64],
2504    ) {
2505        self.borrow_mut()
2506            .add_derived_clause(id, redundant, witness, clause, antecedents);
2507    }
2508    fn delete_clause(&mut self, id: i64, redundant: bool, clause: &[i32]) {
2509        self.borrow_mut().delete_clause(id, redundant, clause);
2510    }
2511    fn weaken_minus(&mut self, id: i64, clause: &[i32]) {
2512        self.borrow_mut().weaken_minus(id, clause);
2513    }
2514    fn strengthen(&mut self, id: i64) {
2515        self.borrow_mut().strengthen(id);
2516    }
2517    fn finalize_clause(&mut self, id: i64, clause: &[i32]) {
2518        self.borrow_mut().finalize_clause(id, clause);
2519    }
2520    fn add_assumption(&mut self, lit: i32) {
2521        self.borrow_mut().add_assumption(lit);
2522    }
2523    fn add_constraint(&mut self, clause: &[i32]) {
2524        self.borrow_mut().add_constraint(clause);
2525    }
2526    fn reset_assumptions(&mut self) {
2527        self.borrow_mut().reset_assumptions();
2528    }
2529    fn add_assumption_clause(&mut self, id: i64, clause: &[i32], antecedents: &[i64]) {
2530        self.borrow_mut()
2531            .add_assumption_clause(id, clause, antecedents);
2532    }
2533    fn conclude_sat(&mut self, conclusion_type: i32, model: &[i32]) {
2534        self.borrow_mut().conclude_sat(conclusion_type, model);
2535    }
2536    fn conclude_unsat(&mut self, conclusion_type: i32, clause_ids: &[i64]) {
2537        self.borrow_mut()
2538            .conclude_unsat(conclusion_type, clause_ids);
2539    }
2540    fn conclude_unknown(&mut self, trail: &[i32]) {
2541        self.borrow_mut().conclude_unknown(trail);
2542    }
2543    fn demote_clause(&mut self, id: i64, clause: &[i32]) {
2544        self.borrow_mut().demote_clause(id, clause);
2545    }
2546    fn report_status(&mut self, status: i32, id: i64) {
2547        self.borrow_mut().report_status(status, id);
2548    }
2549    fn begin_proof(&mut self, first_derived_id: i64) {
2550        self.borrow_mut().begin_proof(first_derived_id);
2551    }
2552    fn solve_query(&mut self) {
2553        self.borrow_mut().solve_query();
2554    }
2555    fn notify_equivalence(&mut self, lit: i32, other: i32) {
2556        self.borrow_mut().notify_equivalence(lit, other);
2557    }
2558}