elinvar-logic 0.1.2

The relational logic of Elinvar and its evaluator, the referee for every answer
Documentation
//! The check made before a formula is evaluated, run, or checked (LOGIC.md
//! section 7): build errors, free and rebound variables, relations that
//! are missing, and capacity. Every error is found, whatever a computation
//! would reach.

use crate::ast::{Decl, Expr, ExprKind, Formula, FormulaKind, IntExpr, IntExprKind};
use crate::bounds::{Bounds, Instance};
use crate::error::Error;
use crate::relation::{Relation, Variable};
use crate::trace::Trace;
use crate::universe::{capacity, capacity_error};
use std::collections::BTreeSet;

/// What a formula is checked against.
#[derive(Clone, Copy, Debug)]
pub enum Against<'a> {
    /// An instance: a relation it lacks is `instance.missing_relation`.
    Instance(&'a Instance),
    /// Bounds: a relation they lack is `logic.unbound_relation`.
    Bounds(&'a Bounds),
    /// A trace: a relation it lacks is `instance.missing_relation`.
    Trace(&'a Trace),
}

impl Against<'_> {
    fn size(&self) -> usize {
        match self {
            Against::Instance(i) => i.universe().size(),
            Against::Bounds(b) => b.universe().size(),
            Against::Trace(t) => t.universe().size(),
        }
    }

    fn has(&self, r: &Relation) -> bool {
        match self {
            Against::Instance(i) => i.contains(r),
            Against::Bounds(b) => b.contains(r),
            Against::Trace(t) => t.contains(r),
        }
    }

    fn missing(&self, r: &Relation) -> Error {
        match self {
            Against::Instance(_) | Against::Trace(_) => Error::new(
                "instance.missing_relation",
                format!("the instance has no tuple set for `{r}`"),
            ),
            Against::Bounds(_) => Error::new(
                "logic.unbound_relation",
                format!("the bounds have no bounds for `{r}`"),
            ),
        }
    }
}

/// Every error in a formula, in the order a walk from the root meets them.
pub fn check_formula(f: &Formula, against: Against<'_>) -> Vec<Error> {
    let mut c = Checker::new(against);
    c.formula(f);
    c.errors
}

/// Every error in a formula whose free variables are all among `bound`, as
/// for [`evaluate_trace_at`](crate::evaluate_trace_at).
pub fn check_formula_bound(f: &Formula, against: Against<'_>, bound: &[Variable]) -> Vec<Error> {
    let mut c = Checker::new(against);
    c.scope.extend(bound.iter().cloned());
    c.formula(f);
    c.errors
}

/// Every error in an expression, in the order a walk from the root meets
/// them.
pub fn check_expr(e: &Expr, against: Against<'_>) -> Vec<Error> {
    let mut c = Checker::new(against);
    c.expr(e);
    c.errors
}

/// Every error in an integer expression, in the order a walk from the root
/// meets them.
pub fn check_int(n: &IntExpr, against: Against<'_>) -> Vec<Error> {
    let mut c = Checker::new(against);
    c.int(n);
    c.errors
}

struct Checker<'a> {
    against: Against<'a>,
    errors: Vec<Error>,
    /// Nodes whose own errors are collected. Membership only, never
    /// iterated (AGENTS.md law 16).
    seen_nodes: BTreeSet<usize>,
    scope: Vec<Variable>,
    reported_free: Vec<Variable>,
    reported_rebound: Vec<Variable>,
    reported_relations: Vec<Relation>,
    reported_arities: BTreeSet<usize>,
}

