elinvar-engine 0.1.2

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
//! LOGIC.md 16.4: the integer circuits agree with the referee's definitions
//! of 16.2 and 16.3 (AGENTS.md law 29).
//!
//! Each problem has one solution for each choice of its free sets, so the
//! number of instances is known by hand, and every instance found is
//! refereed by the evaluator before it is counted (law 13): a wrong circuit
//! either breaks the count or fails the referee. A set a problem does not
//! use is held empty, so it does not multiply the count.

#![allow(clippy::unwrap_used)] // test helpers, as clippy.toml allows in tests

use elinvar_engine::logic::{Bounds, Expr, Formula, IntExpr, IntOp, Relation, Universe};
use elinvar_engine::{Options, count};

/// Bitwidth 3: atoms `-4` to `3`, each its integer; unary `s`, `t`, `u`
/// bounded above by all of them.
fn problem() -> (Bounds, Expr, Expr, Expr) {
    let names: Vec<String> = (-4..=3).map(|v: i64| v.to_string()).collect();
    let pairs: Vec<(&str, i64)> = names
        .iter()
        .map(|n| (n.as_str(), n.parse::<i64>().unwrap()))
        .collect();
    let u = Universe::new(names.clone())
        .unwrap()
        .with_ints(3, &pairs)
        .unwrap();
    let mut b = Bounds::new(&u);
    let all = u.all(1).unwrap();
    let rel = |name: &str, b: &mut Bounds| {
        let r = Relation::unary(name);
        b.bound_upper(&r, all.clone()).unwrap();
        Expr::relation(&r)
    };
    let s = rel("s", &mut b);
    let t = rel("t", &mut b);
    let w = rel("u", &mut b);
    (b, s, t, w)
}

fn instances(b: &Bounds, f: &Formula) -> u64 {
    count(b, f, &Options::default().symmetry_breaking(false), 10_000)
        .unwrap()
        .expect("the default budget is enough")
}

#[test]
fn arithmetic_agrees_with_the_referee() {
    // one s, t, u and (sum s) op (sum t) = sum u: u is fixed by s and t,
    // since every integer has its atom, so there are 8 * 8 instances.
    for op in [
        IntOp::Plus,
        IntOp::Minus,
        IntOp::Times,
        IntOp::Divide,
        IntOp::Remainder,
        // At bitwidth 3 the amount has 2 bits, so 3 shifts every bit out.
        IntOp::ShiftLeft,
        IntOp::ShiftRight,
        IntOp::UnsignedShiftRight,
    ] {
        let (b, s, t, u) = problem();
        let f = Formula::and_all([
            s.one(),
            t.one(),
            u.one(),
            s.sum().apply(op, &t.sum()).equals(&u.sum()),
        ]);
        assert_eq!(instances(&b, &f), 64, "{op:?}");
    }
}

#[test]
fn negation_and_conditionals() {
    let (b, s, t, u) = problem();
    let f = Formula::and_all([s.one(), t.no(), u.one(), s.sum().negate().equals(&u.sum())]);
    assert_eq!(instances(&b, &f), 8);
    let (b, s, t, u) = problem();
    let max = IntExpr::if_then_else(&s.sum().gt(&t.sum()), &s.sum(), &t.sum());
    let f = Formula::and_all([s.one(), t.one(), u.one(), max.equals(&u.sum())]);
    assert_eq!(instances(&b, &f), 64);
}

#[test]
fn comparisons_agree_with_the_referee() {
    // Of the 64 pairs of integers, 28 are less, 8 equal, 28 greater.
    let (b, s, t, u) = problem();
    let pair = |f: Formula| Formula::and_all([s.one(), t.one(), u.no(), f]);
    assert_eq!(instances(&b, &pair(s.sum().lt(&t.sum()))), 28);
    assert_eq!(instances(&b, &pair(s.sum().lte(&t.sum()))), 36);
    assert_eq!(instances(&b, &pair(s.sum().equals(&t.sum()))), 8);
    assert_eq!(instances(&b, &pair(s.sum().gt(&t.sum()))), 28);
    assert_eq!(instances(&b, &pair(s.sum().gte(&t.sum()))), 36);
}

#[test]
fn counts_and_sums_of_sets() {
    // Any s, one u: u is #s or sum s, wrapped, so 2^8 instances each.
    let (b, s, t, u) = problem();
    let f = Formula::and_all([t.no(), u.one(), s.count().equals(&u.sum())]);
    assert_eq!(instances(&b, &f), 256);
    let (b, s, t, u) = problem();
    let f = Formula::and_all([t.no(), u.one(), s.sum().equals(&u.sum())]);
    assert_eq!(instances(&b, &f), 256);
}

