elinvar-logic 0.1.2

The relational logic of Elinvar and its evaluator, the referee for every answer
Documentation
//! Brute-force enumeration of the instances within bounds (LOGIC.md
//! section 8). No solver: the independent count the solver is compared
//! with (R18).

use crate::ast::Formula;
use crate::bounds::{Bounds, Instance};
use crate::check::{Against, check_formula};
use crate::error::Error;
use crate::eval::{evaluate_checked, evaluate_trace_checked};
use crate::trace::Trace;
use crate::universe::TupleSet;

/// Every instance within bounds, in the order of LOGIC.md section 8.
#[derive(Debug)]
pub struct Instances<'a> {
    bounds: &'a Bounds,
    /// The free tuples: (relation position, tuple index), relation by
    /// relation in declaration order and by index within a relation.
    free: Vec<(usize, u64)>,
    next: u64,
    end: u64,
}

impl Instances<'_> {
    /// The number of free tuples, `m`.
    pub fn free_tuples(&self) -> usize {
        self.free.len()
    }

    /// The number of instances, `2^m`.
    pub fn total(&self) -> u64 {
        self.end
    }
}

/// Every instance within `bounds`, if there are at most `cap` free tuples.
///
/// Errors: `enumerate.too_large` when `m` is above `cap` or above 63.
pub fn instances(bounds: &Bounds, cap: usize) -> Result<Instances<'_>, Error> {
    let mut free = Vec::new();
    for (pos, (_, lower, upper)) in bounds.entries().enumerate() {
        for i in upper.indices() {
            if !lower.indices.contains(&i) {
                free.push((pos, i));
            }
        }
    }
    let m = free.len();
    if m > cap || m > 63 {
        return Err(Error::new(
            "enumerate.too_large",
            format!("{m} free tuples, and the cap is {}", cap.min(63)),
        ));
    }
    Ok(Instances {
        bounds,
        free,
        next: 0,
        end: 1u64 << m,
    })
}

impl Iterator for Instances<'_> {
    type Item = Instance;

    fn next(&mut self) -> Option<Instance> {
        if self.next >= self.end {
            return None;
        }
        let j = self.next;
        self.next += 1;
        let universe = self.bounds.universe();
        let mut instance = Instance::new(universe);
        for (pos, (r, lower, _)) in self.bounds.entries().enumerate() {
            let mut indices = lower.indices.clone();
            for (bit, &(p, i)) in self.free.iter().enumerate() {
                if p == pos && (j >> bit) & 1 == 1 {
                    indices.insert(i);
                }
            }
            instance.push_unchecked(r, TupleSet::from_indices(universe, r.arity(), indices));
        }
        Some(instance)
    }
}

/// The number of instances within `bounds` under which `formula` is true
/// (LOGIC.md section 8).
pub fn count(bounds: &Bounds, formula: &Formula, cap: usize) -> Result<u64, Vec<Error>> {
    let errors = check_formula(formula, Against::Bounds(bounds));
    if !errors.is_empty() {
        return Err(errors);
    }
    let all = instances(bounds, cap).map_err(|e| vec![e])?;
    let mut n = 0;
    for instance in all {
        if evaluate_checked(&instance, formula).map_err(|e| vec![e])? {
            n += 1;
        }
    }
    Ok(n)
}

/// Every trace of `length` states looping to `loop_to` within `bounds`
/// (LOGIC.md 13.1), as [`instances`] lists instances: the free tuples are
/// taken relation by relation in bounds order, a changing relation's block
/// by block, state by state.
///
/// Errors: `enumerate.too_large`, `trace.no_states`, `trace.loop`.
pub fn traces(
    bounds: &Bounds,
    length: usize,
    loop_to: usize,
    cap: usize,
) -> Result<Vec<Trace>, Error> {
    if length == 0 {
        return Err(Error::new("trace.no_states", "a trace with no states"));
    }
    if loop_to >= length {
        return Err(Error::new(
            "trace.loop",
            format!("the trace loops to state {loop_to}, and it has {length} states"),
        ));
    }
    // (relation position, state, tuple index); the state is 0 for a fixed
    // relation.
    let mut free = Vec::new();
    for (pos, (r, lower, upper)) in bounds.entries().enumerate() {
        let states = if r.is_changing() { length } else { 1 };
        for state in 0..states {
            for i in upper.indices() {
                if !lower.indices.contains(&i) {
                    free.push((pos, state, i));
                }
            }
        }
    }
    let m = free.len();
    if m > cap || m > 63 {
        return Err(Error::new(
            "enumerate.too_large",
            format!("{m} free tuples, and the cap is {}", cap.min(63)),
        ));
    }
    let universe = bounds.universe();
    let mut out = Vec::new();
    for j in 0..(1u64 << m) {
        let mut fixed = Instance::new(universe);
        let mut states: Vec<Instance> = (0..length).map(|_| Instance::new(universe)).collect();
        for (pos, (r, lower, _)) in bounds.entries().enumerate() {
            let set_for = |state: usize| {
                let mut indices = lower.indices.clone();
                for (bit, &(p, s, i)) in free.iter().enumerate() {
                    if p == pos && s == state && (j >> bit) & 1 == 1 {
                        indices.insert(i);
                    }
                }
                TupleSet::from_indices(universe, r.arity(), indices)
            };
            if r.is_changing() {
                for (state, instance) in states.iter_mut().enumerate() {
                    instance.push_unchecked(r, set_for(state));
                }
            } else {
                fixed.push_unchecked(r, set_for(0));
            }
        }
        out.push(Trace::new(fixed, states, loop_to)?);
    }
    Ok(out)
}

/// The number of traces of `length` states looping to `loop_to` within
/// `bounds` on which `formula` is true.
pub fn count_traces(
    bounds: &Bounds,
    formula: &Formula,
    length: usize,
    loop_to: usize,
    cap: usize,
) -> Result<u64, Vec<Error>> {
    let errors = check_formula(formula, Against::Bounds(bounds));
    if !errors.is_empty() {
        return Err(errors);
    }
    let all = traces(bounds, length, loop_to, cap).map_err(|e| vec![e])?;
    let mut n = 0;
    for t in &all {
        if evaluate_trace_checked(t.fixed(), t.states(), t.loop_to(), formula)
            .map_err(|e| vec![e])?
        {
            n += 1;
        }
    }
    Ok(n)
}