1
//! Quasiquote expansion into the standard backquote form.
2
//!
3
//! A template with no unquote is one quoted datum. Otherwise a list becomes
4
//! `(list …)`, a `,@x` element splits it into nested two-list `append`s
5
//! and a dotted pair becomes `(cons car cdr)`. The form is then compiled or
6
//! evaluated like any other, so an unquoted call or runtime value is computed.
7
//!
8
//! Inside a macro body an unquoted parameter holds a FORM, to be substituted
9
//! as it is, so [`quasiquote_datum`] builds the expansion as a datum instead.
10

            
11
use crate::ast::Expr;
12
use crate::error::{Error, Result};
13
use crate::runtime::SymbolTable;
14

            
15
use super::eval::eval_value;
16
use super::format::format_expr;
17

            
18
3291
fn call(head: &str, args: Vec<Expr>) -> Expr {
19
3291
    let mut form = vec![Expr::Symbol(head.to_string())];
20
3291
    form.extend(args);
21
3291
    Expr::List(form)
22
3291
}
23

            
24
15198
fn has_unquote(expr: &Expr) -> bool {
25
15198
    match expr {
26
4365
        Expr::Unquote(_) | Expr::UnquoteSplicing(_) => true,
27
595
        Expr::Quote(inner) => has_unquote(inner),
28
3604
        Expr::List(items) => items.iter().any(has_unquote),
29
1
        Expr::Cons(car, cdr) => has_unquote(car) || has_unquote(cdr),
30
6633
        _ => false,
31
    }
32
15198
}
33

            
34
6151
pub(in crate::compiler) fn quasiquote_form(template: &Expr) -> Result<Expr> {
35
6151
    match template {
36
6151
        _ if !has_unquote(template) => Ok(Expr::quoted(template.clone())),
37
1082
        Expr::Unquote(inner) => Ok(inner.as_ref().clone()),
38
296
        Expr::Quote(inner) => Ok(call(
39
296
            "LIST",
40
296
            vec![
41
296
                Expr::quoted(Expr::Symbol("QUOTE".to_string())),
42
296
                quasiquote_form(inner)?,
43
            ],
44
        )),
45
1684
        Expr::List(items) => list_form(items),
46
1
        Expr::Cons(car, cdr) => Ok(call(
47
1
            "CONS",
48
1
            vec![quasiquote_form(car)?, quasiquote_form(cdr)?],
49
        )),
50
        _ => Err(Error::Compile(
51
            "unquote-splicing outside of list in quasiquote".to_string(),
52
        )),
53
    }
54
6151
}
55

            
56
1684
fn list_form(items: &[Expr]) -> Result<Expr> {
57
1684
    let mut segments: Vec<Expr> = Vec::new();
58
1684
    let mut cells: Vec<Expr> = Vec::new();
59
1684
    let mut spliced = false;
60
1684
    for item in items {
61
4184
        let Expr::UnquoteSplicing(inner) = item else {
62
3730
            cells.push(quasiquote_form(item)?);
63
3730
            continue;
64
        };
65
454
        reject_non_list(inner)?;
66
453
        spliced = true;
67
453
        if !cells.is_empty() {
68
453
            segments.push(call("LIST", std::mem::take(&mut cells)));
69
        }
70
453
        segments.push(inner.as_ref().clone());
71
    }
72
1683
    if !spliced {
73
1230
        return Ok(call("LIST", cells));
74
453
    }
75
453
    if !cells.is_empty() {
76
429
        segments.push(call("LIST", cells));
77
24
    }
78
453
    let last = segments.pop().unwrap_or(Expr::Nil);
79
453
    Ok(segments
80
453
        .into_iter()
81
453
        .rev()
82
882
        .fold(last, |tail, head| call("APPEND", vec![head, tail])))
83
1684
}
84

            
85
454
fn reject_non_list(spliced: &Expr) -> Result<()> {
86
454
    match spliced {
87
1
        Expr::Number(_) | Expr::String(_) | Expr::T | Expr::Keyword(_) => Err(not_a_list(spliced)),
88
453
        _ => Ok(()),
89
    }
90
454
}
91

            
92
/// The expansion of `template` as a quoted datum, each `,form` replaced by
93
/// its evaluated value and each `,@form` spliced.
94
633696
pub(in crate::compiler) fn quasiquote_datum(
95
633696
    symbols: &mut SymbolTable,
96
633696
    template: &Expr,
97
633696
) -> Result<Expr> {
98
633696
    let data = datum(symbols, template)?;
99
633693
    crate::compiler::datum::bounded(symbols, Expr::quoted(data))
100
633696
}
101

            
102
6729113
fn datum(symbols: &mut SymbolTable, expr: &Expr) -> Result<Expr> {
103
6729113
    match expr {
104
2164
        Expr::Quote(inner) if has_unquote(inner) => Ok(Expr::List(vec![
105
1302
            Expr::Symbol("QUOTE".to_string()),
106
1302
            datum(symbols, inner)?,
107
        ])),
108
654840
        Expr::Unquote(inner) => unquoted(symbols, inner),
109
        Expr::UnquoteSplicing(_) => Err(Error::Compile(
110
            "unquote-splicing outside of list in quasiquote".to_string(),
111
        )),
112
        Expr::List(elems) => {
113
2771947
            let mut resolved = Vec::new();
114
2771947
            for elem in elems {
115
6635944
                match elem {
116
                    Expr::UnquoteSplicing(inner) => {
117
541829
                        let spliced = eval_value(symbols, inner)?;
118
541829
                        resolved.extend(splice_elements(spliced)?);
119
                    }
120
6094115
                    _ => resolved.push(datum(symbols, elem)?),
121
                }
122
            }
123
2771944
            Ok(Expr::List(resolved))
124
        }
125
        Expr::Cons(car, cdr) => Ok(Expr::cons(datum(symbols, car)?, datum(symbols, cdr)?)),
126
3301024
        _ => Ok(expr.clone()),
127
    }
128
6729113
}
129

            
130
/// An unquoted form is evaluated and its value becomes code.
131
654840
fn unquoted(symbols: &mut SymbolTable, inner: &Expr) -> Result<Expr> {
132
654840
    eval_value(symbols, inner).map(Expr::into_code)
133
654840
}
134

            
135
541829
fn splice_elements(spliced: Expr) -> Result<Vec<Expr>> {
136
541829
    match spliced {
137
85127
        Expr::Nil => Ok(Vec::new()),
138
        Expr::List(elems) => Ok(elems),
139
456702
        Expr::Datum(inner) => match *inner {
140
            Expr::Nil => Ok(Vec::new()),
141
456702
            Expr::List(elems) => Ok(elems),
142
            other => Err(not_a_list(&other)),
143
        },
144
        other => Err(not_a_list(&other)),
145
    }
146
541829
}
147

            
148
1
fn not_a_list(value: &Expr) -> Error {
149
1
    Error::Compile(format!(
150
1
        "unquote-splicing requires a list, got {}",
151
1
        format_expr(value)
152
1
    ))
153
1
}
154

            
155
#[cfg(test)]
156
#[path = "quasiquote_tests.rs"]
157
mod tests;