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