elinvar-logic 0.1.2

The relational logic of Elinvar and its evaluator, the referee for every answer
Documentation
//! LOGIC.md sections 1, 2, 6, and 8: the error codes outside expressions,
//! and the code table itself.

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

use elinvar_logic::{
    Against, Bounds, CODES, Expr, Formula, Instance, Relation, TupleSet, Universe, check_formula,
    count, evaluate, instances,
};

fn code<T: std::fmt::Debug>(r: Result<T, elinvar_logic::Error>) -> &'static str {
    r.unwrap_err().code
}

#[test]
fn universe_errors() {
    assert_eq!(code(Universe::new(Vec::<String>::new())), "universe.empty");
    assert_eq!(code(Universe::new(["A", "A"])), "universe.duplicate_atom");
    let u = Universe::new(["A", "B"]).unwrap();
    assert_eq!(code(u.tuple(&["C"])), "universe.unknown_atom");
    assert_eq!(code(u.tuple(&[])), "arity.zero");
    assert_eq!(code(TupleSet::empty(&u, 0)), "arity.zero");
}

#[test]
fn a_tuple_index_past_the_last_tuple_is_refused() {
    // LOGIC.md 1: the tuples of arity k over n atoms have indices 0 to n^k - 1.
    let u = Universe::new(["A", "B"]).unwrap();
    let mut t = TupleSet::empty(&u, 2).unwrap();
    assert_eq!(t.insert_index(3), Ok(true));
    assert_eq!(code(t.insert_index(4)), "tuples.index");
}

#[test]
fn capacity_is_n_to_the_k_at_most_2_to_the_64_minus_1() {
    // LOGIC.md 1: n^k <= 2^64 - 1. With n = 2, k = 63 fits and k = 64 does not.
    let two = Universe::new(["A", "B"]).unwrap();
    assert!(TupleSet::empty(&two, 63).is_ok());
    assert_eq!(code(TupleSet::empty(&two, 64)), "universe.capacity");

    // An expression meets the universe when it is evaluated.
    let r = Relation::new("r", 40);
    let mut i = Instance::new(&two);
    i.set(&r, TupleSet::empty(&two, 40).unwrap()).unwrap();
    let wide = Expr::relation(&r).product(&Expr::relation(&r));
    let errors = evaluate(&i, &wide.no()).unwrap_err();
    assert_eq!(errors.len(), 1);
    assert_eq!(errors[0].code, "universe.capacity");
}

#[test]
fn tuple_set_errors() {
    let u = Universe::new(["A", "B"]).unwrap();
    let v = Universe::new(["B", "A"]).unwrap();
    let mut s = TupleSet::empty(&u, 1).unwrap();
    assert_eq!(
        code(s.insert(&u.tuple(&["A", "B"]).unwrap())),
        "tuples.arity"
    );
    assert_eq!(
        code(s.insert(&v.tuple(&["A"]).unwrap())),
        "tuples.other_universe"
    );
    // Same names in the same order are the same universe.
    let w = Universe::new(["A", "B"]).unwrap();
    assert!(s.insert(&w.tuple(&["A"]).unwrap()).unwrap());
}

#[test]
fn bounds_errors() {
    let u = Universe::new(["A", "B"]).unwrap();
    let other = Universe::new(["X"]).unwrap();
    let r = Relation::binary("r");
    let mut b = Bounds::new(&u);
    let all2 = u.all(2).unwrap();
    assert_eq!(code(b.bound_upper(&r, u.all(1).unwrap())), "bounds.arity");
    assert_eq!(
        code(b.bound_upper(&r, other.all(2).unwrap())),
        "bounds.other_universe"
    );
    assert_eq!(
        code(b.bound(
            &r,
            u.tuple_set(2, &[&["A", "B"]]).unwrap(),
            u.tuple_set(2, &[&["B", "A"]]).unwrap()
        )),
        "bounds.lower_outside_upper"
    );
    b.bound_upper(&r, all2.clone()).unwrap();
    assert_eq!(
        code(b.bound_upper(&r, all2.clone())),
        "bounds.duplicate_relation"
    );
    let r2 = Relation::binary("r");
    assert_eq!(code(b.bound_upper(&r2, all2)), "bounds.duplicate_name");
    let z = Relation::new("z", 0);
    assert_eq!(code(b.bound_upper(&z, u.all(1).unwrap())), "arity.zero");
}

#[test]
fn instance_errors() {
    let u = Universe::new(["A", "B"]).unwrap();
    let other = Universe::new(["X"]).unwrap();
    let r = Relation::binary("r");
    let mut i = Instance::new(&u);
    assert_eq!(code(i.set(&r, u.all(1).unwrap())), "instance.arity");
    assert_eq!(
        code(i.set(&r, other.all(2).unwrap())),
        "instance.other_universe"
    );
    i.set(&r, u.all(2).unwrap()).unwrap();
    assert_eq!(
        code(i.set(&r, u.all(2).unwrap())),
        "instance.duplicate_relation"
    );
    assert_eq!(
        code(i.set(&Relation::binary("r"), u.all(2).unwrap())),
        "instance.duplicate_name"
    );
}

#[test]
fn missing_and_unbound_relations() {
    let u = Universe::new(["A"]).unwrap();
    let r = Relation::unary("r");
    let i = Instance::new(&u);
    let f = Expr::relation(&r).some();
    let errors = evaluate(&i, &f).unwrap_err();
    assert_eq!(errors[0].code, "instance.missing_relation");
    let b = Bounds::new(&u);
    let errors = check_formula(&f, Against::Bounds(&b));
    assert_eq!(errors[0].code, "logic.unbound_relation");
}

