Lines
86.36 %
Functions
100 %
Branches
//! The code inside a quasiquote template: its unquoted forms, wherever they
//! sit, including under a quote that is itself template text.
use crate::ast::Expr;
use crate::error::Result;
impl Expr {
/// The forms the quasiquote template `self` runs: its unquotes and
/// unquote-splicings at the template's own depth, in order.
#[must_use]
pub fn unquoted_forms(&self) -> Vec<&Expr> {
let mut forms = Vec::new();
self.collect_unquoted(1, &mut forms);
forms
}
fn collect_unquoted<'a>(&'a self, depth: usize, forms: &mut Vec<&'a Expr>) {
match self {
Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) if depth == 1 => forms.push(inner),
Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
inner.collect_unquoted(depth - 1, forms);
Expr::Quasiquote(inner) => inner.collect_unquoted(depth + 1, forms),
Expr::Quote(inner) | Expr::Datum(inner) => inner.collect_unquoted(depth, forms),
Expr::List(elems) => elems
.iter()
.for_each(|elem| elem.collect_unquoted(depth, forms)),
Expr::Cons(car, cdr) => {
car.collect_unquoted(depth, forms);
cdr.collect_unquoted(depth, forms);
_ => {}
/// The template `self` with each of its [`Self::unquoted_forms`] replaced
/// by `rewrite` of it.
pub fn map_unquoted(&self, rewrite: &mut impl FnMut(&Expr) -> Result<Expr>) -> Result<Expr> {
self.map_at_depth(1, rewrite)
fn map_at_depth(
&self,
depth: usize,
rewrite: &mut impl FnMut(&Expr) -> Result<Expr>,
) -> Result<Expr> {
let mut inner = |expr: &Expr, depth| expr.map_at_depth(depth, rewrite);
Expr::Unquote(form) if depth == 1 => Ok(Expr::Unquote(Box::new(rewrite(form)?))),
Expr::UnquoteSplicing(form) if depth == 1 => {
Ok(Expr::UnquoteSplicing(Box::new(rewrite(form)?)))
Expr::Unquote(form) => Ok(Expr::Unquote(Box::new(inner(form, depth - 1)?))),
Expr::UnquoteSplicing(form) => {
Ok(Expr::UnquoteSplicing(Box::new(inner(form, depth - 1)?)))
Expr::Quasiquote(form) => Ok(Expr::Quasiquote(Box::new(inner(form, depth + 1)?))),
Expr::Quote(form) => Ok(Expr::Quote(Box::new(inner(form, depth)?))),
Expr::Datum(form) => Ok(Expr::Datum(Box::new(inner(form, depth)?))),
.map(|elem| inner(elem, depth))
.collect::<Result<_>>()
.map(Expr::List),
Expr::Cons(car, cdr) => Ok(Expr::Cons(
Box::new(inner(car, depth)?),
Box::new(inner(cdr, depth)?),
)),
_ => Ok(self.clone()),
#[cfg(test)]
#[path = "ast_template_tests.rs"]
mod tests;