1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
pub use crate::{
    ffi::sys::*,

    Result,

    Sign,
    Var,
    Lit,
    InvalidLitVal,
    Clause,
    LitIter,

    SolverErrorKind,
    SolverError,
    SolveResponse,
    ResponseError,
    LitValue,
    IpasirSolver,
    SolveControl,
};
use std::{
    os::raw::{
        c_int,
        c_void,
    },
    ffi::CStr,
    marker,
    mem,
};

/// The incremental solver implementing the IPASIR interface.
pub struct Solver {
    ptr: *mut SysSolver,
    terminate_cb: Option<Box<Box<FnMut() -> SolveControl>>>,
    learn_cb: Option<Box<Box<FnMut(Clause)>>>,
}

unsafe impl marker::Send for Solver {}
unsafe impl marker::Sync for Solver {}

impl Solver {
    /// Returns a raw representation of this solver that is consumable by the IPASIR interface.
    fn raw_mut(&mut self) -> *mut SysSolver {
        self.ptr
    }
}

impl IpasirSolver for Solver {
    fn signature(&self) -> &'static str {
        let c_chars = unsafe{ ipasir_signature() };
        let c_str = unsafe{ CStr::from_ptr(c_chars) };
        c_str.to_str()
             .expect("The IPASIR implementation returned invalid UTF-8.")
    }

    fn init() -> Solver {
        Solver {
            ptr: unsafe{ ipasir_init() },
            terminate_cb: None,
            learn_cb: None,
        }
    }

    fn add_clause<I, L>(&mut self, lits: I)
    where
        I: IntoIterator<Item = L>,
        L: Into<Lit>,
    {
        for lit in lits.into_iter() {
            unsafe { ipasir_add(self.raw_mut(), lit.into().to_raw()) }
        }
        unsafe { ipasir_add(self.raw_mut(), 0) }
    }

    fn assume(&mut self, lit: Lit) {
        unsafe{ ipasir_assume(self.raw_mut(), lit.to_raw()) }
    }

    fn solve(&mut self) -> Result<SolveResponse> {
        match unsafe{ ipasir_solve(self.raw_mut()) } {
            0 => Ok(SolveResponse::Interrupted),
            10 => Ok(SolveResponse::Sat),
            20 => Ok(SolveResponse::Unsat),
            invalid => Err(ResponseError::Solve(invalid).into())
        }
    }

    fn val(&mut self, lit: Lit) -> Result<LitValue> {
        match unsafe{ ipasir_val(self.raw_mut(), lit.to_raw()) } {
            0 => Ok(LitValue::DontCare),
            p if p == lit.to_raw() => Ok(LitValue::True),
            n if n == -lit.to_raw() => Ok(LitValue::False),
            invalid => Err(InvalidLitVal(invalid).into())
        }
    }

    fn failed(&mut self, lit: Lit) -> Result<bool> {
        match unsafe{ ipasir_failed(self.raw_mut(), lit.to_raw()) } {
            0 => Ok(true),
            1 => Ok(false),
            invalid => Err(ResponseError::Failed(invalid).into())
        }
    }

    fn set_terminate<F>(&mut self, cb: F)
    where
        F: FnMut() -> SolveControl + 'static,
    {
        self.terminate_cb = Some(Box::new(Box::new(cb)));
        unsafe {
            ipasir_set_terminate(
                self.raw_mut(),
                self.terminate_cb.as_mut().unwrap().as_mut() as *const _ as *const c_void,
                ipasir_set_terminate_callback
            )
        }
    }

    fn set_learn<F>(&mut self, max_len: usize, cb: F)
    where
        F: FnMut(Clause) + 'static
    {
        self.learn_cb = Some(Box::new(Box::new(cb)));
        unsafe {
            ipasir_set_learn(
                self.raw_mut(),
                self.learn_cb.as_mut().unwrap().as_mut() as *const _ as *const c_void,
                max_len as c_int,
                ipasir_set_learn_callback
            )
        }
    }
}

impl Drop for Solver {
    fn drop(&mut self) {
        unsafe{ ipasir_release(self.raw_mut()) }
    }
}

/// The raw callback for the C side of the IPASIR implementation of `ipasir_set_terminate`.
///
/// # Note
/// 
/// This simply forwards to the real user-provided implementation
/// of the user provided callback.
/// 
/// Don't use this directly!
extern "C" fn ipasir_set_terminate_callback(state: *const c_void) -> c_int
{
    let cb: &mut Box<FnMut() -> SolveControl> = unsafe {
        mem::transmute(state)
    };
    match cb() {
        SolveControl::Continue => 0,
        SolveControl::Stop => 1
    }
}

/// The raw callback for the C side of the IPASIR implementation of `ipasir_set_learn`.
///
/// # Note
/// 
/// This simply forwards to the real user-provided implementation
/// of the user provided callback.
/// 
/// Don't use this directly!
extern "C" fn ipasir_set_learn_callback(state: *const c_void, learnt_clause: *const c_int)
{
    let cb: &mut Box<FnMut(Clause)> = unsafe {
        mem::transmute(state)
    };
    let mut count_lits = 0;
    for n in 0.. {
        if unsafe { *learnt_clause.offset(n) } != 0 {
            count_lits += 1;
        }
    }
    let lits_slice = unsafe {
        std::mem::transmute::<&[c_int], &[Lit]>(
            std::slice::from_raw_parts(learnt_clause, count_lits))
    };
    cb(Clause::from(lits_slice))
}