elinvar-engine 0.1.2

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
//! Skolemization (LOGIC.md section 12.2): an existential with no universal
//! above it becomes a relation, so its witness has a name in the instance.

use elinvar_logic::{
    BinaryOp, Bounds, Decl, DeclMult, Expr, ExprKind, Formula, FormulaKind, Instance, IntExpr,
    IntExprKind, Quantifier, Relation, TupleSet, Variable, evaluate_expr,
};
use std::collections::BTreeMap;

/// The result: the new formula and the bounds with the skolem relations
/// added after the user's.
pub struct Skolemized {
    pub formula: Formula,
    pub bounds: Bounds,
}

/// Skolemizes a checked formula under checked 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,
    /// Every relation at its upper bound, for the approximations.
    upper: Instance,
}

impl Skolemizer {
    fn formula(&mut self, f: &Formula, negated: bool) -> Formula {
        match f.kind() {
            FormulaKind::Not(g) => self.formula(g, !negated).not(),
            // A conjunction or disjunction of one formula is that formula.
            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 => {
                // not (a implies b) is a and not b.
                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);
                    // LOGIC.md 12.2: `m $x and $x in e`, nothing for `set`.
                    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 {
                    // not (no x | B) is satisfied as `guard and B`, B
                    // positive, so the formula under the negation is its
                    // negation (LOGIC.md 12.2).
                    let body = self.formula(&body, false);
                    return guard.and(&body).not();
                }
                let body = self.formula(&body, negated);
                if negated {
                    // not (all x | B) is satisfied as `guard and not B`,
                    // so the formula under the negation is `guard implies B`.
                    guard.implies(&body)
                } else {
                    guard.and(&body)
                }
            }
            _ => f.clone(),
        }
    }

    /// A new skolem relation for `var`, bounded above by the upper
    /// approximation of `e`.
    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
    }
}

/// The upper approximation of an expression (LOGIC.md 12.2), as an
/// expression with only operators that grow with their operands. A
/// variable stands for its declaration's approximation.
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)),
        // Every relation holds its upper bound in every state, so the next
        // state's value is approximated as the current one's.
        ExprKind::Prime(a) => approximate(a, vars),
        // LOGIC.md 16.4: no relation holds just the integer atoms; `univ`
        // holds them all.
        ExprKind::IntToSet(_) => Expr::univ(),
        ExprKind::Relation(_) | ExprKind::None | ExprKind::Univ | ExprKind::Iden => e.clone(),
    }
}

type Memo<T> = BTreeMap<usize, T>;

/// Replaces variables by expressions, keeping shared nodes shared.
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
}

/// Replaces variables by expressions in an integer expression.
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()
}

/// Replaces variables by expressions in a formula.
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
}