1#![doc = include_str!("../README.md")]
2
3pub mod ast;
14mod dl_theory;
15mod enum_theory;
16mod euf_theory;
17mod lra_theory;
18#[cfg(feature = "parser")]
19pub mod parser;
20#[cfg(feature = "profiling")]
21mod profiling;
22mod proxy;
23pub mod rational;
24mod sat_solver;
25#[cfg(feature = "solver")]
26pub mod solver;
27
28#[cfg(feature = "profiling")]
29use crate::profiling::{SmtProf, TheoryKind};
30use crate::{
31 ast::{ArithExpr, BoolExpr, EnumExpr, EufExpr, Expr},
32 dl_theory::DlTheory,
33 enum_theory::EnumTheory,
34 euf_theory::EufTheory,
35 lra_theory::{ArithVar, LraTheory, SparseRow, tighten_int_bound},
36 proxy::{ProxyRegistry, TheoryConstraint},
37 rational::{InfRational, Rational},
38 sat_solver::{Conflict, SatSolver},
39};
40pub use dl_theory::DlVar;
41pub use euf_theory::FuncId;
42use rug::Assign;
43use rustc_hash::FxHashSet;
44pub use sat_solver::{BoolVar, Lit};
45use tracing::trace;
46
47pub struct SeMiTONE {
53 registry: ProxyRegistry,
54 sat_solver: SatSolver,
55 lra_theory: LraTheory,
56 enum_theory: EnumTheory,
57 dl_theory: DlTheory,
58 euf_theory: EufTheory,
59 notified_len: usize,
60 #[cfg(feature = "profiling")]
61 prof: SmtProf,
62}
63
64impl Default for SeMiTONE {
65 fn default() -> Self {
66 Self::new()
67 }
68}
69
70impl SeMiTONE {
71 pub fn new() -> Self {
73 Self {
74 registry: ProxyRegistry::new(),
75 sat_solver: SatSolver::new(),
76 lra_theory: LraTheory::new(),
77 enum_theory: EnumTheory::new(),
78 dl_theory: DlTheory::new(),
79 euf_theory: EufTheory::new(),
80 notified_len: 0,
81 #[cfg(feature = "profiling")]
82 prof: SmtProf::default(),
83 }
84 }
85
86 pub fn new_lit(&mut self) -> Lit {
88 Lit::new(self.sat_solver.mk_var(), false)
89 }
90
91 pub fn new_bool(&mut self) -> BoolExpr {
93 BoolExpr::Var(self.sat_solver.mk_var())
94 }
95
96 pub fn new_int(&mut self) -> ArithExpr {
98 ArithExpr::IntVar(self.lra_theory.mk_int())
99 }
100
101 pub fn new_real(&mut self) -> ArithExpr {
103 ArithExpr::RealVar(self.lra_theory.mk_real())
104 }
105
106 pub fn new_enum(&mut self, domain: impl IntoIterator<Item = usize>) -> EnumExpr {
108 let domain_set: FxHashSet<usize> = domain.into_iter().collect();
109 let var = self.enum_theory.mk_var(domain_set.clone());
110
111 let lits: Vec<Lit> = domain_set.into_iter().map(|val| self.get_or_create_proxy(TheoryConstraint::EnumEq(var, val))).collect();
112
113 if !lits.is_empty() {
114 let _ = self.sat_solver.add_clause(lits.iter().copied());
116
117 for i in 0..lits.len() {
119 for j in (i + 1)..lits.len() {
120 let _ = self.sat_solver.add_clause([!lits[i], !lits[j]]);
121 }
122 }
123 }
124
125 EnumExpr::Var(var)
126 }
127
128 pub fn new_dl_var(&mut self) -> DlVar {
130 self.dl_theory.mk_var()
131 }
132
133 pub fn new_euf_var(&mut self) -> EufExpr {
135 EufExpr::Var(self.euf_theory.new_var())
136 }
137
138 pub fn new_euf_func(&mut self) -> FuncId {
140 self.euf_theory.new_func_id()
141 }
142
143 pub fn new_euf_app(&mut self, func_id: FuncId, args: Vec<Expr>) -> EufExpr {
145 let mut internal_args = Vec::with_capacity(args.len());
146 for arg in &args {
147 if let Expr::Euf(euf_arg) = arg {
148 internal_args.push(euf_arg.node());
149 } else {
150 panic!("EUF application arguments must be EUF expressions, but got: {:?}", arg);
151 }
152 }
153
154 let node_id = self.euf_theory.new_app(func_id, internal_args);
155 EufExpr::App(node_id, func_id, args)
156 }
157
158 pub fn num_vars(&self) -> usize {
163 self.sat_solver.num_vars()
164 }
165
166 pub fn add_clause(&mut self, clause: impl IntoIterator<Item = Lit>) -> Result<(), Conflict> {
171 self.sat_solver.add_clause(clause)
172 }
173
174 pub fn add_clauses(&mut self, clauses: impl IntoIterator<Item = Vec<Lit>>) -> Result<(), Conflict> {
176 for clause in clauses {
177 self.sat_solver.add_clause(clause)?;
178 }
179 Ok(())
180 }
181
182 pub fn assert(&mut self, expr: impl AsRef<BoolExpr>) -> Result<(), Conflict> {
189 self.assert_internal(expr.as_ref(), true)
190 }
191
192 fn assert_internal(&mut self, expr: &BoolExpr, polarity: bool) -> Result<(), Conflict> {
193 match (expr, polarity) {
194 (BoolExpr::Not(inner), _) => self.assert_internal(inner, !polarity),
195 (BoolExpr::And(args), true) | (BoolExpr::Or(args), false) => {
196 for arg in args {
197 self.assert_internal(arg, polarity)?;
198 }
199 Ok(())
200 }
201 (BoolExpr::Or(args), true) | (BoolExpr::And(args), false) => {
202 let mut clause = Vec::with_capacity(args.len());
203 for arg in args {
204 let lit = self.encode_bool(arg)?;
205 let target_lit = if polarity { lit } else { !lit };
206 match self.get_lit_val_and_level(target_lit) {
207 Some((true, 0)) => return Ok(()),
208 Some((false, 0)) => continue,
209 _ => clause.push(target_lit),
210 }
211 }
212 self.add_clause(clause)
213 }
214 (BoolExpr::Lt(e1, e2), true) | (BoolExpr::Ge(e1, e2), false) => {
215 let lit = self.mk_le(e1, e2, true);
216 self.add_clause([lit])
217 }
218 (BoolExpr::Le(e1, e2), true) | (BoolExpr::Gt(e1, e2), false) => {
219 let lit = self.mk_le(e1, e2, false);
220 self.add_clause([lit])
221 }
222 (BoolExpr::Ge(e1, e2), true) | (BoolExpr::Lt(e1, e2), false) => {
223 let lit = self.mk_ge(e1, e2, false);
224 self.add_clause([lit])
225 }
226 (BoolExpr::Gt(e1, e2), true) | (BoolExpr::Le(e1, e2), false) => {
227 let lit = self.mk_ge(e1, e2, true);
228 self.add_clause([lit])
229 }
230 _ => {
231 let lit = self.encode_bool(expr)?;
232 let target_lit = if polarity { lit } else { !lit };
233 self.add_clause([target_lit])
234 }
235 }
236 }
237
238 pub fn track_expr(&mut self, expr: impl AsRef<BoolExpr>) -> Result<Lit, Conflict> {
246 self.encode_bool(expr.as_ref())
247 }
248
249 fn encode_bool(&mut self, expr: &BoolExpr) -> Result<Lit, Conflict> {
250 match expr {
251 BoolExpr::True => Ok(Lit::TRUE),
252 BoolExpr::False => Ok(Lit::FALSE),
253 BoolExpr::Var(v) => Ok(Lit::new(*v, false)),
254
255 BoolExpr::Not(inner) => match inner.as_ref() {
256 BoolExpr::Lt(a1, a2) => Ok(self.mk_ge(a1, a2, false)),
257 BoolExpr::Le(a1, a2) => Ok(self.mk_ge(a1, a2, true)),
258 BoolExpr::Ge(a1, a2) => Ok(self.mk_le(a1, a2, true)),
259 BoolExpr::Gt(a1, a2) => Ok(self.mk_le(a1, a2, false)),
260 BoolExpr::DlLt(from, to, b) => Ok(self.mk_dl_ge(*from, *to, b.clone(), false)),
261 BoolExpr::DlLe(from, to, b) => Ok(self.mk_dl_ge(*from, *to, b.clone(), true)),
262 BoolExpr::DlGe(from, to, b) => Ok(self.mk_dl_le(*from, *to, b.clone(), true)),
263 BoolExpr::DlGt(from, to, b) => Ok(self.mk_dl_le(*from, *to, b.clone(), false)),
264 _ => Ok(!self.encode_bool(inner)?),
265 },
266
267 BoolExpr::And(terms) => {
268 let mut lits = Vec::with_capacity(terms.len());
269 for term in terms {
270 let lit = self.encode_bool(term)?;
271 match self.get_lit_val_and_level(lit) {
272 Some((false, 0)) => return Ok(Lit::FALSE),
273 Some((true, 0)) => continue,
274 _ => {
275 if lits.contains(&!lit) {
276 return Ok(Lit::FALSE);
277 }
278 if !lits.contains(&lit) {
279 lits.push(lit);
280 }
281 }
282 }
283 }
284
285 match lits.len() {
286 0 => Ok(Lit::TRUE),
287 1 => Ok(lits[0]),
288 _ => {
289 let proxy_var = self.sat_solver.mk_var();
290 let proxy_lit = Lit::new(proxy_var, true);
291 let mut clauses = Vec::with_capacity(lits.len() + 1);
292
293 for &lit in &lits {
294 clauses.push(vec![!proxy_lit, lit]);
295 }
296
297 let mut big_clause: Vec<Lit> = lits.iter().map(|&l| !l).collect();
298 big_clause.push(proxy_lit);
299 clauses.push(big_clause);
300
301 self.add_clauses(clauses)?;
302 Ok(proxy_lit)
303 }
304 }
305 }
306
307 BoolExpr::Or(terms) => {
308 let mut lits = Vec::with_capacity(terms.len());
309 for term in terms {
310 let lit = self.encode_bool(term)?;
311 match self.get_lit_val_and_level(lit) {
312 Some((true, 0)) => return Ok(Lit::TRUE),
313 Some((false, 0)) => continue,
314 _ => {
315 if lits.contains(&!lit) {
316 return Ok(Lit::TRUE);
317 }
318 if !lits.contains(&lit) {
319 lits.push(lit);
320 }
321 }
322 }
323 }
324
325 match lits.len() {
326 0 => Ok(Lit::FALSE),
327 1 => Ok(lits[0]),
328 _ => {
329 let proxy_var = self.sat_solver.mk_var();
330 let proxy_lit = Lit::new(proxy_var, true);
331 let mut clauses = Vec::with_capacity(lits.len() + 1);
332
333 for &lit in &lits {
334 clauses.push(vec![!lit, proxy_lit]);
335 }
336
337 let mut big_clause = lits;
338 big_clause.push(!proxy_lit);
339 clauses.push(big_clause);
340
341 self.add_clauses(clauses)?;
342 Ok(proxy_lit)
343 }
344 }
345 }
346 BoolExpr::Lt(e1, e2) => Ok(self.mk_le(e1, e2, true)),
347 BoolExpr::Le(e1, e2) => Ok(self.mk_le(e1, e2, false)),
348 BoolExpr::Ge(e1, e2) => Ok(self.mk_ge(e1, e2, false)),
349 BoolExpr::Gt(e1, e2) => Ok(self.mk_ge(e1, e2, true)),
350
351 BoolExpr::Eq(e1, e2) => self.encode_eq(e1, e2),
352
353 BoolExpr::DlLt(from, to, b) => Ok(self.mk_dl_le(*from, *to, b.clone(), true)),
354 BoolExpr::DlLe(from, to, b) => Ok(self.mk_dl_le(*from, *to, b.clone(), false)),
355 BoolExpr::DlGt(from, to, b) => Ok(self.mk_dl_ge(*from, *to, b.clone(), true)),
356 BoolExpr::DlGe(from, to, b) => Ok(self.mk_dl_ge(*from, *to, b.clone(), false)),
357
358 BoolExpr::DlEq(from, to, b) => self.mk_dl_eq(*from, *to, b.clone()),
359 }
360 }
361
362 fn encode_eq(&mut self, expr1: &Expr, expr2: &Expr) -> Result<Lit, Conflict> {
363 match (expr1, expr2) {
364 (Expr::Arith(a1), Expr::Arith(a2)) => self.mk_arith_eq(a1, a2),
365 (Expr::Bool(b1), Expr::Bool(b2)) => {
366 let l1 = self.encode_bool(b1)?;
367 let l2 = self.encode_bool(b2)?;
368
369 if l1 == l2 {
370 return Ok(Lit::TRUE);
371 }
372 if l1 == !l2 {
373 return Ok(Lit::FALSE);
374 }
375 if let Some((val, 0)) = self.get_lit_val_and_level(l1) {
376 return Ok(if val { l2 } else { !l2 });
377 }
378 if let Some((val, 0)) = self.get_lit_val_and_level(l2) {
379 return Ok(if val { l1 } else { !l1 });
380 }
381
382 let p = self.new_lit();
383 self.add_clauses([vec![!p, l1, !l2], vec![!p, !l1, l2], vec![p, l1, l2], vec![p, !l1, !l2]])?;
384 Ok(p)
385 }
386 (Expr::Enum(e1), Expr::Enum(e2)) => self.mk_enum_eq(e1, e2),
387 (Expr::Euf(u1), Expr::Euf(u2)) => {
388 let (id1, id2) = (u1.node(), u2.node());
389 if id1 == id2 {
390 return Ok(Lit::TRUE);
391 }
392 let (min_id, max_id) = if id1 < id2 { (id1, id2) } else { (id2, id1) };
393 Ok(self.get_or_create_proxy(TheoryConstraint::EufEq(min_id, max_id)))
394 }
395 _ => panic!("Type mismatch in Eq: cannot compare different domains.\nLeft: {:?}\nRight: {:?}", expr1, expr2),
396 }
397 }
398
399 fn mk_enum_eq(&mut self, e1: &EnumExpr, e2: &EnumExpr) -> Result<Lit, Conflict> {
400 match (e1, e2) {
401 (EnumExpr::Const(c1), EnumExpr::Const(c2)) => {
402 if c1 == c2 {
403 Ok(Lit::TRUE)
404 } else {
405 Ok(Lit::FALSE)
406 }
407 }
408 (EnumExpr::Var(v), EnumExpr::Const(c)) | (EnumExpr::Const(c), EnumExpr::Var(v)) => Ok(self.get_or_create_proxy(TheoryConstraint::EnumEq(*v, *c))),
409 (EnumExpr::Var(v1), EnumExpr::Var(v2)) => {
410 if v1 == v2 {
411 return Ok(Lit::TRUE);
412 }
413
414 let common: Vec<usize> = self.enum_theory.initial_domain(*v1).intersection(self.enum_theory.initial_domain(*v2)).copied().collect();
415
416 if common.is_empty() {
417 return Ok(Lit::FALSE);
418 }
419
420 let mut clauses = Vec::new();
421 let mut lits = Vec::with_capacity(common.len());
422 for val in common {
423 let p1 = self.get_or_create_proxy(TheoryConstraint::EnumEq(*v1, val));
424 let p2 = self.get_or_create_proxy(TheoryConstraint::EnumEq(*v2, val));
425
426 match (self.get_lit_val_and_level(p1), self.get_lit_val_and_level(p2)) {
427 (Some((false, 0)), _) | (_, Some((false, 0))) => continue,
428 (Some((true, 0)), Some((true, 0))) => return Ok(Lit::TRUE),
429 (Some((true, 0)), _) => lits.push(p2),
430 (_, Some((true, 0))) => lits.push(p1),
431 _ => {
432 let and_proxy_var = self.sat_solver.mk_var();
433 let and_proxy = Lit::new(and_proxy_var, false);
434
435 clauses.push(vec![!and_proxy, p1]);
436 clauses.push(vec![!and_proxy, p2]);
437 clauses.push(vec![!p1, !p2, and_proxy]);
438
439 lits.push(and_proxy);
440 }
441 }
442 }
443
444 match lits.len() {
445 0 => Ok(Lit::FALSE),
446 1 => {
447 self.add_clauses(clauses)?;
448 Ok(lits[0])
449 }
450 _ => {
451 let or_proxy_var = self.sat_solver.mk_var();
452 let or_proxy = Lit::new(or_proxy_var, false);
453
454 for &lit in &lits {
455 clauses.push(vec![!lit, or_proxy]);
456 }
457
458 let mut big_clause = lits;
459 big_clause.push(!or_proxy);
460 clauses.push(big_clause);
461
462 self.add_clauses(clauses)?;
463 Ok(or_proxy)
464 }
465 }
466 }
467 }
468 }
469
470 #[inline]
471 fn mk_le(&mut self, e1: &ArithExpr, e2: &ArithExpr, strict: bool) -> Lit {
472 self.mk_ineq(e1, e2, true, strict)
473 }
474
475 #[inline]
476 fn mk_ge(&mut self, e1: &ArithExpr, e2: &ArithExpr, strict: bool) -> Lit {
477 self.mk_ineq(e1, e2, false, strict)
478 }
479
480 fn mk_ineq(&mut self, e1: &ArithExpr, e2: &ArithExpr, is_upper_bound: bool, strict: bool) -> Lit {
481 let (vars, const_term) = self.diff(e1, e2);
482
483 match vars.len() {
484 0 => {
485 let is_sat = if is_upper_bound { if strict { const_term.is_negative() } else { !const_term.is_positive() } } else { if strict { const_term.is_positive() } else { !const_term.is_negative() } };
486 if is_sat { Lit::TRUE } else { Lit::FALSE }
487 }
488 1 => {
489 let (var, coeff) = vars.iter().next().unwrap();
490 let is_int = self.lra_theory.is_int_var(*var);
491 let is_upper_for_var = is_upper_bound == coeff.is_positive();
492
493 let bound = if is_int {
494 let val = -const_term / coeff.clone();
495 let tight_val = tighten_int_bound(val, is_upper_for_var, strict);
496 InfRational::new(Rational::Finite(tight_val), rug::Rational::from(0))
497 } else {
498 let eps_shift = if strict { if is_upper_bound { rug::Rational::from(-1) } else { rug::Rational::from(1) } } else { rug::Rational::from(0) };
499 InfRational::new(Rational::Finite(-const_term / coeff.clone()), eps_shift / coeff)
500 };
501
502 if self.sat_solver.decision_level() == 0 {
503 if is_upper_for_var {
504 if self.lra_theory.ub(*var) <= &bound {
505 return Lit::TRUE;
506 }
507 if self.lra_theory.lb(*var) > &bound {
508 return Lit::FALSE;
509 }
510 } else {
511 if self.lra_theory.lb(*var) >= &bound {
512 return Lit::TRUE;
513 }
514 if self.lra_theory.ub(*var) < &bound {
515 return Lit::FALSE;
516 }
517 }
518 }
519
520 let constraint = if is_upper_for_var { TheoryConstraint::LraUb(*var, bound) } else { TheoryConstraint::LraLb(*var, bound) };
521 self.get_or_create_proxy(constraint)
522 }
523 _ => {
524 let slack = self.lra_theory.get_or_create_slack(vars);
525 let is_int = self.lra_theory.is_int_var(slack);
526
527 let bound = if is_int {
528 let tight_val = tighten_int_bound(-const_term, is_upper_bound, strict);
529 InfRational::new(Rational::Finite(tight_val), rug::Rational::from(0))
530 } else {
531 let eps_shift = if strict { if is_upper_bound { rug::Rational::from(-1) } else { rug::Rational::from(1) } } else { rug::Rational::from(0) };
532 InfRational::new(Rational::Finite(-const_term), eps_shift)
533 };
534
535 if self.sat_solver.decision_level() == 0 {
536 if is_upper_bound {
537 if self.lra_theory.ub(slack) <= &bound {
538 return Lit::TRUE;
539 }
540 if self.lra_theory.lb(slack) > &bound {
541 return Lit::FALSE;
542 }
543 } else {
544 if self.lra_theory.lb(slack) >= &bound {
545 return Lit::TRUE;
546 }
547 if self.lra_theory.ub(slack) < &bound {
548 return Lit::FALSE;
549 }
550 }
551 }
552
553 let constraint = if is_upper_bound { TheoryConstraint::LraUb(slack, bound) } else { TheoryConstraint::LraLb(slack, bound) };
554 self.get_or_create_proxy(constraint)
555 }
556 }
557 }
558
559 fn mk_arith_eq(&mut self, e1: &ArithExpr, e2: &ArithExpr) -> Result<Lit, Conflict> {
560 if e1 == e2 {
561 return Ok(Lit::TRUE);
562 }
563
564 let le_lit = self.mk_le(e1, e2, false);
565 let ge_lit = self.mk_ge(e1, e2, false);
566
567 match (self.get_lit_val_and_level(le_lit), self.get_lit_val_and_level(ge_lit)) {
568 (Some((false, 0)), _) | (_, Some((false, 0))) => return Ok(Lit::FALSE),
569 (Some((true, 0)), Some((true, 0))) => return Ok(Lit::TRUE),
570 (Some((true, 0)), _) => return Ok(ge_lit),
571 (_, Some((true, 0))) => return Ok(le_lit),
572 _ => {}
573 }
574
575 let p = self.new_lit();
576 self.add_clauses([vec![!p, le_lit], vec![!p, ge_lit], vec![!le_lit, !ge_lit, p]])?;
577 Ok(p)
578 }
579
580 fn mk_dl_le(&mut self, from: DlVar, to: DlVar, bound: rug::Rational, strict: bool) -> Lit {
581 let delta = if strict { rug::Rational::from(-1) } else { rug::Rational::from(0) };
582 let inf_bound = InfRational::new(Rational::Finite(bound), delta);
583
584 let constraint = TheoryConstraint::DlLeq(from, to, inf_bound);
585 self.get_or_create_proxy(constraint)
586 }
587
588 fn mk_dl_ge(&mut self, from: DlVar, to: DlVar, bound: rug::Rational, strict: bool) -> Lit {
589 self.mk_dl_le(to, from, -bound, strict)
590 }
591
592 fn mk_dl_eq(&mut self, from: DlVar, to: DlVar, bound: rug::Rational) -> Result<Lit, Conflict> {
593 let le_lit = self.mk_dl_le(from, to, bound.clone(), false);
594 let ge_lit = self.mk_dl_ge(from, to, bound, false);
595
596 match (self.get_lit_val_and_level(le_lit), self.get_lit_val_and_level(ge_lit)) {
597 (Some((false, 0)), _) | (_, Some((false, 0))) => return Ok(Lit::FALSE),
598 (Some((true, 0)), Some((true, 0))) => return Ok(Lit::TRUE),
599 (Some((true, 0)), _) => return Ok(ge_lit),
600 (_, Some((true, 0))) => return Ok(le_lit),
601 _ => {}
602 }
603
604 let p = self.new_lit();
605 self.add_clauses([vec![!p, le_lit], vec![!p, ge_lit], vec![!le_lit, !ge_lit, p]])?;
606 Ok(p)
607 }
608
609 fn diff(&self, e1: &ArithExpr, e2: &ArithExpr) -> (SparseRow, rug::Rational) {
610 let mut vars = SparseRow::new();
611 let mut const_term = rug::Rational::from(0);
612
613 let pos_one = rug::Rational::from(1);
614 let neg_one = rug::Rational::from(-1);
615
616 let mut temp = rug::Rational::new();
617
618 self.accumulate_expr(e1, &pos_one, &mut vars, &mut const_term, &mut temp);
619 self.accumulate_expr(e2, &neg_one, &mut vars, &mut const_term, &mut temp);
620
621 vars.retain(|_, c| *c != 0);
622
623 (vars, const_term)
624 }
625
626 fn accumulate_expr(&self, expr: &ArithExpr, scale: &rug::Rational, vars: &mut SparseRow, const_term: &mut rug::Rational, temp: &mut rug::Rational) {
627 match expr {
628 ArithExpr::Const(c) => {
629 temp.assign(c * scale);
630 *const_term += &*temp;
631 }
632 ArithExpr::IntVar(var) => {
633 self.accumulate_var(*var, scale, vars, temp);
634 }
635 ArithExpr::RealVar(var) => {
636 self.accumulate_var(*var, scale, vars, temp);
637 }
638 ArithExpr::Add(terms) => {
639 for term in terms {
640 self.accumulate_expr(term, scale, vars, const_term, temp);
641 }
642 }
643 ArithExpr::Mul(terms) => {
644 if terms.len() != 2 {
645 panic!("Only binary multiplication is supported in linear arithmetic");
646 }
647 let (first, second) = (&terms[0], &terms[1]);
648
649 match (first, second) {
651 (ArithExpr::Const(c), sub_expr) | (sub_expr, ArithExpr::Const(c)) => {
652 let mut new_scale = rug::Rational::new();
653 new_scale.assign(c * scale);
654 self.accumulate_expr(sub_expr, &new_scale, vars, const_term, temp);
655 }
656 _ => {
657 panic!("Non-linear arithmetic: multiplication between two non-constant expressions is not supported");
658 }
659 }
660 }
661 ArithExpr::Div(numerator, denominator) => {
662 if let ArithExpr::Const(c) = &**denominator {
664 if c.is_zero() {
665 panic!("Division by zero detected in AST");
666 }
667 let mut div_scale = rug::Rational::new();
668 div_scale.assign(scale / c);
669 self.accumulate_expr(numerator, &div_scale, vars, const_term, temp);
670 } else {
671 panic!("Non-linear arithmetic: division by a non-constant expression is not supported");
672 }
673 }
674 ArithExpr::Neg(sub_expr) => {
675 let mut neg_scale = rug::Rational::new();
676 neg_scale.assign(scale * -1);
677 self.accumulate_expr(sub_expr, &neg_scale, vars, const_term, temp);
678 }
679 }
680 }
681
682 fn accumulate_var(&self, var: ArithVar, scale: &rug::Rational, vars: &mut SparseRow, temp: &mut rug::Rational) {
683 if let Some(basic_row) = self.lra_theory.tableau[var].as_ref() {
684 for (sub_var, sub_coeff) in basic_row.iter() {
685 temp.assign(sub_coeff * scale);
686 vars.add_coeff(*sub_var, temp);
687 }
688 } else {
689 vars.add_coeff(var, scale);
690 }
691 }
692
693 fn get_or_create_proxy(&mut self, constraint: TheoryConstraint) -> Lit {
694 if let Some(sat_var) = self.registry.get_proxy(&constraint) {
695 Lit::new(sat_var, false)
696 } else {
697 let sat_var = self.sat_solver.mk_var();
698 self.registry.register(constraint, sat_var);
699 Lit::new(sat_var, false)
700 }
701 }
702
703 pub fn decide(&mut self, lit: Lit) -> bool {
712 self.sat_solver.push_decision();
713 self.lra_theory.push();
714 self.enum_theory.push();
715 self.dl_theory.push();
716 self.euf_theory.push();
717 self.sat_solver.enqueue_decision(lit)
718 }
719
720 pub fn decide_enum(&mut self, expr: impl AsRef<EnumExpr>, value: usize) -> bool {
725 let var = match expr.as_ref() {
726 EnumExpr::Var(v) => *v,
727 EnumExpr::Const(_) => panic!("Cannot decide on a constant value"),
728 };
729
730 let lit = self.get_or_create_proxy(TheoryConstraint::EnumEq(var, value));
731 self.decide(lit)
732 }
733
734 pub fn decision_level(&self) -> usize {
738 self.sat_solver.decision_level()
739 }
740
741 pub fn cancel_until(&mut self, level: usize) -> Vec<Lit> {
747 #[cfg(feature = "profiling")]
748 let t0 = SmtProf::start();
749 let retracted = self.sat_solver.cancel_until(level);
750 self.lra_theory.cancel_until(level);
751 self.enum_theory.cancel_until(level);
752 self.dl_theory.cancel_until(level);
753 self.euf_theory.cancel_until(level);
754
755 self.notified_len = self.sat_solver.trail.len();
756 #[cfg(feature = "profiling")]
757 self.prof.stop_cancel(t0);
758 retracted
759 }
760
761 pub fn get_trail_delta(&self, from_index: usize) -> &[Lit] {
765 &self.sat_solver.trail[from_index..]
766 }
767
768 pub fn current_trail_len(&self) -> usize {
770 self.sat_solver.trail.len()
771 }
772
773 pub fn user_scopes_len(&self) -> usize {
775 self.sat_solver.floor_level()
776 }
777
778 pub fn propagate(&mut self) -> Result<(), (usize, Vec<Lit>)> {
787 #[cfg(feature = "profiling")]
788 self.prof.on_prop_call();
789
790 let base_level = self.user_scopes_len();
791 #[cfg(feature = "profiling")]
792 let t0 = SmtProf::start();
793 let sat_res = self.sat_solver.propagate();
794 #[cfg(feature = "profiling")]
795 self.prof.stop_sat_prop(t0);
796 if let Err((bt_level, conflict)) = sat_res {
797 #[cfg(feature = "profiling")]
798 self.prof.on_sat_conflict();
799 return Err((bt_level.max(base_level), conflict));
800 }
801
802 while self.notified_len < self.sat_solver.trail.len() {
803 let lit = self.sat_solver.trail[self.notified_len];
804
805 if let Some(constraint) = self.registry.get_constraint(lit.var()) {
806 #[cfg(feature = "profiling")]
807 let kind = TheoryKind::of(constraint);
808 #[cfg(feature = "profiling")]
809 let t0 = SmtProf::start();
810 let theory_result = match (constraint, lit.sign()) {
811 (TheoryConstraint::LraLb(var, bound), false) => self.lra_theory.set_lb(Some(lit), *var, bound.clone()),
812 (TheoryConstraint::LraLb(var, bound), true) => {
813 let new_bound = if self.lra_theory.is_int_var(*var) {
814 if let Rational::Finite(r) = bound.rational_part() {
815 let tight_val = tighten_int_bound(r.clone(), true, true);
816 InfRational::new(Rational::Finite(tight_val), rug::Rational::from(0))
817 } else {
818 unreachable!()
819 }
820 } else {
821 InfRational::new(bound.rational_part().clone(), if bound.infinitesimal_part().is_positive() { rug::Rational::from(0) } else { rug::Rational::from(-1) })
822 };
823 self.lra_theory.set_ub(Some(lit), *var, new_bound)
824 }
825 (TheoryConstraint::LraUb(var, bound), false) => self.lra_theory.set_ub(Some(lit), *var, bound.clone()),
826 (TheoryConstraint::LraUb(var, bound), true) => {
827 let new_bound = if self.lra_theory.is_int_var(*var) {
828 if let Rational::Finite(r) = bound.rational_part() {
829 let tight_val = tighten_int_bound(r.clone(), false, true);
830 InfRational::new(Rational::Finite(tight_val), rug::Rational::from(0))
831 } else {
832 unreachable!()
833 }
834 } else {
835 InfRational::new(bound.rational_part().clone(), if bound.infinitesimal_part().is_negative() { rug::Rational::from(0) } else { rug::Rational::from(1) })
836 };
837 self.lra_theory.set_lb(Some(lit), *var, new_bound)
838 }
839 (TheoryConstraint::EnumEq(var, val), false) => self.enum_theory.set_eq(Some(lit), *var, *val),
840 (TheoryConstraint::EnumEq(var, val), true) => self.enum_theory.set_neq(Some(lit), *var, *val),
841 (TheoryConstraint::DlLeq(from, to, bound), false) => self.dl_theory.assert_edge(*from, *to, bound.clone(), lit),
842 (TheoryConstraint::DlLeq(from, to, bound), true) => {
843 let rat_part = bound.rational_part().clone();
844 let neg_rat = match rat_part {
845 Rational::Finite(val) => Rational::Finite(-val),
846 Rational::PositiveInf => Rational::NegativeInf,
847 Rational::NegativeInf => Rational::PositiveInf,
848 };
849
850 let neg_inf = -bound.infinitesimal_part().clone() - rug::Rational::from(1);
851 let neg_bound = InfRational::new(neg_rat, neg_inf);
852
853 self.dl_theory.assert_edge(*to, *from, neg_bound, lit)
854 }
855 (TheoryConstraint::EufEq(t1, t2), false) => {
856 self.euf_theory.merge(*t1, *t2, Some(lit));
857 self.euf_theory.propagate_congruences();
858 self.euf_theory.check_disequalities()
859 }
860 (TheoryConstraint::EufEq(t1, t2), true) => {
861 self.euf_theory.propagate_congruences();
862 self.euf_theory.assert_disequality(*t1, *t2, lit)
863 }
864 };
865 #[cfg(feature = "profiling")]
866 self.prof.stop_notify(t0, kind);
867
868 if let Err(lemma) = theory_result {
869 #[cfg(feature = "profiling")]
870 self.prof.on_notify_conflict(kind);
871 #[cfg(feature = "profiling")]
872 let ta = SmtProf::start();
873 let res = self.sat_solver.analyze_conflict(&lemma);
874 #[cfg(feature = "profiling")]
875 self.prof.stop_analyze(ta);
876 return Err(res);
877 }
878 }
879 self.notified_len += 1;
880 }
881
882 #[cfg(feature = "profiling")]
883 let t0 = SmtProf::start();
884 let lra_res = self.lra_theory.check();
885 #[cfg(feature = "profiling")]
886 self.prof.stop_lra_check(t0);
887 if let Err(conflict) = lra_res {
888 #[cfg(feature = "profiling")]
889 self.prof.on_lra_check_conflict();
890 #[cfg(feature = "profiling")]
891 let ta = SmtProf::start();
892 let res = self.sat_solver.analyze_conflict(&conflict);
893 #[cfg(feature = "profiling")]
894 self.prof.stop_analyze(ta);
895 return Err(res);
896 }
897 Ok(())
898 }
899
900 pub fn probe_implied(&mut self, assumptions: &[Lit]) -> Result<Option<Vec<Lit>>, (usize, Vec<Lit>)> {
908 let init_level = self.decision_level();
909 'probe_loop: loop {
910 if let Err((bt_level, lemma)) = self.propagate() {
911 if self.decision_level() == 0 || bt_level < init_level {
912 return Err((bt_level, lemma));
913 }
914 self.cancel_until(bt_level);
915 let mut cur_lemma = lemma;
916 while let Err((next_bt, next_lemma)) = self.add_clause(cur_lemma) {
917 if self.decision_level() == 0 || next_bt < init_level {
918 return Err((next_bt, next_lemma));
919 }
920 self.cancel_until(next_bt);
921 cur_lemma = next_lemma;
922 }
923 continue 'probe_loop;
924 }
925
926 for &lit in assumptions {
927 match self.get_lit_val(lit) {
928 Some(true) => continue,
929 Some(false) => {
930 if self.decision_level() > init_level {
931 self.cancel_until(init_level);
932 }
933 return Ok(None);
934 }
935 None => {
936 self.decide(lit);
937 continue 'probe_loop;
938 }
939 }
940 }
941
942 let implied = if self.decision_level() > init_level { self.cancel_until(init_level) } else { Vec::new() };
943 return Ok(Some(implied));
944 }
945 }
946
947 pub fn probe(&mut self, assumptions: &[Lit]) -> Result<bool, (usize, Vec<Lit>)> {
949 self.probe_implied(assumptions).map(|opt| opt.is_some())
950 }
951
952 #[inline]
954 pub fn get_lit_level(&self, lit: Lit) -> Option<usize> {
955 self.sat_solver.lit_level(lit)
956 }
957
958 #[inline]
960 pub fn get_lit_val(&self, lit: Lit) -> Option<bool> {
961 self.sat_solver.lit_value(lit)
962 }
963
964 #[inline]
966 pub fn get_lit_antecedents(&self, lit: Lit) -> Option<&[Lit]> {
967 self.sat_solver.lit_antecedents(lit)
968 }
969
970 #[inline]
972 pub fn get_lit_val_and_level(&self, lit: Lit) -> Option<(bool, usize)> {
973 self.sat_solver.lit_value_and_level(lit)
974 }
975
976 pub fn vars(&self) -> impl ExactSizeIterator<Item = BoolVar> {
978 self.sat_solver.vars()
979 }
980
981 pub fn get_bool_val(&self, expr: impl AsRef<BoolExpr>) -> Option<bool> {
983 match expr.as_ref() {
984 BoolExpr::True => Some(true),
985 BoolExpr::False => Some(false),
986 BoolExpr::Var(v) => self.sat_solver.value(*v),
987 BoolExpr::Not(inner) => self.get_bool_val(inner).map(|val| !val),
988 BoolExpr::And(args) => {
989 let mut result = Some(true);
990 for arg in args {
991 match self.get_bool_val(arg) {
992 Some(val) => {
993 if !val {
994 return Some(false);
995 }
996 }
997 None => result = None,
998 }
999 }
1000 result
1001 }
1002 BoolExpr::Or(args) => {
1003 let mut result = Some(false);
1004 for arg in args {
1005 match self.get_bool_val(arg) {
1006 Some(val) => {
1007 if val {
1008 return Some(true);
1009 }
1010 }
1011 None => result = None,
1012 }
1013 }
1014 result
1015 }
1016 BoolExpr::Lt(e1, e2) => {
1017 let (lb1, ub1) = self.get_arith_bounds(e1)?;
1018 let (lb2, ub2) = self.get_arith_bounds(e2)?;
1019 if ub1 < lb2 {
1020 Some(true)
1021 } else if lb1 >= ub2 {
1022 Some(false)
1023 } else {
1024 None
1025 }
1026 }
1027 BoolExpr::Le(e1, e2) => {
1028 let (lb1, ub1) = self.get_arith_bounds(e1)?;
1029 let (lb2, ub2) = self.get_arith_bounds(e2)?;
1030 if ub1 <= lb2 {
1031 Some(true)
1032 } else if lb1 > ub2 {
1033 Some(false)
1034 } else {
1035 None
1036 }
1037 }
1038 BoolExpr::Ge(e1, e2) => {
1039 let (lb1, ub1) = self.get_arith_bounds(e1)?;
1040 let (lb2, ub2) = self.get_arith_bounds(e2)?;
1041 if lb1 >= ub2 {
1042 Some(true)
1043 } else if ub1 < lb2 {
1044 Some(false)
1045 } else {
1046 None
1047 }
1048 }
1049 BoolExpr::Gt(e1, e2) => {
1050 let (lb1, ub1) = self.get_arith_bounds(e1)?;
1051 let (lb2, ub2) = self.get_arith_bounds(e2)?;
1052 if lb1 > ub2 {
1053 Some(true)
1054 } else if ub1 <= lb2 {
1055 Some(false)
1056 } else {
1057 None
1058 }
1059 }
1060 BoolExpr::DlLt(from, to, bound) => {
1061 let (lb_from, ub_from) = self.get_dl_bounds(*from);
1062 let (lb_to, ub_to) = self.get_dl_bounds(*to);
1063 let bound_inf = InfRational::new(Rational::Finite(bound.clone()), rug::Rational::from(0));
1064
1065 let max_dist = ub_to.clone() - lb_from.clone();
1068 let min_dist = lb_to - ub_from;
1069
1070 if max_dist < bound_inf {
1071 Some(true)
1072 } else if min_dist >= bound_inf {
1073 Some(false)
1074 } else {
1075 None
1076 }
1077 }
1078 BoolExpr::DlLe(from, to, bound) => {
1079 let (lb_from, ub_from) = self.get_dl_bounds(*from);
1080 let (lb_to, ub_to) = self.get_dl_bounds(*to);
1081 let bound_inf = InfRational::new(Rational::Finite(bound.clone()), rug::Rational::from(0));
1082
1083 let max_dist = ub_to.clone() - lb_from.clone();
1084 let min_dist = lb_to - ub_from;
1085
1086 if max_dist <= bound_inf {
1087 Some(true)
1088 } else if min_dist > bound_inf {
1089 Some(false)
1090 } else {
1091 None
1092 }
1093 }
1094 BoolExpr::DlGt(from, to, bound) => {
1095 let (lb_from, ub_from) = self.get_dl_bounds(*from);
1096 let (lb_to, ub_to) = self.get_dl_bounds(*to);
1097 let bound_inf = InfRational::new(Rational::Finite(bound.clone()), rug::Rational::from(0));
1098
1099 let max_dist = ub_to.clone() - lb_from.clone();
1100 let min_dist = lb_to - ub_from;
1101
1102 if min_dist > bound_inf {
1103 Some(true)
1104 } else if max_dist <= bound_inf {
1105 Some(false)
1106 } else {
1107 None
1108 }
1109 }
1110 BoolExpr::DlGe(from, to, bound) => {
1111 let (lb_from, ub_from) = self.get_dl_bounds(*from);
1112 let (lb_to, ub_to) = self.get_dl_bounds(*to);
1113 let bound_inf = InfRational::new(Rational::Finite(bound.clone()), rug::Rational::from(0));
1114
1115 let max_dist = ub_to.clone() - lb_from.clone();
1116 let min_dist = lb_to - ub_from;
1117
1118 if min_dist >= bound_inf {
1119 Some(true)
1120 } else if max_dist < bound_inf {
1121 Some(false)
1122 } else {
1123 None
1124 }
1125 }
1126 BoolExpr::DlEq(from, to, bound) => {
1127 let (lb_from, ub_from) = self.get_dl_bounds(*from);
1128 let (lb_to, ub_to) = self.get_dl_bounds(*to);
1129 let bound_inf = InfRational::new(Rational::Finite(bound.clone()), rug::Rational::from(0));
1130
1131 let max_dist = ub_to.clone() - lb_from.clone();
1132 let min_dist = lb_to - ub_from;
1133
1134 if max_dist == bound_inf && min_dist == bound_inf {
1136 Some(true)
1137 } else if max_dist < bound_inf || min_dist > bound_inf {
1138 Some(false) } else {
1140 None
1141 }
1142 }
1143 BoolExpr::Eq(e1, e2) => match (e1.as_ref(), e2.as_ref()) {
1144 (Expr::Arith(a1), Expr::Arith(a2)) => {
1145 let (lb1, ub1) = self.get_arith_bounds(a1)?;
1146 let (lb2, ub2) = self.get_arith_bounds(a2)?;
1147 if ub1 < lb2 || ub2 < lb1 {
1148 Some(false)
1149 } else if lb1 == ub1 && lb2 == ub2 && lb1 == lb2 {
1150 Some(true)
1151 } else {
1152 None
1153 }
1154 }
1155 (Expr::Bool(b1), Expr::Bool(b2)) => {
1156 let val1 = self.get_bool_val(b1);
1157 let val2 = self.get_bool_val(b2);
1158 match (val1, val2) {
1159 (Some(v1), Some(v2)) => Some(v1 == v2),
1160 _ => None,
1161 }
1162 }
1163 (Expr::Enum(e1), Expr::Enum(e2)) => {
1164 let val1 = self.get_enum_val(e1);
1165 let val2 = self.get_enum_val(e2);
1166 match (val1, val2) {
1167 (Some(v1), Some(v2)) => Some(v1 == v2),
1168 _ => None,
1169 }
1170 }
1171 (Expr::Euf(u1), Expr::Euf(u2)) => (self.euf_theory.find(u1.node()) == self.euf_theory.find(u2.node())).then_some(true),
1172 _ => None,
1173 },
1174 }
1175 }
1176
1177 pub fn get_arith_val(&self, expr: impl AsRef<ArithExpr>) -> Option<InfRational> {
1179 match expr.as_ref() {
1180 ArithExpr::Const(c) => Some(InfRational::new(Rational::Finite(c.clone()), rug::Rational::from(0))),
1181 ArithExpr::IntVar(v) => Some(self.lra_theory.value(*v).clone()),
1182 ArithExpr::RealVar(v) => Some(self.lra_theory.value(*v).clone()),
1183 ArithExpr::Add(terms) => {
1184 let mut sum = InfRational::new(Rational::Finite(rug::Rational::from(0)), rug::Rational::from(0));
1185 for term in terms {
1186 sum += self.get_arith_val(term)?;
1187 }
1188 Some(sum)
1189 }
1190 ArithExpr::Neg(term) => self.get_arith_val(term).map(|val| -val),
1191 _ => None,
1192 }
1193 }
1194
1195 pub fn get_arith_bounds(&self, expr: impl AsRef<ArithExpr>) -> Option<(InfRational, InfRational)> {
1197 match expr.as_ref() {
1198 ArithExpr::Const(c) => {
1199 let val = InfRational::new(Rational::Finite(c.clone()), rug::Rational::from(0));
1200 Some((val.clone(), val))
1201 }
1202 ArithExpr::IntVar(v) => Some((self.lra_theory.lb(*v).clone(), self.lra_theory.ub(*v).clone())),
1203 ArithExpr::RealVar(v) => Some((self.lra_theory.lb(*v).clone(), self.lra_theory.ub(*v).clone())),
1204 ArithExpr::Add(terms) => {
1205 let mut sum_lb = InfRational::new(Rational::Finite(rug::Rational::from(0)), rug::Rational::from(0));
1206 let mut sum_ub = sum_lb.clone();
1207 for term in terms {
1208 let (lb, ub) = self.get_arith_bounds(term)?;
1209 sum_lb += lb;
1210 sum_ub += ub;
1211 }
1212 Some((sum_lb, sum_ub))
1213 }
1214 ArithExpr::Neg(term) => {
1215 let (lb, ub) = self.get_arith_bounds(term)?;
1216 Some((-ub, -lb))
1217 }
1218 _ => None,
1219 }
1220 }
1221
1222 pub fn get_enum_val(&self, expr: impl AsRef<EnumExpr>) -> Option<usize> {
1224 match expr.as_ref() {
1225 EnumExpr::Const(c) => Some(*c),
1226 EnumExpr::Var(v) => {
1227 let domain = self.enum_theory.domain(*v);
1228 (domain.len() == 1).then(|| *domain.iter().next().unwrap())
1229 }
1230 }
1231 }
1232
1233 pub fn get_dl_val(&self, var: DlVar) -> InfRational {
1235 self.dl_theory.value(var)
1236 }
1237
1238 pub fn get_dl_bounds(&self, var: DlVar) -> (InfRational, InfRational) {
1240 (self.dl_theory.lb(var), self.dl_theory.ub(var))
1241 }
1242
1243 pub fn push(&mut self) {
1248 self.sat_solver.push();
1249 self.lra_theory.push();
1250 self.enum_theory.push();
1251 self.dl_theory.push();
1252 self.euf_theory.push();
1253 }
1254
1255 pub fn pop(&mut self) -> Option<Vec<Lit>> {
1261 let undone = self.sat_solver.pop()?;
1262 let level = self.sat_solver.decision_level();
1263 self.lra_theory.cancel_until(level);
1264 self.enum_theory.cancel_until(level);
1265 self.dl_theory.cancel_until(level);
1266 self.euf_theory.cancel_until(level);
1267 self.notified_len = self.sat_solver.trail.len();
1268 Some(undone)
1269 }
1270
1271 pub fn check_ints(&mut self) -> Result<(), (usize, Vec<Lit>)> {
1277 if let Err((var, val)) = self.lra_theory.check_ints() {
1278 trace!("Integer variable {} has fractional value {}", var, val);
1279
1280 if let Some((cut_row, cut_rhs, explanation_bounds)) = self.lra_theory.new_gomory_cut() {
1281 let cut_slack = self.lra_theory.get_or_create_slack(cut_row);
1282 let bound = InfRational::new(Rational::Finite(cut_rhs), rug::Rational::from(0));
1283 let cut_lit = self.get_or_create_proxy(TheoryConstraint::LraLb(cut_slack, bound));
1284
1285 let mut lemma = Vec::with_capacity(explanation_bounds.len() + 1);
1286 for constraint in explanation_bounds {
1287 let proxy = self.get_or_create_proxy(constraint);
1288 if self.get_lit_val_and_level(proxy) != Some((true, 0)) {
1289 lemma.push(!proxy);
1290 }
1291 }
1292 lemma.push(cut_lit);
1293
1294 trace!("Generated global Gomory cut with {} dependencies!", lemma.len() - 1);
1295
1296 if self.sat_solver.lit_value(cut_lit) != Some(true) {
1297 let backtrack_level = if lemma.len() == 1 { self.user_scopes_len() } else { self.sat_solver.decision_level() };
1298 return Err((backtrack_level, lemma));
1299 }
1300 }
1301
1302 let Rational::Finite(inner_frac) = val.rational_part() else {
1303 unreachable!("Fractional variable in Branch & Bound must be finite");
1304 };
1305
1306 let mut floor_val = inner_frac.clone();
1307 floor_val.floor_mut();
1308 let mut ceil_val = inner_frac.clone();
1309 ceil_val.ceil_mut();
1310
1311 if floor_val == ceil_val {
1312 let inf_part = val.infinitesimal_part();
1313 if inf_part > &rug::Rational::from(0) {
1314 ceil_val += rug::Rational::from(1);
1315 } else if inf_part < &rug::Rational::from(0) {
1316 floor_val -= rug::Rational::from(1);
1317 }
1318 }
1319
1320 let ub = InfRational::new(Rational::Finite(floor_val), rug::Rational::from(0));
1321 let lb = InfRational::new(Rational::Finite(ceil_val), rug::Rational::from(0));
1322 trace!("Branching on variable {}: x <= {} or x >= {}", var, ub, lb);
1323
1324 let lit_ub = self.get_or_create_proxy(TheoryConstraint::LraUb(var, ub));
1325 let lit_lb = self.get_or_create_proxy(TheoryConstraint::LraLb(var, lb));
1326 let lemma = vec![lit_ub, lit_lb];
1327
1328 let current_level = self.sat_solver.decision_level();
1329 return Err((current_level, lemma));
1330 }
1331 Ok(())
1332 }
1333
1334 pub fn simplify(&mut self) -> bool {
1336 self.sat_solver.simplify_db()
1337 }
1338
1339 #[cfg(feature = "profiling")]
1340 pub fn debug_stats(&self) -> String {
1341 self.prof.format_stats(self.sat_solver.num_vars(), self.lra_theory.total_pivots, self.lra_theory.tableau_stats())
1342 }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use super::*;
1348
1349 #[test]
1350 fn test_pure_sat_resolution() {
1351 let mut solver = SeMiTONE::new();
1352
1353 let a = solver.new_bool();
1354 let b = solver.new_bool();
1355 let c = solver.new_bool();
1356
1357 let expr = (&a | &b) & (&!&b | &c) & (!&b | !&c) & !&a;
1360
1361 let _ = solver.assert(expr);
1362 assert!(solver.propagate().is_err(), "The solver should detect that the system is unsatisfiable");
1363 }
1364
1365 #[test]
1366 fn test_early_bounding_unsat() {
1367 let mut solver = SeMiTONE::new();
1368 let x = solver.new_real();
1369
1370 let expr = (x.clone().gt(10)) & (x.lt(5));
1372
1373 assert!(solver.assert(expr).is_ok());
1374 assert!(solver.propagate().is_err(), "The solver should detect that the system is unsatisfiable");
1375 }
1376
1377 #[test]
1378 fn test_equality_mutually_exclusive() {
1379 let mut solver = SeMiTONE::new();
1380 let x = solver.new_real();
1381
1382 let expr = (x.clone().eq(5)) & (x.gt(6));
1384
1385 assert!(solver.assert(expr).is_ok());
1386 assert!(solver.propagate().is_err(), "The solver should detect that the system is unsatisfiable");
1387 }
1388
1389 #[test]
1390 fn test_simplex_system_unsat() {
1391 let mut solver = SeMiTONE::new();
1392 let x = solver.new_real();
1393 let y = solver.new_real();
1394
1395 let eq_expr = (x.clone() + y.clone()).eq(10);
1397 let gt_x = x.clone().gt(6);
1399 let gt_y = y.clone().gt(6);
1401
1402 let expr = eq_expr & gt_x & gt_y;
1403
1404 let _ = solver.assert(expr);
1405 assert!(solver.propagate().is_err(), "The solver should detect that the system is unsatisfiable");
1406 }
1407
1408 #[test]
1409 fn test_constant_arithmetic_evaluations() {
1410 let mut solver = SeMiTONE::new();
1411
1412 assert!(solver.assert(ArithExpr::from(5).lt(10)).is_ok());
1413 assert!(solver.assert(ArithExpr::from(5).le(5)).is_ok());
1414 assert!(solver.assert(ArithExpr::from(10).ge(5)).is_ok());
1415 assert!(solver.assert(ArithExpr::from(10).gt(5)).is_ok());
1416
1417 assert!(solver.assert(ArithExpr::from(10).lt(5)).is_err());
1418 assert!(solver.assert(ArithExpr::from(10).le(5)).is_err());
1419 assert!(solver.assert(ArithExpr::from(5).ge(10)).is_err());
1420 assert!(solver.assert(ArithExpr::from(5).gt(10)).is_err());
1421
1422 assert!(solver.assert(!ArithExpr::from(10).lt(5)).is_ok());
1423 assert!(solver.assert(!ArithExpr::from(5).lt(10)).is_err());
1424 }
1425
1426 #[test]
1427 fn test_negated_variable_inequalities() {
1428 let mut solver = SeMiTONE::new();
1429 let x = solver.new_real();
1430
1431 solver.push();
1432 assert!(solver.assert(!x.clone().lt(5)).is_ok());
1433 assert!(solver.assert(x.clone().lt(4)).is_ok());
1434 assert!(solver.propagate().is_err());
1435 solver.pop();
1436
1437 solver.push();
1438 assert!(solver.assert(!x.clone().le(5)).is_ok());
1439 assert!(solver.assert(x.clone().le(5)).is_ok());
1440 assert!(solver.propagate().is_err());
1441 solver.pop();
1442
1443 solver.push();
1444 assert!(solver.assert(!x.clone().ge(5)).is_ok());
1445 assert!(solver.assert(x.clone().ge(5)).is_ok());
1446 assert!(solver.propagate().is_err());
1447 solver.pop();
1448
1449 solver.push();
1450 assert!(solver.assert(!x.clone().gt(5)).is_ok());
1451 assert!(solver.assert(x.clone().gt(5)).is_ok());
1452 assert!(solver.propagate().is_err());
1453 solver.pop();
1454 }
1455
1456 #[test]
1457 #[should_panic(expected = "Type mismatch in Eq")]
1458 fn test_encode_eq_type_mismatch_panic() {
1459 let mut solver = SeMiTONE::new();
1460 let a = solver.new_bool();
1461 let x = solver.new_real();
1462
1463 let bad_eq = BoolExpr::Eq(Box::new(Expr::Bool(a)), Box::new(Expr::Arith(x)));
1464
1465 let _ = solver.assert(bad_eq);
1466 }
1467
1468 #[test]
1469 fn test_enum_out_of_domain_unsat() {
1470 let mut solver = SeMiTONE::new();
1471 let e = solver.new_enum(vec![1, 2]);
1472
1473 let expr = e.eq(3);
1474
1475 let _ = solver.assert(expr);
1476 assert!(solver.propagate().is_err(), "The solver should detect that the enum variable cannot take a value outside its domain");
1477 }
1478
1479 #[test]
1480 fn test_enum_exhaustive_denial_integration() {
1481 let mut solver = SeMiTONE::new();
1482 let e = solver.new_enum(vec![1, 2]);
1483
1484 let expr = !(e.clone().eq(1)) & !(e.clone().eq(2));
1486
1487 let _ = solver.assert(expr);
1488 assert!(solver.propagate().is_err(), "The solver should detect that the enum variable cannot take a value outside its domain");
1489 }
1490
1491 #[test]
1492 fn test_dl_chain_upper_bounds() {
1493 let mut solver = SeMiTONE::new();
1494 let zero = solver.new_dl_var(); let t1 = solver.new_dl_var();
1496 let t2 = solver.new_dl_var();
1497
1498 let _ = solver.assert(BoolExpr::DlLe(zero, t1, rug::Rational::from(10))); let _ = solver.assert(BoolExpr::DlLe(t1, t2, rug::Rational::from(5))); assert!(solver.propagate().is_ok());
1502
1503 assert_eq!(solver.get_dl_bounds(t1).1, InfRational::from(10));
1504 assert_eq!(solver.get_dl_bounds(t2).1, InfRational::from(15));
1505 assert_eq!(solver.get_dl_bounds(t1).0, InfRational::from(Rational::NegativeInf), "no lower bound imposed");
1506 }
1507
1508 #[test]
1509 fn test_dl_lower_and_upper_bound_interval() {
1510 let mut solver = SeMiTONE::new();
1511 let zero = solver.new_dl_var();
1512 let t1 = solver.new_dl_var();
1513
1514 let _ = solver.assert(BoolExpr::DlLe(zero, t1, rug::Rational::from(8))); let _ = solver.assert(BoolExpr::DlGe(zero, t1, rug::Rational::from(3))); assert!(solver.propagate().is_ok());
1518 assert_eq!(solver.get_dl_bounds(t1), (InfRational::from(3), InfRational::from(8)));
1519 }
1520
1521 #[test]
1522 fn test_dl_eq_pins_value() {
1523 let mut solver = SeMiTONE::new();
1524 let zero = solver.new_dl_var();
1525 let t1 = solver.new_dl_var();
1526
1527 let _ = solver.assert(BoolExpr::DlEq(zero, t1, rug::Rational::from(7)));
1528 assert!(solver.propagate().is_ok());
1529
1530 assert_eq!(solver.get_dl_bounds(t1), (InfRational::from(7), InfRational::from(7)));
1531 }
1532
1533 #[test]
1534 fn test_dl_negative_cycle_conflict() {
1535 let mut solver = SeMiTONE::new();
1536 let a = solver.new_dl_var();
1537 let b = solver.new_dl_var();
1538
1539 let _ = solver.assert(BoolExpr::DlLe(a, b, rug::Rational::from(5)));
1541 let _ = solver.assert(BoolExpr::DlLe(b, a, rug::Rational::from(-10)));
1542
1543 assert!(solver.propagate().is_err(), "the negative cycle must produce a conflict");
1544 }
1545
1546 #[test]
1547 fn test_dl_strict_boundary_conflict() {
1548 let mut solver = SeMiTONE::new();
1549 let a = solver.new_dl_var();
1550 let b = solver.new_dl_var();
1551
1552 let _ = solver.assert(BoolExpr::DlLe(a, b, rug::Rational::from(0)));
1555 let _ = solver.assert(BoolExpr::DlLt(b, a, rug::Rational::from(0)));
1556
1557 assert!(solver.propagate().is_err());
1558 }
1559
1560 #[test]
1561 fn test_dl_non_strict_boundary_is_sat() {
1562 let mut solver = SeMiTONE::new();
1563 let a = solver.new_dl_var();
1564 let b = solver.new_dl_var();
1565
1566 let _ = solver.assert(BoolExpr::DlLe(a, b, rug::Rational::from(0)));
1567 let _ = solver.assert(BoolExpr::DlLe(b, a, rug::Rational::from(0)));
1568
1569 assert!(solver.propagate().is_ok());
1570 assert_eq!(solver.get_dl_bounds(b), solver.get_dl_bounds(a), "b == a == 0");
1571 }
1572
1573 #[test]
1574 fn test_dl_backtracking_via_push_pop() {
1575 let mut solver = SeMiTONE::new();
1576 let zero = solver.new_dl_var();
1577 let t1 = solver.new_dl_var();
1578
1579 solver.push();
1580 let _ = solver.assert(BoolExpr::DlLe(zero, t1, rug::Rational::from(4)));
1581 assert!(solver.propagate().is_ok());
1582 assert_eq!(solver.get_dl_bounds(t1).1, InfRational::from(4));
1583 solver.pop();
1584
1585 assert_eq!(solver.get_dl_bounds(t1).1, InfRational::from(Rational::PositiveInf), "the constraint must disappear after the pop");
1586 }
1587
1588 #[test]
1589 fn test_dl_negated_le_forces_strict_gt() {
1590 let mut solver = SeMiTONE::new();
1594 let a = solver.new_dl_var();
1595 let b = solver.new_dl_var();
1596
1597 let neg_le = BoolExpr::Not(Box::new(BoolExpr::DlLe(a, b, rug::Rational::from(4))));
1598 let _ = solver.assert(neg_le);
1599 assert!(solver.propagate().is_ok());
1600
1601 let (lb_b, _) = solver.get_dl_bounds(b);
1602 assert!(lb_b > InfRational::from(4), "!(b - a <= 4) must imply b - a > 4, found lb(b) = {:?}", lb_b);
1603 }
1604
1605 #[test]
1606 fn test_lit_level_tracking_across_decisions() {
1607 let mut solver = SeMiTONE::new();
1608 let a = solver.new_bool();
1609 let b = solver.new_bool();
1610
1611 let lit_a = solver.track_expr(&a).unwrap();
1612 let lit_b = solver.track_expr(&b).unwrap();
1613
1614 assert_eq!(solver.get_lit_val_and_level(lit_a), None);
1615 assert_eq!(solver.get_lit_level(lit_b), None);
1616
1617 assert!(solver.assert(&a).is_ok());
1619 assert!(solver.propagate().is_ok());
1620 assert_eq!(solver.get_lit_val_and_level(lit_a), Some((true, 0)));
1621
1622 assert!(solver.decide(!lit_b));
1624 assert!(solver.propagate().is_ok());
1625 assert_eq!(solver.get_lit_val_and_level(lit_b), Some((false, 1)));
1626
1627 solver.cancel_until(0);
1629 assert_eq!(solver.get_lit_val_and_level(lit_a), Some((true, 0)));
1630 assert_eq!(solver.get_lit_val_and_level(lit_b), None);
1631 }
1632
1633 #[test]
1634 fn test_level_zero_pruning_avoids_proxy_allocation() {
1635 let mut solver = SeMiTONE::new();
1636 let a = solver.new_bool();
1637 let b = solver.new_bool();
1638
1639 let lit_a = solver.track_expr(&a).unwrap();
1640 let lit_b = solver.track_expr(&b).unwrap();
1641
1642 assert!(solver.assert(&a).is_ok());
1644 assert!(solver.propagate().is_ok());
1645
1646 let vars_before = solver.num_vars();
1647
1648 let and_lit = solver.track_expr(&a & &b).unwrap();
1650 assert_eq!(and_lit, lit_b);
1651 assert_eq!(solver.num_vars(), vars_before);
1652
1653 let false_and_lit = solver.track_expr(!&a & b.clone()).unwrap();
1655 assert_eq!(false_and_lit, Lit::FALSE);
1656 assert_eq!(solver.get_lit_val_and_level(false_and_lit), Some((false, 0)));
1657 assert_eq!(solver.num_vars(), vars_before);
1658
1659 let or_lit = solver.track_expr(&a | &b).unwrap();
1661 assert_eq!(or_lit, Lit::TRUE);
1662 assert_eq!(solver.get_lit_val_and_level(or_lit), Some((true, 0)));
1663 assert_eq!(solver.num_vars(), vars_before);
1664
1665 let _ = lit_a;
1666 }
1667
1668 #[test]
1669 fn test_dl_conflict_lemma_polarities_and_backtrack() {
1670 let mut solver = SeMiTONE::new();
1671 let a = solver.new_dl_var();
1672 let b = solver.new_dl_var();
1673
1674 assert!(solver.assert(BoolExpr::DlLe(a, b, rug::Rational::from(5))).is_ok());
1676 assert!(solver.propagate().is_ok());
1677
1678 let rho = solver.new_lit();
1680 let dl_cnstr = solver.track_expr(BoolExpr::DlGe(a, b, rug::Rational::from(10))).unwrap();
1681 assert!(solver.add_clause([!rho, dl_cnstr]).is_ok());
1682 assert!(solver.propagate().is_ok());
1683
1684 assert!(solver.decide(rho));
1686 let prop_res = solver.propagate();
1687 assert!(prop_res.is_err(), "Activating rho must generate a conflict in Difference Logic");
1688
1689 let (bt_level, lemma) = prop_res.unwrap_err();
1690 assert_eq!(bt_level, 0);
1691
1692 for &lit in &lemma {
1694 assert_eq!(solver.get_lit_val(lit), Some(false), "Literal {} in the conflict lemma should be Some(false), but is {:?}", lit, solver.get_lit_val(lit));
1695 }
1696
1697 solver.cancel_until(bt_level);
1699 assert!(solver.add_clause(lemma).is_ok());
1700 assert!(solver.propagate().is_ok());
1701
1702 assert_eq!(solver.get_lit_val_and_level(dl_cnstr), Some((false, 0)), "dl_cnstr must be forced to false at level 0");
1704 assert_eq!(solver.get_lit_val_and_level(rho), Some((false, 0)), "rho must be forced to false by unit propagation");
1705 }
1706
1707 #[test]
1708 fn test_theory_conflict_reduces_to_1uip_directly() {
1709 let mut solver = SeMiTONE::new();
1710 let a = solver.new_dl_var();
1711 let b = solver.new_dl_var();
1712 let c = solver.new_dl_var();
1713
1714 let r1 = solver.new_lit();
1716 let c_ac = solver.track_expr(BoolExpr::DlLe(a, c, rug::Rational::from(5))).unwrap();
1717 assert!(solver.add_clause([!r1, c_ac]).is_ok());
1718 assert!(solver.decide(r1));
1719 assert!(solver.propagate().is_ok());
1720
1721 let dummy = solver.new_lit();
1723 assert!(solver.decide(dummy));
1724 assert!(solver.propagate().is_ok());
1725
1726 let r2 = solver.new_lit();
1731 let c_ab = solver.track_expr(BoolExpr::DlGe(a, b, rug::Rational::from(4))).unwrap();
1732 let c_bc = solver.track_expr(BoolExpr::DlGe(b, c, rug::Rational::from(4))).unwrap();
1733 assert!(solver.add_clause([!r2, c_ab]).is_ok());
1734 assert!(solver.add_clause([!r2, c_bc]).is_ok());
1735
1736 assert!(solver.decide(r2));
1737 let err = solver.propagate().expect_err("The DL cycle must cause a conflict at level 3");
1738
1739 let (bt_level, lemma) = err;
1740 assert_eq!(bt_level, 1, "The conflict must jump directly to level 1 via 1-UIP");
1743 assert_eq!(lemma[0], !r2, "The first literal in the lemma must be the 1-UIP !r2");
1744
1745 solver.cancel_until(bt_level);
1746 assert!(solver.add_clause(lemma).is_ok());
1747 assert_eq!(solver.get_lit_val_and_level(r2), Some((false, 1)), "!r2 must be propagated immediately at level 1");
1748 }
1749}