impl<'a> Checker<'a> {
    fn new(against: Against<'a>) -> Checker<'a> {
        Checker {
            against,
            errors: Vec::new(),
            seen_nodes: BTreeSet::new(),
            scope: Vec::new(),
            reported_free: Vec::new(),
            reported_rebound: Vec::new(),
            reported_relations: Vec::new(),
            reported_arities: BTreeSet::new(),
        }
    }

    fn push(&mut self, e: Error) {
        if !self.errors.contains(&e) {
            self.errors.push(e);
        }
    }

    fn own(&mut self, id: usize, errors: &[Error]) {
        if self.seen_nodes.insert(id) {
            for e in errors {
                self.push(e.clone());
            }
        }
    }

    fn arity(&mut self, e: &Expr) {
        if let Some(k) = e.arity() {
            let n = self.against.size();
            if capacity(n, k).is_none() && self.reported_arities.insert(k) {
                self.push(capacity_error(n, k).at(e.place().clone()));
            }
        }
    }

    /// Declarations: each expression is checked with the earlier variables
    /// in scope, then its variable must not already be bound (LOGIC.md
    /// section 5). Returns how many variables were pushed.
    fn decls(&mut self, decls: &[Decl], place: &crate::error::Place) -> usize {
        let mut pushed = 0;
        for d in decls {
            self.expr(&d.expr);
            if self.scope.contains(&d.var) {
                if !self.reported_rebound.contains(&d.var) {
                    self.reported_rebound.push(d.var.clone());
                    self.push(
                        Error::new(
                            "logic.rebound_variable",
                            format!("`{}` is declared where it is already bound", d.var),
                        )
                        .at(place.clone()),
                    );
                }
            } else {
                self.scope.push(d.var.clone());
                pushed += 1;
            }
        }
        pushed
    }

    fn pop(&mut self, n: usize) {
        self.scope.truncate(self.scope.len() - n);
    }

    fn expr(&mut self, e: &Expr) {
        self.own(e.node_id(), e.own_errors());
        self.arity(e);
        match e.kind() {
            ExprKind::Relation(r) => {
                if r.arity() > 0 && !self.against.has(r) && !self.reported_relations.contains(r) {
                    self.reported_relations.push(r.clone());
                    let err = self.against.missing(r).at(e.place().clone());
                    self.push(err);
                }
            }
            ExprKind::Variable(v) => {
                if !self.scope.contains(v) && !self.reported_free.contains(v) {
                    self.reported_free.push(v.clone());
                    self.push(
                        Error::new(
                            "logic.free_variable",
                            format!("`{v}` is used outside the quantifier that declares it"),
                        )
                        .at(e.place().clone()),
                    );
                }
            }
            ExprKind::None | ExprKind::Univ | ExprKind::Iden => {}
            ExprKind::Binary(_, a, b) => {
                self.expr(a);
                self.expr(b);
            }
            ExprKind::Unary(_, a) | ExprKind::Prime(a) => self.expr(a),
            ExprKind::Comprehension(decls, body) => {
                let n = self.decls(decls, e.place());
                self.formula(body);
                self.pop(n);
            }
            ExprKind::IfThenElse(c, a, b) => {
                self.formula(c);
                self.expr(a);
                self.expr(b);
            }
            ExprKind::IntToSet(n) => self.int(n),
        }
    }

    fn int(&mut self, n: &IntExpr) {
        self.own(n.node_id(), n.own_errors());
        match n.kind() {
            IntExprKind::Constant(_) => {}
            IntExprKind::Count(e) | IntExprKind::Sum(e) => self.expr(e),
            IntExprKind::Binary(_, a, b) => {
                self.int(a);
                self.int(b);
            }
            IntExprKind::Negate(a) => self.int(a),
            IntExprKind::IfThenElse(c, a, b) => {
                self.formula(c);
                self.int(a);
                self.int(b);
            }
            IntExprKind::SumOver(decls, body) => {
                let k = self.decls(decls, n.place());
                self.int(body);
                self.pop(k);
            }
        }
    }

    fn formula(&mut self, f: &Formula) {
        self.own(f.node_id(), f.own_errors());
        match f.kind() {
            FormulaKind::Constant(_) => {}
            FormulaKind::Subset(a, b) | FormulaKind::Equal(a, b) => {
                self.expr(a);
                self.expr(b);
            }
            FormulaKind::Multiplicity(_, a) => self.expr(a),
            FormulaKind::Not(g) => self.formula(g),
            FormulaKind::And(fs) | FormulaKind::Or(fs) => {
                for g in fs {
                    self.formula(g);
                }
            }
            FormulaKind::Implies(a, b)
            | FormulaKind::Iff(a, b)
            | FormulaKind::TemporalBinary(_, a, b) => {
                self.formula(a);
                self.formula(b);
            }
            FormulaKind::Temporal(_, g) => self.formula(g),
            FormulaKind::Quantified(_, decls, body) => {
                let n = self.decls(decls, f.place());
                self.formula(body);
                self.pop(n);
            }
            FormulaKind::IntCompare(_, a, b) => {
                self.int(a);
                self.int(b);
            }
        }
    }
}