1use crate::equivalence::Trace;
17use crate::ir::{VerifyExpr, VerifyOp};
18use crate::kinduction;
19use std::collections::{HashMap, HashSet};
20use z3::{ast::Bool, SatResult};
21
22#[derive(Debug, Clone)]
23pub struct AbstractModel {
24 pub predicates: Vec<VerifyExpr>,
25 pub abstract_init: VerifyExpr,
26 pub abstract_transition: VerifyExpr,
27}
28
29#[derive(Debug)]
30pub enum AbstractionResult {
31 Safe,
32 Unsafe { concrete_trace: Trace },
33 SpuriousRefined { new_predicates: Vec<VerifyExpr> },
34 Unknown,
35}
36
37pub fn abstract_model(init: &VerifyExpr, predicates: &[VerifyExpr]) -> AbstractModel {
43 let abstract_init = if predicates.is_empty() {
44 init.clone()
45 } else {
46 let mut abs = init.clone();
47 for pred in predicates {
48 abs = VerifyExpr::and(abs, pred.clone());
49 }
50 abs
51 };
52
53 AbstractModel {
54 predicates: predicates.to_vec(),
55 abstract_init,
56 abstract_transition: VerifyExpr::bool(true),
57 }
58}
59
60pub fn abstract_model_full(
74 init: &VerifyExpr,
75 transition: &VerifyExpr,
76 predicates: &[VerifyExpr],
77) -> AbstractModel {
78 if predicates.is_empty() {
79 return AbstractModel {
80 predicates: vec![],
81 abstract_init: init.clone(),
82 abstract_transition: transition.clone(),
83 };
84 }
85
86 let mut abstract_init = init.clone();
88 for pred in predicates {
89 abstract_init = VerifyExpr::and(abstract_init, pred.clone());
90 }
91
92 let mut abstract_trans_parts: Vec<VerifyExpr> = Vec::new();
95 abstract_trans_parts.push(transition.clone());
96
97 for pred in predicates {
98 let pred_next = replace_t_with_t1(pred);
99
100 let check = VerifyExpr::and(
103 pred.clone(),
104 VerifyExpr::and(transition.clone(), VerifyExpr::not(pred_next.clone())),
105 );
106
107 let check_inst =
109 kinduction::instantiate_transition(&kinduction::instantiate_at(&check, 0), 0);
110
111 let is_inductive = {
112 let solver = crate::solver::new_solver();
113 let encoded = encode_bool(&check_inst);
114 solver.assert(&encoded);
115 matches!(solver.check(), SatResult::Unsat)
116 };
117
118 if is_inductive {
119 let implication =
121 VerifyExpr::implies(VerifyExpr::and(pred.clone(), transition.clone()), pred_next);
122 abstract_trans_parts.push(implication);
123 } else {
124 let soft = VerifyExpr::implies(
133 pred.clone(),
134 VerifyExpr::or(pred_next.clone(), VerifyExpr::not(pred_next)),
135 );
136 abstract_trans_parts.push(soft);
137 }
138 }
139
140 let mut abstract_transition = abstract_trans_parts[0].clone();
141 for part in &abstract_trans_parts[1..] {
142 abstract_transition = VerifyExpr::and(abstract_transition, part.clone());
143 }
144
145 AbstractModel {
146 predicates: predicates.to_vec(),
147 abstract_init,
148 abstract_transition,
149 }
150}
151
152fn replace_t_with_t1(expr: &VerifyExpr) -> VerifyExpr {
154 match expr {
155 VerifyExpr::Var(name) => {
156 if name.ends_with("@t") {
157 let base = &name[..name.len() - 2];
158 VerifyExpr::Var(format!("{}@t1", base))
159 } else {
160 VerifyExpr::Var(name.clone())
161 }
162 }
163 VerifyExpr::Binary { op, left, right } => {
164 VerifyExpr::binary(*op, replace_t_with_t1(left), replace_t_with_t1(right))
165 }
166 VerifyExpr::Not(inner) => VerifyExpr::not(replace_t_with_t1(inner)),
167 VerifyExpr::Bool(b) => VerifyExpr::Bool(*b),
168 VerifyExpr::Int(n) => VerifyExpr::Int(*n),
169 VerifyExpr::Iff(l, r) => VerifyExpr::iff(replace_t_with_t1(l), replace_t_with_t1(r)),
170 VerifyExpr::ForAll { vars, body } => {
171 VerifyExpr::forall(vars.clone(), replace_t_with_t1(body))
172 }
173 VerifyExpr::Exists { vars, body } => {
174 VerifyExpr::exists(vars.clone(), replace_t_with_t1(body))
175 }
176 VerifyExpr::ApplyInt { name, args } => VerifyExpr::apply_int(
177 name.clone(),
178 args.iter().map(|a| replace_t_with_t1(a)).collect(),
179 ),
180 VerifyExpr::Apply { name, args } => VerifyExpr::apply(
181 name.clone(),
182 args.iter().map(|a| replace_t_with_t1(a)).collect(),
183 ),
184 VerifyExpr::BitVecConst { width, value } => VerifyExpr::bv_const(*width, *value),
185 VerifyExpr::BitVecBinary { op, left, right } => {
186 VerifyExpr::bv_binary(*op, replace_t_with_t1(left), replace_t_with_t1(right))
187 }
188 VerifyExpr::BitVecExtract { high, low, operand } => VerifyExpr::BitVecExtract {
189 high: *high,
190 low: *low,
191 operand: Box::new(replace_t_with_t1(operand)),
192 },
193 VerifyExpr::BitVecConcat(l, r) => VerifyExpr::BitVecConcat(
194 Box::new(replace_t_with_t1(l)),
195 Box::new(replace_t_with_t1(r)),
196 ),
197 VerifyExpr::Select { array, index } => VerifyExpr::Select {
198 array: Box::new(replace_t_with_t1(array)),
199 index: Box::new(replace_t_with_t1(index)),
200 },
201 VerifyExpr::Store {
202 array,
203 index,
204 value,
205 } => VerifyExpr::Store {
206 array: Box::new(replace_t_with_t1(array)),
207 index: Box::new(replace_t_with_t1(index)),
208 value: Box::new(replace_t_with_t1(value)),
209 },
210 VerifyExpr::AtState { state, expr } => VerifyExpr::AtState {
211 state: Box::new(replace_t_with_t1(state)),
212 expr: Box::new(replace_t_with_t1(expr)),
213 },
214 VerifyExpr::Transition { from, to } => VerifyExpr::Transition {
215 from: Box::new(replace_t_with_t1(from)),
216 to: Box::new(replace_t_with_t1(to)),
217 },
218 }
219}
220
221pub fn cegar_verify(
230 init: &VerifyExpr,
231 transition: &VerifyExpr,
232 property: &VerifyExpr,
233 initial_predicates: &[VerifyExpr],
234 max_refinements: u32,
235) -> AbstractionResult {
236 let mut predicates = initial_predicates.to_vec();
237
238 for _iteration in 0..max_refinements {
239 let abs_model = abstract_model_full(init, transition, &predicates);
241
242 let abs_result = kinduction::k_induction(
244 &abs_model.abstract_init,
245 &abs_model.abstract_transition,
246 property,
247 &[],
248 10,
249 );
250
251 match abs_result {
252 kinduction::KInductionResult::Proven { .. } => {
253 return AbstractionResult::Safe;
258 }
259 kinduction::KInductionResult::Counterexample { trace: _, k } => {
260 let concrete_result =
263 kinduction::k_induction(init, transition, property, &[], k.max(10));
264
265 match concrete_result {
266 kinduction::KInductionResult::Counterexample { trace: ctrace, .. } => {
267 return AbstractionResult::Unsafe {
268 concrete_trace: ctrace,
269 };
270 }
271 kinduction::KInductionResult::Proven { .. } => {
272 let new_preds = extract_refinement_predicates(
274 init,
275 transition,
276 property,
277 &predicates,
278 k,
279 );
280 if new_preds.is_empty() {
281 return AbstractionResult::SpuriousRefined {
282 new_predicates: predicates,
283 };
284 }
285 predicates.extend(new_preds);
286 }
287 _ => {
288 let new_preds = extract_refinement_predicates(
290 init,
291 transition,
292 property,
293 &predicates,
294 k,
295 );
296 if new_preds.is_empty() {
297 return AbstractionResult::SpuriousRefined {
298 new_predicates: predicates,
299 };
300 }
301 predicates.extend(new_preds);
302 }
303 }
304 }
305 kinduction::KInductionResult::InductionFailed { k, .. } => {
306 let concrete_result =
309 kinduction::k_induction(init, transition, property, &[], k.max(10));
310 match concrete_result {
311 kinduction::KInductionResult::Proven { .. } => {
312 return AbstractionResult::Safe;
313 }
314 kinduction::KInductionResult::Counterexample { trace, .. } => {
315 return AbstractionResult::Unsafe {
316 concrete_trace: trace,
317 };
318 }
319 _ => {
320 let new_preds = extract_refinement_predicates(
321 init,
322 transition,
323 property,
324 &predicates,
325 k,
326 );
327 if new_preds.is_empty() {
328 return AbstractionResult::Unknown;
329 }
330 predicates.extend(new_preds);
331 }
332 }
333 }
334 kinduction::KInductionResult::Unknown => {
335 return AbstractionResult::Unknown;
336 }
337 }
338 }
339
340 let final_result = kinduction::k_induction(init, transition, property, &[], 10);
342 match final_result {
343 kinduction::KInductionResult::Proven { .. } => AbstractionResult::Safe,
344 kinduction::KInductionResult::Counterexample { trace, .. } => AbstractionResult::Unsafe {
345 concrete_trace: trace,
346 },
347 _ => AbstractionResult::Unknown,
348 }
349}
350
351fn extract_refinement_predicates(
364 init: &VerifyExpr,
365 transition: &VerifyExpr,
366 property: &VerifyExpr,
367 existing_predicates: &[VerifyExpr],
368 _depth: u32,
369) -> Vec<VerifyExpr> {
370 let mut candidates = Vec::new();
371
372 collect_comparison_predicates(transition, &mut candidates);
374 collect_comparison_predicates(init, &mut candidates);
375 collect_comparison_predicates(property, &mut candidates);
376
377 for pred in existing_predicates {
379 if let VerifyExpr::Binary { op, left, right } = pred {
380 match op {
381 VerifyOp::Gte | VerifyOp::Gt | VerifyOp::Lte | VerifyOp::Lt => {
382 if let VerifyExpr::Int(n) = right.as_ref() {
383 candidates.push(VerifyExpr::binary(
384 *op,
385 *left.clone(),
386 VerifyExpr::int(n + 1),
387 ));
388 candidates.push(VerifyExpr::binary(
389 *op,
390 *left.clone(),
391 VerifyExpr::int(n - 1),
392 ));
393 }
394 }
395 _ => {}
396 }
397 }
398 }
399
400 let existing_dbg: HashSet<String> = existing_predicates
402 .iter()
403 .map(|p| format!("{:?}", p))
404 .collect();
405
406 let mut seen = HashSet::new();
407 let mut result = Vec::new();
408 for candidate in candidates {
409 let dbg = format!("{:?}", candidate);
410 if !existing_dbg.contains(&dbg) && seen.insert(dbg) {
411 result.push(candidate);
412 }
413 }
414
415 result
416}
417
418fn collect_comparison_predicates(expr: &VerifyExpr, out: &mut Vec<VerifyExpr>) {
420 match expr {
421 VerifyExpr::Binary { op, left, right } => {
422 match op {
423 VerifyOp::Gte
424 | VerifyOp::Gt
425 | VerifyOp::Lte
426 | VerifyOp::Lt
427 | VerifyOp::Eq
428 | VerifyOp::Neq => {
429 out.push(expr.clone());
430 }
431 _ => {}
432 }
433 collect_comparison_predicates(left, out);
434 collect_comparison_predicates(right, out);
435 }
436 VerifyExpr::Not(inner) => collect_comparison_predicates(inner, out),
437 VerifyExpr::Iff(l, r) => {
438 collect_comparison_predicates(l, out);
439 collect_comparison_predicates(r, out);
440 }
441 VerifyExpr::ForAll { body, .. } | VerifyExpr::Exists { body, .. } => {
442 collect_comparison_predicates(body, out);
443 }
444 _ => {}
445 }
446}
447
448fn encode_bool(expr: &VerifyExpr) -> Bool {
450 let mut bool_vars = HashMap::new();
451 let mut int_vars = HashMap::new();
452 let mut all_vars = HashSet::new();
453 crate::equivalence::collect_vars_pub(expr, &mut all_vars);
454 for name in &all_vars {
455 bool_vars.insert(name.clone(), Bool::new_const(name.as_str()));
456 }
457 crate::equivalence::collect_int_vars_pub(expr, &mut int_vars);
458 kinduction::encode_expr_bool(expr, &bool_vars, &int_vars)
459}