elinvar-engine 0.1.2

The engine of Elinvar, a relational model finder: models, translation, the SAT solver, and verdicts
Documentation
//! LOGIC.md 14.1 and R31: results validate against their JSON Schema, the
//! engine's codes match LOGIC.md, and every code is explained.

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

use elinvar_engine::prelude::*;
use serde_json::Value;

/// Validates `v` against the subset of JSON Schema `RESULT_SCHEMA` uses:
/// `type`, `const`, `enum`, `required`, `properties`,
/// `additionalProperties`, `items`, `minItems`, `minimum`, `oneOf`, `$ref`.
fn validate(schema: &Value, root: &Value, v: &Value, path: &str) -> Result<(), String> {
    if let Some(r) = schema.get("$ref").and_then(Value::as_str) {
        let name = r.trim_start_matches("#/$defs/");
        return validate(&root["$defs"][name], root, v, path);
    }
    if let Some(options) = schema.get("oneOf").and_then(Value::as_array) {
        let ok = options
            .iter()
            .filter(|s| validate(s, root, v, path).is_ok())
            .count();
        return if ok == 1 {
            Ok(())
        } else {
            Err(format!("{path}: matches {ok} of oneOf"))
        };
    }
    if let Some(c) = schema.get("const")
        && c != v
    {
        return Err(format!("{path}: {v} is not {c}"));
    }
    if let Some(options) = schema.get("enum").and_then(Value::as_array)
        && !options.contains(v)
    {
        return Err(format!("{path}: {v} not in enum"));
    }
    if let Some(t) = schema.get("type") {
        let types: Vec<&str> = match t {
            Value::String(s) => vec![s.as_str()],
            Value::Array(a) => a.iter().filter_map(Value::as_str).collect(),
            _ => vec![],
        };
        let actual = match v {
            Value::Null => "null",
            Value::Bool(_) => "boolean",
            Value::Number(n) if n.is_u64() || n.is_i64() => "integer",
            Value::Number(_) => "number",
            Value::String(_) => "string",
            Value::Array(_) => "array",
            Value::Object(_) => "object",
        };
        if !types.contains(&actual) {
            return Err(format!("{path}: {actual} is not {types:?}"));
        }
    }
    if let (Some(min), Some(n)) = (schema.get("minimum").and_then(Value::as_u64), v.as_u64())
        && n < min
    {
        return Err(format!("{path}: {n} below {min}"));
    }
    if let Value::Object(map) = v {
        for k in schema
            .get("required")
            .and_then(Value::as_array)
            .into_iter()
            .flatten()
            .filter_map(Value::as_str)
        {
            if !map.contains_key(k) {
                return Err(format!("{path}: missing {k}"));
            }
        }
        let props = schema.get("properties").and_then(Value::as_object);
        for (k, x) in map {
            match props.and_then(|p| p.get(k)) {
                Some(s) => validate(s, root, x, &format!("{path}.{k}"))?,
                None => match schema.get("additionalProperties") {
                    Some(Value::Bool(false)) => return Err(format!("{path}: unexpected {k}")),
                    Some(s @ Value::Object(_)) => validate(s, root, x, &format!("{path}.{k}"))?,
                    _ => {}
                },
            }
        }
    }
    if let Value::Array(items) = v {
        if let Some(min) = schema.get("minItems").and_then(Value::as_u64)
            && (items.len() as u64) < min
        {
            return Err(format!("{path}: fewer than {min} items"));
        }
        if let Some(s) = schema.get("items") {
            for (i, x) in items.iter().enumerate() {
                validate(s, root, x, &format!("{path}[{i}]"))?;
            }
        }
    }
    Ok(())
}

fn check_valid(report: &Report) {
    let schema: Value = serde_json::from_str(elinvar_engine::RESULT_SCHEMA).unwrap();
    let v = serde_json::to_value(report).unwrap();
    validate(&schema, &schema, &v, "$").unwrap();
}

fn people() -> (Model, Expr, Expr) {
    let mut m = Model::new();
    let person = m.set("Person");
    let knows = m.field("knows", &person, &person);
    (m, person, knows)
}

#[test]
fn every_kind_of_result_validates() {
    let (m, person, knows) = people();
    // A counterexample with a witness, shrunk.
    let assertion = all([&person], |[p]| p.join(&knows).some());
    check_valid(&m.check(&assertion).named("KnowsSomeone").scope(3).report());
    // Holds.
    let typed = knows.is_in(&person.product(&person));
    check_valid(&m.check(&typed).scope(3).report());
    // Found and none.
    check_valid(&m.run(&knows.some()).scope(2).report());
    check_valid(&m.run(&person.some().and(&person.no())).scope(2).report());
    // Errors.
    let r = m.check(&typed).report();
    assert_eq!(r.errors[0].code, "model.no_scope");
    check_valid(&r);
    // A trace.
    let mut t = Model::new();
    let item = t.set("Item");
    let held = t.changing_subset("Held", &item);
    t.action("take", [&item], |s, [i]| s.add(&held, i));
    let r = t.check(&always(held.no())).scope(2).steps(3).report();
    assert_eq!(r.verdict, Some(Verdict::Counterexample));
    check_valid(&r);
}

#[test]
fn model_codes_match_the_spec_and_every_code_is_explained() {
    for c in elinvar_engine::codes() {
        assert_eq!(elinvar_engine::explain(c.code).unwrap().code, c.code);
        assert!(!c.fix.is_empty() && !c.when.is_empty(), "{}", c.code);
    }
    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(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/LOGIC.md"))
        .unwrap();
    let mut in_spec: Vec<&str> = spec
        .lines()
        .filter_map(|l| l.strip_prefix("| `model."))
        .filter_map(|l| l.split('`').next())
        .collect();
    let mut in_code: Vec<&str> = elinvar_engine::MODEL_CODES
        .iter()
        .map(|c| c.code.trim_start_matches("model."))
        .collect();
    in_spec.sort_unstable();
    in_code.sort_unstable();
    assert_eq!(in_spec, in_code);
}