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 {
around: Vec<Kind>,
refusal: Option<String>,
}
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);
}
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),
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),
}
}
}
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(()),
}
}