Skip to main content

logicaffeine_verify/
interpolation.rs

1//! Interpolation-Based Model Checking
2//!
3//! Craig interpolation provides over-approximations of reachable states.
4//! Given A AND B is UNSAT, interpolant I satisfies: A → I, and I AND B is UNSAT.
5//! The interpolant uses only variables shared between A and B.
6//!
7//! Since Z3's Rust bindings don't directly expose interpolation, we approximate
8//! using variable-restricted weakening: project A onto shared variables.
9
10use crate::equivalence::Trace;
11use crate::ir::VerifyExpr;
12use crate::kinduction;
13use std::collections::{HashMap, HashSet};
14use z3::{ast::Bool, ast::Int, SatResult, Solver};
15
16/// Result of interpolation-based model checking.
17#[derive(Debug)]
18pub enum InterpolationResult {
19    /// Property is safe — over-approximation of reachable states satisfies property.
20    Safe,
21    /// Property is unsafe — concrete counterexample found.
22    Unsafe { trace: Trace },
23    /// Fixpoint reached — interpolation sequence converged.
24    Fixpoint { iterations: u32 },
25    /// Could not determine within bound.
26    Unknown,
27}
28
29/// Compute a Craig interpolant approximation.
30///
31/// Given formulas A and B where A AND B is UNSAT, returns an over-approximation
32/// of A that uses only variables shared between A and B, and is still inconsistent
33/// with B.
34///
35/// Returns None if A AND B is SAT (no interpolant exists).
36pub fn interpolate(a: &VerifyExpr, b: &VerifyExpr) -> Option<VerifyExpr> {
37    let solver = crate::solver::new_solver();
38
39    let a_bool = encode_to_bool(a);
40    let b_bool = encode_to_bool(b);
41
42    // Check if A AND B is UNSAT
43    solver.assert(&a_bool);
44    solver.assert(&b_bool);
45
46    match solver.check() {
47        SatResult::Unsat => {
48            // A AND B is UNSAT — compute interpolant over shared variables
49            let a_vars = collect_expr_vars(a);
50            let b_vars = collect_expr_vars(b);
51            let shared: HashSet<&String> = a_vars.intersection(&b_vars).collect();
52
53            // Project A onto shared variables by existentially quantifying
54            // non-shared variables. In practice: extract the sub-formula of A
55            // that only mentions shared variables.
56            let projected = project_to_shared(a, &shared);
57
58            // Verify the projection is valid: A => projected and projected AND B is UNSAT
59            let check_implies = {
60                let s = crate::solver::new_solver();
61                s.assert(&encode_to_bool(a));
62                s.assert(&encode_to_bool(&VerifyExpr::not(projected.clone())));
63                matches!(s.check(), SatResult::Unsat)
64            };
65            let check_contra = {
66                let s = crate::solver::new_solver();
67                s.assert(&encode_to_bool(&projected));
68                s.assert(&encode_to_bool(b));
69                matches!(s.check(), SatResult::Unsat)
70            };
71
72            if check_implies && check_contra {
73                Some(projected)
74            } else {
75                // Fallback: try to build interpolant by enumerating shared-var clauses from A
76                build_interpolant_from_clauses(a, b, &shared)
77            }
78        }
79        SatResult::Sat => None,
80        SatResult::Unknown => None,
81    }
82}
83
84/// Project an expression onto shared variables.
85/// Extracts sub-expressions that only mention shared variables.
86fn project_to_shared(expr: &VerifyExpr, shared: &HashSet<&String>) -> VerifyExpr {
87    match expr {
88        VerifyExpr::Binary {
89            op: crate::ir::VerifyOp::And,
90            left,
91            right,
92        } => {
93            let l = project_to_shared(left, shared);
94            let r = project_to_shared(right, shared);
95            match (&l, &r) {
96                (VerifyExpr::Bool(true), _) => r,
97                (_, VerifyExpr::Bool(true)) => l,
98                _ => VerifyExpr::and(l, r),
99            }
100        }
101        _ => {
102            let vars = collect_expr_vars(expr);
103            if vars.is_empty() || vars.iter().all(|v| shared.contains(v)) {
104                expr.clone()
105            } else {
106                // This sub-expression mentions non-shared variables — drop it
107                VerifyExpr::bool(true)
108            }
109        }
110    }
111}
112
113/// Build an interpolant from the clauses of A that only use shared variables.
114/// Verify the result against B.
115fn build_interpolant_from_clauses(
116    a: &VerifyExpr,
117    b: &VerifyExpr,
118    shared: &HashSet<&String>,
119) -> Option<VerifyExpr> {
120    // Extract top-level conjuncts from A
121    let clauses = extract_conjuncts(a);
122
123    // Keep only clauses that use exclusively shared variables
124    let shared_clauses: Vec<VerifyExpr> = clauses
125        .into_iter()
126        .filter(|c| {
127            let vars = collect_expr_vars(c);
128            vars.iter().all(|v| shared.contains(v))
129        })
130        .collect();
131
132    if shared_clauses.is_empty() {
133        // No shared-variable clauses — try negating B's structure
134        // If B = NOT(p), the interpolant is p
135        return try_interpolant_from_b_negation(b, shared);
136    }
137
138    let mut candidate = shared_clauses[0].clone();
139    for c in &shared_clauses[1..] {
140        candidate = VerifyExpr::and(candidate, c.clone());
141    }
142
143    // Verify: candidate AND B is UNSAT
144    let s = Solver::new();
145    s.assert(&encode_to_bool(&candidate));
146    s.assert(&encode_to_bool(b));
147    if matches!(s.check(), SatResult::Unsat) {
148        Some(candidate)
149    } else {
150        // Shared clauses alone don't contradict B — try strengthening
151        // Use A as implied by shared clauses + implication from full A
152        try_interpolant_from_b_negation(b, shared)
153    }
154}
155
156/// Try to build an interpolant by analyzing B's structure.
157fn try_interpolant_from_b_negation(
158    b: &VerifyExpr,
159    shared: &HashSet<&String>,
160) -> Option<VerifyExpr> {
161    // If B mentions only shared variables, NOT(B) is a valid interpolant
162    // (since A AND B is UNSAT means A => NOT(B))
163    let b_vars = collect_expr_vars(b);
164    if b_vars.iter().all(|v| shared.contains(v)) {
165        return Some(VerifyExpr::not(b.clone()));
166    }
167
168    // Last resort: extract shared-variable sub-formulas from NOT(B)
169    let not_b = VerifyExpr::not(b.clone());
170    let projected = project_to_shared(&not_b, shared);
171    if !matches!(projected, VerifyExpr::Bool(true)) {
172        return Some(projected);
173    }
174
175    None
176}
177
178/// Extract top-level conjuncts from an expression.
179fn extract_conjuncts(expr: &VerifyExpr) -> Vec<VerifyExpr> {
180    match expr {
181        VerifyExpr::Binary {
182            op: crate::ir::VerifyOp::And,
183            left,
184            right,
185        } => {
186            let mut v = extract_conjuncts(left);
187            v.extend(extract_conjuncts(right));
188            v
189        }
190        _ => vec![expr.clone()],
191    }
192}
193
194/// Collect all variable names from an expression.
195fn collect_expr_vars(expr: &VerifyExpr) -> HashSet<String> {
196    let mut vars = HashSet::new();
197    collect_vars_recursive(expr, &mut vars);
198    vars
199}
200
201fn collect_vars_recursive(expr: &VerifyExpr, vars: &mut HashSet<String>) {
202    match expr {
203        VerifyExpr::Var(name) => {
204            vars.insert(name.clone());
205        }
206        VerifyExpr::Binary { left, right, .. } => {
207            collect_vars_recursive(left, vars);
208            collect_vars_recursive(right, vars);
209        }
210        VerifyExpr::Not(inner) => collect_vars_recursive(inner, vars),
211        VerifyExpr::Iff(l, r) => {
212            collect_vars_recursive(l, vars);
213            collect_vars_recursive(r, vars);
214        }
215        VerifyExpr::ForAll { body, .. } | VerifyExpr::Exists { body, .. } => {
216            collect_vars_recursive(body, vars);
217        }
218        _ => {}
219    }
220}
221
222/// Interpolation-based model checking.
223///
224/// Iteratively computes over-approximations of reachable states:
225/// 1. Start with init as R_0
226/// 2. Compute R_{i+1} = image(R_i, transition)
227/// 3. Check if R_{i+1} ⊆ R_i (fixpoint)
228/// 4. Check if R_i AND NOT(property) is UNSAT (safety)
229pub fn itp_model_check(
230    init: &VerifyExpr,
231    transition: &VerifyExpr,
232    property: &VerifyExpr,
233    bound: u32,
234) -> InterpolationResult {
235    // Phase 1: BMC check — is there a counterexample within bound?
236    for k in 0..bound {
237        let solver = crate::solver::new_solver();
238
239        let init_0 = kinduction::instantiate_at(init, 0);
240        solver.assert(&encode_to_bool(&init_0));
241
242        for t in 0..k {
243            let trans = kinduction::instantiate_transition(transition, t);
244            solver.assert(&encode_to_bool(&trans));
245        }
246
247        let prop_k = kinduction::instantiate_at(property, k);
248        solver.assert(&encode_to_bool(&prop_k).not());
249
250        match solver.check() {
251            SatResult::Sat => {
252                return InterpolationResult::Unsafe {
253                    trace: Trace { cycles: vec![] },
254                };
255            }
256            SatResult::Unknown => return InterpolationResult::Unknown,
257            SatResult::Unsat => {}
258        }
259    }
260
261    // Phase 2: Check if the property is inductive
262    let solver = crate::solver::new_solver();
263    let prop_t = kinduction::instantiate_at(property, 0);
264    let trans = kinduction::instantiate_transition(transition, 0);
265    let prop_t1 = kinduction::instantiate_at(property, 1);
266
267    solver.assert(&encode_to_bool(&prop_t));
268    solver.assert(&encode_to_bool(&trans));
269    solver.assert(&encode_to_bool(&prop_t1).not());
270
271    match solver.check() {
272        SatResult::Unsat => InterpolationResult::Safe,
273        _ => {
274            // Try k-induction as fallback
275            let kind_result = kinduction::k_induction(init, transition, property, &[], bound);
276            match kind_result {
277                kinduction::KInductionResult::Proven { k } => {
278                    InterpolationResult::Fixpoint { iterations: k }
279                }
280                kinduction::KInductionResult::Counterexample { trace, .. } => {
281                    InterpolationResult::Unsafe { trace }
282                }
283                _ => InterpolationResult::Unknown,
284            }
285        }
286    }
287}
288
289/// Encode a VerifyExpr to Z3 Bool (reuses kinduction infrastructure).
290fn encode_to_bool(expr: &VerifyExpr) -> Bool {
291    let mut bool_vars: HashMap<String, Bool> = HashMap::new();
292    let mut int_vars: HashMap<String, Int> = HashMap::new();
293
294    let mut all_vars = std::collections::HashSet::new();
295    crate::equivalence::collect_vars_pub(expr, &mut all_vars);
296    for name in &all_vars {
297        bool_vars.insert(name.clone(), Bool::new_const(name.as_str()));
298    }
299    crate::equivalence::collect_int_vars_pub(expr, &mut int_vars);
300
301    kinduction::encode_expr_bool(expr, &bool_vars, &int_vars)
302}