use crate::{
prelude::*,
strcmd::StrCmd,
term::{CmdOrHole, Term as _},
};
use std::fmt::Write as _;
pub fn qsnap(term: &QTerm) -> String {
let mut out = String::new();
render(term, &mut out, "", true, true);
out
}
pub fn qhead(term: &QTerm) -> String {
let mut out = String::new();
head(term, &mut out);
out
}
fn head(term: &QTerm, out: &mut String) {
match term {
QTerm::Tuple { tag, cmds, .. } => {
let _ = write!(out, "Tuple {tag} {}", cmds_str(cmds));
}
QTerm::Quote {
tag,
index,
lang,
cmds,
..
} => {
let _ = write!(out, "Quote[{index}] {lang}:{tag} {}", cmds_str(cmds));
}
QTerm::Unquote {
tag,
index,
lang,
cmds,
..
} => {
let _ = write!(out, "Unquote[{index}] {lang}:{tag} {}", cmds_str(cmds));
}
}
}
fn render(term: &QTerm, out: &mut String, prefix: &str, last: bool, root: bool) {
if !root {
out.push_str(prefix);
out.push_str(if last { "╰─ " } else { "├─ " });
}
head(term, out);
out.push('\n');
let child_prefix = if root {
String::new()
} else {
format!("{prefix}{}", if last { " " } else { "│ " })
};
let children: Vec<&QTerm> = term.children().collect();
let n = children.len();
for (i, child) in children.into_iter().enumerate() {
render(child, out, &child_prefix, i + 1 == n, false);
}
}
fn cmds_str(cmds: &[CmdOrHole]) -> String {
let mut s = String::from("⟨");
for (i, c) in cmds.iter().enumerate() {
if i > 0 {
s.push_str(", ");
}
match c {
CmdOrHole::Hole => s.push('·'),
CmdOrHole::Cmd(StrCmd::Write(w)) => {
let _ = write!(s, "{:?}", w.as_ref());
}
CmdOrHole::Cmd(StrCmd::NewLine) => s.push('⏎'),
CmdOrHole::Cmd(StrCmd::Push(p)) => {
let _ = write!(s, "»{:?}", p.as_ref());
}
CmdOrHole::Cmd(StrCmd::Pop) => s.push('«'),
}
}
s.push('⟩');
s
}
pub fn structural_violations(term: &QTerm) -> Vec<String> {
let mut bad = Vec::new();
check(term, &mut bad, "root");
bad
}
fn check(term: &QTerm, bad: &mut Vec<String>, path: &str) {
let cmds = match term {
QTerm::Tuple { cmds, .. } | QTerm::Quote { cmds, .. } | QTerm::Unquote { cmds, .. } => cmds,
};
let holes = cmds.iter().filter(|c| matches!(c, CmdOrHole::Hole)).count();
let children: Vec<&QTerm> = term.children().collect();
if holes != children.len() {
bad.push(format!(
"{path}: {} child(ren) but {holes} hole(s) in cmds — {}",
children.len(),
qhead(term),
));
}
for (i, child) in children.into_iter().enumerate() {
check(child, bad, &format!("{path}.{i}"));
}
}