#[test]
fn a_relation_of_arity_zero_is_reported_where_it_is_used() {
    let u = Universe::new(["A"]).unwrap();
    let z = Relation::new("z", 0);
    let f = Expr::relation(&z).some();
    let errors = evaluate(&Instance::new(&u), &f).unwrap_err();
    let codes: Vec<_> = errors.iter().map(|e| e.code).collect();
    assert_eq!(codes, ["arity.zero"]);
}

#[test]
fn empty_declarations() {
    let u = Universe::new(["A"]).unwrap();
    let f = Formula::all(vec![], &Formula::truth());
    let errors = evaluate(&Instance::new(&u), &f).unwrap_err();
    assert_eq!(errors[0].code, "logic.no_declarations");
    let e = Expr::comprehension(vec![], &Formula::truth());
    assert_eq!(e.arity(), None);
}

#[test]
fn enumeration_cap() {
    let u = Universe::new(["A", "B", "C", "D", "E", "F", "G", "H"]).unwrap();
    let r = Relation::binary("r");
    let mut b = Bounds::new(&u);
    b.bound_upper(&r, u.all(2).unwrap()).unwrap();
    // 64 free tuples: above 63 whatever the cap.
    assert_eq!(
        instances(&b, usize::MAX).unwrap_err().code,
        "enumerate.too_large"
    );
    assert_eq!(instances(&b, 10).unwrap_err().code, "enumerate.too_large");
    let errors = count(&b, &Formula::truth(), usize::MAX).unwrap_err();
    assert_eq!(errors[0].code, "enumerate.too_large");
}

#[test]
fn enumeration_order() {
    // LOGIC.md 8: free tuples relation by relation, then by index; instance
    // j sets the free tuples whose bit is set.
    let u = Universe::new(["A", "B"]).unwrap();
    let s = Relation::unary("s");
    let t = Relation::unary("t");
    let mut b = Bounds::new(&u);
    b.bound(&s, u.tuple_set(1, &[&["A"]]).unwrap(), u.all(1).unwrap())
        .unwrap();
    b.bound_upper(&t, u.tuple_set(1, &[&["A"]]).unwrap())
        .unwrap();
    let seen: Vec<String> = instances(&b, 8)
        .unwrap()
        .map(|i| format!("s={} t={}", i.get(&s).unwrap(), i.get(&t).unwrap()))
        .collect();
    assert_eq!(
        seen,
        [
            "s={A} t={}",
            "s={A, B} t={}",
            "s={A} t={A}",
            "s={A, B} t={A}",
        ]
    );
}

#[test]
fn instances_serialize_by_name_in_order() {
    let u = Universe::new(["A", "B"]).unwrap();
    let r = Relation::binary("r");
    let s = Relation::unary("s");
    let mut i = Instance::new(&u);
    i.set(&r, u.tuple_set(2, &[&["B", "A"], &["A", "B"]]).unwrap())
        .unwrap();
    i.set(&s, u.tuple_set(1, &[]).unwrap()).unwrap();
    let json = serde_json::to_string(&i).unwrap();
    assert_eq!(
        json,
        r#"{"atoms":["A","B"],"relations":[{"name":"r","arity":2,"tuples":[["A","B"],["B","A"]]},{"name":"s","arity":1,"tuples":[]}]}"#
    );
}

#[test]
fn errors_serialize_with_code_fix_and_place() {
    let u = Universe::new(["A"]).unwrap();
    let s = Relation::unary("s");
    let r = Relation::binary("r");
    let mut i = Instance::new(&u);
    i.set(&s, u.all(1).unwrap()).unwrap();
    i.set(&r, u.all(2).unwrap()).unwrap();
    let errors = evaluate(&i, &Expr::relation(&s).union(&Expr::relation(&r)).some()).unwrap_err();
    let v: serde_json::Value = serde_json::to_value(&errors[0]).unwrap();
    assert_eq!(v["code"], "arity.mismatch");
    assert!(v["fix"].as_str().unwrap().contains("same arity"));
    assert!(v["place"]["line"].as_u64().unwrap() > 0);
}

/// Every code in the tables of LOGIC.md, but those of the model builder and
/// the text reader, is in `CODES`, and every code in `CODES` is in a table.
#[test]
fn codes_match_the_spec() {
    let spec_path =
        std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/LOGIC.md"));
    if !std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../Cargo.toml")).exists() {
        // Unpacked crate tarball without the workspace's docs/ directory.
        return;
    }
    let spec = std::fs::read_to_string(spec_path).unwrap();
    let is_code = |c: &&str| {
        c.split_once('.').is_some_and(|(a, b)| {
            !a.is_empty()
                && a.chars().all(|ch| ch.is_ascii_lowercase())
                && !b.is_empty()
                && b.chars().all(|ch| ch.is_ascii_lowercase() || ch == '_')
        })
    };
    let in_spec: Vec<&str> = spec
        .lines()
        .filter_map(|l| l.strip_prefix("| `"))
        .filter_map(|l| l.split('`').next())
        .filter(is_code)
        .filter(|c| {
            !["model.", "als.", "eval.", "sql."]
                .iter()
                .any(|p| c.starts_with(p))
        })
        .collect();
    let mut in_code: Vec<&str> = CODES.iter().map(|c| c.code).collect();
    let mut sorted_spec = in_spec.clone();
    sorted_spec.sort_unstable();
    in_code.sort_unstable();
    assert_eq!(sorted_spec, in_code);
}