elinvar-logic 0.1.2

The relational logic of Elinvar and its evaluator, the referee for every answer
Documentation
//! Bounds and instances (LOGIC.md section 2).

use crate::error::{Error, Place};
use crate::relation::Relation;
use crate::universe::{TupleSet, Universe};
use serde::Serialize;
use serde::ser::{SerializeStruct, Serializer};

/// Lower and upper bounds for a list of relations over one universe. The
/// order of the list is the order the relations were given their bounds,
/// which is the declaration order every later step means.
#[derive(Clone, Debug)]
pub struct Bounds {
    universe: Universe,
    entries: Vec<(Relation, TupleSet, TupleSet)>,
}

/// Checks a relation and a tuple set being added to bounds or an instance.
fn check_entry(
    prefix: &'static str,
    universe: &Universe,
    existing: &mut dyn Iterator<Item = &Relation>,
    r: &Relation,
    sets: &[&TupleSet],
    place: &Place,
) -> Result<(), Error> {
    let err = |code: &'static str, msg: String| Err(Error::new(code, msg).at(place.clone()));
    if r.arity() == 0 {
        return err("arity.zero", format!("the relation `{r}` has arity 0"));
    }
    for other in existing {
        if other == r {
            let code = if prefix == "bounds" {
                "bounds.duplicate_relation"
            } else {
                "instance.duplicate_relation"
            };
            return err(code, format!("`{r}` is given twice"));
        }
        if other.name() == r.name() {
            let code = if prefix == "bounds" {
                "bounds.duplicate_name"
            } else {
                "instance.duplicate_name"
            };
            return err(code, format!("two relations are named `{r}`"));
        }
    }
    for s in sets {
        if s.arity() != r.arity() {
            let code = if prefix == "bounds" {
                "bounds.arity"
            } else {
                "instance.arity"
            };
            return err(
                code,
                format!(
                    "`{r}` has arity {} and is given a tuple set of arity {}",
                    r.arity(),
                    s.arity()
                ),
            );
        }
        if s.universe() != universe {
            let code = if prefix == "bounds" {
                "bounds.other_universe"
            } else {
                "instance.other_universe"
            };
            return err(
                code,
                format!("the tuple set given to `{r}` is over another universe"),
            );
        }
    }
    Ok(())
}

impl Bounds {
    /// Empty bounds over a universe.
    pub fn new(universe: &Universe) -> Bounds {
        Bounds {
            universe: universe.clone(),
            entries: Vec::new(),
        }
    }

    /// Bounds a relation: it holds every tuple of `lower` and only tuples
    /// of `upper`.
    ///
    /// Errors: `arity.zero`, `bounds.duplicate_relation`,
    /// `bounds.duplicate_name`, `bounds.arity`, `bounds.other_universe`,
    /// `bounds.lower_outside_upper`.
    #[track_caller]
    pub fn bound(&mut self, r: &Relation, lower: TupleSet, upper: TupleSet) -> Result<(), Error> {
        let place = Place::caller();
        check_entry(
            "bounds",
            &self.universe,
            &mut self.entries.iter().map(|e| &e.0),
            r,
            &[&lower, &upper],
            &place,
        )?;
        if let Some(t) = lower.iter().find(|t| !upper.contains(t)) {
            return Err(Error::new(
                "bounds.lower_outside_upper",
                format!("the lower bound of `{r}` has {t}, which its upper bound lacks"),
            )
            .at(place));
        }
        self.entries.push((r.clone(), lower, upper));
        Ok(())
    }

    /// Bounds a relation exactly: it holds the tuples of `tuples` and no
    /// others.
    #[track_caller]
    pub fn bound_exactly(&mut self, r: &Relation, tuples: TupleSet) -> Result<(), Error> {
        self.bound(r, tuples.clone(), tuples)
    }

    /// Bounds a relation from above only.
    #[track_caller]
    pub fn bound_upper(&mut self, r: &Relation, upper: TupleSet) -> Result<(), Error> {
        let lower = TupleSet::empty(&self.universe, upper.arity())?;
        self.bound(r, lower, upper)
    }

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

    /// The relations, in the order they were bounded.
    pub fn relations(&self) -> impl Iterator<Item = &Relation> {
        self.entries.iter().map(|e| &e.0)
    }