#[test]
fn sums_over_bindings_and_the_set_of_an_integer() {
    let (b, s, t, u) = problem();
    let x = elinvar_engine::logic::Variable::new("x");
    let per = IntExpr::sum_over(
        vec![elinvar_engine::logic::Decl::new(&x, &s)],
        &Expr::variable(&x).sum(),
    );
    let f = Formula::and_all([t.no(), u.one(), per.equals(&u.sum())]);
    assert_eq!(instances(&b, &f), 256);
    // Int[sum s + sum t] = u, with one s and one t: 64.
    let (b, s, t, u) = problem();
    let f = Formula::and_all([s.one(), t.one(), s.sum().plus(&t.sum()).to_set().equals(&u)]);
    assert_eq!(instances(&b, &f), 64);
}

/// LOGIC.md 12.9: `Int` holds one atom per integer of the bitwidth, from
/// the least, and a bitwidth above 16 is an error.
#[test]
fn the_builders_int_set() {
    let mut m = elinvar_engine::Model::new();
    let ints = m.ints();
    // 16 atoms at the default bitwidth of 4, named -8 to 7.
    let b = m.check(&Formula::truth()).bounds().unwrap();
    let names: Vec<&str> = b.universe().atoms().collect();
    assert_eq!(names.first(), Some(&"-8"));
    assert_eq!(names.last(), Some(&"7"));
    assert_eq!(b.universe().int_of(0), Some(-8));
    let wide = m.check(&Formula::truth()).bitwidth(17);
    let errors = wide.bounds().unwrap_err();
    assert_eq!(errors[0].code, "model.bitwidth");
    let narrow = m
        .check(&ints.count().equals(&IntExpr::constant(0)))
        .bitwidth(3);
    assert_eq!(narrow.bounds().unwrap().universe().size(), 8);
}

/// Alloy `noOverflow`: at bitwidth 3 (-4..3), `3 + 1` wraps to `-4` by default
/// (so `some s: one Int | sum s + 1 < 0` is satisfiable), while with
/// `no_overflow(true)` every overflowing case is ruled out.
#[test]
fn no_overflow_forbids_wrapping_arithmetic() {
    let (b, s, t, u) = problem(); // bitwidth 3: -4..=3
    // 3 + 1 wraps to -4; without no_overflow, `s = {3}` satisfies `s > 0 && s + 1 < 0`.
    let positive_wraps_negative = Formula::and_all([
        s.one(),
        t.no(),
        u.no(),
        s.sum().gt(&IntExpr::constant(0)),
        s.sum()
            .plus(&IntExpr::constant(1))
            .lt(&IntExpr::constant(0)),
    ]);
    let default_out =
        elinvar_engine::run(&b, &positive_wraps_negative, &Options::default()).unwrap();
    assert_eq!(default_out.verdict, elinvar_engine::Verdict::Found);
    let no_ovf_out = elinvar_engine::run(
        &b,
        &positive_wraps_negative,
        &Options::default().no_overflow(true),
    )
    .unwrap();
    assert_eq!(no_ovf_out.verdict, elinvar_engine::Verdict::None);

    // Multiplication overflow: `2 * 2 = 4` wraps to `-4` in 3-bit signed.
    let mul_wraps = Formula::and_all([
        s.one(),
        t.no(),
        u.no(),
        s.sum().equals(&IntExpr::constant(2)),
        s.sum()
            .times(&IntExpr::constant(2))
            .lt(&IntExpr::constant(0)),
    ]);
    assert_eq!(
        elinvar_engine::run(&b, &mul_wraps, &Options::default())
            .unwrap()
            .verdict,
        elinvar_engine::Verdict::Found
    );
    assert_eq!(
        elinvar_engine::run(&b, &mul_wraps, &Options::default().no_overflow(true))
            .unwrap()
            .verdict,
        elinvar_engine::Verdict::None
    );

    // Negation overflow: `-(-4)` wraps to `-4` in 3-bit signed.
    let neg_wraps = Formula::and_all([
        s.one(),
        t.no(),
        u.no(),
        s.sum().equals(&IntExpr::constant(-4)),
        s.sum().negate().lt(&IntExpr::constant(0)),
    ]);
    assert_eq!(
        elinvar_engine::run(&b, &neg_wraps, &Options::default())
            .unwrap()
            .verdict,
        elinvar_engine::Verdict::Found
    );
    assert_eq!(
        elinvar_engine::run(&b, &neg_wraps, &Options::default().no_overflow(true))
            .unwrap()
            .verdict,
        elinvar_engine::Verdict::None
    );
}