nomiscript/
ast_template.rs1use crate::ast::Expr;
5use crate::error::Result;
6
7impl Expr {
8 #[must_use]
11 pub fn unquoted_forms(&self) -> Vec<&Expr> {
12 let mut forms = Vec::new();
13 self.collect_unquoted(1, &mut forms);
14 forms
15 }
16
17 fn collect_unquoted<'a>(&'a self, depth: usize, forms: &mut Vec<&'a Expr>) {
18 match self {
19 Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) if depth == 1 => forms.push(inner),
20 Expr::Unquote(inner) | Expr::UnquoteSplicing(inner) => {
21 inner.collect_unquoted(depth - 1, forms);
22 }
23 Expr::Quasiquote(inner) => inner.collect_unquoted(depth + 1, forms),
24 Expr::Quote(inner) | Expr::Datum(inner) => inner.collect_unquoted(depth, forms),
25 Expr::List(elems) => elems
26 .iter()
27 .for_each(|elem| elem.collect_unquoted(depth, forms)),
28 Expr::Cons(car, cdr) => {
29 car.collect_unquoted(depth, forms);
30 cdr.collect_unquoted(depth, forms);
31 }
32 _ => {}
33 }
34 }
35
36 pub fn map_unquoted(&self, rewrite: &mut impl FnMut(&Expr) -> Result<Expr>) -> Result<Expr> {
39 self.map_at_depth(1, rewrite)
40 }
41
42 fn map_at_depth(
43 &self,
44 depth: usize,
45 rewrite: &mut impl FnMut(&Expr) -> Result<Expr>,
46 ) -> Result<Expr> {
47 let mut inner = |expr: &Expr, depth| expr.map_at_depth(depth, rewrite);
48 match self {
49 Expr::Unquote(form) if depth == 1 => Ok(Expr::Unquote(Box::new(rewrite(form)?))),
50 Expr::UnquoteSplicing(form) if depth == 1 => {
51 Ok(Expr::UnquoteSplicing(Box::new(rewrite(form)?)))
52 }
53 Expr::Unquote(form) => Ok(Expr::Unquote(Box::new(inner(form, depth - 1)?))),
54 Expr::UnquoteSplicing(form) => {
55 Ok(Expr::UnquoteSplicing(Box::new(inner(form, depth - 1)?)))
56 }
57 Expr::Quasiquote(form) => Ok(Expr::Quasiquote(Box::new(inner(form, depth + 1)?))),
58 Expr::Quote(form) => Ok(Expr::Quote(Box::new(inner(form, depth)?))),
59 Expr::Datum(form) => Ok(Expr::Datum(Box::new(inner(form, depth)?))),
60 Expr::List(elems) => elems
61 .iter()
62 .map(|elem| inner(elem, depth))
63 .collect::<Result<_>>()
64 .map(Expr::List),
65 Expr::Cons(car, cdr) => Ok(Expr::Cons(
66 Box::new(inner(car, depth)?),
67 Box::new(inner(cdr, depth)?),
68 )),
69 _ => Ok(self.clone()),
70 }
71 }
72}
73
74#[cfg(test)]
75#[path = "ast_template_tests.rs"]
76mod tests;