    /// Each relation with its lower and upper bound, in order.
    pub fn entries(&self) -> impl Iterator<Item = (&Relation, &TupleSet, &TupleSet)> {
        self.entries.iter().map(|(r, l, u)| (r, l, u))
    }

    /// Whether the relation has bounds.
    pub fn contains(&self, r: &Relation) -> bool {
        self.entries.iter().any(|e| &e.0 == r)
    }

    /// The lower bound of a relation.
    pub fn lower(&self, r: &Relation) -> Option<&TupleSet> {
        self.entries.iter().find(|e| &e.0 == r).map(|e| &e.1)
    }

    /// The upper bound of a relation.
    pub fn upper(&self, r: &Relation) -> Option<&TupleSet> {
        self.entries.iter().find(|e| &e.0 == r).map(|e| &e.2)
    }

    /// Whether an instance gives every relation of these bounds a tuple set
    /// between its lower and upper bound.
    pub fn admits(&self, instance: &Instance) -> bool {
        instance.universe() == &self.universe
            && self.entries.iter().all(|(r, lower, upper)| {
                instance
                    .get(r)
                    .is_some_and(|s| lower.is_subset(s) && s.is_subset(upper))
            })
    }
}

/// An assignment of a tuple set to each of a list of relations.
#[derive(Clone, Debug)]
pub struct Instance {
    universe: Universe,
    entries: Vec<(Relation, TupleSet)>,
}

impl Instance {
    /// An instance with no relations.
    pub fn new(universe: &Universe) -> Instance {
        Instance {
            universe: universe.clone(),
            entries: Vec::new(),
        }
    }

    /// Gives a relation its tuple set.
    ///
    /// Errors: `arity.zero`, `instance.duplicate_relation`,
    /// `instance.duplicate_name`, `instance.arity`,
    /// `instance.other_universe`.
    #[track_caller]
    pub fn set(&mut self, r: &Relation, tuples: TupleSet) -> Result<(), Error> {
        let place = Place::caller();
        check_entry(
            "instance",
            &self.universe,
            &mut self.entries.iter().map(|e| &e.0),
            r,
            &[&tuples],
            &place,
        )?;
        self.entries.push((r.clone(), tuples));
        Ok(())
    }

    pub(crate) fn push_unchecked(&mut self, r: &Relation, tuples: TupleSet) {
        self.entries.push((r.clone(), tuples));
    }

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

    /// The tuple set of a relation.
    pub fn get(&self, r: &Relation) -> Option<&TupleSet> {
        self.entries.iter().find(|e| &e.0 == r).map(|e| &e.1)
    }

    /// The relations and their tuple sets, in the order they were given.
    pub fn entries(&self) -> impl Iterator<Item = (&Relation, &TupleSet)> {
        self.entries.iter().map(|(r, s)| (r, s))
    }

    /// Whether the instance gives the relation a tuple set.
    pub fn contains(&self, r: &Relation) -> bool {
        self.entries.iter().any(|e| &e.0 == r)
    }
}

#[derive(Serialize)]
struct RelationEntry<'a> {
    name: &'a str,
    arity: usize,
    tuples: &'a TupleSet,
}

/// An instance is written as its atoms and its relations by name, in list
/// order; identity is never written (LOGIC.md section 2).
impl Serialize for Instance {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let relations: Vec<RelationEntry<'_>> = self
            .entries
            .iter()
            .map(|(r, t)| RelationEntry {
                name: r.name(),
                arity: r.arity(),
                tuples: t,
            })
            .collect();
        // LOGIC.md 16.1: the bitwidth and the integer atoms, only where
        // there are integer atoms.
        let ints: std::collections::BTreeMap<&str, i64> = self
            .universe
            .int_atoms()
            .filter_map(|(a, v)| self.universe.atom(a).map(|n| (n, v)))
            .collect();
        let fields = if ints.is_empty() { 2 } else { 4 };
        let mut st = s.serialize_struct("Instance", fields)?;
        st.serialize_field("atoms", &self.universe)?;
        if !ints.is_empty() {
            st.serialize_field("bitwidth", &self.universe.bitwidth())?;
            st.serialize_field("ints", &ints)?;
        }
        st.serialize_field("relations", &relations)?;
        st.end()
    }
}