use elinvar_logic::{
BinaryOp, Bounds, Decl, DeclMult, Expr, ExprKind, Formula, FormulaKind, Instance, IntExpr,
IntExprKind, Quantifier, Relation, TupleSet, Variable, evaluate_expr,
};
use std::collections::BTreeMap;
pub struct Skolemized {
pub formula: Formula,
pub bounds: Bounds,
}
pub fn skolemize(formula: &Formula, bounds: &Bounds) -> Skolemized {
let mut upper = Instance::new(bounds.universe());
for (r, _, u) in bounds.entries() {
upper
.set(r, u.clone())
.expect("relations of checked bounds are distinct and well formed");
}
let mut s = Skolemizer {
bounds: bounds.clone(),
upper,
};
let formula = s.formula(formula, false);
Skolemized {
formula,
bounds: s.bounds,
}
}
struct Skolemizer {
bounds: Bounds,
upper: Instance,
}
impl Skolemizer {
fn formula(&mut self, f: &Formula, negated: bool) -> Formula {
match f.kind() {
FormulaKind::Not(g) => self.formula(g, !negated).not(),
FormulaKind::And(fs) | FormulaKind::Or(fs) if fs.len() == 1 => {
self.formula(&fs[0], negated)
}
FormulaKind::And(fs) if !negated => Formula::and_all(
fs.iter()
.map(|g| self.formula(g, false))
.collect::<Vec<_>>(),
),
FormulaKind::Or(fs) if negated => {
Formula::or_all(fs.iter().map(|g| self.formula(g, true)).collect::<Vec<_>>())
}
FormulaKind::Implies(a, b) if negated => {
let a = self.formula(a, false);
let b = self.formula(b, true);
a.implies(&b)
}
FormulaKind::Quantified(q, decls, body)
if (*q == Quantifier::Some && !negated)
|| (matches!(q, Quantifier::All | Quantifier::No) && negated) =>
{
let mut map: Vec<(Variable, Expr)> = Vec::new();
let mut constraints = Vec::new();
for d in decls {
let e = substitute_expr(&d.expr, &map, &mut BTreeMap::new());
let sk = self.fresh(&d.var, &e);
let ske = Expr::relation(&sk);
match d.mult {
DeclMult::One => constraints.push(ske.one()),
DeclMult::Lone => constraints.push(ske.lone()),
DeclMult::Some => constraints.push(ske.some()),
DeclMult::Set => {}
}
constraints.push(ske.is_in(&e));
map.push((d.var.clone(), ske));
}
let body = substitute_formula(body, &map, &mut BTreeMap::new());
let guard = Formula::and_all(constraints);
if *q == Quantifier::No {
let body = self.formula(&body, false);
return guard.and(&body).not();
}
let body = self.formula(&body, negated);
if negated {
guard.implies(&body)
} else {
guard.and(&body)
}
}
_ => f.clone(),
}
}
fn fresh(&mut self, var: &Variable, e: &Expr) -> Relation {
let base = format!("${}", var.name());
let taken = |name: &str| self.bounds.relations().any(|r| r.name() == name);
let mut name = base.clone();
let mut k = 2;
while taken(&name) {
name = format!("{base}_{k}");
k += 1;
}
let approx = approximate(e, &mut Vec::new());
let upper: TupleSet = evaluate_expr(&self.upper, &approx)
.expect("the approximation of a checked expression is well formed");
let r = Relation::new(name, var.arity());
self.bounds
.bound_upper(&r, upper.clone())
.expect("a skolem relation has a fresh name and an upper bound of its arity");
self.upper
.set(&r, upper)
.expect("a skolem relation has a fresh name and an upper bound of its arity");
r
}
}
fn approximate(e: &Expr, vars: &mut Vec<(Variable, Expr)>) -> Expr {
match e.kind() {
ExprKind::Variable(v) => vars
.iter()
.rev()
.find(|(w, _)| w == v)
.map(|(_, a)| a.clone())
.unwrap_or_else(|| e.clone()),
ExprKind::Binary(BinaryOp::Difference, a, _) => approximate(a, vars),
ExprKind::Binary(BinaryOp::Override, a, b) => {
approximate(a, vars).union(&approximate(b, vars))
}
ExprKind::Binary(op, a, b) => approximate(a, vars).apply_binary(*op, &approximate(b, vars)),
ExprKind::Unary(op, a) => approximate(a, vars).apply_unary(*op),
ExprKind::Comprehension(decls, _) => {
let mut product: Option<Expr> = None;
let depth = vars.len();
for d in decls {
let a = approximate(&d.expr, vars);
vars.push((d.var.clone(), a.clone()));
product = Some(match product {
None => a,
Some(p) => p.product(&a),
});
}
vars.truncate(depth);
product.expect("a checked comprehension has a declaration")
}
ExprKind::IfThenElse(_, a, b) => approximate(a, vars).union(&approximate(b, vars)),
ExprKind::Prime(a) => approximate(a, vars),
ExprKind::IntToSet(_) => Expr::univ(),
ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => e.clone(),
}
}
type Memo<T> = BTreeMap<usize, T>;
pub fn substitute_expr(e: &Expr, map: &[(Variable, Expr)], memo: &mut Memo<Expr>) -> Expr {
if map.is_empty() {
return e.clone();
}
let id = (e.kind() as *const ExprKind) as usize;
if let Some(x) = memo.get(&id) {
return x.clone();
}
let out = match e.kind() {
ExprKind::Variable(v) => map
.iter()
.find(|(w, _)| w == v)
.map(|(_, x)| x.clone())
.unwrap_or_else(|| e.clone()),
ExprKind::Binary(op, a, b) => {
substitute_expr(a, map, memo).apply_binary(*op, &substitute_expr(b, map, memo))
}
ExprKind::Unary(op, a) => substitute_expr(a, map, memo).apply_unary(*op),
ExprKind::Comprehension(decls, body) => {
let decls = substitute_decls(decls, map, memo);
let body = substitute_formula(body, map, &mut BTreeMap::new());
Expr::comprehension(decls, &body)
}
ExprKind::IfThenElse(c, a, b) => Expr::if_then_else(
&substitute_formula(c, map, &mut BTreeMap::new()),
&substitute_expr(a, map, memo),
&substitute_expr(b, map, memo),
),
ExprKind::Prime(a) => substitute_expr(a, map, memo).prime(),
ExprKind::IntToSet(v) => substitute_int(v, map).to_set(),
ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => e.clone(),
};
memo.insert(id, out.clone());
out
}
pub fn substitute_int(v: &IntExpr, map: &[(Variable, Expr)]) -> IntExpr {
if map.is_empty() {
return v.clone();
}
let mut em = BTreeMap::new();
match v.kind() {
IntExprKind::Constant(_) => v.clone(),
IntExprKind::Count(e) => substitute_expr(e, map, &mut em).count(),
IntExprKind::Sum(e) => substitute_expr(e, map, &mut em).sum(),
IntExprKind::Binary(op, a, b) => substitute_int(a, map).apply(*op, &substitute_int(b, map)),
IntExprKind::Negate(a) => substitute_int(a, map).negate(),
IntExprKind::IfThenElse(c, a, b) => IntExpr::if_then_else(
&substitute_formula(c, map, &mut BTreeMap::new()),
&substitute_int(a, map),
&substitute_int(b, map),
),
IntExprKind::SumOver(decls, body) => IntExpr::sum_over(
substitute_decls(decls, map, &mut em),
&substitute_int(body, map),
),
}
}
fn substitute_decls(decls: &[Decl], map: &[(Variable, Expr)], memo: &mut Memo<Expr>) -> Vec<Decl> {
decls
.iter()
.map(|d| Decl::with(&d.var, d.mult, &substitute_expr(&d.expr, map, memo)))
.collect()
}
pub fn substitute_formula(
f: &Formula,
map: &[(Variable, Expr)],
memo: &mut Memo<Formula>,
) -> Formula {
if map.is_empty() {
return f.clone();
}
let id = (f.kind() as *const FormulaKind) as usize;
if let Some(x) = memo.get(&id) {
return x.clone();
}
let mut em = BTreeMap::new();
let out = match f.kind() {
FormulaKind::Subset(a, b) => {
substitute_expr(a, map, &mut em).is_in(&substitute_expr(b, map, &mut em))
}
FormulaKind::Equal(a, b) => {
substitute_expr(a, map, &mut em).equals(&substitute_expr(b, map, &mut em))
}
FormulaKind::Multiplicity(m, a) => substitute_expr(a, map, &mut em).apply_multiplicity(*m),
FormulaKind::Not(g) => substitute_formula(g, map, memo).not(),
FormulaKind::And(fs) => Formula::and_all(
fs.iter()
.map(|g| substitute_formula(g, map, memo))
.collect::<Vec<_>>(),
),
FormulaKind::Or(fs) => Formula::or_all(
fs.iter()
.map(|g| substitute_formula(g, map, memo))
.collect::<Vec<_>>(),
),
FormulaKind::Implies(a, b) => {
substitute_formula(a, map, memo).implies(&substitute_formula(b, map, memo))
}
FormulaKind::Iff(a, b) => {
substitute_formula(a, map, memo).iff(&substitute_formula(b, map, memo))
}
FormulaKind::Quantified(q, decls, body) => Formula::quantified(
*q,
substitute_decls(decls, map, &mut em),
&substitute_formula(body, map, memo),
),
FormulaKind::Temporal(op, g) => substitute_formula(g, map, memo).temporal(*op),
FormulaKind::TemporalBinary(op, a, b) => {
substitute_formula(a, map, memo).temporal_binary(*op, &substitute_formula(b, map, memo))
}
FormulaKind::IntCompare(op, a, b) => {
substitute_int(a, map).compare_with(*op, &substitute_int(b, map))
}
FormulaKind::Constant(_) => f.clone(),
};
memo.insert(id, out.clone());
out
}