1
//! A macro place of SETF is the place its expansion names (CLHS 5.1.2.7).
2

            
3
use crate::ast::Expr;
4
use crate::error::{Error, Result};
5
use crate::runtime::{Head, SymbolTable};
6

            
7
use super::fully_macro_expanded;
8

            
9
/// The place/value pairs `args` of a SETF with each macro place replaced by
10
/// its expansion.
11
1767109
pub(in crate::compiler) fn expand_macro_places(
12
1767109
    symbols: &SymbolTable,
13
1767109
    args: &[Expr],
14
1767109
) -> Result<Vec<Expr>> {
15
1767109
    args.iter()
16
1767109
        .enumerate()
17
        .map(
18
3541292
            |(at, arg)| match at % 2 == 0 && is_macro_use(symbols, arg) {
19
3122
                true => fully_macro_expanded(symbols, arg),
20
3538170
                false => Ok(arg.clone()),
21
3541292
            },
22
        )
23
        .collect()
24
1767109
}
25

            
26
/// The call `((SETF f) operands… value)` a compound place `(f operands…)`
27
/// stores through; the place's subforms run before the value, as in Common
28
/// Lisp. `None` for a place that is not a form.
29
1220627
pub(in crate::compiler) fn compound_setf_call(
30
1220627
    symbols: &SymbolTable,
31
1220627
    place: &Expr,
32
1220627
    value: &Expr,
33
1220627
) -> Result<Option<Expr>> {
34
1220627
    let Expr::List(parts) = place else {
35
1192128
        return Ok(None);
36
    };
37
28499
    let Some((head, operands)) = parts.split_first() else {
38
        return Ok(None);
39
    };
40
28499
    let Expr::Symbol(accessor) = head else {
41
1
        return Err(Error::Compile(
42
1
            "Invalid place in SETF - expected function call".to_string(),
43
1
        ));
44
    };
45
28498
    let setter = format!("(SETF {accessor})");
46
28498
    if !symbols.contains(&setter) {
47
417
        return Err(Error::Compile(format!(
48
417
            "No setf method defined for accessor '{accessor}'"
49
417
        )));
50
28081
    }
51
28081
    let call = std::iter::once(Expr::Symbol(setter))
52
28081
        .chain(operands.iter().cloned())
53
28081
        .chain(std::iter::once(value.clone()));
54
28081
    Ok(Some(Expr::List(call.collect())))
55
1220627
}
56

            
57
1770646
fn is_macro_use(symbols: &SymbolTable, form: &Expr) -> bool {
58
1770646
    matches!(form, Expr::List(items) if matches!(items.first(),
59
52216
        Some(Expr::Symbol(head)) if matches!(symbols.resolve_head(head), Head::Macro(..))))
60
1770646
}
61

            
62
#[cfg(test)]
63
#[path = "setf_place_tests.rs"]
64
mod tests;