use crate::circuit::{Bool, Circuit};
use crate::sat::{Budget, BudgetExhausted, Cdcl, Lit, Solved, Solver};
use crate::skolem::skolemize;
use crate::symmetry;
use crate::translate::{Primary, Shape, Translator};
use elinvar_logic::{
Against, Bounds, Error, Expr, ExprKind, Formula, FormulaKind, Instance, IntExpr, IntExprKind,
Relation, TemporalOp, Trace, TupleSet, check_formula, evaluate, evaluate_trace,
};
use serde::Serialize;
use std::fmt;
use std::time::{Duration, Instant};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Options {
pub symmetry_breaking: bool,
pub budget: Budget,
pub steps: usize,
pub predicate_length: usize,
pub slicing: bool,
}
pub const DEFAULT_STEPS: usize = 10;
pub const DEFAULT_CONFLICTS: u64 = 10_000_000;
impl Default for Options {
fn default() -> Options {
Options {
symmetry_breaking: true,
budget: Budget::conflicts(DEFAULT_CONFLICTS),
steps: DEFAULT_STEPS,
predicate_length: symmetry::PREDICATE_LENGTH,
slicing: true,
}
}
}
impl Options {
#[must_use]
pub fn symmetry_breaking(mut self, on: bool) -> Options {
self.symmetry_breaking = on;
self
}
#[must_use]
pub fn predicate_length(mut self, length: usize) -> Options {
self.predicate_length = length;
self
}
#[must_use]
pub fn slicing(mut self, on: bool) -> Options {
self.slicing = on;
self
}
#[must_use]
pub fn steps(mut self, steps: usize) -> Options {
self.steps = steps;
self
}
#[must_use]
pub fn budget(mut self, budget: Budget) -> Options {
self.budget = budget;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Verdict {
Found,
None,
Counterexample,
Holds,
Proved,
Vacuous,
Unknown,
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Verdict::Found => "found",
Verdict::None => "none",
Verdict::Counterexample => "counterexample",
Verdict::Holds => "holds",
Verdict::Proved => "proved",
Verdict::Vacuous => "vacuous",
Verdict::Unknown => "unknown",
};
write!(f, "{s}")
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct Stats {
pub primary_variables: u32,
pub gates: usize,
pub conflicts: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct StepLabel {
pub action: Option<String>,
pub args: Vec<String>,
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
#[must_use]
pub struct Outcome {
pub verdict: Verdict,
pub instance: Option<Instance>,
pub trace: Option<Trace>,
pub labels: Vec<StepLabel>,
pub note: Option<String>,
pub stats: Stats,
}
impl fmt::Display for Outcome {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.verdict)?;
if let Some(note) = &self.note {
write!(f, " ({note})")?;
}
Ok(())
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Next {
Instance(Instance),
Trace(Trace),
Done,
Unknown,
}
struct Search {
bounds: Bounds,
shape: Shape,
circuit: Circuit,
solver: Box<dyn Solver>,
primaries: Vec<Primary>,
loop_vars: Vec<Bool>,
checked_sat: bool,
cur_loop: usize,
saved: Option<(Instance, Vec<Instance>, usize, Vec<Lit>)>,
exhausted: bool,
timed_out: bool,
}
impl Search {
fn new(
bounds: &Bounds,
formula: &Formula,
shape: Shape,
options: &Options,
mut solver: Box<dyn Solver>,
) -> Search {
let deadline = options.budget.time.map(|t| Instant::now() + t);
let expired = || deadline.is_some_and(|d| Instant::now() >= d);
let mut circuit = Circuit::new();
let mut timed_out = expired();
let (root, primaries, loop_vars) = if timed_out {
(Bool::FALSE, Vec::new(), Vec::new())
} else {
let (mut tr, primaries, loop_vars) = Translator::new(&mut circuit, bounds, shape);
tr.set_deadline(deadline);
let mut root = tr.formula(formula);
if tr.timed_out() || expired() {
timed_out = true;
}
if !timed_out && !loop_vars.is_empty() && root != Bool::FALSE {
let lc = tr.loop_constraint();
root = tr.circuit.and([root, lc]);
}
if !timed_out && options.symmetry_breaking && root != Bool::FALSE {
let sbp =
symmetry::predicate(&mut tr, bounds, &primaries, options.predicate_length);
root = tr.circuit.and([root, sbp]);
if expired() {
timed_out = true;
}
}
(root, primaries, loop_vars)
};
let satisfiable = if timed_out {
false
} else {
circuit.assert(solver.as_mut(), root)
};
Search {
bounds: bounds.clone(),
shape,
circuit,
solver,
primaries,
loop_vars,
checked_sat: false,
cur_loop: 0,
saved: None,
exhausted: !satisfiable,
timed_out,
}
}
fn is_true(&self, b: Bool) -> bool {
let l = self.circuit.lit(b);
self.solver.value(l.var()) != l.is_negative()
}
fn block_clause(&self, loop_j: Option<usize>) -> Vec<Lit> {
let mut block: Vec<Lit> = self
.primaries
.iter()
.map(|p| {
let l = self.circuit.lit(p.value);
if self.is_true(p.value) { !l } else { l }
})
.collect();
if let Some(j) = loop_j {
block.push(!self.circuit.lit(self.loop_vars[j]));
}
block
}
fn next(&mut self, budget: &Budget) -> Result<Option<(Instance, Vec<Instance>, usize)>, ()> {
if self.timed_out {
return Err(());
}
if self.exhausted {
return Ok(None);
}
if self.loop_vars.is_empty() {
let j = self.shape.loop_to.unwrap_or(0);
return match self.solver.solve(&[], budget) {
Solved::Unsat => {
self.exhausted = true;
Ok(None)
}
Solved::Unknown => Err(()),
Solved::Sat => {
let (fixed, states) = self.read();
let block = self.block_clause(None);
if block.is_empty() {
self.exhausted = true;
} else {
self.solver.add_clause(&block);
}
Ok(Some((fixed, states, j)))
}
};
}
if !self.checked_sat {
match self.solver.solve(&[], budget) {
Solved::Unsat => {
self.exhausted = true;
return Ok(None);
}
Solved::Unknown => return Err(()),
Solved::Sat => {
self.checked_sat = true;
let j = self
.loop_vars
.iter()
.position(|&lv| self.is_true(lv))
.expect("loop_constraint forces exactly one loop target true");
let (fixed, states) = self.read();
let block = self.block_clause(Some(j));
if j == 0 {
self.solver.add_clause(&block);
return Ok(Some((fixed, states, 0)));
}
self.saved = Some((fixed, states, j, block));
}
}
}
while self.cur_loop < self.loop_vars.len() {
if self
.saved
.as_ref()
.is_some_and(|(_, _, j, _)| *j == self.cur_loop)
{
let (fixed, states, j, block) = self.saved.take().expect("checked just above");
self.solver.add_clause(&block);
return Ok(Some((fixed, states, j)));
}
let lv = self.circuit.lit(self.loop_vars[self.cur_loop]);
match self.solver.solve(&[lv], budget) {
Solved::Sat => {
let (fixed, states) = self.read();
let block = self.block_clause(Some(self.cur_loop));
self.solver.add_clause(&block);
return Ok(Some((fixed, states, self.cur_loop)));
}
Solved::Unsat => self.cur_loop += 1,
Solved::Unknown => return Err(()),
}
}
self.exhausted = true;
Ok(None)
}
fn solve_assuming(
&mut self,
assumptions: &[Lit],
budget: &Budget,
) -> Result<Option<(Instance, Vec<Instance>)>, ()> {
if self.timed_out {
return Err(());
}
if self.exhausted {
return Ok(None);
}
match self.solver.solve(assumptions, budget) {
Solved::Unsat => Ok(None),
Solved::Unknown => Err(()),
Solved::Sat => Ok(Some(self.read())),
}
}
fn read(&self) -> (Instance, Vec<Instance>) {
let universe = self.bounds.universe();
let mut fixed = Instance::new(universe);
let mut states: Vec<Instance> = (0..self.shape.states)
.map(|_| Instance::new(universe))
.collect();
let mut sets: Vec<Vec<TupleSet>> = self
.bounds
.entries()
.map(|(r, lower, _)| {
let count = if r.is_changing() {
self.shape.states
} else {
1
};
vec![lower.clone(); count]
})
.collect();
for p in &self.primaries {
if self.is_true(p.value) {
sets[p.relation][p.state]
.insert_index(p.tuple)
.expect("a primary variable's tuple is in its relation's upper bound");
}
}
for (r, sets) in self.bounds.relations().zip(sets) {
if r.is_changing() {
for (instance, set) in states.iter_mut().zip(sets) {
instance
.set(r, set)
.expect("the bounds' relations are distinct and well formed");
}
} else {
let set = sets
.into_iter()
.next()
.expect("a static relation has one set");
fixed
.set(r, set)
.expect("the bounds' relations are distinct and well formed");
}
}
(fixed, states)
}
}
fn shapes(temporal: bool, steps: usize, depth: usize) -> Vec<Shape> {
if temporal {
(1..=steps.max(1))
.map(|l| Shape::variable_loop(l, depth))
.collect()
} else {
vec![Shape::single(depth)]
}
}
struct Engine<'f> {
user_bounds: Bounds,
bounds: Bounds,
formula: Formula,
skolemized: Formula,
options: Options,
temporal: bool,
shapes: Vec<Shape>,
next_shape: usize,
current: Option<Search>,
make_solver: Box<dyn FnMut() -> Box<dyn Solver> + 'f>,
stats: Stats,
deadline: Option<Instant>,
last_unknown: Option<BudgetExhausted>,
}
impl<'f> Engine<'f> {
fn new(
bounds: &Bounds,
formula: &Formula,
options: &Options,
make_solver: Box<dyn FnMut() -> Box<dyn Solver> + 'f>,
) -> Result<Engine<'f>, Vec<Error>> {
let errors = check_formula(formula, Against::Bounds(bounds));
if !errors.is_empty() {
return Err(errors);
}
let sk = skolemize(formula, bounds);
let remaining = higher_order(&sk.formula);
if !remaining.is_empty() {
return Err(remaining);
}
let temporal = bounds.relations().any(Relation::is_changing);
let shapes = shapes(temporal, options.steps, formula.past_depth());
let deadline = options.budget.time.map(|t| Instant::now() + t);
Ok(Engine {
user_bounds: bounds.clone(),
bounds: sk.bounds,
formula: formula.clone(),
skolemized: sk.formula,
options: *options,
temporal,
shapes,
next_shape: 0,
current: None,
make_solver,
stats: Stats::default(),
deadline,
last_unknown: None,
})
}
fn stats(&self) -> Stats {
let mut stats = self.stats;
stats.conflicts += self.current.as_ref().map_or(0, |s| s.solver.conflicts());
stats
}
fn unknown_reason(&self) -> Option<BudgetExhausted> {
self.last_unknown
}
fn remaining_budget(&self) -> Option<Budget> {
let mut b = self.options.budget;
if let Some(deadline) = self.deadline {
let rem = deadline.checked_duration_since(Instant::now())?;
b.time = Some(rem);
}
Some(b)
}
fn next_instance(&mut self) -> Next {
self.last_unknown = None;
loop {
let Some(budget) = self.remaining_budget() else {
self.last_unknown = Some(BudgetExhausted::Time);
return Next::Unknown;
};
if self.current.is_none() {
let Some(&shape) = self.shapes.get(self.next_shape) else {
return Next::Done;
};
self.next_shape += 1;
let solver = (self.make_solver)();
let search =
Search::new(&self.bounds, &self.skolemized, shape, &self.options, solver);
self.stats.primary_variables = search.primaries.len() as u32;
self.stats.gates = search.circuit.gate_count();
self.current = Some(search);
}
let search = self.current.as_mut().expect("set just above");
match search.next(&budget) {
Err(()) => {
self.last_unknown = search.solver.unknown_reason().or_else(|| {
if self.deadline.is_some_and(|d| Instant::now() >= d) {
Some(BudgetExhausted::Time)
} else {
None
}
});
return Next::Unknown;
}
Ok(None) => {
self.stats.conflicts += search.solver.conflicts();
self.current = None;
}
Ok(Some((fixed, states, loop_to))) => {
return if self.temporal {
let trace = Trace::new(fixed, states, loop_to)
.expect("a shape has states and a loop target among them");
self.referee_trace(&trace);
Next::Trace(trace)
} else {
self.referee(&fixed);
Next::Instance(fixed)
};
}
}
}
}
fn referee(&self, instance: &Instance) {
referee_instance(&self.user_bounds, &self.formula, &self.skolemized, instance);
}
fn referee_trace(&self, trace: &Trace) {
referee_trace(&self.user_bounds, &self.formula, &self.skolemized, trace);
}
}
pub struct Finder(Engine<'static>);
impl Finder {
pub fn new(
bounds: &Bounds,
formula: &Formula,
options: &Options,
) -> Result<Finder, Vec<Error>> {
Finder::with_solver(bounds, formula, options, Cdcl::new)
}
pub fn with_solver<S, F>(
bounds: &Bounds,
formula: &Formula,
options: &Options,
mut make_solver: F,
) -> Result<Finder, Vec<Error>>
where
S: Solver + 'static,
F: FnMut() -> S + 'static,
{
let factory = Box::new(move || Box::new(make_solver()) as Box<dyn Solver>);
Ok(Finder(Engine::new(bounds, formula, options, factory)?))
}
pub fn stats(&self) -> Stats {
self.0.stats()
}
pub fn next_instance(&mut self) -> Next {
self.0.next_instance()
}
}
fn higher_order(f: &Formula) -> Vec<Error> {
fn expr(e: &elinvar_logic::Expr, out: &mut Vec<Error>) {
match e.kind() {
ExprKind::Binary(_, a, b) => {
expr(a, out);
expr(b, out);
}
ExprKind::Unary(_, a) | ExprKind::Prime(a) => expr(a, out),
ExprKind::Comprehension(decls, body) => {
for d in decls {
expr(&d.expr, out);
}
formula(body, out);
}
ExprKind::IfThenElse(c, a, b) => {
formula(c, out);
expr(a, out);
expr(b, out);
}
ExprKind::IntToSet(v) => int(v, out),
ExprKind::Relation(_)
| ExprKind::Variable(_)
| ExprKind::None
| ExprKind::Univ
| ExprKind::Iden => {}
}
}
fn int(v: &elinvar_logic::IntExpr, out: &mut Vec<Error>) {
use elinvar_logic::IntExprKind as K;
match v.kind() {
K::Constant(_) => {}
K::Count(e) | K::Sum(e) => expr(e, out),
K::Binary(_, a, b) => {
int(a, out);
int(b, out);
}
K::Negate(a) => int(a, out),
K::IfThenElse(c, a, b) => {
formula(c, out);
int(a, out);
int(b, out);
}
K::SumOver(decls, body) => {
for d in decls {
expr(&d.expr, out);
}
int(body, out);
}
}
}
fn formula(f: &Formula, out: &mut Vec<Error>) {
match f.kind() {
FormulaKind::Constant(_) => {}
FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
expr(a, out);
expr(b, out);
}
FormulaKind::Multiplicity(_, a) => expr(a, out),
FormulaKind::Not(g) | FormulaKind::Temporal(_, g) => formula(g, out),
FormulaKind::And(fs) | FormulaKind::Or(fs) => {
for g in fs {
formula(g, out);
}
}
FormulaKind::Implies(a, b)
| FormulaKind::Iff(a, b)
| FormulaKind::TemporalBinary(_, a, b) => {
formula(a, out);
formula(b, out);
}
FormulaKind::Quantified(_, decls, body) => {
for d in decls {
expr(&d.expr, out);
if !d.is_first_order() {
let e = Error::new(
"logic.higher_order",
format!(
"`{}` ranges over sets or relations under a quantifier that \
skolemization cannot remove",
d.var
),
)
.at(f.place().clone());
if !out.contains(&e) {
out.push(e);
}
}
}
formula(body, out);
}
FormulaKind::IntCompare(_, a, b) => {
int(a, out);
int(b, out);
}
}
}
let mut out = Vec::new();
formula(f, &mut out);
out
}
fn referee_instance(bounds: &Bounds, formula: &Formula, skolemized: &Formula, instance: &Instance) {
assert!(
bounds.admits(instance),
"Elinvar bug: the solver returned an instance outside the bounds \
(the referee's check of LOGIC.md 12.7). Please report it with the model."
);
let verdict = match evaluate(instance, formula) {
Err(e) if e.iter().all(|e| e.code == "enumerate.too_large") => {
evaluate(instance, skolemized)
}
other => other,
};
if verdict != Ok(true) {
panic!(
"Elinvar bug: the solver returned an instance under which the formula \
is {verdict:?}, not true (the referee's check of LOGIC.md 12.7). Please \
report it with the model."
);
}
}
fn referee_trace(bounds: &Bounds, formula: &Formula, skolemized: &Formula, trace: &Trace) {
assert!(
trace.within(bounds),
"Elinvar bug: the solver returned a trace outside the bounds \
(the referee's check of LOGIC.md 12.7). Please report it with the model."
);
let verdict = match evaluate_trace(trace, formula) {
Err(e) if e.iter().all(|e| e.code == "enumerate.too_large") => {
evaluate_trace(trace, skolemized)
}
other => other,
};
if verdict != Ok(true) {
panic!(
"Elinvar bug: the solver returned a trace on which the formula is \
{verdict:?}, not true (the referee's check of LOGIC.md 12.7). Please \
report it with the model."
);
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn shrink_tuples(
full_bounds: &Bounds,
full_formula: &Formula,
shrink_bounds: &Bounds,
shrink_formula: &Formula,
states: usize,
loop_to: usize,
budget: u64,
solver: Box<dyn Solver>,
) -> Option<(Next, u64, bool)> {
let sk = skolemize(shrink_formula, shrink_bounds);
let temporal = full_bounds.relations().any(Relation::is_changing);
let depth = shrink_formula.past_depth();
let shape = if temporal {
Shape::new(states, loop_to, depth)
} else {
Shape::single(depth)
};
let off = Options::default().symmetry_breaking(false);
let mut search = Search::new(&sk.bounds, &sk.formula, shape, &off, solver);
let wrap = |(fixed, states): (Instance, Vec<Instance>)| {
if temporal {
let trace = Trace::new(fixed, states, loop_to)
.expect("a shape has states and a loop target among them");
referee_trace(full_bounds, full_formula, &sk.formula, &trace);
Next::Trace(trace)
} else {
referee_instance(full_bounds, full_formula, &sk.formula, &fixed);
Next::Instance(fixed)
}
};
let spent = |s: &Search| s.solver.conflicts();
let left = |s: &Search| Budget::conflicts(budget.saturating_sub(spent(s)).max(1));
let first_budget = left(&search);
let Ok(Some(mut current)) = search.solve_assuming(&[], &first_budget) else {
return None;
};
let mut forced: Vec<Lit> = Vec::new();
let mut finished = true;
for k in 0..search.primaries.len() {
let p = search.primaries[k];
let (r, _, _) = sk
.bounds
.entries()
.nth(p.relation)
.expect("a primary variable's relation is in the bounds");
let owner = if temporal && r.is_changing() {
¤t.1[p.state]
} else {
¤t.0
};
if !owner.get(r).is_some_and(|t| t.contains_index(p.tuple)) {
continue;
}
if spent(&search) >= budget {
finished = false;
break;
}
let step_budget = left(&search);
forced.push(!search.circuit.lit(p.value));
match search.solve_assuming(&forced, &step_budget) {
Ok(Some(found)) => current = found,
Ok(None) => {
forced.pop();
}
Err(()) => {
finished = false;
break;
}
}
}
let used = spent(&search);
Some((wrap(current), used, finished))
}
fn format_duration(d: Duration) -> String {
let ms = d.as_millis();
if ms == 0 {
"0ms".to_string()
} else if ms < 1000 {
format!("{ms}ms")
} else if ms.is_multiple_of(60_000) {
format!("{}m", ms / 60_000)
} else if ms.is_multiple_of(1000) {
format!("{}s", ms / 1000)
} else {
format!("{:.2}s", d.as_secs_f64())
}
}
fn unknown_note(budget: &Budget, reason: Option<BudgetExhausted>, known: &str) -> String {
let which = match reason {
Some(BudgetExhausted::Time) => match budget.time {
Some(t) => format!("the time limit of {}", format_duration(t)),
None => "the time limit".to_string(),
},
Some(BudgetExhausted::Conflicts) => match budget.conflicts {
Some(c) => format!("the conflict budget of {c} conflicts"),
None => "the conflict budget".to_string(),
},
None => match (budget.conflicts, budget.time) {
(Some(c), Some(t)) => {
format!("the budget of {c} conflicts or {}", format_duration(t))
}
(Some(c), None) => format!("the conflict budget of {c} conflicts"),
(None, Some(t)) => format!("the time limit of {}", format_duration(t)),
(None, None) => "the budget".to_string(),
},
};
format!("{which} ran out; {known}")
}
impl Outcome {
fn from_next(next: Next, found: Verdict, stats: Stats) -> Option<Outcome> {
let (instance, trace) = match next {
Next::Instance(i) => (Some(i), None),
Next::Trace(t) => (None, Some(t)),
Next::Done | Next::Unknown => return None,
};
Some(Outcome {
verdict: found,
instance,
trace,
labels: Vec::new(),
note: None,
stats,
})
}
fn without(verdict: Verdict, note: Option<String>, stats: Stats) -> Outcome {
Outcome {
verdict,
instance: None,
trace: None,
labels: Vec::new(),
note,
stats,
}
}
}
pub fn run(bounds: &Bounds, formula: &Formula, options: &Options) -> Result<Outcome, Vec<Error>> {
run_with_solver(bounds, formula, options, Cdcl::new)
}
pub fn run_with_solver<S, F>(
bounds: &Bounds,
formula: &Formula,
options: &Options,
mut make_solver: F,
) -> Result<Outcome, Vec<Error>>
where
S: Solver + 'static,
F: FnMut() -> S,
{
let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
let mut finder = Engine::new(bounds, formula, options, factory)?;
let next = finder.next_instance();
let stats = finder.stats();
Ok(match next {
Next::Done => Outcome::without(Verdict::None, None, stats),
Next::Unknown => Outcome::without(
Verdict::Unknown,
Some(unknown_note(
&options.budget,
finder.unknown_reason(),
"nothing is known",
)),
stats,
),
next => Outcome::from_next(next, Verdict::Found, stats).expect("an instance or a trace"),
})
}
pub fn check(
bounds: &Bounds,
rules: &Formula,
assertion: &Formula,
options: &Options,
) -> Result<Outcome, Vec<Error>> {
check_with_solver(bounds, rules, assertion, options, Cdcl::new)
}
pub fn check_with_solver<S, F>(
bounds: &Bounds,
rules: &Formula,
assertion: &Formula,
options: &Options,
mut make_solver: F,
) -> Result<Outcome, Vec<Error>>
where
S: Solver + 'static,
F: FnMut() -> S,
{
let deadline = options.budget.time.map(|t| Instant::now() + t);
let negated = rules.and(&assertion.not());
let mut stats = {
let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
let mut finder = Engine::new(bounds, &negated, options, factory)?;
let next = finder.next_instance();
let stats = finder.stats();
match next {
Next::Done => stats,
Next::Unknown => {
return Ok(Outcome::without(
Verdict::Unknown,
Some(unknown_note(
&options.budget,
finder.unknown_reason(),
"nothing is known",
)),
stats,
));
}
next => {
return Ok(Outcome::from_next(next, Verdict::Counterexample, stats)
.expect("an instance or a trace"));
}
}
};
let mut rules_opts = *options;
if let Some(d) = deadline {
let Some(rem) = d.checked_duration_since(Instant::now()) else {
return Ok(Outcome::without(
Verdict::Unknown,
Some(unknown_note(
&options.budget,
Some(BudgetExhausted::Time),
"no counterexample exists within the bounds, and whether the rules allow any case is not settled",
)),
stats,
));
};
rules_opts.budget.time = Some(rem);
}
let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
let mut rules_only = Engine::new(bounds, rules, &rules_opts, factory)?;
let next = rules_only.next_instance();
stats.conflicts += rules_only.stats().conflicts;
let (verdict, note) = match next {
Next::Instance(_) | Next::Trace(_) => (Verdict::Holds, None),
Next::Done => (Verdict::Vacuous, None),
Next::Unknown => (
Verdict::Unknown,
Some(unknown_note(
&options.budget,
rules_only.unknown_reason(),
"no counterexample exists within the bounds, and whether the rules allow any case is not settled",
)),
),
};
Ok(Outcome::without(verdict, note, stats))
}
pub(crate) fn solve_fixed_states<S, F>(
bounds: &Bounds,
formula: &Formula,
states: usize,
options: &Options,
mut make_solver: F,
) -> Result<(Next, Stats), Vec<Error>>
where
S: Solver + 'static,
F: FnMut() -> S,
{
let errors = check_formula(formula, Against::Bounds(bounds));
if !errors.is_empty() {
return Err(errors);
}
let sk = skolemize(formula, bounds);
let errors = higher_order(&sk.formula);
if !errors.is_empty() {
return Err(errors);
}
let temporal = bounds.relations().any(Relation::is_changing) || formula.is_temporal();
let depth = 0;
let loop_to = states.saturating_sub(1);
let shape = if temporal {
Shape::new(states.max(1), loop_to, depth)
} else {
Shape::single(depth)
};
let deadline = options.budget.time.map(|t| Instant::now() + t);
let solver = Box::new(make_solver()) as Box<dyn Solver>;
let mut search = Search::new(&sk.bounds, &sk.formula, shape, options, solver);
let stats = |s: &Search| Stats {
primary_variables: s.primaries.len() as u32,
gates: s.circuit.gate_count(),
conflicts: s.solver.conflicts(),
};
let mut eff_budget = options.budget;
if let Some(d) = deadline {
let Some(rem) = d.checked_duration_since(Instant::now()) else {
return Ok((Next::Unknown, stats(&search)));
};
if rem.is_zero() {
return Ok((Next::Unknown, stats(&search)));
}
eff_budget.time = Some(rem);
}
match search.solve_assuming(&[], &eff_budget) {
Ok(Some((fixed, st))) => {
let st_out = stats(&search);
let next = if temporal {
let trace = Trace::new(fixed, st, loop_to)
.expect("a shape has states and a loop target among them");
referee_trace(bounds, formula, &sk.formula, &trace);
Next::Trace(trace)
} else {
referee_instance(bounds, formula, &sk.formula, &fixed);
Next::Instance(fixed)
};
Ok((next, st_out))
}
Ok(None) => Ok((Next::Done, stats(&search))),
Err(()) => Ok((Next::Unknown, stats(&search))),
}
}
pub fn count(
bounds: &Bounds,
formula: &Formula,
options: &Options,
limit: u64,
) -> Result<Option<u64>, Vec<Error>> {
count_with_solver(bounds, formula, options, limit, Cdcl::new)
}
pub fn count_with_solver<S, F>(
bounds: &Bounds,
formula: &Formula,
options: &Options,
limit: u64,
mut make_solver: F,
) -> Result<Option<u64>, Vec<Error>>
where
S: Solver + 'static,
F: FnMut() -> S,
{
let factory = Box::new(|| Box::new(make_solver()) as Box<dyn Solver>);
let mut finder = Engine::new(bounds, formula, options, factory)?;
let mut n = 0;
while n < limit {
match finder.next_instance() {
Next::Instance(_) | Next::Trace(_) => n += 1,
Next::Done => return Ok(Some(n)),
Next::Unknown => return Ok(None),
}
}
Ok(Some(n))
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct HoldsCore {
pub used: Vec<String>,
pub unused: Vec<String>,
}
impl fmt::Display for HoldsCore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "used rules: {}", self.used.join(", "))?;
if !self.unused.is_empty() {
write!(f, "; unused rules: {}", self.unused.join(", "))?;
}
Ok(())
}
}
pub(crate) enum CoreResult {
Complete(HoldsCore),
Incomplete {
core: Option<HoldsCore>,
note: String,
},
NotUnsat,
}
fn expr_is_state_only(e: &Expr) -> bool {
match e.kind() {
ExprKind::Relation(_)
| ExprKind::Variable(_)
| ExprKind::None
| ExprKind::Univ
| ExprKind::Iden => true,
ExprKind::Prime(_) => false,
ExprKind::Unary(_, a) => expr_is_state_only(a),
ExprKind::Binary(_, a, b) => expr_is_state_only(a) && expr_is_state_only(b),
ExprKind::IfThenElse(c, a, b) => {
formula_is_state_only(c) && expr_is_state_only(a) && expr_is_state_only(b)
}
ExprKind::Comprehension(ds, body) => {
ds.iter().all(|d| expr_is_state_only(&d.expr)) && formula_is_state_only(body)
}
ExprKind::IntToSet(n) => int_is_state_only(n),
}
}
fn int_is_state_only(n: &IntExpr) -> bool {
match n.kind() {
IntExprKind::Constant(_) => true,
IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_is_state_only(e),
IntExprKind::Negate(a) => int_is_state_only(a),
IntExprKind::Binary(_, a, b) => int_is_state_only(a) && int_is_state_only(b),
IntExprKind::IfThenElse(c, a, b) => {
formula_is_state_only(c) && int_is_state_only(a) && int_is_state_only(b)
}
IntExprKind::SumOver(ds, body) => {
ds.iter().all(|d| expr_is_state_only(&d.expr)) && int_is_state_only(body)
}
}
}
fn formula_is_state_only(f: &Formula) -> bool {
match f.kind() {
FormulaKind::Constant(_) => true,
FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
expr_is_state_only(a) && expr_is_state_only(b)
}
FormulaKind::Multiplicity(_, a) => expr_is_state_only(a),
FormulaKind::Not(g) => formula_is_state_only(g),
FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().all(formula_is_state_only),
FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
formula_is_state_only(a) && formula_is_state_only(b)
}
FormulaKind::Quantified(_, ds, body) => {
ds.iter().all(|d| expr_is_state_only(&d.expr)) && formula_is_state_only(body)
}
FormulaKind::Temporal(_, _) | FormulaKind::TemporalBinary(_, _, _) => false,
FormulaKind::IntCompare(_, a, b) => int_is_state_only(a) && int_is_state_only(b),
}
}
fn expr_mentions_changing(e: &Expr) -> bool {
match e.kind() {
ExprKind::Relation(r) => r.is_changing(),
ExprKind::Variable(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => false,
ExprKind::Prime(_) => true,
ExprKind::Unary(_, a) => expr_mentions_changing(a),
ExprKind::Binary(_, a, b) => expr_mentions_changing(a) || expr_mentions_changing(b),
ExprKind::IfThenElse(c, a, b) => {
formula_mentions_changing(c) || expr_mentions_changing(a) || expr_mentions_changing(b)
}
ExprKind::Comprehension(ds, body) => {
ds.iter().any(|d| expr_mentions_changing(&d.expr)) || formula_mentions_changing(body)
}
ExprKind::IntToSet(n) => int_mentions_changing(n),
}
}
fn int_mentions_changing(n: &IntExpr) -> bool {
match n.kind() {
IntExprKind::Constant(_) => false,
IntExprKind::Count(e) | IntExprKind::Sum(e) => expr_mentions_changing(e),
IntExprKind::Negate(a) => int_mentions_changing(a),
IntExprKind::Binary(_, a, b) => int_mentions_changing(a) || int_mentions_changing(b),
IntExprKind::IfThenElse(c, a, b) => {
formula_mentions_changing(c) || int_mentions_changing(a) || int_mentions_changing(b)
}
IntExprKind::SumOver(ds, body) => {
ds.iter().any(|d| expr_mentions_changing(&d.expr)) || int_mentions_changing(body)
}
}
}
fn formula_mentions_changing(f: &Formula) -> bool {
match f.kind() {
FormulaKind::Constant(_) => false,
FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
expr_mentions_changing(a) || expr_mentions_changing(b)
}
FormulaKind::Multiplicity(_, a) => expr_mentions_changing(a),
FormulaKind::Not(g) => formula_mentions_changing(g),
FormulaKind::And(fs) | FormulaKind::Or(fs) => fs.iter().any(formula_mentions_changing),
FormulaKind::Implies(a, b) | FormulaKind::Iff(a, b) => {
formula_mentions_changing(a) || formula_mentions_changing(b)
}
FormulaKind::Quantified(_, ds, body) => {
ds.iter().any(|d| expr_mentions_changing(&d.expr)) || formula_mentions_changing(body)
}
FormulaKind::Temporal(_, g) => formula_mentions_changing(g),
FormulaKind::TemporalBinary(_, a, b) => {
formula_mentions_changing(a) || formula_mentions_changing(b)
}
FormulaKind::IntCompare(_, a, b) => int_mentions_changing(a) || int_mentions_changing(b),
}
}
fn unwrap_always_state_only(f: &Formula) -> Option<Formula> {
let mut cur = f;
while let FormulaKind::And(fs) = cur.kind()
&& fs.len() == 1
{
cur = &fs[0];
}
match cur.kind() {
FormulaKind::Temporal(TemporalOp::Always, inner) if formula_is_state_only(inner) => {
Some(inner.clone())
}
_ if formula_is_state_only(cur) => Some(cur.clone()),
_ => None,
}
}
fn every_state_rule(f: &Formula) -> Option<Formula> {
let mut cur = f;
while let FormulaKind::And(fs) = cur.kind()
&& fs.len() == 1
{
cur = &fs[0];
}
match cur.kind() {
FormulaKind::Temporal(TemporalOp::Always, inner) if formula_is_state_only(inner) => {
Some(inner.clone())
}
FormulaKind::And(fs) => {
let mut parts = Vec::with_capacity(fs.len());
for g in fs {
parts.push(every_state_rule(g)?);
}
Some(Formula::and_all(parts))
}
_ if formula_is_state_only(cur) && !formula_mentions_changing(cur) => Some(cur.clone()),
_ => None,
}
}
fn build_holds_core(rules: &[(String, Formula)], used_indices: &[usize]) -> HoldsCore {
let mut used = Vec::new();
let mut unused = Vec::new();
for (i, (name, _)) in rules.iter().enumerate() {
if used_indices.contains(&i) {
if !used.contains(name) {
used.push(name.clone());
}
} else if !used.contains(name) && !unused.contains(name) {
unused.push(name.clone());
}
}
unused.retain(|n| !used.contains(n));
HoldsCore { used, unused }
}
fn solve_budgeted(
solver: &mut Cdcl,
assumptions: &[Lit],
remaining: &mut u64,
deadline: Option<std::time::Instant>,
) -> Solved {
if *remaining == 0 {
return Solved::Unknown;
}
let time = match deadline {
Some(d) => {
let Some(rem) = d.checked_duration_since(std::time::Instant::now()) else {
return Solved::Unknown;
};
if rem.is_zero() {
return Solved::Unknown;
}
Some(rem)
}
None => None,
};
let before = solver.conflicts();
let budget = Budget {
conflicts: Some(*remaining),
time,
};
let res = solver.solve(assumptions, &budget);
let spent = solver.conflicts().saturating_sub(before);
*remaining = remaining.saturating_sub(spent);
res
}
pub(crate) fn explain_core_budgeted(
bounds: &Bounds,
rules: &[(String, Formula)],
assertion: &Formula,
options: &Options,
remaining: &mut u64,
) -> Result<CoreResult, Vec<Error>> {
let mut errors = check_formula(assertion, Against::Bounds(bounds));
for (_, f) in rules {
for e in check_formula(f, Against::Bounds(bounds)) {
if !errors.contains(&e) {
errors.push(e);
}
}
}
if !errors.is_empty() {
return Err(errors);
}
let time_limit = options.budget.time.map(|d| std::time::Instant::now() + d);
if let Some(p) = unwrap_always_state_only(assertion) {
let sk_p = skolemize(&p.not(), bounds);
if higher_order(&sk_p.formula).is_empty() {
let mut circuit0 = Circuit::new();
let mut solver0 = Cdcl::new();
let root0 = {
let (mut tr, _, _) = Translator::new(&mut circuit0, &sk_p.bounds, Shape::single(0));
tr.formula(&sk_p.formula)
};
if !circuit0.assert(&mut solver0, root0) {
return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
}
match solve_budgeted(&mut solver0, &[], remaining, time_limit) {
Solved::Unsat => {
return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
}
Solved::Unknown => {
return Ok(CoreResult::Incomplete {
core: None,
note: "core extraction did not finish within budget".to_string(),
});
}
Solved::Sat => {}
}
let static_pairs: Vec<(usize, Formula)> = rules
.iter()
.enumerate()
.filter_map(|(i, (_, f))| every_state_rule(f).map(|sf| (i, sf)))
.collect();
if !static_pairs.is_empty() {
if *remaining == 0 || time_limit.is_some_and(|d| std::time::Instant::now() >= d) {
return Ok(CoreResult::Incomplete {
core: None,
note: "core extraction did not finish within budget".to_string(),
});
}
let mut cur_b = sk_p.bounds.clone();
let mut sk_static = Vec::with_capacity(static_pairs.len());
let mut static_ok = true;
for (orig_i, sf) in &static_pairs {
let skr = skolemize(sf, &cur_b);
if !higher_order(&skr.formula).is_empty() {
static_ok = false;
break;
}
cur_b = skr.bounds;
sk_static.push((*orig_i, skr.formula));
}
if static_ok {
let mut circuit1 = Circuit::new();
let mut solver1 = Cdcl::new();
let (root1, rbs) = {
let (mut tr, _, _) =
Translator::new(&mut circuit1, &cur_b, Shape::single(0));
let r = tr.formula(&sk_p.formula);
let bs: Vec<Bool> = sk_static.iter().map(|(_, f)| tr.formula(f)).collect();
(r, bs)
};
if !circuit1.assert(&mut solver1, root1) {
return Ok(CoreResult::Complete(build_holds_core(rules, &[])));
}
let mut lits = Vec::with_capacity(rbs.len());
for rb in rbs {
let act = Lit::positive(solver1.new_var());
circuit1.assert_if(&mut solver1, act, rb);
lits.push(act);
}
match solve_budgeted(&mut solver1, &lits, remaining, time_limit) {
Solved::Unsat => {
let init = solver1.unsat_core();
let mut core_pos: Vec<usize> = (0..lits.len())
.filter(|&k| init.contains(&lits[k]))
.collect();
let mut i = core_pos.len();
while i > 0 {
i -= 1;
let without: Vec<Lit> = core_pos
.iter()
.enumerate()
.filter(|&(j, _)| j != i)
.map(|(_, &k)| lits[k])
.collect();
match solve_budgeted(&mut solver1, &without, remaining, time_limit)
{
Solved::Unsat => {
let refined = solver1.unsat_core();
core_pos.retain(|&k| refined.contains(&lits[k]));
i = i.min(core_pos.len());
}
Solved::Unknown => {
let orig: Vec<usize> =
core_pos.iter().map(|&k| sk_static[k].0).collect();
return Ok(CoreResult::Incomplete {
core: Some(build_holds_core(rules, &orig)),
note: "core minimization did not finish within budget; used rules may not be minimal".to_string(),
});
}
Solved::Sat => {}
}
}
let orig: Vec<usize> =
core_pos.iter().map(|&k| sk_static[k].0).collect();
return Ok(CoreResult::Complete(build_holds_core(rules, &orig)));
}
Solved::Unknown => {
return Ok(CoreResult::Incomplete {
core: None,
note: "core extraction did not finish within budget".to_string(),
});
}
Solved::Sat => {}
}
}
}
}
}
let sk_assert = skolemize(&assertion.not(), bounds);
let mut ho = higher_order(&sk_assert.formula);
let mut sk_rules = Vec::with_capacity(rules.len());
let mut cur_bounds = sk_assert.bounds;
for (_, f) in rules {
let sk_r = skolemize(f, &cur_bounds);
for e in higher_order(&sk_r.formula) {
if !ho.contains(&e) {
ho.push(e);
}
}
cur_bounds = sk_r.bounds;
sk_rules.push(sk_r.formula);
}
if !ho.is_empty() {
return Err(ho);
}
let temporal = cur_bounds.relations().any(Relation::is_changing);
let mut depth = sk_assert.formula.past_depth();
for f in &sk_rules {
depth = depth.max(f.past_depth());
}
let mut shape_list = shapes(temporal, options.steps, depth);
shape_list.reverse();
let mut active_solvers: Vec<(Cdcl, Vec<Lit>)> = Vec::new();
let mut union_mask = vec![false; rules.len()];
for shape in shape_list {
if *remaining == 0 || time_limit.is_some_and(|d| std::time::Instant::now() >= d) {
return Ok(CoreResult::Incomplete {
core: None,
note: "core extraction did not finish within budget".to_string(),
});
}
let mut circuit = Circuit::new();
let mut solver = Cdcl::new();
let (root, rule_bools) = {
let (mut tr, _, loop_vars) = Translator::new(&mut circuit, &cur_bounds, shape);
let mut root = tr.formula(&sk_assert.formula);
if !loop_vars.is_empty() && root != Bool::FALSE {
let lc = tr.loop_constraint();
root = tr.circuit.and([root, lc]);
}
let rbs: Vec<Bool> = sk_rules.iter().map(|f| tr.formula(f)).collect();
(root, rbs)
};
if !circuit.assert(&mut solver, root) {
continue;
}
let mut lits = Vec::with_capacity(rule_bools.len());
for rb in rule_bools {
let act = Lit::positive(solver.new_var());
circuit.assert_if(&mut solver, act, rb);
lits.push(act);
}
match solve_budgeted(&mut solver, &lits, remaining, time_limit) {
Solved::Sat => return Ok(CoreResult::NotUnsat),
Solved::Unknown => {
return Ok(CoreResult::Incomplete {
core: None,
note: "core extraction did not finish within budget".to_string(),
});
}
Solved::Unsat => {
let init = solver.unsat_core();
for (i, lit) in lits.iter().enumerate() {
if init.contains(lit) {
union_mask[i] = true;
}
}
active_solvers.push((solver, lits));
}
}
}
let mut core: Vec<usize> = (0..rules.len()).filter(|&i| union_mask[i]).collect();
let mut trial_order: Vec<usize> = core
.iter()
.copied()
.filter(|&i| every_state_rule(&rules[i].1).is_none())
.rev()
.collect();
trial_order.extend(
core.iter()
.copied()
.filter(|&i| every_state_rule(&rules[i].1).is_some())
.rev(),
);
for cand in trial_order {
if !core.contains(&cand) {
continue;
}
let without_idx: Vec<usize> = core.iter().copied().filter(|&i| i != cand).collect();
let mut all_unsat = true;
for (solver, lits) in &mut active_solvers {
let assumps: Vec<Lit> = without_idx.iter().map(|&i| lits[i]).collect();
match solve_budgeted(solver, &assumps, remaining, time_limit) {
Solved::Unsat => {}
Solved::Sat => {
all_unsat = false;
break;
}
Solved::Unknown => {
return Ok(CoreResult::Incomplete {
core: Some(build_holds_core(rules, &core)),
note: "core minimization did not finish within budget; used rules may not be minimal".to_string(),
});
}
}
}
if all_unsat {
core = without_idx;
}
}
Ok(CoreResult::Complete(build_holds_core(rules, &core)))
}
pub fn explain_core(
bounds: &Bounds,
rules: &[(String, Formula)],
assertion: &Formula,
options: &Options,
) -> Result<Option<HoldsCore>, Vec<Error>> {
let mut remaining = options.budget.conflicts.unwrap_or(DEFAULT_CONFLICTS);
match explain_core_budgeted(bounds, rules, assertion, options, &mut remaining)? {
CoreResult::Complete(core) => Ok(Some(core)),
CoreResult::Incomplete { .. } | CoreResult::NotUnsat => Ok(None),
}
}
pub fn tuples_named<'a>(instance: &'a Instance, name: &str) -> Option<&'a TupleSet> {
instance
.entries()
.find(|(r, _)| r.name() == name)
.map(|(_, t)| t)
}
#[cfg(test)]
mod tests {
use super::*;
use elinvar_logic::{Expr, Universe};
#[test]
fn worked_examples_on_a_fixed_loop() {
let u = Universe::new(["A"]).expect("one atom is a universe");
let r = Relation::changing("s", 1);
let mut bounds = Bounds::new(&u);
bounds
.bound_upper(&r, u.all(1).expect("arity 1"))
.expect("s is new");
let s = Expr::relation(&r);
let (some, none) = (s.some(), s.no());
let pinned = none.and(&some.and(&none.after()).after());
let cases: Vec<(Formula, bool)> = vec![
(some.clone(), false),
(some.after(), true),
(some.eventually(), true),
(some.always(), false),
(some.eventually().always(), true),
(some.always().eventually(), false),
(none.until(&some), true),
(some.releases(&none), false),
(some.once(), false),
(some.once().after(), true),
(some.before().after().after(), true),
(none.historically().eventually(), true),
(some.implies(&none.before()).always(), true),
(none.since(&some).after(), true),
(some.triggered(&none), true),
(s.prime().equals(&s), false),
(s.prime().equals(&s).not().always(), true),
];
for (f, want) in cases {
for (g, holds) in [(f.clone(), want), (f.not(), !want)] {
let full = pinned.and(&g);
let found = shrink_tuples(
&bounds,
&full,
&bounds,
&full,
3,
1,
1_000_000,
Box::new(Cdcl::new()),
);
assert_eq!(found.is_some(), holds, "{g}");
}
}
}
}