quarb 0.73.0

Query engine for arbors (arboreal graphs - tree-spanned or tree-dominated graphs)
Documentation
//! The reads of a quantifier's facts, checked against the text
//! (rulings 2026-11-21): `$iter`, `$steps`, `$total`, `@total` and
//! their numbered forms name a quantifier that encloses the read,
//! the nearest first, and a read that no such quantifier encloses is
//! refused when the query is parsed.
//!
//! What encloses a read is a place in the text. A quantified group
//! encloses its own elements (a step's own predicate, a push inside
//! it, a group nested in it) and its guard, and the one command
//! right after a path that ends in it. A quantified push encloses its
//! body. The numbers count them outward, a walk or a push alike; a
//! push has an iteration and no steps.
//!
//! The check refuses what the text shows. A quarq is held and run
//! elsewhere, and its text does not say what will stand around it:
//! its reads are not looked at here and are refused, if at all, when
//! it runs (`walk_fact` in the pipeline's evaluator, which this
//! check mirrors). Where the text leaves room for doubt (a pipe
//! inside a parenthesis, a union of branches of which one ends in a
//! group) the read passes here and the run decides.

use super::ast::visit::{self, Visitor};
use super::ast::{Branch, Command, Operand, PathElem, Query, WalkFact};

#[derive(Clone, Copy, PartialEq)]
enum Kind {
    Walk,
    Push,
}

struct Check {
    /// The quantifiers around the place being read, outermost first.
    around: Vec<Kind>,
    refusal: Option<String>,
}

/// Whether a path's last move is a quantified group: its walk is in
/// scope for the one command after the path. A mark or a push after
/// the group does not move the path; a parameter or a hole may be
/// anything, and passes.
fn ends_in_walk(steps: &[PathElem]) -> bool {
    steps
        .iter()
        .rev()
        .find(|e| !matches!(e, PathElem::Mark(_) | PathElem::Push { .. }))
        .is_some_and(|e| {
            matches!(
                e,
                PathElem::Group(_) | PathElem::Param(_) | PathElem::Hole(_)
            )
        })
}

impl Check {
    fn within(&mut self, kind: Kind, f: impl FnOnce(&mut Self)) {
        self.around.push(kind);
        f(self);
        self.around.pop();
    }

    fn read(&mut self, fact: WalkFact, level: usize) {
        if self.refusal.is_some() {
            return;
        }
        let name = fact.spelling(level);
        let n = self.around.len();
        let at = level.max(1);
        if at > n {
            self.refusal = Some(match n {
                0 => format!("'{name}' reads a quantifier around it, and none encloses it here"),
                1 => format!(
                    "'{name}' counts {level} quantifiers outward, and one encloses it here: '{}'",
                    fact.spelling(1)
                ),
                k => format!(
                    "'{name}' counts {level} quantifiers outward, and {k} enclose it here: the \
                     outermost is '{}'",
                    fact.spelling(k)
                ),
            });
            return;
        }
        if self.around[n - at] == Kind::Push && fact != WalkFact::Iter {
            self.refusal = Some(format!(
                "'{name}' reads a walk, and the quantifier it names here is a quantified \
                 push, which takes no steps: its rounds are '{}'",
                WalkFact::Iter.spelling(level)
            ));
        }
    }
}

impl Visitor for Check {
    fn query(&mut self, q: &Query) {
        for c in &q.correlations {
            self.query(c);
        }
        for b in &q.branches {
            self.branch(b);
        }
        // the walk a branch ends in is in scope for the first command
        let mut after_walk = q.branches.iter().any(|b: &Branch| ends_in_walk(&b.steps));
        for command in &q.pipeline {
            if after_walk {
                self.within(Kind::Walk, |v| v.command(command));
            } else {
                self.command(command);
            }
            after_walk = matches!(command, Command::Nav(b) if ends_in_walk(&b.steps));
        }
    }

    fn elem(&mut self, e: &PathElem) {
        match e {
            PathElem::Group(g) => self.within(Kind::Walk, |v| {
                for alt in &g.alts {
                    for e in alt {
                        v.elem(e);
                    }
                }
                for p in &g.predicates {
                    v.predicate(p);
                }
            }),
            other => visit::walk_elem(self, other),
        }
    }

    fn command(&mut self, c: &Command) {
        match c {
            Command::Repeat { command, .. } => self.within(Kind::Push, |v| v.command(command)),
            other => visit::walk_command(self, other),
        }
    }

    fn operand(&mut self, o: &Operand) {
        match o {
            Operand::WalkFact { fact, level, .. } => self.read(*fact, *level),
            // a pipe inside a parenthesis after a path that ends in a
            // group: the walk is in scope after it; how far along the
            // pipe, the run decides
            Operand::Piped { expr, commands } if matches!(&**expr, Operand::Rel { steps, .. } if ends_in_walk(steps)) =>
            {
                self.operand(expr);
                self.within(Kind::Walk, |v| {
                    for c in commands {
                        v.command(c);
                    }
                });
            }
            other => visit::walk_operand(self, other),
        }
    }
}

/// Refuse a read of a quantifier's fact that the text shows no
/// quantifier around.
pub(crate) fn check(q: &Query) -> Result<(), String> {
    let mut v = Check {
        around: Vec::new(),
        refusal: None,
    };
    v.query(q);
    match v.refusal {
        Some(why) => Err(why),
        None => Ok(()),
    }
}