elinvar-logic 0.1.2

The relational logic of Elinvar and its evaluator, the referee for every answer
Documentation
//! Traces: a lasso of states (LOGIC.md section 13.1).

use crate::bounds::{Bounds, Instance};
use crate::error::Error;
use crate::relation::Relation;
use crate::universe::Universe;
use serde::Serialize;
use serde::ser::{SerializeStruct, Serializer};

/// A trace: the fixed relations, `L` states of the changing relations, and
/// the state the last one loops back to.
#[derive(Clone, Debug)]
pub struct Trace {
    fixed: Instance,
    states: Vec<Instance>,
    loop_to: usize,
}

impl Trace {
    /// A trace.
    ///
    /// Errors: `trace.no_states`, `trace.loop`, `trace.relations`.
    pub fn new(fixed: Instance, states: Vec<Instance>, loop_to: usize) -> Result<Trace, Error> {
        let Some(first) = states.first() else {
            return Err(Error::new("trace.no_states", "a trace with no states"));
        };
        if loop_to >= states.len() {
            return Err(Error::new(
                "trace.loop",
                format!(
                    "the trace loops to state {loop_to}, and it has {} states",
                    states.len()
                ),
            ));
        }
        let changing: Vec<&Relation> = first.entries().map(|(r, _)| r).collect();
        for s in &states {
            if s.universe() != fixed.universe() {
                return Err(Error::new(
                    "trace.relations",
                    "a state is over another universe than the fixed relations",
                ));
            }
            let here: Vec<&Relation> = s.entries().map(|(r, _)| r).collect();
            if let Some(r) = here
                .iter()
                .find(|r| !changing.contains(r) || !r.is_changing())
                .or_else(|| changing.iter().find(|r| !here.contains(r)))
            {
                return Err(Error::new(
                    "trace.relations",
                    format!("the states disagree about `{r}`, or it is not a changing relation"),
                ));
            }
        }
        Ok(Trace {
            fixed,
            states,
            loop_to,
        })
    }

    /// A trace of one state that loops to itself: how a static instance is
    /// read when a formula has temporal operators.
    pub fn of_instance(instance: &Instance) -> Trace {
        Trace {
            fixed: instance.clone(),
            states: vec![Instance::new(instance.universe())],
            loop_to: 0,
        }
    }

    /// The universe.
    pub fn universe(&self) -> &Universe {
        self.fixed.universe()
    }

    /// The fixed relations.
    pub fn fixed(&self) -> &Instance {
        &self.fixed
    }

    /// The states, in order.
    pub fn states(&self) -> &[Instance] {
        &self.states
    }

    /// The state the last one loops back to.
    pub fn loop_to(&self) -> usize {
        self.loop_to
    }

    /// The state shown at position `p` (LOGIC.md 13.1).
    pub fn state_at(&self, p: usize) -> usize {
        let len = self.states.len();
        if p < len {
            p
        } else {
            self.loop_to + (p - self.loop_to) % (len - self.loop_to)
        }
    }

    /// The tuple set of a relation at a position: from the state shown
    /// there, or from the fixed relations.
    pub fn get(&self, r: &Relation, p: usize) -> Option<&crate::universe::TupleSet> {
        self.states[self.state_at(p)]
            .get(r)
            .or_else(|| self.fixed.get(r))
    }

    /// Whether the trace gives the relation a tuple set.
    pub fn contains(&self, r: &Relation) -> bool {
        self.fixed.contains(r) || self.states[0].contains(r)
    }

    /// Whether the trace is within the bounds (LOGIC.md 13.1): every
    /// relation of the bounds has, in the fixed instance or in every state,
    /// a tuple set between its bounds.
    pub fn within(&self, bounds: &Bounds) -> bool {
        self.universe() == bounds.universe()
            && bounds.entries().all(|(r, lower, upper)| {
                let ok = |s: &crate::universe::TupleSet| lower.is_subset(s) && s.is_subset(upper);
                if r.is_changing() {
                    self.states.iter().all(|i| i.get(r).is_some_and(ok))
                } else {
                    self.fixed.get(r).is_some_and(ok)
                }
            })
    }
}

/// A trace is written as its fixed relations, its states, and its loop.
impl Serialize for Trace {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut st = s.serialize_struct("Trace", 3)?;
        st.serialize_field("fixed", &self.fixed)?;
        st.serialize_field("states", &self.states)?;
        st.serialize_field("loop_to", &self.loop_to)?;
        st.end()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::universe::Universe;

    #[test]
    fn loop_to_and_state_at_periodicity() {
        let u = Universe::new(["A"]).expect("valid universe");
        let fixed = Instance::new(&u);
        let states = vec![Instance::new(&u), Instance::new(&u), Instance::new(&u)];
        let t1 = Trace::new(fixed.clone(), states.clone(), 1).expect("valid trace");
        assert_eq!(t1.loop_to(), 1);
        assert_eq!(t1.state_at(0), 0);
        assert_eq!(t1.state_at(1), 1);
        assert_eq!(t1.state_at(2), 2);
        assert_eq!(t1.state_at(3), 1);
        assert_eq!(t1.state_at(4), 2);
        assert_eq!(t1.state_at(5), 1);

        let t2 = Trace::new(fixed, states, 2).expect("valid trace");
        assert_eq!(t2.loop_to(), 2);
        assert_eq!(t2.state_at(3), 2);
        assert_eq!(t2.state_at(4), 2);
    }
}