use super::ast::visit::{self, Visitor};
use super::ast::{Command, IndexSpec, Operand, Query, RegRef};
fn written_list(o: &Operand) -> bool {
match o {
Operand::List(_)
| Operand::Topics
| Operand::Positions { .. }
| Operand::Recall(RegRef::Whole) => true,
Operand::Index {
base,
rows: IndexSpec::Cond(_),
cols: None,
} => written_list(base),
Operand::Field { base, .. } | Operand::Through { base, .. } => written_list(base),
_ => false,
}
}
fn head_text(o: &Operand) -> String {
match o {
Operand::List(items) if items.len() > 1 => {
format!("@({}; …)", super::unparse::operand(&items[0]))
}
other => super::unparse::operand(other),
}
}
fn refusal(head: &Operand, first: &Command) -> String {
let head = head_text(head);
let command = super::unparse::command(first);
let bare = command.strip_prefix("@| ").unwrap_or(&command);
match first {
Command::Select(_) => format!(
"'({head} {command})': a list written there is one thread, and '@|' selects \
among threads; the bracket on the list reads it, '{head}{bare}', and \
'| ... {command}' opens it into threads first"
),
_ => format!(
"'({head} {command})': a list written there is one thread, and '@|' reads \
threads; '| {bare}' reads the list, '| ... {command}' opens it into threads \
first"
),
}
}
struct Check {
refusal: Option<String>,
}
impl Visitor for Check {
fn operand(&mut self, o: &Operand) {
if self.refusal.is_some() {
return;
}
if let Operand::Piped { expr, commands } = o
&& written_list(expr)
&& let Some(first @ (Command::Agg(_) | Command::Select(_))) = commands.first()
{
self.refusal = Some(refusal(expr, first));
return;
}
visit::walk_operand(self, o);
}
}
pub(crate) fn check(q: &Query) -> Result<(), String> {
let mut v = Check { refusal: None };
v.query(q);
match v.refusal {
Some(why) => Err(why),
None => Ok(()),
}
}